lang
stringclasses
1 value
license
stringclasses
13 values
stderr
stringlengths
0
350
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
7
45.1k
new_contents
stringlengths
0
1.87M
new_file
stringlengths
6
292
old_contents
stringlengths
0
1.87M
message
stringlengths
6
9.26k
old_file
stringlengths
6
292
subject
stringlengths
0
4.45k
Java
apache-2.0
4b6af18931cacc1d74c6e1d232bebd4955f395db
0
HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j
package org.neo4j.graphalgo.shortestpath; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.neo4j.commons.iterator.PrefetchingIterator; import org.neo4j.graphalgo.Path; import org.neo4j.graphalgo.RelationshipExpander; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; public class AStar { private final GraphDatabaseService graphDb; private final RelationshipExpander expander; private final CostEvaluator<Double> lengthEvaluator; private final EstimateEvaluator<Double> estimateEvaluator; public AStar( GraphDatabaseService graphDb, RelationshipExpander expander, CostEvaluator<Double> lengthEvaluator, EstimateEvaluator<Double> estimateEvaluator ) { this.graphDb = graphDb; this.expander = expander; this.lengthEvaluator = lengthEvaluator; this.estimateEvaluator = estimateEvaluator; } public Path findPath( Node start, Node end ) { int i = 0; Doer doer = new Doer( start, end ); while ( doer.hasNext() ) { Node node = doer.next(); if ( node.equals( end ) ) { // Hit, return path LinkedList<Relationship> rels = new LinkedList<Relationship>(); Relationship rel = graphDb.getRelationshipById( doer.cameFrom.get( node.getId() ) ); while ( rel != null ) { rels.addFirst( rel ); node = rel.getOtherNode( node ); Long nextRelId = doer.cameFrom.get( node.getId() ); rel = nextRelId == null ? null : graphDb.getRelationshipById( nextRelId ); } Path path = toPath( start, rels ); return path; } } return null; } private Path toPath( Node start, LinkedList<Relationship> rels ) { Path.Builder builder = new Path.Builder( start ); for ( Relationship rel : rels ) { builder = builder.push( rel ); } return builder.build(); } private static class Data { private double wayLength; // acumulated cost to get here (g) private double estimate; // heuristic estimate of cost to reach end (h) double getFscore() { return wayLength + estimate; } } private class Doer extends PrefetchingIterator<Node> { private final Node end; private Node lastNode; private boolean expand; private final Set<Long> visitedNodes = new HashSet<Long>(); private final Set<Node> nextNodesSet = new HashSet<Node>(); private final TreeMap<Double, Collection<Node>> nextNodes = new TreeMap<Double, Collection<Node>>(); private final Map<Long, Long> cameFrom = new HashMap<Long, Long>(); private final Map<Long, Data> score = new HashMap<Long, Data>(); Doer( Node start, Node end ) { this.end = end; Data data = new Data(); data.wayLength = 0; data.estimate = estimateEvaluator.getCost( start, end ); addNext( start, data.getFscore() ); this.score.put( start.getId(), data ); } private void addNext( Node node, double fscore ) { Collection<Node> nodes = this.nextNodes.get( fscore ); if ( nodes == null ) { nodes = new HashSet<Node>(); this.nextNodes.put( fscore, nodes ); } nodes.add( node ); this.nextNodesSet.add( node ); } private Node popLowestScoreNode() { Iterator<Map.Entry<Double, Collection<Node>>> itr = this.nextNodes.entrySet().iterator(); if ( !itr.hasNext() ) { return null; } Map.Entry<Double, Collection<Node>> entry = itr.next(); Node node = entry.getValue().isEmpty() ? null : entry.getValue().iterator().next(); if ( node == null ) { return null; } if ( node != null ) { entry.getValue().remove( node ); this.nextNodesSet.remove( node ); if ( entry.getValue().isEmpty() ) { this.nextNodes.remove( entry.getKey() ); } this.visitedNodes.add( node.getId() ); } return node; } @Override protected Node fetchNextOrNull() { // FIXME if ( !this.expand ) { this.expand = true; } else { expand(); } Node node = popLowestScoreNode(); this.lastNode = node; return node; } private void expand() { for ( Relationship rel : expander.expand( this.lastNode ) ) { Node node = rel.getOtherNode( this.lastNode ); if ( this.visitedNodes.contains( node.getId() ) ) { continue; } Data lastNodeData = this.score.get( this.lastNode.getId() ); double tentativeGScore = lastNodeData.wayLength + lengthEvaluator.getCost( rel, false ); boolean isBetter = false; double estimate = estimateEvaluator.getCost( node, this.end ); if ( !this.nextNodesSet.contains( node ) ) { addNext( node, estimate + tentativeGScore ); isBetter = true; } else if ( tentativeGScore < this.score.get( node.getId() ).wayLength ) { isBetter = true; } if ( isBetter ) { this.cameFrom.put( node.getId(), rel.getId() ); Data data = new Data(); data.wayLength = tentativeGScore; data.estimate = estimate; this.score.put( node.getId(), data ); } } } } }
community/src/main/java/org/neo4j/graphalgo/shortestpath/AStar.java
package org.neo4j.graphalgo.shortestpath; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.neo4j.commons.iterator.PrefetchingIterator; import org.neo4j.graphalgo.Path; import org.neo4j.graphalgo.RelationshipExpander; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; public class AStar { private final GraphDatabaseService graphDb; private final RelationshipExpander expander; private final CostEvaluator<Double> lengthEvaluator; private final EstimateEvaluator<Double> estimateEvaluator; public AStar( GraphDatabaseService graphDb, RelationshipExpander expander, CostEvaluator<Double> lengthEvaluator, EstimateEvaluator<Double> estimateEvaluator ) { this.graphDb = graphDb; this.expander = expander; this.lengthEvaluator = lengthEvaluator; this.estimateEvaluator = estimateEvaluator; } public Path findPath( Node start, Node end ) { int i = 0; Doer doer = new Doer( start, end ); while ( doer.hasNext() ) { Node node = doer.next(); if ( node.equals( end ) ) { // Hit, return path LinkedList<Relationship> rels = new LinkedList<Relationship>(); Relationship rel = graphDb.getRelationshipById( doer.cameFrom.get( node.getId() ) ); while ( rel != null ) { rels.addFirst( rel ); node = rel.getOtherNode( node ); Long nextRelId = doer.cameFrom.get( node.getId() ); rel = nextRelId == null ? null : graphDb.getRelationshipById( nextRelId ); } Path path = toPath( start, rels ); return path; } } return null; } private Path toPath( Node start, LinkedList<Relationship> rels ) { Path.Builder builder = new Path.Builder( start ); for ( Relationship rel : rels ) { builder = builder.push( rel ); } return builder.build(); } private static class Data { private double wayLength; // acumulated cost to get here (g) private double estimate; // heuristic estimate of cost to reach end (h) double getFscore() { return wayLength + estimate; } } private class Doer extends PrefetchingIterator<Node> { private final Node end; private Node lastNode; private boolean expand; private final Set<Long> visitedNodes = new HashSet<Long>(); private final Set<Node> nextNodesSet = new HashSet<Node>(); private final TreeMap<Double, Collection<Node>> nextNodes = new TreeMap<Double, Collection<Node>>(); private final Map<Long, Long> cameFrom = new HashMap<Long, Long>(); private final Map<Long, Data> score = new HashMap<Long, Data>(); Doer( Node start, Node end ) { this.end = end; Data data = new Data(); data.wayLength = 0; data.estimate = estimateEvaluator.getCost( start, end ); addNext( start, data.getFscore() ); this.score.put( start.getId(), data ); } private void addNext( Node node, double fscore ) { Collection<Node> nodes = this.nextNodes.get( fscore ); if ( nodes == null ) { nodes = new HashSet<Node>(); this.nextNodes.put( fscore, nodes ); } nodes.add( node ); this.nextNodesSet.add( node ); } private Node popLowestScoreNode() { Iterator<Map.Entry<Double, Collection<Node>>> itr = this.nextNodes.entrySet().iterator(); if ( !itr.hasNext() ) { return null; } Map.Entry<Double, Collection<Node>> entry = itr.next(); Node node = entry.getValue().isEmpty() ? null : entry.getValue().iterator().next(); if ( node == null ) { return null; } if ( node != null ) { entry.getValue().remove( node ); this.nextNodesSet.remove( node ); if ( entry.getValue().isEmpty() ) { this.nextNodes.remove( entry.getKey() ); } this.visitedNodes.add( node.getId() ); } return node; } @Override protected Node fetchNextOrNull() { // FIXME if ( !this.expand ) { this.expand = true; } else { expand(); } Node node = popLowestScoreNode(); this.lastNode = node; return node; } private void expand() { for ( Relationship rel : expander.expand( this.lastNode ) ) { Node node = rel.getOtherNode( this.lastNode ); if ( this.visitedNodes.contains( node.getId() ) ) { continue; } Data lastNodeData = this.score.get( this.lastNode.getId() ); double tentativeGScore = lastNodeData.wayLength + lengthEvaluator.getCost( rel, false, null ); boolean isBetter = false; double estimate = estimateEvaluator.getCost( node, this.end ); if ( !this.nextNodesSet.contains( node ) ) { addNext( node, estimate + tentativeGScore ); isBetter = true; } else if ( tentativeGScore < this.score.get( node.getId() ).wayLength ) { isBetter = true; } if ( isBetter ) { this.cameFrom.put( node.getId(), rel.getId() ); Data data = new Data(); data.wayLength = tentativeGScore; data.estimate = estimate; this.score.put( node.getId(), data ); } } } } }
A compilation error :) git-svn-id: 153979b1b6856005f89f303a7dd326e07c869f86@4067 0b971d98-bb2f-0410-8247-b05b2b5feb2a
community/src/main/java/org/neo4j/graphalgo/shortestpath/AStar.java
A compilation error :)
Java
apache-2.0
ebaeca311ff9eab79e005b5aaed0377eb8e98937
0
tcat-tamu/HathiTrust-SDK
package edu.tamu.tcat.hathitrust; public enum RightsCode { // NOTE: See http://www.hathitrust.org/access_use // http://www.hathitrust.org/rights_database#Attributes // These two definitions seem to be in conflict. // This looks a lot like something that should be an extension point PublicDomain(1, "pd", RightsType.Copyright, "public domain"), InCopyright(2, "ic", RightsType.Copyright, "in-copyright"), OutOfPrint(3, "op", RightsType.Copyright, "out-of-print (implies in-copyright)"), Orphan(4, "orph", RightsType.Copyright, "copyright-orphaned (implies in-copyright)"), Undetermined(5, "und", RightsType.Copyright, "undetermined copyright status"), UMAll(6, "umall", RightsType.Access, "available to UM affiliates and walk-in patrons (all campuses)"), InCopyrightWorld(7, "ic-world", RightsType.Access, "in-copyright and permitted as world viewable by the copyright holder"), Nobody(8, "nobody", RightsType.Access, "available to nobody; blocked for all users"), PublicDomainUS(9, "pdus", RightsType.Copyright, "public domain only when viewed in the US"), CC_BY_3(10, "cc-by-3.0", RightsType.Copyright, "Creative Commons Attribution license, 3.0 Unported"), CC_BY_ND_3(11, "cc-by-nd-3.0", RightsType.Copyright, "Creative Commons Attribution-NoDerivatives license, 3.0 Unported"), CC_BY_NC_ND_3(12, "cc-by-nc-nd-3.0", RightsType.Copyright, "Creative Commons Attribution-NonCommercial-NoDerivatives license, 3.0 Unported"), CC_BY_NC_3(13, "cc-by-nc-3.0", RightsType.Copyright, "Creative Commons Attribution-NonCommercial license, 3.0 Unported"), CC_BY_NC_SA_3(14, "cc-by-nc-sa-3.0", RightsType.Copyright, "Creative Commons Attribution-NonCommercial-ShareAlike license, 3.0 Unported"), CC_BY_SA_3(15, "cc-by-sa-3.0", RightsType.Copyright, "Creative Commons Attribution-ShareAlike license, 3.0 Unported"), OrphanCandidate(16, "orphcand", RightsType.Copyright, "orphan candidate - in 90-day holding period (implies in-copyright)"), CC0(17, "cc-zero", RightsType.Copyright, "Creative Commons Zero license (implies pd)"), UndeterminedWorld(18, "und-world", RightsType.Access, "undetermined copyright status and permitted as world viewable by the depositor"), InCopyrightUS(19, "icus", RightsType.Copyright, "in copyright in the US"), CC_BY_4(20, "cc-by-4.0", RightsType.Copyright, "Creative Commons Attribution 4.0 International license"), CC_BY_ND_4(21, "cc-by-nd-4.0", RightsType.Copyright, "Creative Commons Attribution-NoDerivatives 4.0 International license"), CC_BY_NC_ND_4(22, "cc-by-nc-nd-4.0", RightsType.Copyright, "Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International license"), CC_BY_NC_4(23, "cc-by-nc-4.0", RightsType.Copyright, "Creative Commons Attribution-NonCommercial 4.0 International license"), CC_BY_NC_SA_4(24, "cc-by-nc-sa-4.0", RightsType.Copyright, "Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license"), CC_BY_SA_4(25, "cc-by-sa-4.0", RightsType.Copyright, "Creative Commons Attribution-ShareAlike 4.0 International license"); // http://schemas.hathitrust.org/htd/2009#pd // http://schemas.hathitrust.org/htd/2009#pd-google // http://schemas.hathitrust.org/htd/2009#pd-us // http://schemas.hathitrust.org/htd/2009#pd-us-google // http://schemas.hathitrust.org/htd/2009#oa // http://schemas.hathitrust.org/htd/2009#oa-google // http://schemas.hathitrust.org/htd/2009#section108 // http://schemas.hathitrust.org/htd/2009#ic // http://schemas.hathitrust.org/htd/2009#cc-by // http://schemas.hathitrust.org/htd/2009#cc-by-nd // http://schemas.hathitrust.org/htd/2009#cc-by-nc-nd // http://schemas.hathitrust.org/htd/2009#cc-by-nc // http://schemas.hathitrust.org/htd/2009#cc-by-nc-sa // http://schemas.hathitrust.org/htd/2009#cc-by-sa // http://schemas.hathitrust.org/htd/2009#cc-zero // http://schemas.hathitrust.org/htd/2009#und-world public final int id; public final String key; public final RightsType type; public final String description; private RightsCode(int id, String key, RightsType type, String description) { this.id = id; this.key = key; this.type = type; this.description = description; } public enum RightsType { Copyright, Access } }
bundles/edu.tamu.tcat.hathitrust/src/edu/tamu/tcat/hathitrust/RightsCode.java
package edu.tamu.tcat.hathitrust; public enum RightsCode { // NOTE: See http://www.hathitrust.org/access_use // http://www.hathitrust.org/rights_database#Attributes // These two definitions seem to be in conflict. PublicDomain(1, "pd", RightsType.Copyright, "public domain"), InCopyright(2, "ic", RightsType.Copyright, "in-copyright"), OutOfPrint(3, "op", RightsType.Copyright, "out-of-print (implies in-copyright)"), Orphan(4, "orph", RightsType.Copyright, "copyright-orphaned (implies in-copyright)"), Undetermined(5, "und", RightsType.Copyright, "undetermined copyright status"), UMAll(6, "umall", RightsType.Access, "available to UM affiliates and walk-in patrons (all campuses)"), InCopyrightWorld(7, "ic-world", RightsType.Access, "in-copyright and permitted as world viewable by the copyright holder"), Nobody(8, "nobody", RightsType.Access, "available to nobody; blocked for all users"), PublicDomainUS(9, "pdus", RightsType.Copyright, "public domain only when viewed in the US"), CC_BY_3(10, "cc-by-3.0", RightsType.Copyright, "Creative Commons Attribution license, 3.0 Unported"), CC_BY_ND_3(11, "cc-by-nd-3.0", RightsType.Copyright, "Creative Commons Attribution-NoDerivatives license, 3.0 Unported"), CC_BY_NC_ND_3(12, "cc-by-nc-nd-3.0", RightsType.Copyright, "Creative Commons Attribution-NonCommercial-NoDerivatives license, 3.0 Unported"), CC_BY_NC_3(13, "cc-by-nc-3.0", RightsType.Copyright, "Creative Commons Attribution-NonCommercial license, 3.0 Unported"), CC_BY_NC_SA_3(14, "cc-by-nc-sa-3.0", RightsType.Copyright, "Creative Commons Attribution-NonCommercial-ShareAlike license, 3.0 Unported"), CC_BY_SA_3(15, "cc-by-sa-3.0", RightsType.Copyright, "Creative Commons Attribution-ShareAlike license, 3.0 Unported"), OrphanCandidate(16, "orphcand", RightsType.Copyright, "orphan candidate - in 90-day holding period (implies in-copyright)"), CC0(17, "cc-zero", RightsType.Copyright, "Creative Commons Zero license (implies pd)"), UndeterminedWorld(18, "und-world", RightsType.Access, "undetermined copyright status and permitted as world viewable by the depositor"), InCopyrightUS(19, "icus", RightsType.Copyright, "in copyright in the US"), CC_BY_4(20, "cc-by-4.0", RightsType.Copyright, "Creative Commons Attribution 4.0 International license"), CC_BY_ND_4(21, "cc-by-nd-4.0", RightsType.Copyright, "Creative Commons Attribution-NoDerivatives 4.0 International license"), CC_BY_NC_ND_4(22, "cc-by-nc-nd-4.0", RightsType.Copyright, "Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International license"), CC_BY_NC_4(23, "cc-by-nc-4.0", RightsType.Copyright, "Creative Commons Attribution-NonCommercial 4.0 International license"), CC_BY_NC_SA_4(24, "cc-by-nc-sa-4.0", RightsType.Copyright, "Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license"), CC_BY_SA_4(25, "cc-by-sa-4.0", RightsType.Copyright, "Creative Commons Attribution-ShareAlike 4.0 International license"); // http://schemas.hathitrust.org/htd/2009#pd // http://schemas.hathitrust.org/htd/2009#pd-google // http://schemas.hathitrust.org/htd/2009#pd-us // http://schemas.hathitrust.org/htd/2009#pd-us-google // http://schemas.hathitrust.org/htd/2009#oa // http://schemas.hathitrust.org/htd/2009#oa-google // http://schemas.hathitrust.org/htd/2009#section108 // http://schemas.hathitrust.org/htd/2009#ic // http://schemas.hathitrust.org/htd/2009#cc-by // http://schemas.hathitrust.org/htd/2009#cc-by-nd // http://schemas.hathitrust.org/htd/2009#cc-by-nc-nd // http://schemas.hathitrust.org/htd/2009#cc-by-nc // http://schemas.hathitrust.org/htd/2009#cc-by-nc-sa // http://schemas.hathitrust.org/htd/2009#cc-by-sa // http://schemas.hathitrust.org/htd/2009#cc-zero // http://schemas.hathitrust.org/htd/2009#und-world public final int id; public final String key; public final RightsType type; public final String description; private RightsCode(int id, String key, RightsType type, String description) { this.id = id; this.key = key; this.type = type; this.description = description; } public enum RightsType { Copyright, Access } }
Added note about moving toward more flexible impl https://issues.citd.tamu.edu/HT-1
bundles/edu.tamu.tcat.hathitrust/src/edu/tamu/tcat/hathitrust/RightsCode.java
Added note about moving toward more flexible impl
Java
apache-2.0
be19bfc74fcc2dbbdba88ff1fd72336de5964909
0
gregerrag/selenium,TheBlackTuxCorp/selenium,davehunt/selenium,aluedeke/chromedriver,asolntsev/selenium,tkurnosova/selenium,SouWilliams/selenium,lummyare/lummyare-test,sri85/selenium,chrsmithdemos/selenium,mestihudson/selenium,temyers/selenium,s2oBCN/selenium,amikey/selenium,jsakamoto/selenium,gregerrag/selenium,lummyare/lummyare-test,dkentw/selenium,minhthuanit/selenium,lmtierney/selenium,dkentw/selenium,dimacus/selenium,lrowe/selenium,dkentw/selenium,gurayinan/selenium,minhthuanit/selenium,SouWilliams/selenium,sebady/selenium,manuelpirez/selenium,mach6/selenium,oddui/selenium,lrowe/selenium,minhthuanit/selenium,rrussell39/selenium,jsarenik/jajomojo-selenium,anshumanchatterji/selenium,Dude-X/selenium,petruc/selenium,knorrium/selenium,thanhpete/selenium,clavery/selenium,tbeadle/selenium,lummyare/lummyare-test,amikey/selenium,customcommander/selenium,oddui/selenium,Appdynamics/selenium,uchida/selenium,amar-sharma/selenium,alb-i986/selenium,Sravyaksr/selenium,RamaraoDonta/ramarao-clone,skurochkin/selenium,alb-i986/selenium,JosephCastro/selenium,xsyntrex/selenium,stupidnetizen/selenium,5hawnknight/selenium,krmahadevan/selenium,dibagga/selenium,lmtierney/selenium,eric-stanley/selenium,MeetMe/selenium,amar-sharma/selenium,pulkitsinghal/selenium,rplevka/selenium,markodolancic/selenium,twalpole/selenium,sebady/selenium,jsakamoto/selenium,davehunt/selenium,misttechnologies/selenium,eric-stanley/selenium,jsarenik/jajomojo-selenium,RamaraoDonta/ramarao-clone,pulkitsinghal/selenium,lilredindy/selenium,gurayinan/selenium,amar-sharma/selenium,sag-enorman/selenium,titusfortner/selenium,dbo/selenium,dkentw/selenium,rovner/selenium,rovner/selenium,pulkitsinghal/selenium,jsarenik/jajomojo-selenium,GorK-ChO/selenium,pulkitsinghal/selenium,jerome-jacob/selenium,Herst/selenium,misttechnologies/selenium,bartolkaruza/selenium,5hawnknight/selenium,5hawnknight/selenium,zenefits/selenium,oddui/selenium,misttechnologies/selenium,o-schneider/selenium,gregerrag/selenium,sankha93/selenium,sag-enorman/selenium,houchj/selenium,BlackSmith/selenium,rplevka/selenium,compstak/selenium,dcjohnson1989/selenium,tkurnosova/selenium,rovner/selenium,misttechnologies/selenium,petruc/selenium,MCGallaspy/selenium,quoideneuf/selenium,onedox/selenium,joshmgrant/selenium,sevaseva/selenium,HtmlUnit/selenium,MeetMe/selenium,TikhomirovSergey/selenium,uchida/selenium,skurochkin/selenium,mojwang/selenium,tbeadle/selenium,Appdynamics/selenium,aluedeke/chromedriver,p0deje/selenium,gemini-testing/selenium,wambat/selenium,uchida/selenium,dcjohnson1989/selenium,freynaud/selenium,o-schneider/selenium,JosephCastro/selenium,gemini-testing/selenium,gorlemik/selenium,doungni/selenium,MCGallaspy/selenium,onedox/selenium,lmtierney/selenium,SevInf/IEDriver,jabbrwcky/selenium,p0deje/selenium,tkurnosova/selenium,denis-vilyuzhanin/selenium-fastview,skurochkin/selenium,xmhubj/selenium,Tom-Trumper/selenium,Sravyaksr/selenium,telefonicaid/selenium,lilredindy/selenium,5hawnknight/selenium,livioc/selenium,oddui/selenium,stupidnetizen/selenium,Jarob22/selenium,sankha93/selenium,temyers/selenium,chrsmithdemos/selenium,TheBlackTuxCorp/selenium,tarlabs/selenium,rrussell39/selenium,carlosroh/selenium,livioc/selenium,aluedeke/chromedriver,MeetMe/selenium,gurayinan/selenium,rovner/selenium,gregerrag/selenium,misttechnologies/selenium,eric-stanley/selenium,krosenvold/selenium-git-release-candidate,mach6/selenium,Herst/selenium,arunsingh/selenium,joshmgrant/selenium,arunsingh/selenium,xsyntrex/selenium,MCGallaspy/selenium,meksh/selenium,jknguyen/josephknguyen-selenium,titusfortner/selenium,lummyare/lummyare-lummy,TikhomirovSergey/selenium,xmhubj/selenium,joshbruning/selenium,xsyntrex/selenium,bayandin/selenium,jsarenik/jajomojo-selenium,oddui/selenium,kalyanjvn1/selenium,Tom-Trumper/selenium,joshmgrant/selenium,oddui/selenium,freynaud/selenium,clavery/selenium,krmahadevan/selenium,amar-sharma/selenium,lrowe/selenium,knorrium/selenium,titusfortner/selenium,doungni/selenium,valfirst/selenium,temyers/selenium,RamaraoDonta/ramarao-clone,aluedeke/chromedriver,twalpole/selenium,gabrielsimas/selenium,Ardesco/selenium,SouWilliams/selenium,alb-i986/selenium,thanhpete/selenium,JosephCastro/selenium,mestihudson/selenium,i17c/selenium,eric-stanley/selenium,xsyntrex/selenium,dcjohnson1989/selenium,SevInf/IEDriver,knorrium/selenium,GorK-ChO/selenium,lukeis/selenium,asolntsev/selenium,manuelpirez/selenium,i17c/selenium,dandv/selenium,isaksky/selenium,anshumanchatterji/selenium,vinay-qa/vinayit-android-server-apk,doungni/selenium,mojwang/selenium,yukaReal/selenium,Tom-Trumper/selenium,lilredindy/selenium,bmannix/selenium,yukaReal/selenium,yukaReal/selenium,gorlemik/selenium,jabbrwcky/selenium,sankha93/selenium,customcommander/selenium,mojwang/selenium,freynaud/selenium,quoideneuf/selenium,blueyed/selenium,krosenvold/selenium,dimacus/selenium,twalpole/selenium,denis-vilyuzhanin/selenium-fastview,asashour/selenium,krosenvold/selenium-git-release-candidate,vveliev/selenium,minhthuanit/selenium,arunsingh/selenium,o-schneider/selenium,SeleniumHQ/selenium,alb-i986/selenium,tarlabs/selenium,doungni/selenium,gabrielsimas/selenium,DrMarcII/selenium,gabrielsimas/selenium,TikhomirovSergey/selenium,juangj/selenium,stupidnetizen/selenium,actmd/selenium,stupidnetizen/selenium,sri85/selenium,mestihudson/selenium,tarlabs/selenium,eric-stanley/selenium,gotcha/selenium,jknguyen/josephknguyen-selenium,stupidnetizen/selenium,thanhpete/selenium,sevaseva/selenium,jerome-jacob/selenium,rrussell39/selenium,mojwang/selenium,p0deje/selenium,SeleniumHQ/selenium,Jarob22/selenium,kalyanjvn1/selenium,telefonicaid/selenium,chrsmithdemos/selenium,tarlabs/selenium,knorrium/selenium,lrowe/selenium,livioc/selenium,joshmgrant/selenium,DrMarcII/selenium,vveliev/selenium,lmtierney/selenium,BlackSmith/selenium,dbo/selenium,gemini-testing/selenium,twalpole/selenium,livioc/selenium,dimacus/selenium,denis-vilyuzhanin/selenium-fastview,alexec/selenium,clavery/selenium,joshbruning/selenium,customcommander/selenium,davehunt/selenium,sri85/selenium,SeleniumHQ/selenium,valfirst/selenium,dandv/selenium,gorlemik/selenium,freynaud/selenium,alexec/selenium,blueyed/selenium,compstak/selenium,zenefits/selenium,asashour/selenium,tbeadle/selenium,gorlemik/selenium,xsyntrex/selenium,TikhomirovSergey/selenium,JosephCastro/selenium,dkentw/selenium,lummyare/lummyare-test,meksh/selenium,uchida/selenium,gabrielsimas/selenium,manuelpirez/selenium,Ardesco/selenium,dbo/selenium,Herst/selenium,meksh/selenium,thanhpete/selenium,knorrium/selenium,temyers/selenium,alexec/selenium,Herst/selenium,dibagga/selenium,Sravyaksr/selenium,compstak/selenium,krosenvold/selenium-git-release-candidate,markodolancic/selenium,orange-tv-blagnac/selenium,clavery/selenium,telefonicaid/selenium,freynaud/selenium,minhthuanit/selenium,quoideneuf/selenium,o-schneider/selenium,gregerrag/selenium,Tom-Trumper/selenium,alexec/selenium,joshmgrant/selenium,dibagga/selenium,sag-enorman/selenium,petruc/selenium,sevaseva/selenium,lukeis/selenium,clavery/selenium,isaksky/selenium,mach6/selenium,sankha93/selenium,onedox/selenium,kalyanjvn1/selenium,jsakamoto/selenium,kalyanjvn1/selenium,jsarenik/jajomojo-selenium,compstak/selenium,juangj/selenium,joshuaduffy/selenium,Tom-Trumper/selenium,tbeadle/selenium,BlackSmith/selenium,jsakamoto/selenium,krosenvold/selenium,Jarob22/selenium,actmd/selenium,chrsmithdemos/selenium,TikhomirovSergey/selenium,bartolkaruza/selenium,lukeis/selenium,Tom-Trumper/selenium,manuelpirez/selenium,TikhomirovSergey/selenium,TheBlackTuxCorp/selenium,dcjohnson1989/selenium,SevInf/IEDriver,uchida/selenium,5hawnknight/selenium,valfirst/selenium,titusfortner/selenium,orange-tv-blagnac/selenium,mach6/selenium,Jarob22/selenium,carsonmcdonald/selenium,TikhomirovSergey/selenium,clavery/selenium,gurayinan/selenium,tkurnosova/selenium,Sravyaksr/selenium,wambat/selenium,customcommander/selenium,skurochkin/selenium,chrisblock/selenium,MeetMe/selenium,MCGallaspy/selenium,AutomatedTester/selenium,orange-tv-blagnac/selenium,DrMarcII/selenium,isaksky/selenium,RamaraoDonta/ramarao-clone,knorrium/selenium,oddui/selenium,kalyanjvn1/selenium,petruc/selenium,sankha93/selenium,houchj/selenium,p0deje/selenium,5hawnknight/selenium,onedox/selenium,lummyare/lummyare-test,wambat/selenium,lummyare/lummyare-lummy,Sravyaksr/selenium,gurayinan/selenium,houchj/selenium,compstak/selenium,rrussell39/selenium,xsyntrex/selenium,jsarenik/jajomojo-selenium,uchida/selenium,joshmgrant/selenium,alb-i986/selenium,soundcloud/selenium,RamaraoDonta/ramarao-clone,orange-tv-blagnac/selenium,SouWilliams/selenium,alexec/selenium,joshbruning/selenium,twalpole/selenium,TheBlackTuxCorp/selenium,krmahadevan/selenium,tkurnosova/selenium,TheBlackTuxCorp/selenium,sri85/selenium,meksh/selenium,davehunt/selenium,davehunt/selenium,bmannix/selenium,kalyanjvn1/selenium,jknguyen/josephknguyen-selenium,carsonmcdonald/selenium,quoideneuf/selenium,rovner/selenium,sevaseva/selenium,rplevka/selenium,tarlabs/selenium,SeleniumHQ/selenium,MCGallaspy/selenium,SevInf/IEDriver,dbo/selenium,skurochkin/selenium,juangj/selenium,vinay-qa/vinayit-android-server-apk,eric-stanley/selenium,sri85/selenium,lukeis/selenium,skurochkin/selenium,5hawnknight/selenium,lrowe/selenium,pulkitsinghal/selenium,denis-vilyuzhanin/selenium-fastview,Appdynamics/selenium,chrisblock/selenium,chrisblock/selenium,carlosroh/selenium,joshmgrant/selenium,valfirst/selenium,customcommander/selenium,blackboarddd/selenium,houchj/selenium,rrussell39/selenium,mojwang/selenium,dandv/selenium,asashour/selenium,lukeis/selenium,twalpole/selenium,s2oBCN/selenium,asolntsev/selenium,actmd/selenium,yukaReal/selenium,MCGallaspy/selenium,soundcloud/selenium,i17c/selenium,joshuaduffy/selenium,Jarob22/selenium,sevaseva/selenium,petruc/selenium,amikey/selenium,chrisblock/selenium,SeleniumHQ/selenium,vveliev/selenium,chrisblock/selenium,sag-enorman/selenium,bayandin/selenium,chrsmithdemos/selenium,petruc/selenium,denis-vilyuzhanin/selenium-fastview,dcjohnson1989/selenium,asolntsev/selenium,asashour/selenium,Sravyaksr/selenium,aluedeke/chromedriver,mojwang/selenium,MCGallaspy/selenium,rrussell39/selenium,SevInf/IEDriver,amar-sharma/selenium,kalyanjvn1/selenium,sankha93/selenium,HtmlUnit/selenium,HtmlUnit/selenium,valfirst/selenium,TikhomirovSergey/selenium,chrisblock/selenium,tarlabs/selenium,rplevka/selenium,dimacus/selenium,AutomatedTester/selenium,Herst/selenium,Tom-Trumper/selenium,vveliev/selenium,o-schneider/selenium,chrsmithdemos/selenium,rovner/selenium,jerome-jacob/selenium,eric-stanley/selenium,SevInf/IEDriver,SevInf/IEDriver,bayandin/selenium,Jarob22/selenium,carsonmcdonald/selenium,jerome-jacob/selenium,jabbrwcky/selenium,JosephCastro/selenium,blackboarddd/selenium,jerome-jacob/selenium,asolntsev/selenium,Herst/selenium,arunsingh/selenium,GorK-ChO/selenium,minhthuanit/selenium,onedox/selenium,alb-i986/selenium,vveliev/selenium,krosenvold/selenium-git-release-candidate,gemini-testing/selenium,vveliev/selenium,i17c/selenium,isaksky/selenium,jabbrwcky/selenium,vinay-qa/vinayit-android-server-apk,Appdynamics/selenium,houchj/selenium,lukeis/selenium,actmd/selenium,bayandin/selenium,slongwang/selenium,pulkitsinghal/selenium,lmtierney/selenium,bartolkaruza/selenium,bmannix/selenium,bartolkaruza/selenium,onedox/selenium,SouWilliams/selenium,rrussell39/selenium,arunsingh/selenium,mestihudson/selenium,titusfortner/selenium,amikey/selenium,markodolancic/selenium,zenefits/selenium,gemini-testing/selenium,sebady/selenium,joshmgrant/selenium,knorrium/selenium,bayandin/selenium,chrisblock/selenium,petruc/selenium,temyers/selenium,onedox/selenium,dibagga/selenium,lummyare/lummyare-lummy,GorK-ChO/selenium,blueyed/selenium,Dude-X/selenium,joshmgrant/selenium,lummyare/lummyare-lummy,anshumanchatterji/selenium,gotcha/selenium,xsyntrex/selenium,jerome-jacob/selenium,asashour/selenium,p0deje/selenium,mestihudson/selenium,blueyed/selenium,krosenvold/selenium-git-release-candidate,carlosroh/selenium,gorlemik/selenium,denis-vilyuzhanin/selenium-fastview,Appdynamics/selenium,carsonmcdonald/selenium,RamaraoDonta/ramarao-clone,AutomatedTester/selenium,asashour/selenium,bayandin/selenium,mojwang/selenium,AutomatedTester/selenium,zenefits/selenium,sankha93/selenium,orange-tv-blagnac/selenium,zenefits/selenium,xsyntrex/selenium,soundcloud/selenium,lrowe/selenium,lilredindy/selenium,davehunt/selenium,twalpole/selenium,blackboarddd/selenium,o-schneider/selenium,dandv/selenium,tbeadle/selenium,gurayinan/selenium,mach6/selenium,joshuaduffy/selenium,jabbrwcky/selenium,jknguyen/josephknguyen-selenium,jsakamoto/selenium,markodolancic/selenium,sebady/selenium,dkentw/selenium,sebady/selenium,s2oBCN/selenium,sag-enorman/selenium,Appdynamics/selenium,i17c/selenium,sri85/selenium,bmannix/selenium,BlackSmith/selenium,blackboarddd/selenium,sag-enorman/selenium,rplevka/selenium,jknguyen/josephknguyen-selenium,mestihudson/selenium,sag-enorman/selenium,krosenvold/selenium,blackboarddd/selenium,valfirst/selenium,s2oBCN/selenium,thanhpete/selenium,vinay-qa/vinayit-android-server-apk,customcommander/selenium,s2oBCN/selenium,krosenvold/selenium-git-release-candidate,krosenvold/selenium,telefonicaid/selenium,HtmlUnit/selenium,BlackSmith/selenium,sag-enorman/selenium,MCGallaspy/selenium,blueyed/selenium,AutomatedTester/selenium,freynaud/selenium,joshbruning/selenium,MeetMe/selenium,titusfortner/selenium,gurayinan/selenium,freynaud/selenium,knorrium/selenium,isaksky/selenium,actmd/selenium,jerome-jacob/selenium,bartolkaruza/selenium,quoideneuf/selenium,Ardesco/selenium,bmannix/selenium,dandv/selenium,joshbruning/selenium,SeleniumHQ/selenium,minhthuanit/selenium,lummyare/lummyare-test,xmhubj/selenium,asolntsev/selenium,gotcha/selenium,asolntsev/selenium,titusfortner/selenium,titusfortner/selenium,telefonicaid/selenium,amikey/selenium,bmannix/selenium,AutomatedTester/selenium,eric-stanley/selenium,davehunt/selenium,sankha93/selenium,houchj/selenium,denis-vilyuzhanin/selenium-fastview,carsonmcdonald/selenium,slongwang/selenium,orange-tv-blagnac/selenium,vinay-qa/vinayit-android-server-apk,slongwang/selenium,alb-i986/selenium,sevaseva/selenium,dbo/selenium,isaksky/selenium,minhthuanit/selenium,actmd/selenium,bayandin/selenium,twalpole/selenium,rplevka/selenium,AutomatedTester/selenium,dimacus/selenium,gurayinan/selenium,sevaseva/selenium,wambat/selenium,SeleniumHQ/selenium,livioc/selenium,chrisblock/selenium,jsarenik/jajomojo-selenium,sebady/selenium,s2oBCN/selenium,soundcloud/selenium,valfirst/selenium,quoideneuf/selenium,zenefits/selenium,stupidnetizen/selenium,lummyare/lummyare-lummy,krosenvold/selenium,DrMarcII/selenium,anshumanchatterji/selenium,tbeadle/selenium,vveliev/selenium,gorlemik/selenium,onedox/selenium,juangj/selenium,twalpole/selenium,kalyanjvn1/selenium,gregerrag/selenium,livioc/selenium,blackboarddd/selenium,JosephCastro/selenium,skurochkin/selenium,soundcloud/selenium,i17c/selenium,slongwang/selenium,pulkitsinghal/selenium,thanhpete/selenium,sebady/selenium,lummyare/lummyare-test,carsonmcdonald/selenium,thanhpete/selenium,jerome-jacob/selenium,lummyare/lummyare-test,quoideneuf/selenium,gorlemik/selenium,anshumanchatterji/selenium,lilredindy/selenium,krmahadevan/selenium,rovner/selenium,SeleniumHQ/selenium,stupidnetizen/selenium,5hawnknight/selenium,denis-vilyuzhanin/selenium-fastview,gurayinan/selenium,mestihudson/selenium,doungni/selenium,doungni/selenium,bmannix/selenium,chrisblock/selenium,knorrium/selenium,gemini-testing/selenium,juangj/selenium,gabrielsimas/selenium,joshbruning/selenium,bayandin/selenium,xmhubj/selenium,gotcha/selenium,livioc/selenium,freynaud/selenium,bmannix/selenium,actmd/selenium,rrussell39/selenium,temyers/selenium,tbeadle/selenium,misttechnologies/selenium,slongwang/selenium,onedox/selenium,tarlabs/selenium,davehunt/selenium,tkurnosova/selenium,yukaReal/selenium,DrMarcII/selenium,aluedeke/chromedriver,TheBlackTuxCorp/selenium,GorK-ChO/selenium,orange-tv-blagnac/selenium,misttechnologies/selenium,JosephCastro/selenium,compstak/selenium,alb-i986/selenium,Dude-X/selenium,dandv/selenium,manuelpirez/selenium,vveliev/selenium,carlosroh/selenium,blueyed/selenium,houchj/selenium,dkentw/selenium,vinay-qa/vinayit-android-server-apk,markodolancic/selenium,dkentw/selenium,tbeadle/selenium,sebady/selenium,juangj/selenium,blueyed/selenium,TheBlackTuxCorp/selenium,lummyare/lummyare-lummy,gotcha/selenium,vveliev/selenium,manuelpirez/selenium,dbo/selenium,blackboarddd/selenium,s2oBCN/selenium,lummyare/lummyare-lummy,krmahadevan/selenium,sri85/selenium,TikhomirovSergey/selenium,soundcloud/selenium,gabrielsimas/selenium,Herst/selenium,xmhubj/selenium,krosenvold/selenium,mestihudson/selenium,sevaseva/selenium,MeetMe/selenium,AutomatedTester/selenium,krosenvold/selenium,i17c/selenium,dimacus/selenium,joshuaduffy/selenium,vinay-qa/vinayit-android-server-apk,joshmgrant/selenium,p0deje/selenium,compstak/selenium,5hawnknight/selenium,SeleniumHQ/selenium,gregerrag/selenium,HtmlUnit/selenium,gemini-testing/selenium,lrowe/selenium,dimacus/selenium,bartolkaruza/selenium,joshbruning/selenium,mach6/selenium,blueyed/selenium,lummyare/lummyare-test,jsarenik/jajomojo-selenium,oddui/selenium,Herst/selenium,zenefits/selenium,arunsingh/selenium,meksh/selenium,sebady/selenium,MeetMe/selenium,Ardesco/selenium,dcjohnson1989/selenium,joshuaduffy/selenium,wambat/selenium,slongwang/selenium,vinay-qa/vinayit-android-server-apk,titusfortner/selenium,HtmlUnit/selenium,actmd/selenium,houchj/selenium,isaksky/selenium,isaksky/selenium,lmtierney/selenium,soundcloud/selenium,livioc/selenium,MeetMe/selenium,lrowe/selenium,DrMarcII/selenium,telefonicaid/selenium,pulkitsinghal/selenium,dibagga/selenium,krosenvold/selenium,asashour/selenium,DrMarcII/selenium,gotcha/selenium,SouWilliams/selenium,Appdynamics/selenium,lmtierney/selenium,rplevka/selenium,krmahadevan/selenium,markodolancic/selenium,oddui/selenium,SevInf/IEDriver,SouWilliams/selenium,titusfortner/selenium,pulkitsinghal/selenium,dbo/selenium,jsakamoto/selenium,dcjohnson1989/selenium,amikey/selenium,meksh/selenium,gotcha/selenium,meksh/selenium,Appdynamics/selenium,manuelpirez/selenium,stupidnetizen/selenium,slongwang/selenium,jsakamoto/selenium,carlosroh/selenium,MeetMe/selenium,yukaReal/selenium,telefonicaid/selenium,o-schneider/selenium,gabrielsimas/selenium,dbo/selenium,arunsingh/selenium,skurochkin/selenium,alb-i986/selenium,wambat/selenium,GorK-ChO/selenium,orange-tv-blagnac/selenium,vinay-qa/vinayit-android-server-apk,chrsmithdemos/selenium,wambat/selenium,tarlabs/selenium,Appdynamics/selenium,temyers/selenium,jabbrwcky/selenium,temyers/selenium,Jarob22/selenium,jknguyen/josephknguyen-selenium,jabbrwcky/selenium,carlosroh/selenium,HtmlUnit/selenium,dibagga/selenium,davehunt/selenium,asolntsev/selenium,skurochkin/selenium,clavery/selenium,yukaReal/selenium,quoideneuf/selenium,Sravyaksr/selenium,jsakamoto/selenium,anshumanchatterji/selenium,petruc/selenium,JosephCastro/selenium,dandv/selenium,HtmlUnit/selenium,customcommander/selenium,krosenvold/selenium-git-release-candidate,xmhubj/selenium,temyers/selenium,gorlemik/selenium,asolntsev/selenium,dandv/selenium,meksh/selenium,uchida/selenium,carsonmcdonald/selenium,soundcloud/selenium,Jarob22/selenium,gregerrag/selenium,carlosroh/selenium,p0deje/selenium,jabbrwcky/selenium,jerome-jacob/selenium,orange-tv-blagnac/selenium,blackboarddd/selenium,p0deje/selenium,gotcha/selenium,amar-sharma/selenium,aluedeke/chromedriver,gabrielsimas/selenium,i17c/selenium,juangj/selenium,dibagga/selenium,chrsmithdemos/selenium,Ardesco/selenium,jknguyen/josephknguyen-selenium,krmahadevan/selenium,freynaud/selenium,TheBlackTuxCorp/selenium,tbeadle/selenium,i17c/selenium,tkurnosova/selenium,dkentw/selenium,markodolancic/selenium,juangj/selenium,xmhubj/selenium,bartolkaruza/selenium,bayandin/selenium,dcjohnson1989/selenium,p0deje/selenium,anshumanchatterji/selenium,gorlemik/selenium,lilredindy/selenium,o-schneider/selenium,carlosroh/selenium,joshuaduffy/selenium,Herst/selenium,rrussell39/selenium,quoideneuf/selenium,asashour/selenium,xsyntrex/selenium,anshumanchatterji/selenium,rplevka/selenium,BlackSmith/selenium,minhthuanit/selenium,dimacus/selenium,arunsingh/selenium,Ardesco/selenium,sag-enorman/selenium,livioc/selenium,aluedeke/chromedriver,rovner/selenium,telefonicaid/selenium,s2oBCN/selenium,valfirst/selenium,BlackSmith/selenium,thanhpete/selenium,blueyed/selenium,manuelpirez/selenium,rovner/selenium,joshuaduffy/selenium,lukeis/selenium,amar-sharma/selenium,yukaReal/selenium,dbo/selenium,jsakamoto/selenium,compstak/selenium,GorK-ChO/selenium,Dude-X/selenium,jabbrwcky/selenium,gregerrag/selenium,thanhpete/selenium,BlackSmith/selenium,chrsmithdemos/selenium,compstak/selenium,isaksky/selenium,carsonmcdonald/selenium,amar-sharma/selenium,joshmgrant/selenium,titusfortner/selenium,dimacus/selenium,markodolancic/selenium,dcjohnson1989/selenium,arunsingh/selenium,MCGallaspy/selenium,mojwang/selenium,anshumanchatterji/selenium,lmtierney/selenium,s2oBCN/selenium,RamaraoDonta/ramarao-clone,denis-vilyuzhanin/selenium-fastview,gemini-testing/selenium,lummyare/lummyare-lummy,lrowe/selenium,Dude-X/selenium,actmd/selenium,misttechnologies/selenium,slongwang/selenium,SeleniumHQ/selenium,customcommander/selenium,mach6/selenium,Ardesco/selenium,Jarob22/selenium,wambat/selenium,amar-sharma/selenium,bartolkaruza/selenium,SouWilliams/selenium,valfirst/selenium,markodolancic/selenium,petruc/selenium,tarlabs/selenium,aluedeke/chromedriver,customcommander/selenium,dibagga/selenium,GorK-ChO/selenium,lummyare/lummyare-lummy,houchj/selenium,krmahadevan/selenium,lilredindy/selenium,mach6/selenium,telefonicaid/selenium,alexec/selenium,dibagga/selenium,stupidnetizen/selenium,valfirst/selenium,dandv/selenium,SouWilliams/selenium,xmhubj/selenium,eric-stanley/selenium,joshbruning/selenium,SevInf/IEDriver,Tom-Trumper/selenium,Dude-X/selenium,misttechnologies/selenium,doungni/selenium,krosenvold/selenium-git-release-candidate,alexec/selenium,mojwang/selenium,Sravyaksr/selenium,krosenvold/selenium,sankha93/selenium,o-schneider/selenium,sri85/selenium,Dude-X/selenium,xmhubj/selenium,amikey/selenium,HtmlUnit/selenium,alexec/selenium,yukaReal/selenium,clavery/selenium,gemini-testing/selenium,asashour/selenium,lukeis/selenium,RamaraoDonta/ramarao-clone,zenefits/selenium,jknguyen/josephknguyen-selenium,krmahadevan/selenium,bmannix/selenium,jsarenik/jajomojo-selenium,HtmlUnit/selenium,Dude-X/selenium,manuelpirez/selenium,joshuaduffy/selenium,amikey/selenium,uchida/selenium,carsonmcdonald/selenium,DrMarcII/selenium,GorK-ChO/selenium,blackboarddd/selenium,doungni/selenium,AutomatedTester/selenium,clavery/selenium,jknguyen/josephknguyen-selenium,lukeis/selenium,uchida/selenium,JosephCastro/selenium,meksh/selenium,wambat/selenium,rplevka/selenium,tkurnosova/selenium,lilredindy/selenium,tkurnosova/selenium,mestihudson/selenium,Sravyaksr/selenium,RamaraoDonta/ramarao-clone,BlackSmith/selenium,valfirst/selenium,sevaseva/selenium,soundcloud/selenium,slongwang/selenium,Ardesco/selenium,amikey/selenium,bartolkaruza/selenium,joshuaduffy/selenium,sri85/selenium,juangj/selenium,carlosroh/selenium,SeleniumHQ/selenium,doungni/selenium,Ardesco/selenium,TheBlackTuxCorp/selenium,joshbruning/selenium,alexec/selenium,Tom-Trumper/selenium,lmtierney/selenium,gotcha/selenium,lilredindy/selenium,gabrielsimas/selenium,mach6/selenium,DrMarcII/selenium,zenefits/selenium,Dude-X/selenium,kalyanjvn1/selenium
/* * Copyright 2006 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.openqa.selenium.server; import org.mortbay.http.HttpContext; import org.mortbay.http.SocketListener; import org.mortbay.jetty.Server; import org.openqa.selenium.server.browserlaunchers.AsyncExecute; import org.openqa.selenium.server.htmlrunner.HTMLLauncher; import org.openqa.selenium.server.htmlrunner.HTMLResultsListener; import org.openqa.selenium.server.htmlrunner.SeleniumHTMLRunnerResultsHandler; import org.openqa.selenium.server.htmlrunner.SingleTestSuiteResourceHandler; import java.io.*; import java.net.URL; import java.net.URLConnection; /** * Provides a server that can launch/terminate browsers and can receive Selenese commands * over HTTP and send them on to the browser. * <p/> * <p>To run Selenium Server, run: * <p/> * <blockquote><code>java -jar selenium-server-1.0-SNAPSHOT.jar [-port 4444] [-interactive] [-timeout 1800]</code></blockquote> * <p/> * <p>Where <code>-port</code> specifies the port you wish to run the Server on (default is 4444). * <p/> * <p>Where <code>-timeout</code> specifies the number of seconds that you allow data to wait all in the * communications queues before an exception is thrown. * <p/> * <p>Using the <code>-interactive</code> flag will start the server in Interactive mode. * In this mode you can type Selenese commands on the command line (e.g. cmd=open&1=http://www.yahoo.com). * You may also interactively specify commands to run on a particular "browser session" (see below) like this: * <blockquote><code>cmd=open&1=http://www.yahoo.com&sessionId=1234</code></blockquote></p> * <p/> * <p>The server accepts three types of HTTP requests on its port: * <p/> * <ol> * <li><b>Client-Configured Proxy Requests</b>: By configuring your browser to use the * Selenium Server as an HTTP proxy, you can use the Selenium Server as a web proxy. This allows * the server to create a virtual "/selenium-server" directory on every website that you visit using * the proxy. * <li><b>Browser Selenese</b>: If the browser goes to "/selenium-server/SeleneseRunner.html?sessionId=1234" on any website * via the Client-Configured Proxy, it will ask the Selenium Server for work to do, like this: * <blockquote><code>http://www.yahoo.com/selenium-server/driver/?seleniumStart=true&sessionId=1234</code></blockquote> * The driver will then reply with a command to run in the body of the HTTP response, e.g. "|open|http://www.yahoo.com||". Once * the browser is done with this request, the browser will issue a new request for more work, this * time reporting the results of the previous command:<blockquote><code>http://www.yahoo.com/selenium-server/driver/?commandResult=OK&sessionId=1234</code></blockquote> * The action list is listed in selenium-api.js. Normal actions like "doClick" will return "OK" if * clicking was successful, or some other error string if there was an error. Assertions like * assertTextPresent or verifyTextPresent will return "PASSED" if the assertion was true, or * some other error string if the assertion was false. Getters like "getEval" will return the * result of the get command. "getAllLinks" will return a comma-delimited list of links.</li> * <li><b>Driver Commands</b>: Clients may send commands to the Selenium Server over HTTP. * Command requests should look like this:<blockquote><code>http://localhost:4444/selenium-server/driver/?commandRequest=|open|http://www.yahoo.com||&sessionId=1234</code></blockquote> * The Selenium Server will not respond to the HTTP request until the browser has finished performing the requested * command; when it does, it will reply with the result of the command (e.g. "OK" or "PASSED") in the * body of the HTTP response. (Note that <code>-interactive</code> mode also works by sending these * HTTP requests, so tests using <code>-interactive</code> mode will behave exactly like an external client driver.) * </ol> * <p>There are some special commands that only work in the Selenium Server. These commands are: * <ul><li><p><strong>getNewBrowserSession</strong>( <em>browserString</em>, <em>startURL</em> )</p> * <p>Creates a new "sessionId" number (based on the current time in milliseconds) and launches the browser specified in * <i>browserString</i>. We will then browse directly to <i>startURL</i> + "/selenium-server/SeleneseRunner.html?sessionId=###" * where "###" is the sessionId number. Only commands that are associated with the specified sessionId will be run by this browser.</p> * <p/> * <p><i>browserString</i> may be any one of the following: * <ul> * <li><code>*firefox [absolute path]</code> - Automatically launch a new Firefox process using a custom Firefox profile. * This profile will be automatically configured to use the Selenium Server as a proxy and to have all annoying prompts * ("save your password?" "forms are insecure" "make Firefox your default browser?" disabled. You may optionally specify * an absolute path to your firefox executable, or just say "*firefox". If no absolute path is specified, we'll look for * firefox.exe in a default location (normally c:\program files\mozilla firefox\firefox.exe), which you can override by * setting the Java system property <code>firefoxDefaultPath</code> to the correct path to Firefox.</li> * <li><code>*iexplore [absolute path]</code> - Automatically launch a new Internet Explorer process using custom Windows registry settings. * This process will be automatically configured to use the Selenium Server as a proxy and to have all annoying prompts * ("save your password?" "forms are insecure" "make Firefox your default browser?" disabled. You may optionally specify * an absolute path to your iexplore executable, or just say "*iexplore". If no absolute path is specified, we'll look for * iexplore.exe in a default location (normally c:\program files\internet explorer\iexplore.exe), which you can override by * setting the Java system property <code>iexploreDefaultPath</code> to the correct path to Internet Explorer.</li> * <li><code>/path/to/my/browser [other arguments]</code> - You may also simply specify the absolute path to your browser * executable, or use a relative path to your executable (which we'll try to find on your path). <b>Warning:</b> If you * specify your own custom browser, it's up to you to configure it correctly. At a minimum, you'll need to configure your * browser to use the Selenium Server as a proxy, and disable all browser-specific prompting. * </ul> * </li> * <li><p><strong>testComplete</strong>( )</p> * <p>Kills the currently running browser and erases the old browser session. If the current browser session was not * launched using <code>getNewBrowserSession</code>, or if that session number doesn't exist in the server, this * command will return an error.</p> * </li> * <li><p><strong>shutDown</strong>( )</p> * <p>Causes the server to shut itself down, killing itself and all running browsers along with it.</p> * </li> * </ul> * <p>Example:<blockquote><code>cmd=getNewBrowserSession&1=*firefox&2=http://www.google.com * <br/>Got result: 1140738083345 * <br/>cmd=open&1=http://www.google.com&sessionId=1140738083345 * <br/>Got result: OK * <br/>cmd=type&1=q&2=hello world&sessionId=1140738083345 * <br/>Got result: OK * <br/>cmd=testComplete&sessionId=1140738083345 * <br/>Got result: OK * </code></blockquote></p> * <p/> * <h4>The "null" session</h4> * <p/> * <p>If you open a browser manually and do not specify a session ID, it will look for * commands using the "null" session. You may then similarly send commands to this * browser by not specifying a sessionId when issuing commands.</p> * * @author plightbo */ public class SeleniumServer { private Server server; private SeleniumDriverResourceHandler driver; private SeleniumHTMLRunnerResultsHandler postResultsHandler; private StaticContentHandler staticContentHandler; private int port; private boolean multiWindow = false; private static String debugURL = ""; // add special tracing for debug when this URL is requested private static boolean debugMode = false; private static boolean proxyInjectionMode = false; public static final int DEFAULT_PORT = 4444; // The following port is the one which drivers and browsers should use when they contact the selenium server. // Under normal circumstances, this port will be the same as the port which the selenium server listens on. // But if a developer wants to monitor traffic into and out of the selenium server, he can set this port from // the command line to be a different value and then use a tool like tcptrace to link this port with the // server listening port, thereby opening a window into the raw HTTP traffic. // // For example, if the selenium server is invoked with -portDriversShouldContact 4445, then traffic going // into the selenium server will be routed to port 4445, although the selenium server will still be listening // to the default port 4444. At this point, you would open tcptrace to bridge the gap and be able to watch // all the data coming in and out: private static int portDriversShouldContact = 0; private static PrintStream logOut = null; private static String forcedBrowserMode = null; public static final int DEFAULT_TIMEOUT = (30 * 60); public static int timeoutInSeconds = DEFAULT_TIMEOUT; private static Boolean reusingBrowserSessions = null; private static String dontInjectRegex = null; /** * Starts up the server on the specified port (or default if no port was specified) * and then starts interactive mode if specified. * * @param args - either "-port" followed by a number, or "-interactive" * @throws Exception - you know, just in case. */ public static void main(String[] args) throws Exception { int port = DEFAULT_PORT; boolean interactive = false; boolean htmlSuite = false; boolean multiWindow = false; File userExtensions = null; boolean proxyInjectionModeArg = false; int portDriversShouldContactArg = 0; boolean userJsInjection = false; for (int i = 0; i < args.length; i++) { String arg = args[i]; if ("-help".equalsIgnoreCase(arg)) { usage(null); System.exit(1); } else if ("-defaultBrowserString".equalsIgnoreCase(arg)) { usage("-defaultBrowserString has been renamed -forcedBrowserMode"); } else if ("-forcedBrowserMode".equalsIgnoreCase(arg)) { for (i++; i < args.length; i++) { if (SeleniumServer.forcedBrowserMode == null) SeleniumServer.forcedBrowserMode = ""; else SeleniumServer.forcedBrowserMode += " "; SeleniumServer.forcedBrowserMode += args[i]; } SeleniumServer.log("\"" + forcedBrowserMode + "\" will be used as the browser " + "mode for all sessions, no matter what is passed to getNewBrowserSession."); } else if ("-log".equalsIgnoreCase(arg)) { setLogOut(getArg(args, ++i)); } else if ("-port".equalsIgnoreCase(arg)) { port = Integer.parseInt(getArg(args, ++i)); } else if ("-multiWindow".equalsIgnoreCase(arg)) { multiWindow = true; } else if ("-proxyInjectionMode".equalsIgnoreCase(arg)) { proxyInjectionModeArg = true; } else if ("-portDriversShouldContact".equalsIgnoreCase(arg)) { // to facilitate tcptrace interception of interaction between // injected js and the selenium server portDriversShouldContactArg = Integer.parseInt(getArg(args, ++i)); } else if ("-noBrowserSessionReuse".equalsIgnoreCase(arg)) { SeleniumServer.reusingBrowserSessions = Boolean.FALSE; } else if ("-browserSessionReuse".equalsIgnoreCase(arg)) { SeleniumServer.reusingBrowserSessions = Boolean.TRUE; } else if ("-dontInjectRegex".equalsIgnoreCase(arg)) { dontInjectRegex = getArg(args, ++i); } else if ("-debug".equalsIgnoreCase(arg)) { SeleniumServer.setDebugMode(true); } else if ("-debugURL".equalsIgnoreCase(arg)) { debugURL = getArg(args, ++i); } else if ("-timeout".equalsIgnoreCase(arg)) { timeoutInSeconds = Integer.parseInt(getArg(args, ++i)); } else if ("-userJsInjection".equalsIgnoreCase(arg)) { userJsInjection = true; if (!InjectionHelper.addUserJsInjectionFile(getArg(args, ++i))) { usage(null); System.exit(1); } } else if ("-userContentTransformation".equalsIgnoreCase(arg)) { if (!InjectionHelper.addUserContentTransformation(getArg(args, ++i), getArg(args, ++i))) { usage(null); System.exit(1); } } else if ("-userExtensions".equalsIgnoreCase(arg)) { userExtensions = new File(getArg(args, ++i)); if (!userExtensions.exists()) { System.err.println("User Extensions file doesn't exist: " + userExtensions.getAbsolutePath()); System.exit(1); } if (!"user-extensions.js".equalsIgnoreCase(userExtensions.getName())) { System.err.println("User extensions file MUST be called \"user-extensions.js\": " + userExtensions.getAbsolutePath()); System.exit(1); } } else if ("-htmlSuite".equalsIgnoreCase(arg)) { try { System.setProperty("htmlSuite.browserString", args[++i]); System.setProperty("htmlSuite.startURL", args[++i]); System.setProperty("htmlSuite.suiteFilePath", args[++i]); System.setProperty("htmlSuite.resultFilePath", args[++i]); } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Not enough command line arguments for -htmlSuite"); System.err.println("-htmlSuite requires you to specify:"); System.err.println("* browserString (e.g. \"*firefox\")"); System.err.println("* startURL (e.g. \"http://www.google.com\")"); System.err.println("* suiteFile (e.g. \"c:\\absolute\\path\\to\\my\\HTMLSuite.html\")"); System.err.println("* resultFile (e.g. \"c:\\absolute\\path\\to\\my\\results.html\")"); System.exit(1); } htmlSuite = true; } else if ("-interactive".equalsIgnoreCase(arg)) { timeoutInSeconds = Integer.MAX_VALUE; interactive = true; } else if (arg.startsWith("-D")) { setSystemProperty(arg); } else { usage("unrecognized argument " + arg); System.exit(1); } } if (userJsInjection && !proxyInjectionModeArg) { System.err.println("User js injection can only be used w/ -proxyInjectionMode"); System.exit(1); } if (portDriversShouldContactArg == 0) { portDriversShouldContactArg = port; } System.setProperty("org.mortbay.http.HttpRequest.maxFormContentSize", "0"); // default max is 200k; zero is infinite final SeleniumServer seleniumProxy = new SeleniumServer(port); seleniumProxy.multiWindow = multiWindow; checkArgsSanity(port, interactive, htmlSuite, proxyInjectionModeArg, portDriversShouldContactArg, seleniumProxy); Thread jetty = new Thread(new Runnable() { public void run() { try { seleniumProxy.start(); } catch (Exception e) { System.err.println("jetty run exception seen:"); e.printStackTrace(); } } }); if (interactive) { jetty.setDaemon(true); } jetty.start(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { try { System.out.println("Shutting down..."); seleniumProxy.stop(); } catch (InterruptedException e) { System.err.println("run exception seen:"); e.printStackTrace(); } } })); if (userExtensions != null) { seleniumProxy.addNewStaticContent(userExtensions.getParentFile()); } if (htmlSuite) { runHtmlSuite(seleniumProxy); return; } if (interactive) { AsyncExecute.sleepTight(500); System.out.println("Entering interactive mode... type Selenium commands here (e.g: cmd=open&1=http://www.yahoo.com)"); BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput; final String[] lastSessionId = new String[]{""}; while ((userInput = stdIn.readLine()) != null) { if ("exit".equals(userInput) || "quit".equals(userInput)) { System.out.println("Stopping..."); seleniumProxy.stop(); System.exit(0); } if ("".equals(userInput)) continue; if (!userInput.startsWith("cmd=") && !userInput.startsWith("commandResult=")) { System.err.println("ERROR - Invalid command: \"" + userInput + "\""); continue; } final boolean newBrowserSession = userInput.indexOf("getNewBrowserSession") != -1; if (userInput.indexOf("sessionId") == -1 && !newBrowserSession) { userInput = userInput + "&sessionId=" + lastSessionId[0]; } final URL url = new URL("http://localhost:" + port + "/selenium-server/driver?" + userInput); Thread t = new Thread(new Runnable() { public void run() { try { SeleniumServer.log("---> Requesting " + url.toString()); URLConnection conn = url.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int length = -1; while ((length = is.read(buffer)) != -1) { out.write(buffer, 0, length); } is.close(); String output = out.toString(); if (newBrowserSession) { if (output.startsWith("OK,")) { lastSessionId[0] = output.substring(3); } } } catch (IOException e) { System.err.println(e.getMessage()); if (SeleniumServer.isDebugMode()) { e.printStackTrace(); } } } }); t.start(); } } } private static void setLogOut(String logFileName) { try { logOut = new PrintStream(logFileName); } catch (FileNotFoundException e) { System.err.println("could not write to " + logFileName); Runtime.getRuntime().halt(-1); } } private static void checkArgsSanity(int port, boolean interactive, boolean htmlSuite, boolean proxyInjectionModeArg, int portDriversShouldContactArg, SeleniumServer seleniumProxy) throws Exception { if (interactive && htmlSuite) { System.err.println("You can't use -interactive and -htmlSuite on the same line!"); System.exit(1); } SingleEntryAsyncQueue.setDefaultTimeout(timeoutInSeconds); seleniumProxy.setProxyInjectionMode(proxyInjectionModeArg); if (!isProxyInjectionMode() && (InjectionHelper.userContentTransformationsExist() || InjectionHelper.userJsInjectionsExist())) { usage("-userJsInjection and -userContentTransformation are only " + "valid in combination with -proxyInjectionMode"); System.exit(1); } if (!isProxyInjectionMode() && reusingBrowserSessions()) { usage("-reusingBrowserSessions only valid in combination with -proxyInjectionMode" + " (because of the need for multiple domain support, which only -proxyInjectionMode" + " provides)."); System.exit(1); } if (reusingBrowserSessions()) { SeleniumServer.log("Will recycle browser sessions when possible."); } } private static String getArg(String[] args, int i) { if (i >= args.length) { usage("expected at least one more argument"); System.exit(-1); } return args[i]; } private static void proxyInjectionSpeech() { SeleniumServer.log("The selenium server will execute in proxyInjection mode."); } private static void setSystemProperty(String arg) { if (arg.indexOf('=') == -1) { usage("poorly formatted Java property setting (I expect to see '=') " + arg); System.exit(1); } String property = arg.replaceFirst("-D", "").replaceFirst("=.*", ""); String value = arg.replaceFirst("[^=]*=", ""); System.err.println("Setting system property " + property + " to " + value); System.setProperty(property, value); } private static void usage(String msg) { if (msg != null) { System.err.println(msg + ":"); } System.err.println("Usage: java -jar selenium-server.jar -debug [-port nnnn] [-timeout nnnn] [-interactive]" + " [-forcedBrowserMode browserString] [-userExtensions extensionJs] [-log logfile] [-proxyInjectionMode [-browserSessionReuse|-noBrowserSessionReuse][-userContentTransformation your-before-regexp-string your-after-string] [-userJsInjection your-js-filename] [-dontInjectRegex java-regex]] [-htmlSuite browserString (e.g. \"*firefox\") startURL (e.g. \"http://www.google.com\") " + "suiteFile (e.g. \"c:\\absolute\\path\\to\\my\\HTMLSuite.html\") resultFile (e.g. \"c:\\absolute\\path\\to\\my\\results.html\"]\n" + "where:\n" + "the argument for timeout is an integer number of seconds before we should give up\n" + "the argument for port is the port number the selenium server should use (default 4444)" + "\n\t-interactive puts you into interactive mode. See the tutorial for more details" + "\n\t-multiWindow puts you into a mode where the test web site executes in a separate window, and selenium supports frames" + "\n\t-forcedBrowserMode (e.g., *iexplore) sets the browser mode for all sessions, no matter what is passed to getNewBrowserSession" + "\n\t-userExtensions indicates a JavaScript file that will be loaded into selenium" + "\n\t-browserSessionReuse stops re-initialization and spawning of the browser between tests" + "\n\t-dontInjectRegex is an optional regular expression that proxy injection mode can use to know when to bypss injection" + "\n\t-debug puts you into debug mode, with more trace information and diagnostics" + "\n\t-proxyInjectionMode puts you into proxy injection mode, a mode where the selenium server acts as a proxy server " + "\n\t\tfor all content going to the test application. Under this mode, multiple domains can be visited, and the " + "\n\t\tfollowing additional flags are supported:" + "\n\t\t\tThe -userJsInjection flag allows you to point at a JavaScript file which will then be injected into all pages. " + "\n\t\t\tThe -userContentTransformation flag takes two arguments: the first is a regular expression which is matched " + "\n\t\t\t\tagainst all test HTML content; the second is a string which will replace matches. These flags can be used any " + "\n\t\t\t\tnumber of times. A simple example of how this could be useful: if you add" + "\n" + "\n\t\t\t\t -userContentTransformation https http" + "\n" + "\n\t\t\t\tthen all \"https\" strings in the HTML of the test application will be changed to be \"http\".\n"); } /** * Prepares a Jetty server with its HTTP handlers. * * @param port the port to start on * @param slowResources should the webserver return static resources more slowly? (Note that this will not slow down ordinary RC test runs; this setting is used to debug Selenese HTML tests.) * @param multiWindow run the tests in the "multi-Window" layout, without using the embedded iframe * @throws Exception you know, just in case */ public SeleniumServer(int port, boolean slowResources, boolean multiWindow) throws Exception { this.port = port; if (portDriversShouldContact==0) { SeleniumServer.setPortDriversShouldContact(port); } this.multiWindow = multiWindow; server = new Server(); SocketListener socketListener = new SocketListener(); socketListener.setMaxIdleTimeMs(60000); socketListener.setPort(port); server.addListener(socketListener); configServer(); assembleHandlers(slowResources); } public SeleniumServer(int port, boolean slowResources) throws Exception { this(port, slowResources, false); } private void assembleHandlers(boolean slowResources) { HttpContext root = new HttpContext(); root.setContextPath("/"); ProxyHandler rootProxy = new ProxyHandler(); root.addHandler(rootProxy); server.addContext(root); HttpContext context = new HttpContext(); context.setContextPath("/selenium-server"); context.setMimeMapping("xhtml", "application/xhtml+xml"); log(context.getMimeMap().get("xhtml").toString()); staticContentHandler = new StaticContentHandler(slowResources); String overrideJavascriptDir = System.getProperty("selenium.javascript.dir"); if (overrideJavascriptDir != null) { staticContentHandler.addStaticContent(new FsResourceLocator(new File(overrideJavascriptDir))); } staticContentHandler.addStaticContent(new ClasspathResourceLocator()); String logOutFileName = System.getProperty("selenium.log.fileName"); if (logOutFileName != null) { setLogOut(logOutFileName); } context.addHandler(staticContentHandler); context.addHandler(new SingleTestSuiteResourceHandler()); postResultsHandler = new SeleniumHTMLRunnerResultsHandler(); context.addHandler(postResultsHandler); // Associate the SeleniumDriverResourceHandler with the /selenium-server/driver context HttpContext driverContext = new HttpContext(); driverContext.setContextPath("/selenium-server/driver"); driver = new SeleniumDriverResourceHandler(this); context.addHandler(driver); server.addContext(context); server.addContext(driverContext); } private void configServer() { if (getForcedBrowserMode() == null) { if (null!=System.getProperty("selenium.defaultBrowserString")) { System.err.println("The selenium.defaultBrowserString property is no longer supported; use selenium.forcedBrowserMode instead."); System.exit(-1); } SeleniumServer.setForcedBrowserMode(System.getProperty("selenium.forcedBrowserMode")); } if (!isProxyInjectionMode() && System.getProperty("selenium.proxyInjectionMode") != null) { setProxyInjectionMode("true".equals(System.getProperty("selenium.proxyInjectionMode"))); } if (!isDebugMode() && System.getProperty("selenium.debugMode") != null) { setDebugMode("true".equals(System.getProperty("selenium.debugMode"))); } } public SeleniumServer(int port) throws Exception { this(port, slowResourceProperty()); } public SeleniumServer() throws Exception { this(SeleniumServer.getDefaultPort(), slowResourceProperty()); } public static int getDefaultPort() { String portString = System.getProperty("selenium.port", ""+SeleniumServer.DEFAULT_PORT); return Integer.parseInt(portString); } private static boolean slowResourceProperty() { return ("true".equals(System.getProperty("slowResources"))); } public void addNewStaticContent(File directory) { staticContentHandler.addStaticContent(new FsResourceLocator(directory)); } public void handleHTMLRunnerResults(HTMLResultsListener listener) { postResultsHandler.addListener(listener); } /** * Starts the Jetty server */ public void start() throws Exception { server.start(); } /** * Stops the Jetty server */ public void stop() throws InterruptedException { server.stop(); driver.stopAllBrowsers(); } public int getPort() { return port; } public boolean isMultiWindow() { return multiWindow; } /** * Exposes the internal Jetty server used by Selenium. * This lets users add their own webapp to the Selenium Server jetty instance. * It is also a minor violation of encapsulation principles (what if we stop * using Jetty?) but life is too short to worry about such things. * * @return the internal Jetty server, pre-configured with the /selenium-server context as well as * the proxy server on / */ public Server getServer() { return server; } public static boolean isDebugMode() { return SeleniumServer.debugMode; } static public void setDebugMode(boolean debugMode) { SeleniumServer.debugMode = debugMode; if (debugMode) { SeleniumServer.log("Selenium server running in debug mode."); System.err.println("Standard error test."); } } public static boolean isProxyInjectionMode() { return proxyInjectionMode; } public static int getPortDriversShouldContact() { return portDriversShouldContact; } private static void setPortDriversShouldContact(int port) { SeleniumServer.portDriversShouldContact = port; } public void setProxyInjectionMode(boolean proxyInjectionMode) { if (proxyInjectionMode) { proxyInjectionSpeech(); } SeleniumServer.proxyInjectionMode = proxyInjectionMode; } public static String getForcedBrowserMode() { return forcedBrowserMode; } public static int getTimeoutInSeconds() { return timeoutInSeconds; } public static void setForcedBrowserMode(String s) { SeleniumServer.forcedBrowserMode = s; } public static void setDontInjectRegex(String dontInjectRegex) { SeleniumServer.dontInjectRegex = dontInjectRegex; } public static boolean reusingBrowserSessions() { if (reusingBrowserSessions == null) { // if (isProxyInjectionMode()) { turn off this default until we are stable. Too many variables spoils the soup. // reusingBrowserSessions = Boolean.TRUE; // default in pi mode // } // else { reusingBrowserSessions = Boolean.FALSE; // default in non-pi mode // } } return reusingBrowserSessions; } public static boolean shouldInject(String path) { if (dontInjectRegex == null) { return true; } return !path.matches(dontInjectRegex); } public static String getDebugURL() { return debugURL; } private static String getRequiredSystemProperty(String name) { String value = System.getProperty(name); if (value==null) { usage("expected property " + name + " to be defined"); System.exit(1); } return value; } private static void runHtmlSuite(SeleniumServer seleniumProxy) { String result = null; try { String suiteFilePath = getRequiredSystemProperty("htmlSuite.suiteFilePath"); File suiteFile = new File(suiteFilePath); if (!suiteFile.exists()) { usage("Can't find HTML Suite file:" + suiteFile.getAbsolutePath()); System.exit(1); } seleniumProxy.addNewStaticContent(suiteFile.getParentFile()); String startURL = getRequiredSystemProperty("htmlSuite.startURL"); String suiteURL = startURL + "/selenium-server/" + suiteFile.getName(); HTMLLauncher launcher = new HTMLLauncher(seleniumProxy); String resultFilePath = getRequiredSystemProperty("htmlSuite.resultFilePath"); File resultFile = new File(resultFilePath); if (!resultFile.canWrite()) { usage("can't write to result file " + resultFilePath); System.exit(1); } result = launcher.runHTMLSuite(getRequiredSystemProperty("htmlSuite.browserString"), startURL, suiteURL, resultFile, timeoutInSeconds, seleniumProxy.isMultiWindow()); } catch (Exception e) { System.err.println("HTML suite exception seen:"); e.printStackTrace(); System.exit(1); } if (!"PASSED".equals(result)) { System.err.println("Tests failed"); System.exit(1); } else { System.exit(0); } } public static void log(String logMessages) { PrintStream out = (logOut != null) ? logOut : System.out; if (logMessages.endsWith("\n")) { out.print(logMessages); } else { out.println(logMessages); } } public static void setReusingBrowserSessions(boolean reusingBrowserSessions) { SeleniumServer.reusingBrowserSessions = reusingBrowserSessions; } }
server/src/main/java/org/openqa/selenium/server/SeleniumServer.java
/* * Copyright 2006 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.openqa.selenium.server; import org.mortbay.http.HttpContext; import org.mortbay.http.SocketListener; import org.mortbay.jetty.Server; import org.openqa.selenium.server.browserlaunchers.AsyncExecute; import org.openqa.selenium.server.htmlrunner.HTMLLauncher; import org.openqa.selenium.server.htmlrunner.HTMLResultsListener; import org.openqa.selenium.server.htmlrunner.SeleniumHTMLRunnerResultsHandler; import org.openqa.selenium.server.htmlrunner.SingleTestSuiteResourceHandler; import java.io.*; import java.net.URL; import java.net.URLConnection; /** * Provides a server that can launch/terminate browsers and can receive Selenese commands * over HTTP and send them on to the browser. * <p/> * <p>To run Selenium Server, run: * <p/> * <blockquote><code>java -jar selenium-server-1.0-SNAPSHOT.jar [-port 4444] [-interactive] [-timeout 1800]</code></blockquote> * <p/> * <p>Where <code>-port</code> specifies the port you wish to run the Server on (default is 4444). * <p/> * <p>Where <code>-timeout</code> specifies the number of seconds that you allow data to wait all in the * communications queues before an exception is thrown. * <p/> * <p>Using the <code>-interactive</code> flag will start the server in Interactive mode. * In this mode you can type Selenese commands on the command line (e.g. cmd=open&1=http://www.yahoo.com). * You may also interactively specify commands to run on a particular "browser session" (see below) like this: * <blockquote><code>cmd=open&1=http://www.yahoo.com&sessionId=1234</code></blockquote></p> * <p/> * <p>The server accepts three types of HTTP requests on its port: * <p/> * <ol> * <li><b>Client-Configured Proxy Requests</b>: By configuring your browser to use the * Selenium Server as an HTTP proxy, you can use the Selenium Server as a web proxy. This allows * the server to create a virtual "/selenium-server" directory on every website that you visit using * the proxy. * <li><b>Browser Selenese</b>: If the browser goes to "/selenium-server/SeleneseRunner.html?sessionId=1234" on any website * via the Client-Configured Proxy, it will ask the Selenium Server for work to do, like this: * <blockquote><code>http://www.yahoo.com/selenium-server/driver/?seleniumStart=true&sessionId=1234</code></blockquote> * The driver will then reply with a command to run in the body of the HTTP response, e.g. "|open|http://www.yahoo.com||". Once * the browser is done with this request, the browser will issue a new request for more work, this * time reporting the results of the previous command:<blockquote><code>http://www.yahoo.com/selenium-server/driver/?commandResult=OK&sessionId=1234</code></blockquote> * The action list is listed in selenium-api.js. Normal actions like "doClick" will return "OK" if * clicking was successful, or some other error string if there was an error. Assertions like * assertTextPresent or verifyTextPresent will return "PASSED" if the assertion was true, or * some other error string if the assertion was false. Getters like "getEval" will return the * result of the get command. "getAllLinks" will return a comma-delimited list of links.</li> * <li><b>Driver Commands</b>: Clients may send commands to the Selenium Server over HTTP. * Command requests should look like this:<blockquote><code>http://localhost:4444/selenium-server/driver/?commandRequest=|open|http://www.yahoo.com||&sessionId=1234</code></blockquote> * The Selenium Server will not respond to the HTTP request until the browser has finished performing the requested * command; when it does, it will reply with the result of the command (e.g. "OK" or "PASSED") in the * body of the HTTP response. (Note that <code>-interactive</code> mode also works by sending these * HTTP requests, so tests using <code>-interactive</code> mode will behave exactly like an external client driver.) * </ol> * <p>There are some special commands that only work in the Selenium Server. These commands are: * <ul><li><p><strong>getNewBrowserSession</strong>( <em>browserString</em>, <em>startURL</em> )</p> * <p>Creates a new "sessionId" number (based on the current time in milliseconds) and launches the browser specified in * <i>browserString</i>. We will then browse directly to <i>startURL</i> + "/selenium-server/SeleneseRunner.html?sessionId=###" * where "###" is the sessionId number. Only commands that are associated with the specified sessionId will be run by this browser.</p> * <p/> * <p><i>browserString</i> may be any one of the following: * <ul> * <li><code>*firefox [absolute path]</code> - Automatically launch a new Firefox process using a custom Firefox profile. * This profile will be automatically configured to use the Selenium Server as a proxy and to have all annoying prompts * ("save your password?" "forms are insecure" "make Firefox your default browser?" disabled. You may optionally specify * an absolute path to your firefox executable, or just say "*firefox". If no absolute path is specified, we'll look for * firefox.exe in a default location (normally c:\program files\mozilla firefox\firefox.exe), which you can override by * setting the Java system property <code>firefoxDefaultPath</code> to the correct path to Firefox.</li> * <li><code>*iexplore [absolute path]</code> - Automatically launch a new Internet Explorer process using custom Windows registry settings. * This process will be automatically configured to use the Selenium Server as a proxy and to have all annoying prompts * ("save your password?" "forms are insecure" "make Firefox your default browser?" disabled. You may optionally specify * an absolute path to your iexplore executable, or just say "*iexplore". If no absolute path is specified, we'll look for * iexplore.exe in a default location (normally c:\program files\internet explorer\iexplore.exe), which you can override by * setting the Java system property <code>iexploreDefaultPath</code> to the correct path to Internet Explorer.</li> * <li><code>/path/to/my/browser [other arguments]</code> - You may also simply specify the absolute path to your browser * executable, or use a relative path to your executable (which we'll try to find on your path). <b>Warning:</b> If you * specify your own custom browser, it's up to you to configure it correctly. At a minimum, you'll need to configure your * browser to use the Selenium Server as a proxy, and disable all browser-specific prompting. * </ul> * </li> * <li><p><strong>testComplete</strong>( )</p> * <p>Kills the currently running browser and erases the old browser session. If the current browser session was not * launched using <code>getNewBrowserSession</code>, or if that session number doesn't exist in the server, this * command will return an error.</p> * </li> * <li><p><strong>shutDown</strong>( )</p> * <p>Causes the server to shut itself down, killing itself and all running browsers along with it.</p> * </li> * </ul> * <p>Example:<blockquote><code>cmd=getNewBrowserSession&1=*firefox&2=http://www.google.com * <br/>Got result: 1140738083345 * <br/>cmd=open&1=http://www.google.com&sessionId=1140738083345 * <br/>Got result: OK * <br/>cmd=type&1=q&2=hello world&sessionId=1140738083345 * <br/>Got result: OK * <br/>cmd=testComplete&sessionId=1140738083345 * <br/>Got result: OK * </code></blockquote></p> * <p/> * <h4>The "null" session</h4> * <p/> * <p>If you open a browser manually and do not specify a session ID, it will look for * commands using the "null" session. You may then similarly send commands to this * browser by not specifying a sessionId when issuing commands.</p> * * @author plightbo */ public class SeleniumServer { private Server server; private SeleniumDriverResourceHandler driver; private SeleniumHTMLRunnerResultsHandler postResultsHandler; private StaticContentHandler staticContentHandler; private int port; private boolean multiWindow = false; private static String debugURL = ""; // add special tracing for debug when this URL is requested private static boolean debugMode = false; private static boolean proxyInjectionMode = false; public static final int DEFAULT_PORT = 4444; // The following port is the one which drivers and browsers should use when they contact the selenium server. // Under normal circumstances, this port will be the same as the port which the selenium server listens on. // But if a developer wants to monitor traffic into and out of the selenium server, he can set this port from // the command line to be a different value and then use a tool like tcptrace to link this port with the // server listening port, thereby opening a window into the raw HTTP traffic. // // For example, if the selenium server is invoked with -portDriversShouldContact 4445, then traffic going // into the selenium server will be routed to port 4445, although the selenium server will still be listening // to the default port 4444. At this point, you would open tcptrace to bridge the gap and be able to watch // all the data coming in and out: private static int portDriversShouldContact = DEFAULT_PORT; private static PrintStream logOut = null; private static String forcedBrowserMode = null; public static final int DEFAULT_TIMEOUT = (30 * 60); public static int timeoutInSeconds = DEFAULT_TIMEOUT; private static Boolean reusingBrowserSessions = null; private static String dontInjectRegex = null; /** * Starts up the server on the specified port (or default if no port was specified) * and then starts interactive mode if specified. * * @param args - either "-port" followed by a number, or "-interactive" * @throws Exception - you know, just in case. */ public static void main(String[] args) throws Exception { int port = DEFAULT_PORT; boolean interactive = false; boolean htmlSuite = false; boolean multiWindow = false; File userExtensions = null; boolean proxyInjectionModeArg = false; int portDriversShouldContactArg = 0; boolean userJsInjection = false; for (int i = 0; i < args.length; i++) { String arg = args[i]; if ("-help".equalsIgnoreCase(arg)) { usage(null); System.exit(1); } else if ("-defaultBrowserString".equalsIgnoreCase(arg)) { usage("-defaultBrowserString has been renamed -forcedBrowserMode"); } else if ("-forcedBrowserMode".equalsIgnoreCase(arg)) { for (i++; i < args.length; i++) { if (SeleniumServer.forcedBrowserMode == null) SeleniumServer.forcedBrowserMode = ""; else SeleniumServer.forcedBrowserMode += " "; SeleniumServer.forcedBrowserMode += args[i]; } SeleniumServer.log("\"" + forcedBrowserMode + "\" will be used as the browser " + "mode for all sessions, no matter what is passed to getNewBrowserSession."); } else if ("-log".equalsIgnoreCase(arg)) { setLogOut(getArg(args, ++i)); } else if ("-port".equalsIgnoreCase(arg)) { port = Integer.parseInt(getArg(args, ++i)); } else if ("-multiWindow".equalsIgnoreCase(arg)) { multiWindow = true; } else if ("-proxyInjectionMode".equalsIgnoreCase(arg)) { proxyInjectionModeArg = true; } else if ("-portDriversShouldContact".equalsIgnoreCase(arg)) { // to facilitate tcptrace interception of interaction between // injected js and the selenium server portDriversShouldContactArg = Integer.parseInt(getArg(args, ++i)); } else if ("-noBrowserSessionReuse".equalsIgnoreCase(arg)) { SeleniumServer.reusingBrowserSessions = Boolean.FALSE; } else if ("-browserSessionReuse".equalsIgnoreCase(arg)) { SeleniumServer.reusingBrowserSessions = Boolean.TRUE; } else if ("-dontInjectRegex".equalsIgnoreCase(arg)) { dontInjectRegex = getArg(args, ++i); } else if ("-debug".equalsIgnoreCase(arg)) { SeleniumServer.setDebugMode(true); } else if ("-debugURL".equalsIgnoreCase(arg)) { debugURL = getArg(args, ++i); } else if ("-timeout".equalsIgnoreCase(arg)) { timeoutInSeconds = Integer.parseInt(getArg(args, ++i)); } else if ("-userJsInjection".equalsIgnoreCase(arg)) { userJsInjection = true; if (!InjectionHelper.addUserJsInjectionFile(getArg(args, ++i))) { usage(null); System.exit(1); } } else if ("-userContentTransformation".equalsIgnoreCase(arg)) { if (!InjectionHelper.addUserContentTransformation(getArg(args, ++i), getArg(args, ++i))) { usage(null); System.exit(1); } } else if ("-userExtensions".equalsIgnoreCase(arg)) { userExtensions = new File(getArg(args, ++i)); if (!userExtensions.exists()) { System.err.println("User Extensions file doesn't exist: " + userExtensions.getAbsolutePath()); System.exit(1); } if (!"user-extensions.js".equalsIgnoreCase(userExtensions.getName())) { System.err.println("User extensions file MUST be called \"user-extensions.js\": " + userExtensions.getAbsolutePath()); System.exit(1); } } else if ("-htmlSuite".equalsIgnoreCase(arg)) { try { System.setProperty("htmlSuite.browserString", args[++i]); System.setProperty("htmlSuite.startURL", args[++i]); System.setProperty("htmlSuite.suiteFilePath", args[++i]); System.setProperty("htmlSuite.resultFilePath", args[++i]); } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Not enough command line arguments for -htmlSuite"); System.err.println("-htmlSuite requires you to specify:"); System.err.println("* browserString (e.g. \"*firefox\")"); System.err.println("* startURL (e.g. \"http://www.google.com\")"); System.err.println("* suiteFile (e.g. \"c:\\absolute\\path\\to\\my\\HTMLSuite.html\")"); System.err.println("* resultFile (e.g. \"c:\\absolute\\path\\to\\my\\results.html\")"); System.exit(1); } htmlSuite = true; } else if ("-interactive".equalsIgnoreCase(arg)) { timeoutInSeconds = Integer.MAX_VALUE; interactive = true; } else if (arg.startsWith("-D")) { setSystemProperty(arg); } else { usage("unrecognized argument " + arg); System.exit(1); } } if (userJsInjection && !proxyInjectionModeArg) { System.err.println("User js injection can only be used w/ -proxyInjectionMode"); System.exit(1); } if (portDriversShouldContactArg == 0) { portDriversShouldContactArg = port; } System.setProperty("org.mortbay.http.HttpRequest.maxFormContentSize", "0"); // default max is 200k; zero is infinite final SeleniumServer seleniumProxy = new SeleniumServer(port); seleniumProxy.multiWindow = multiWindow; checkArgsSanity(port, interactive, htmlSuite, proxyInjectionModeArg, portDriversShouldContactArg, seleniumProxy); Thread jetty = new Thread(new Runnable() { public void run() { try { seleniumProxy.start(); } catch (Exception e) { System.err.println("jetty run exception seen:"); e.printStackTrace(); } } }); if (interactive) { jetty.setDaemon(true); } jetty.start(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { try { System.out.println("Shutting down..."); seleniumProxy.stop(); } catch (InterruptedException e) { System.err.println("run exception seen:"); e.printStackTrace(); } } })); if (userExtensions != null) { seleniumProxy.addNewStaticContent(userExtensions.getParentFile()); } if (htmlSuite) { runHtmlSuite(seleniumProxy); return; } if (interactive) { AsyncExecute.sleepTight(500); System.out.println("Entering interactive mode... type Selenium commands here (e.g: cmd=open&1=http://www.yahoo.com)"); BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput; final String[] lastSessionId = new String[]{""}; while ((userInput = stdIn.readLine()) != null) { if ("exit".equals(userInput) || "quit".equals(userInput)) { System.out.println("Stopping..."); seleniumProxy.stop(); System.exit(0); } if ("".equals(userInput)) continue; if (!userInput.startsWith("cmd=") && !userInput.startsWith("commandResult=")) { System.err.println("ERROR - Invalid command: \"" + userInput + "\""); continue; } final boolean newBrowserSession = userInput.indexOf("getNewBrowserSession") != -1; if (userInput.indexOf("sessionId") == -1 && !newBrowserSession) { userInput = userInput + "&sessionId=" + lastSessionId[0]; } final URL url = new URL("http://localhost:" + port + "/selenium-server/driver?" + userInput); Thread t = new Thread(new Runnable() { public void run() { try { SeleniumServer.log("---> Requesting " + url.toString()); URLConnection conn = url.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int length = -1; while ((length = is.read(buffer)) != -1) { out.write(buffer, 0, length); } is.close(); String output = out.toString(); if (newBrowserSession) { if (output.startsWith("OK,")) { lastSessionId[0] = output.substring(3); } } } catch (IOException e) { System.err.println(e.getMessage()); if (SeleniumServer.isDebugMode()) { e.printStackTrace(); } } } }); t.start(); } } } private static void setLogOut(String logFileName) { try { logOut = new PrintStream(logFileName); } catch (FileNotFoundException e) { System.err.println("could not write to " + logFileName); Runtime.getRuntime().halt(-1); } } private static void checkArgsSanity(int port, boolean interactive, boolean htmlSuite, boolean proxyInjectionModeArg, int portDriversShouldContactArg, SeleniumServer seleniumProxy) throws Exception { if (interactive && htmlSuite) { System.err.println("You can't use -interactive and -htmlSuite on the same line!"); System.exit(1); } SingleEntryAsyncQueue.setDefaultTimeout(timeoutInSeconds); seleniumProxy.setProxyInjectionMode(proxyInjectionModeArg); SeleniumServer.setPortDriversShouldContact(portDriversShouldContactArg); if (!isProxyInjectionMode() && (InjectionHelper.userContentTransformationsExist() || InjectionHelper.userJsInjectionsExist())) { usage("-userJsInjection and -userContentTransformation are only " + "valid in combination with -proxyInjectionMode"); System.exit(1); } if (!isProxyInjectionMode() && reusingBrowserSessions()) { usage("-reusingBrowserSessions only valid in combination with -proxyInjectionMode" + " (because of the need for multiple domain support, which only -proxyInjectionMode" + " provides)."); System.exit(1); } if (reusingBrowserSessions()) { SeleniumServer.log("Will recycle browser sessions when possible."); } } private static String getArg(String[] args, int i) { if (i >= args.length) { usage("expected at least one more argument"); System.exit(-1); } return args[i]; } private static void proxyInjectionSpeech() { SeleniumServer.log("The selenium server will execute in proxyInjection mode."); } private static void setSystemProperty(String arg) { if (arg.indexOf('=') == -1) { usage("poorly formatted Java property setting (I expect to see '=') " + arg); System.exit(1); } String property = arg.replaceFirst("-D", "").replaceFirst("=.*", ""); String value = arg.replaceFirst("[^=]*=", ""); System.err.println("Setting system property " + property + " to " + value); System.setProperty(property, value); } private static void usage(String msg) { if (msg != null) { System.err.println(msg + ":"); } System.err.println("Usage: java -jar selenium-server.jar -debug [-port nnnn] [-timeout nnnn] [-interactive]" + " [-forcedBrowserMode browserString] [-userExtensions extensionJs] [-log logfile] [-proxyInjectionMode [-browserSessionReuse|-noBrowserSessionReuse][-userContentTransformation your-before-regexp-string your-after-string] [-userJsInjection your-js-filename] [-dontInjectRegex java-regex]] [-htmlSuite browserString (e.g. \"*firefox\") startURL (e.g. \"http://www.google.com\") " + "suiteFile (e.g. \"c:\\absolute\\path\\to\\my\\HTMLSuite.html\") resultFile (e.g. \"c:\\absolute\\path\\to\\my\\results.html\"]\n" + "where:\n" + "the argument for timeout is an integer number of seconds before we should give up\n" + "the argument for port is the port number the selenium server should use (default 4444)" + "\n\t-interactive puts you into interactive mode. See the tutorial for more details" + "\n\t-multiWindow puts you into a mode where the test web site executes in a separate window, and selenium supports frames" + "\n\t-forcedBrowserMode (e.g., *iexplore) sets the browser mode for all sessions, no matter what is passed to getNewBrowserSession" + "\n\t-userExtensions indicates a JavaScript file that will be loaded into selenium" + "\n\t-browserSessionReuse stops re-initialization and spawning of the browser between tests" + "\n\t-dontInjectRegex is an optional regular expression that proxy injection mode can use to know when to bypss injection" + "\n\t-debug puts you into debug mode, with more trace information and diagnostics" + "\n\t-proxyInjectionMode puts you into proxy injection mode, a mode where the selenium server acts as a proxy server " + "\n\t\tfor all content going to the test application. Under this mode, multiple domains can be visited, and the " + "\n\t\tfollowing additional flags are supported:" + "\n\t\t\tThe -userJsInjection flag allows you to point at a JavaScript file which will then be injected into all pages. " + "\n\t\t\tThe -userContentTransformation flag takes two arguments: the first is a regular expression which is matched " + "\n\t\t\t\tagainst all test HTML content; the second is a string which will replace matches. These flags can be used any " + "\n\t\t\t\tnumber of times. A simple example of how this could be useful: if you add" + "\n" + "\n\t\t\t\t -userContentTransformation https http" + "\n" + "\n\t\t\t\tthen all \"https\" strings in the HTML of the test application will be changed to be \"http\".\n"); } /** * Prepares a Jetty server with its HTTP handlers. * * @param port the port to start on * @param slowResources should the webserver return static resources more slowly? (Note that this will not slow down ordinary RC test runs; this setting is used to debug Selenese HTML tests.) * @param multiWindow run the tests in the "multi-Window" layout, without using the embedded iframe * @throws Exception you know, just in case */ public SeleniumServer(int port, boolean slowResources, boolean multiWindow) throws Exception { this.port = port; this.multiWindow = multiWindow; server = new Server(); SocketListener socketListener = new SocketListener(); socketListener.setMaxIdleTimeMs(60000); socketListener.setPort(port); server.addListener(socketListener); configServer(); assembleHandlers(slowResources); } public SeleniumServer(int port, boolean slowResources) throws Exception { this(port, slowResources, false); } private void assembleHandlers(boolean slowResources) { HttpContext root = new HttpContext(); root.setContextPath("/"); ProxyHandler rootProxy = new ProxyHandler(); root.addHandler(rootProxy); server.addContext(root); HttpContext context = new HttpContext(); context.setContextPath("/selenium-server"); context.setMimeMapping("xhtml", "application/xhtml+xml"); log(context.getMimeMap().get("xhtml").toString()); staticContentHandler = new StaticContentHandler(slowResources); String overrideJavascriptDir = System.getProperty("selenium.javascript.dir"); if (overrideJavascriptDir != null) { staticContentHandler.addStaticContent(new FsResourceLocator(new File(overrideJavascriptDir))); } staticContentHandler.addStaticContent(new ClasspathResourceLocator()); String logOutFileName = System.getProperty("selenium.log.fileName"); if (logOutFileName != null) { setLogOut(logOutFileName); } context.addHandler(staticContentHandler); context.addHandler(new SingleTestSuiteResourceHandler()); postResultsHandler = new SeleniumHTMLRunnerResultsHandler(); context.addHandler(postResultsHandler); // Associate the SeleniumDriverResourceHandler with the /selenium-server/driver context HttpContext driverContext = new HttpContext(); driverContext.setContextPath("/selenium-server/driver"); driver = new SeleniumDriverResourceHandler(this); context.addHandler(driver); server.addContext(context); server.addContext(driverContext); } private void configServer() { if (getForcedBrowserMode() == null) { if (null!=System.getProperty("selenium.defaultBrowserString")) { System.err.println("The selenium.defaultBrowserString property is no longer supported; use selenium.forcedBrowserMode instead."); System.exit(-1); } SeleniumServer.setForcedBrowserMode(System.getProperty("selenium.forcedBrowserMode")); } if (!isProxyInjectionMode() && System.getProperty("selenium.proxyInjectionMode") != null) { setProxyInjectionMode("true".equals(System.getProperty("selenium.proxyInjectionMode"))); } if (!isDebugMode() && System.getProperty("selenium.debugMode") != null) { setDebugMode("true".equals(System.getProperty("selenium.debugMode"))); } } public SeleniumServer(int port) throws Exception { this(port, slowResourceProperty()); } public SeleniumServer() throws Exception { this(SeleniumServer.getDefaultPort(), slowResourceProperty()); } public static int getDefaultPort() { String portString = System.getProperty("selenium.port", ""+SeleniumServer.DEFAULT_PORT); return Integer.parseInt(portString); } private static boolean slowResourceProperty() { return ("true".equals(System.getProperty("slowResources"))); } public void addNewStaticContent(File directory) { staticContentHandler.addStaticContent(new FsResourceLocator(directory)); } public void handleHTMLRunnerResults(HTMLResultsListener listener) { postResultsHandler.addListener(listener); } /** * Starts the Jetty server */ public void start() throws Exception { server.start(); } /** * Stops the Jetty server */ public void stop() throws InterruptedException { server.stop(); driver.stopAllBrowsers(); } public int getPort() { return port; } public boolean isMultiWindow() { return multiWindow; } /** * Exposes the internal Jetty server used by Selenium. * This lets users add their own webapp to the Selenium Server jetty instance. * It is also a minor violation of encapsulation principles (what if we stop * using Jetty?) but life is too short to worry about such things. * * @return the internal Jetty server, pre-configured with the /selenium-server context as well as * the proxy server on / */ public Server getServer() { return server; } public static boolean isDebugMode() { return SeleniumServer.debugMode; } static public void setDebugMode(boolean debugMode) { SeleniumServer.debugMode = debugMode; if (debugMode) { SeleniumServer.log("Selenium server running in debug mode."); System.err.println("Standard error test."); } } public static boolean isProxyInjectionMode() { return proxyInjectionMode; } public static int getPortDriversShouldContact() { return portDriversShouldContact; } private static void setPortDriversShouldContact(int port) { SeleniumServer.portDriversShouldContact = port; } public void setProxyInjectionMode(boolean proxyInjectionMode) { if (proxyInjectionMode) { proxyInjectionSpeech(); } SeleniumServer.proxyInjectionMode = proxyInjectionMode; } public static String getForcedBrowserMode() { return forcedBrowserMode; } public static int getTimeoutInSeconds() { return timeoutInSeconds; } public static void setForcedBrowserMode(String s) { SeleniumServer.forcedBrowserMode = s; } public static void setDontInjectRegex(String dontInjectRegex) { SeleniumServer.dontInjectRegex = dontInjectRegex; } public static boolean reusingBrowserSessions() { if (reusingBrowserSessions == null) { // if (isProxyInjectionMode()) { turn off this default until we are stable. Too many variables spoils the soup. // reusingBrowserSessions = Boolean.TRUE; // default in pi mode // } // else { reusingBrowserSessions = Boolean.FALSE; // default in non-pi mode // } } return reusingBrowserSessions; } public static boolean shouldInject(String path) { if (dontInjectRegex == null) { return true; } return !path.matches(dontInjectRegex); } public static String getDebugURL() { return debugURL; } private static String getRequiredSystemProperty(String name) { String value = System.getProperty(name); if (value==null) { usage("expected property " + name + " to be defined"); System.exit(1); } return value; } private static void runHtmlSuite(SeleniumServer seleniumProxy) { String result = null; try { String suiteFilePath = getRequiredSystemProperty("htmlSuite.suiteFilePath"); File suiteFile = new File(suiteFilePath); if (!suiteFile.exists()) { usage("Can't find HTML Suite file:" + suiteFile.getAbsolutePath()); System.exit(1); } seleniumProxy.addNewStaticContent(suiteFile.getParentFile()); String startURL = getRequiredSystemProperty("htmlSuite.startURL"); String suiteURL = startURL + "/selenium-server/" + suiteFile.getName(); HTMLLauncher launcher = new HTMLLauncher(seleniumProxy); String resultFilePath = getRequiredSystemProperty("htmlSuite.resultFilePath"); File resultFile = new File(resultFilePath); if (!resultFile.canWrite()) { usage("can't write to result file " + resultFilePath); System.exit(1); } result = launcher.runHTMLSuite(getRequiredSystemProperty("htmlSuite.browserString"), startURL, suiteURL, resultFile, timeoutInSeconds, seleniumProxy.isMultiWindow()); } catch (Exception e) { System.err.println("HTML suite exception seen:"); e.printStackTrace(); System.exit(1); } if (!"PASSED".equals(result)) { System.err.println("Tests failed"); System.exit(1); } else { System.exit(0); } } public static void log(String logMessages) { PrintStream out = (logOut != null) ? logOut : System.out; if (logMessages.endsWith("\n")) { out.print(logMessages); } else { out.println(logMessages); } } public static void setReusingBrowserSessions(boolean reusingBrowserSessions) { SeleniumServer.reusingBrowserSessions = reusingBrowserSessions; } }
fix port override when using IE launcher (previously portDriversShouldContact was not getting set to port override) r3435
server/src/main/java/org/openqa/selenium/server/SeleniumServer.java
fix port override when using IE launcher (previously portDriversShouldContact was not getting set to port override)
Java
apache-2.0
3775e336bd33fa859640cd164c506606bd3f97e5
0
webdriverextensions/webdriverextensions,gilsouza/webdriverextensions,webdriverextensions/webdriverextensions,gilsouza/webdriverextensions
package org.webdriverextensions.internal; import org.webdriverextensions.ThreadDriver; import org.apache.commons.lang3.StringUtils; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Platform; import org.openqa.selenium.android.AndroidDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.remote.BrowserType; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.safari.SafariDriver; public class ExperimentalBot { /* Browser */ public static String browser() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return ((RemoteWebDriver) ThreadDriver.getDriver()).getCapabilities().getBrowserName(); } throw new WebDriverExtensionException("Sorry! browser() is only " + "implemented for RemoteWebDriver at the moment."); } public static boolean browserIs(String browserName) { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return isRemoteWebDriverBrowser(browserName); } throw new WebDriverExtensionException("Sorry! browserIs(String browserType) is only " + "implemented for RemoteWebDriver at the moment."); } public static boolean browserIsAndroid() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return isRemoteWebDriverBrowser(BrowserType.ANDROID); } else if (ThreadDriver.getDriver() instanceof AndroidDriver) { return true; } return false; } public static boolean browserIsChrome() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return isRemoteWebDriverBrowser(BrowserType.CHROME); } else if (ThreadDriver.getDriver() instanceof ChromeDriver) { return true; } return false; } public static boolean browserIsFirefox() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return isRemoteWebDriverBrowser(BrowserType.FIREFOX); } else if (ThreadDriver.getDriver() instanceof FirefoxDriver) { return true; } return false; } public static boolean browserIsHtmlUnit() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return isRemoteWebDriverBrowser(BrowserType.HTMLUNIT); } else if (ThreadDriver.getDriver() instanceof HtmlUnitDriver) { return true; } return false; } public static boolean browserIsIPad() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return isRemoteWebDriverBrowser(BrowserType.IPAD); } throw new WebDriverExtensionException("Sorry! browserIsIPad() is only " + "implemented for RemoteWebDriver at the moment."); } public static boolean browserIsIPhone() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return isRemoteWebDriverBrowser(BrowserType.IPHONE); } throw new WebDriverExtensionException("Sorry! browserIsIPhone() is only " + "implemented for RemoteWebDriver at the moment."); } public static boolean browserIsInternetExplorer() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return isRemoteWebDriverBrowser(BrowserType.IE); } else if (ThreadDriver.getDriver() instanceof InternetExplorerDriver) { return true; } return false; } public static boolean browserIsOpera() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return isRemoteWebDriverBrowser(BrowserType.OPERA); } throw new WebDriverExtensionException("Sorry! browserIsOpera() is only " + "implemented for RemoteWebDriver at the moment."); } public static boolean browserIsPhantomJS() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return isRemoteWebDriverBrowser(BrowserType.PHANTOMJS); } throw new WebDriverExtensionException("Sorry! browserIsPhantomJS() is only " + "implemented for RemoteWebDriver at the moment."); } public static boolean browserIsSafari() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return isRemoteWebDriverBrowser(BrowserType.SAFARI); } else if (ThreadDriver.getDriver() instanceof SafariDriver) { return true; } return false; } /* Browser Utils */ private static boolean isRemoteWebDriverBrowser(String browserName) { String currentBrowserName = ((RemoteWebDriver) ThreadDriver.getDriver()).getCapabilities().getBrowserName(); if (StringUtils.equalsIgnoreCase(browserName, currentBrowserName)) { return true; } return false; } /* Browser Version */ public static String browserVersion() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return ((RemoteWebDriver) ThreadDriver.getDriver()).getCapabilities().getVersion(); } throw new WebDriverExtensionException("Sorry! browserVersion() is only " + "implemented for RemoteWebDriver at the moment."); } /* Platform */ public static Platform platform() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return ((RemoteWebDriver) ThreadDriver.getDriver()).getCapabilities().getPlatform(); } throw new WebDriverExtensionException("Sorry! platform() is only " + "implemented for RemoteWebDriver at the moment."); } public static String platformAsString() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return ((RemoteWebDriver) ThreadDriver.getDriver()).getCapabilities().getPlatform().toString(); } throw new WebDriverExtensionException("Sorry! platformAsString() is only " + "implemented for RemoteWebDriver at the moment."); } /* Execute JavaScript */ public static Object executeJavaScript(String script, Object... args) { return ((JavascriptExecutor) ThreadDriver.getDriver()).executeScript(script, args); } public static Object executeJavaScriptAsynchronously(String script, Object... args) { return ((JavascriptExecutor) ThreadDriver.getDriver()).executeAsyncScript(script, args); } }
src/main/java/org/webdriverextensions/internal/ExperimentalBot.java
package org.webdriverextensions.internal; import org.webdriverextensions.ThreadDriver; import org.apache.commons.lang3.StringUtils; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Platform; import org.openqa.selenium.android.AndroidDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.remote.BrowserType; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.safari.SafariDriver; public class ExperimentalBot { /* Browser */ public static String browser() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return ((RemoteWebDriver) ThreadDriver.getDriver()).getCapabilities().getBrowserName(); } throw new WebDriverExtensionException("Sorry! browser() is only " + "implemented for RemoteWebDriver at the moment."); } public static boolean browserIs(String browserName) { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return isRemoteWebdriverBrowser(browserName); } throw new WebDriverExtensionException("Sorry! browserIs(String browserType) is only " + "implemented for RemoteWebDriver at the moment."); } public static boolean browserIsAndroid() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return isRemoteWebdriverBrowser(BrowserType.ANDROID); } else if (ThreadDriver.getDriver() instanceof AndroidDriver) { return true; } return false; } public static boolean browserIsChrome() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return isRemoteWebdriverBrowser(BrowserType.CHROME); } else if (ThreadDriver.getDriver() instanceof ChromeDriver) { return true; } return false; } public static boolean browserIsFirefox() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return isRemoteWebdriverBrowser(BrowserType.FIREFOX); } else if (ThreadDriver.getDriver() instanceof FirefoxDriver) { return true; } return false; } public static boolean browserIsHtmlUnit() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return isRemoteWebdriverBrowser(BrowserType.HTMLUNIT); } else if (ThreadDriver.getDriver() instanceof HtmlUnitDriver) { return true; } return false; } public static boolean browserIsIPad() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return isRemoteWebdriverBrowser(BrowserType.IPAD); } throw new WebDriverExtensionException("Sorry! browserIsIPad() is only " + "implemented for RemoteWebDriver at the moment."); } public static boolean browserIsIPhone() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return isRemoteWebdriverBrowser(BrowserType.IPHONE); } throw new WebDriverExtensionException("Sorry! browserIsIPhone() is only " + "implemented for RemoteWebDriver at the moment."); } public static boolean browserIsInternetExplorer() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return isRemoteWebdriverBrowser(BrowserType.IE); } else if (ThreadDriver.getDriver() instanceof InternetExplorerDriver) { return true; } return false; } public static boolean browserIsOpera() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return isRemoteWebdriverBrowser(BrowserType.OPERA); } throw new WebDriverExtensionException("Sorry! browserIsOpera() is only " + "implemented for RemoteWebDriver at the moment."); } public static boolean browserIsPhantomJS() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return isRemoteWebdriverBrowser(BrowserType.PHANTOMJS); } throw new WebDriverExtensionException("Sorry! browserIsPhantomJS() is only " + "implemented for RemoteWebDriver at the moment."); } public static boolean browserIsSafari() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return isRemoteWebdriverBrowser(BrowserType.SAFARI); } else if (ThreadDriver.getDriver() instanceof SafariDriver) { return true; } return false; } /* Browser Utils */ private static boolean isRemoteWebdriverBrowser(String browserName) { String currentBrowserName = ((RemoteWebDriver) ThreadDriver.getDriver()).getCapabilities().getBrowserName(); if (StringUtils.equalsIgnoreCase(browserName, currentBrowserName)) { return true; } return false; } /* Browser Version */ public static String browserVersion() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return ((RemoteWebDriver) ThreadDriver.getDriver()).getCapabilities().getVersion(); } throw new WebDriverExtensionException("Sorry! browserVersion() is only " + "implemented for RemoteWebDriver at the moment."); } /* Platform */ public static Platform platform() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return ((RemoteWebDriver) ThreadDriver.getDriver()).getCapabilities().getPlatform(); } throw new WebDriverExtensionException("Sorry! platform() is only " + "implemented for RemoteWebDriver at the moment."); } public static String platformAsString() { if (ThreadDriver.getDriver() instanceof RemoteWebDriver) { return ((RemoteWebDriver) ThreadDriver.getDriver()).getCapabilities().getPlatform().toString(); } throw new WebDriverExtensionException("Sorry! platformAsString() is only " + "implemented for RemoteWebDriver at the moment."); } /* Execute JavaScript */ public static Object executeJavaScript(String script, Object... args) { return ((JavascriptExecutor) ThreadDriver.getDriver()).executeScript(script, args); } public static Object executeJavaScriptAsynchronously(String script, Object... args) { return ((JavascriptExecutor) ThreadDriver.getDriver()).executeAsyncScript(script, args); } }
Renamed methid name to follow camel-case convention
src/main/java/org/webdriverextensions/internal/ExperimentalBot.java
Renamed methid name to follow camel-case convention
Java
apache-2.0
bdd9c3ff1afb8d60a1c3d786ab24705bc1ea31d5
0
hmusavi/jpo-ode,hmusavi/jpo-ode,hmusavi/jpo-ode,hmusavi/jpo-ode,hmusavi/jpo-ode
package us.dot.its.jpo.ode.rsuHealth; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import java.io.IOException; import java.util.Vector; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.mockito.Mock; import org.snmp4j.PDU; import org.snmp4j.Snmp; import org.snmp4j.Target; import org.snmp4j.event.ResponseEvent; import mockit.Expectations; import mockit.Injectable; import us.dot.its.jpo.ode.heartbeat.RsuSnmp; public class RsuSnmpTest { @Mock private Snmp mockSnmp; @Ignore @Before public void setUpSnmp() throws IOException { //MockitoAnnotations.initMocks(this); mockSnmp = mock(Snmp.class); } @Ignore @Test public void shouldCreateSnmpV3Request() throws IOException { String targetAddress = null; String targetOid = null; try { RsuSnmp.sendSnmpV3Request(targetAddress, targetOid, mockSnmp, null); fail("Expected IllegalArgumentException"); } catch (Exception e) { assertEquals(IllegalArgumentException.class, e.getClass()); } } @Test public void shouldThrowExceptionNullParameter() { try { RsuSnmp.sendSnmpV3Request(null, null, null, null); } catch (Exception e) { assertEquals("Incorrect exception thrown.", IllegalArgumentException.class, e.getClass()); assertTrue("Incorrect exception message", ("Invalid SNMP request parameter").equals(e.getMessage())); } } @Test public void sendShouldCatchException(@Injectable Snmp mockSnmp) { try { new Expectations() { { mockSnmp.send((PDU) any, (Target) any); // result = null; result = new IOException("testException123"); // mockSnmp.close(); } }; } catch (IOException e) { fail("Unexpected exception in expectations block" + e); } RsuSnmp.sendSnmpV3Request("127.0.0.1", "1.1", mockSnmp, null); } @Test public void sendShouldReturnConnectionError(@Injectable Snmp mockSnmp) { String expectedMessage = "[ERROR] SNMP connection error"; try { new Expectations() { { mockSnmp.send((PDU) any, (Target) any); result = null; // result = new IOException("testException123"); mockSnmp.close(); } }; } catch (IOException e) { fail("Unexpected exception in expectations block" + e); } String actualMessage = RsuSnmp.sendSnmpV3Request("127.0.0.1", "1.1", mockSnmp, null); assertEquals(expectedMessage, actualMessage); } @Test public void shouldReturnEmptyResponse(@Injectable Snmp mockSnmp, @Injectable ResponseEvent mockResponseEvent) { String expectedMessage = "[ERROR] Empty SNMP response"; try { new Expectations() { { mockSnmp.send((PDU) any, (Target) any); result = mockResponseEvent; // result = new IOException("testException123"); mockSnmp.close(); mockResponseEvent.getResponse(); result = null; } }; } catch (IOException e) { fail("Unexpected exception in expectations block" + e); } String actualMessage = RsuSnmp.sendSnmpV3Request("127.0.0.1", "1.1", mockSnmp, null); assertEquals(expectedMessage, actualMessage); } @Test public void shouldReturnVariableBindings(@Injectable Snmp mockSnmp, @Injectable ResponseEvent mockResponseEvent, @Injectable PDU mockPDU) { String inputMessage = "test_rsu_message_1"; String expectedMessage = "[test_rsu_message_1]"; Vector<String> fakeVector = new Vector<>(); fakeVector.add(inputMessage); try { new Expectations() { { mockSnmp.send((PDU) any, (Target) any); result = mockResponseEvent; mockSnmp.close(); mockResponseEvent.getResponse(); result = mockPDU; mockPDU.getVariableBindings(); result = fakeVector; } }; } catch (IOException e) { fail("Unexpected exception in expectations block" + e); } String actualMessage = RsuSnmp.sendSnmpV3Request("127.0.0.1", "1.1", mockSnmp, null); assertEquals(expectedMessage, actualMessage); } }
jpo-ode-svcs/src/test/java/us/dot/its/jpo/ode/rsuHealth/RsuSnmpTest.java
package us.dot.its.jpo.ode.rsuHealth; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import java.io.IOException; import java.util.Vector; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.mockito.Mock; import org.snmp4j.PDU; import org.snmp4j.Snmp; import org.snmp4j.Target; import org.snmp4j.event.ResponseEvent; import mockit.Expectations; import mockit.Injectable; import mockit.Mocked; import us.dot.its.jpo.ode.heartbeat.RsuSnmp; public class RsuSnmpTest { @Mock private Snmp mockSnmp; @Ignore @Before public void setUpSnmp() throws IOException { //MockitoAnnotations.initMocks(this); mockSnmp = mock(Snmp.class); } @Ignore @Test public void shouldCreateSnmpV3Request() throws IOException { String targetAddress = null; String targetOid = null; try { RsuSnmp.sendSnmpV3Request(targetAddress, targetOid, mockSnmp, null); fail("Expected IllegalArgumentException"); } catch (Exception e) { assertEquals(IllegalArgumentException.class, e.getClass()); } } @Test public void shouldThrowExceptionNullParameter() { try { RsuSnmp.sendSnmpV3Request(null, null, null, null); } catch (Exception e) { assertEquals("Incorrect exception thrown.", IllegalArgumentException.class, e.getClass()); assertTrue("Incorrect exception message", ("Invalid SNMP request parameter").equals(e.getMessage())); } } @Test public void sendShouldCatchException(@Injectable Snmp mockSnmp) { try { new Expectations() { { mockSnmp.send((PDU) any, (Target) any); // result = null; result = new IOException("testException123"); // mockSnmp.close(); } }; } catch (IOException e) { fail("Unexpected exception in expectations block" + e); } RsuSnmp.sendSnmpV3Request("127.0.0.1", "1.1", mockSnmp, null); } @Test public void sendShouldReturnConnectionError(@Injectable Snmp mockSnmp) { String expectedMessage = "[ERROR] SNMP connection error"; try { new Expectations() { { mockSnmp.send((PDU) any, (Target) any); result = null; // result = new IOException("testException123"); mockSnmp.close(); } }; } catch (IOException e) { fail("Unexpected exception in expectations block" + e); } String actualMessage = RsuSnmp.sendSnmpV3Request("127.0.0.1", "1.1", mockSnmp, null); assertEquals(expectedMessage, actualMessage); } @Test public void shouldReturnEmptyResponse(@Injectable Snmp mockSnmp, @Injectable ResponseEvent mockResponseEvent) { String expectedMessage = "[ERROR] Empty SNMP response"; try { new Expectations() { { mockSnmp.send((PDU) any, (Target) any); result = mockResponseEvent; // result = new IOException("testException123"); mockSnmp.close(); mockResponseEvent.getResponse(); result = null; } }; } catch (IOException e) { fail("Unexpected exception in expectations block" + e); } String actualMessage = RsuSnmp.sendSnmpV3Request("127.0.0.1", "1.1", mockSnmp, null); assertEquals(expectedMessage, actualMessage); } @Test public void shouldReturnVariableBindings(@Injectable Snmp mockSnmp, @Injectable ResponseEvent mockResponseEvent, @Injectable PDU mockPDU, @Mocked Vector<?> mockVector) { String inputMessage = "test_rsu_message_1"; String expectedMessage = "test_rsu_message_1"; try { new Expectations() { { mockSnmp.send((PDU) any, (Target) any); result = mockResponseEvent; // result = new IOException("testException123"); mockSnmp.close(); mockResponseEvent.getResponse(); result = mockPDU; mockPDU.getVariableBindings(); result = mockVector; mockVector.toString(); result = inputMessage; } }; } catch (IOException e) { fail("Unexpected exception in expectations block" + e); } String actualMessage = RsuSnmp.sendSnmpV3Request("127.0.0.1", "1.1", mockSnmp, null); assertEquals(expectedMessage, actualMessage); } }
Fix snmp unit test
jpo-ode-svcs/src/test/java/us/dot/its/jpo/ode/rsuHealth/RsuSnmpTest.java
Fix snmp unit test
Java
apache-2.0
b34d01793fb91157cfeb66458a0513e8e753e52c
0
Praveen2112/presto,ebyhr/presto,dain/presto,Praveen2112/presto,dain/presto,Praveen2112/presto,smartnews/presto,smartnews/presto,erichwang/presto,losipiuk/presto,electrum/presto,losipiuk/presto,dain/presto,erichwang/presto,losipiuk/presto,smartnews/presto,smartnews/presto,electrum/presto,losipiuk/presto,11xor6/presto,losipiuk/presto,dain/presto,11xor6/presto,smartnews/presto,erichwang/presto,ebyhr/presto,ebyhr/presto,Praveen2112/presto,ebyhr/presto,ebyhr/presto,erichwang/presto,Praveen2112/presto,erichwang/presto,11xor6/presto,11xor6/presto,dain/presto,11xor6/presto,electrum/presto,electrum/presto,electrum/presto
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.plugin.oracle; import io.prestosql.Session; import io.prestosql.execution.QueryInfo; import io.prestosql.testing.AbstractTestDistributedQueries; import io.prestosql.testing.MaterializedResult; import io.prestosql.testing.ResultWithQueryId; import io.prestosql.testing.sql.SqlExecutor; import io.prestosql.testing.sql.TestTable; import org.testng.annotations.Test; import java.util.Optional; import static io.prestosql.spi.type.VarcharType.VARCHAR; import static io.prestosql.testing.MaterializedResult.resultBuilder; import static io.prestosql.testing.sql.TestTable.randomTableSuffix; import static java.lang.String.format; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public abstract class BaseTestOracleDistributedQueries extends AbstractTestDistributedQueries { @Override protected boolean supportsDelete() { return false; } @Override protected boolean supportsViews() { return false; } @Override protected boolean supportsArrays() { return false; } @Override protected boolean supportsCommentOnTable() { return false; } @Override public void testCreateSchema() { // schema creation is not supported assertQueryFails("CREATE SCHEMA test_schema_create", "This connector does not support creating schemas"); } @Override protected String dataMappingTableName(String prestoTypeName) { return "presto_tmp_" + System.nanoTime(); } @Override protected Optional<DataMappingTestSetup> filterDataMappingSmokeTestData(DataMappingTestSetup dataMappingTestSetup) { String typeName = dataMappingTestSetup.getPrestoTypeName(); if (typeName.equals("time")) { return Optional.empty(); } if (typeName.equals("boolean")) { // Oracle does not have native support for boolean however usually it is represented as number(1) return Optional.empty(); } return Optional.of(dataMappingTestSetup); } @Override protected TestTable createTableWithDefaultColumns() { return new TestTable( createJdbcSqlExecutor(), "test_default_columns", "(col_required decimal(20,0) NOT NULL," + "col_nullable decimal(20,0)," + "col_default decimal(20,0) DEFAULT 43," + "col_nonnull_default decimal(20,0) DEFAULT 42 NOT NULL ," + "col_required2 decimal(20,0) NOT NULL)"); } @Test @Override public void testCreateTableAsSelect() { String tableName = "test_ctas" + randomTableSuffix(); assertUpdate("CREATE TABLE IF NOT EXISTS " + tableName + " AS SELECT name, regionkey FROM nation", "SELECT count(*) FROM nation"); assertTableColumnNames(tableName, "name", "regionkey"); assertUpdate("DROP TABLE " + tableName); // Some connectors support CREATE TABLE AS but not the ordinary CREATE TABLE. Let's test CTAS IF NOT EXISTS with a table that is guaranteed to exist. assertUpdate("CREATE TABLE IF NOT EXISTS nation AS SELECT orderkey, discount FROM lineitem", 0); assertTableColumnNames("nation", "nationkey", "name", "regionkey", "comment"); assertCreateTableAsSelect( "SELECT orderdate, orderkey, totalprice FROM orders", "SELECT count(*) FROM orders"); assertCreateTableAsSelect( "SELECT orderstatus, sum(totalprice) x FROM orders GROUP BY orderstatus", "SELECT count(DISTINCT orderstatus) FROM orders"); assertCreateTableAsSelect( "SELECT count(*) x FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey", "SELECT 1"); assertCreateTableAsSelect( "SELECT orderkey FROM orders ORDER BY orderkey LIMIT 10", "SELECT 10"); // this is comment because presto creates a table of varchar(1) and in oracle this unicode occupy 3 char // we should try to get bytes instead of size ?? /* assertCreateTableAsSelect( "SELECT '\u2603' unicode", "SELECT 1"); */ assertCreateTableAsSelect( "SELECT * FROM orders WITH DATA", "SELECT * FROM orders", "SELECT count(*) FROM orders"); assertCreateTableAsSelect( "SELECT * FROM orders WITH NO DATA", "SELECT * FROM orders LIMIT 0", "SELECT 0"); // Tests for CREATE TABLE with UNION ALL: exercises PushTableWriteThroughUnion optimizer assertCreateTableAsSelect( "SELECT orderdate, orderkey, totalprice FROM orders WHERE orderkey % 2 = 0 UNION ALL " + "SELECT orderdate, orderkey, totalprice FROM orders WHERE orderkey % 2 = 1", "SELECT orderdate, orderkey, totalprice FROM orders", "SELECT count(*) FROM orders"); assertCreateTableAsSelect( Session.builder(getSession()).setSystemProperty("redistribute_writes", "true").build(), "SELECT CAST(orderdate AS DATE) orderdate, orderkey, totalprice FROM orders UNION ALL " + "SELECT DATE '2000-01-01', 1234567890, 1.23", "SELECT orderdate, orderkey, totalprice FROM orders UNION ALL " + "SELECT DATE '2000-01-01', 1234567890, 1.23", "SELECT count(*) + 1 FROM orders"); assertCreateTableAsSelect( Session.builder(getSession()).setSystemProperty("redistribute_writes", "false").build(), "SELECT CAST(orderdate AS DATE) orderdate, orderkey, totalprice FROM orders UNION ALL " + "SELECT DATE '2000-01-01', 1234567890, 1.23", "SELECT orderdate, orderkey, totalprice FROM orders UNION ALL " + "SELECT DATE '2000-01-01', 1234567890, 1.23", "SELECT count(*) + 1 FROM orders"); assertExplainAnalyze("EXPLAIN ANALYZE CREATE TABLE " + tableName + " AS SELECT orderstatus FROM orders"); assertQuery("SELECT * from " + tableName, "SELECT orderstatus FROM orders"); assertUpdate("DROP TABLE " + tableName); } @Test @Override public void testSymbolAliasing() { // Replace tablename to less than 30chars, max size naming on oracle String tableName = "symbol_aliasing" + System.currentTimeMillis(); assertUpdate("CREATE TABLE " + tableName + " AS SELECT 1 foo_1, 2 foo_2_4", 1); assertQuery("SELECT foo_1, foo_2_4 FROM " + tableName, "SELECT 1, 2"); assertUpdate("DROP TABLE " + tableName); } @Test @Override public void testRenameColumn() { // Replace tablename to less than 30chars, max size naming on oracle String tableName = "test_renamecol_" + System.currentTimeMillis(); assertUpdate("CREATE TABLE " + tableName + " AS SELECT 'some value' x", 1); assertUpdate("ALTER TABLE " + tableName + " RENAME COLUMN x TO y"); assertQuery("SELECT y FROM " + tableName, "VALUES 'some value'"); assertUpdate("ALTER TABLE " + tableName + " RENAME COLUMN y TO Z"); // 'Z' is upper-case, not delimited assertQuery( "SELECT z FROM " + tableName, // 'z' is lower-case, not delimited "VALUES 'some value'"); // There should be exactly one column assertQuery("SELECT * FROM " + tableName, "VALUES 'some value'"); assertUpdate("DROP TABLE " + tableName); } @Test @Override public void testQueryLoggingCount() { // table name has more than 30chars,max size naming on oracle. // but as this methods call on private methods we disable it } @Test @Override public void testWrittenStats() { // Replace tablename to fetch max size naming on oracle String tableName = "written_stats_" + System.currentTimeMillis(); String sql = "CREATE TABLE " + tableName + " AS SELECT * FROM nation"; ResultWithQueryId<MaterializedResult> resultResultWithQueryId = getDistributedQueryRunner().executeWithQueryId(getSession(), sql); QueryInfo queryInfo = getDistributedQueryRunner().getCoordinator().getQueryManager().getFullQueryInfo(resultResultWithQueryId.getQueryId()); assertEquals(queryInfo.getQueryStats().getOutputPositions(), 1L); assertEquals(queryInfo.getQueryStats().getWrittenPositions(), 25L); assertTrue(queryInfo.getQueryStats().getLogicalWrittenDataSize().toBytes() > 0L); sql = "INSERT INTO " + tableName + " SELECT * FROM nation LIMIT 10"; resultResultWithQueryId = getDistributedQueryRunner().executeWithQueryId(getSession(), sql); queryInfo = getDistributedQueryRunner().getCoordinator().getQueryManager().getFullQueryInfo(resultResultWithQueryId.getQueryId()); assertEquals(queryInfo.getQueryStats().getOutputPositions(), 1L); assertEquals(queryInfo.getQueryStats().getWrittenPositions(), 10L); assertTrue(queryInfo.getQueryStats().getLogicalWrittenDataSize().toBytes() > 0L); assertUpdate("DROP TABLE " + tableName); } @Test @Override public void testShowColumns() { MaterializedResult actual = computeActual("SHOW COLUMNS FROM orders"); MaterializedResult expectedParametrizedVarchar = resultBuilder(getSession(), VARCHAR, VARCHAR, VARCHAR, VARCHAR) .row("orderkey", "decimal(19,0)", "", "") .row("custkey", "decimal(19,0)", "", "") .row("orderstatus", "varchar(1)", "", "") .row("totalprice", "double", "", "") .row("orderdate", "timestamp(3)", "", "") .row("orderpriority", "varchar(15)", "", "") .row("clerk", "varchar(15)", "", "") .row("shippriority", "decimal(10,0)", "", "") .row("comment", "varchar(79)", "", "") .build(); // Until we migrate all connectors to parametrized varchar we check two options assertTrue(actual.equals(expectedParametrizedVarchar), format("%s does not matches %s", actual, expectedParametrizedVarchar)); } @Override public void testInformationSchemaFiltering() { assertQuery( "SELECT table_name FROM information_schema.tables WHERE table_name = 'orders' LIMIT 1", "SELECT 'orders' table_name"); assertQuery( "SELECT table_name FROM information_schema.columns WHERE data_type = 'decimal(19,0)' AND table_name = 'customer' AND column_name = 'custkey' LIMIT 1", "SELECT 'customer' table_name"); } @Test @Override public void testInsertUnicode() { // unicode not working correctly as one unicode char takes more than one byte } @Test @Override public void testInsertWithCoercion() { assertUpdate("CREATE TABLE test_insert_with_coercion (" + "tinyint_column TINYINT, " + "integer_column INTEGER, " + "decimal_column DECIMAL(5, 3), " + "real_column REAL, " + "char_column CHAR(3), " + "bounded_varchar_column VARCHAR(3), " + "unbounded_varchar_column VARCHAR, " + "date_column DATE)"); assertUpdate("INSERT INTO test_insert_with_coercion (tinyint_column, integer_column, decimal_column, real_column) VALUES (1e0, 2e0, 3e0, 4e0)", 1); assertUpdate("INSERT INTO test_insert_with_coercion (char_column, bounded_varchar_column, unbounded_varchar_column) VALUES (CAST('aa ' AS varchar), CAST('aa ' AS varchar), CAST('aa ' AS varchar))", 1); assertUpdate("INSERT INTO test_insert_with_coercion (char_column, bounded_varchar_column, unbounded_varchar_column) VALUES (NULL, NULL, NULL)", 1); assertUpdate("INSERT INTO test_insert_with_coercion (char_column, bounded_varchar_column, unbounded_varchar_column) VALUES (CAST(NULL AS varchar), CAST(NULL AS varchar), CAST(NULL AS varchar))", 1); // Note this case does not actually require coercion, because the `date_column` ends up as Oracle's DATE, which is mapped to Presto's TIMESTAMP. // The test case is still retained for black box testing purposes. assertUpdate("INSERT INTO test_insert_with_coercion (date_column) VALUES (TIMESTAMP '2019-11-18 22:13:40')", 1); // at oracle date field has time part to assertQuery( "SELECT * FROM test_insert_with_coercion", "VALUES " + "(1, 2, 3, 4, NULL, NULL, NULL, NULL), " + "(NULL, NULL, NULL, NULL, 'aa ', 'aa ', 'aa ', NULL), " + "(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL), " + "(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL), " + "(NULL, NULL, NULL, NULL, NULL, NULL, NULL, TIMESTAMP '2019-11-18 22:13:40')"); // this wont fail //assertQueryFails("INSERT INTO test_insert_with_coercion (integer_column) VALUES (3e9)", "Out of range for integer: 3.0E9"); assertQueryFails("INSERT INTO test_insert_with_coercion (char_column) VALUES ('abcd')", "Cannot truncate non-space characters on INSERT"); assertQueryFails("INSERT INTO test_insert_with_coercion (bounded_varchar_column) VALUES ('abcd')", "Cannot truncate non-space characters on INSERT"); assertUpdate("DROP TABLE test_insert_with_coercion"); } @Override protected Optional<String> filterColumnNameTestData(String columnName) { // table names generated has more than 30chars, max size naming on oracle. return Optional.empty(); } protected abstract SqlExecutor createJdbcSqlExecutor(); }
presto-oracle/src/test/java/io/prestosql/plugin/oracle/BaseTestOracleDistributedQueries.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.plugin.oracle; import io.prestosql.Session; import io.prestosql.execution.QueryInfo; import io.prestosql.testing.AbstractTestDistributedQueries; import io.prestosql.testing.MaterializedResult; import io.prestosql.testing.ResultWithQueryId; import io.prestosql.testing.sql.SqlExecutor; import io.prestosql.testing.sql.TestTable; import org.testng.annotations.Test; import java.util.Optional; import static io.prestosql.spi.type.VarcharType.VARCHAR; import static io.prestosql.testing.MaterializedResult.resultBuilder; import static io.prestosql.testing.sql.TestTable.randomTableSuffix; import static java.lang.String.format; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; public abstract class BaseTestOracleDistributedQueries extends AbstractTestDistributedQueries { @Override protected boolean supportsDelete() { return false; } @Override protected boolean supportsViews() { return false; } @Override protected boolean supportsArrays() { return false; } @Override protected boolean supportsCommentOnTable() { return false; } @Override public void testCreateSchema() { // schema creation is not supported assertQueryFails("CREATE SCHEMA test_schema_create", "This connector does not support creating schemas"); } @Override protected String dataMappingTableName(String prestoTypeName) { return "presto_tmp_" + System.nanoTime(); } @Override protected Optional<DataMappingTestSetup> filterDataMappingSmokeTestData(DataMappingTestSetup dataMappingTestSetup) { String typeName = dataMappingTestSetup.getPrestoTypeName(); if (typeName.equals("time")) { return Optional.empty(); } if (typeName.equals("boolean")) { // Oracle does not have native support for boolean however usually it is represented as number(1) return Optional.empty(); } return Optional.of(dataMappingTestSetup); } @Override protected TestTable createTableWithDefaultColumns() { return new TestTable( createJdbcSqlExecutor(), "test_default_columns", "(col_required decimal(20,0) NOT NULL," + "col_nullable decimal(20,0)," + "col_default decimal(20,0) DEFAULT 43," + "col_nonnull_default decimal(20,0) DEFAULT 42 NOT NULL ," + "col_required2 decimal(20,0) NOT NULL)"); } @Test @Override public void testCreateTableAsSelect() { String tableName = "test_ctas" + randomTableSuffix(); assertUpdate("CREATE TABLE IF NOT EXISTS " + tableName + " AS SELECT name, regionkey FROM nation", "SELECT count(*) FROM nation"); assertTableColumnNames(tableName, "name", "regionkey"); assertUpdate("DROP TABLE " + tableName); // Some connectors support CREATE TABLE AS but not the ordinary CREATE TABLE. Let's test CTAS IF NOT EXISTS with a table that is guaranteed to exist. assertUpdate("CREATE TABLE IF NOT EXISTS nation AS SELECT orderkey, discount FROM lineitem", 0); assertTableColumnNames("nation", "nationkey", "name", "regionkey", "comment"); assertCreateTableAsSelect( "SELECT orderdate, orderkey, totalprice FROM orders", "SELECT count(*) FROM orders"); assertCreateTableAsSelect( "SELECT orderstatus, sum(totalprice) x FROM orders GROUP BY orderstatus", "SELECT count(DISTINCT orderstatus) FROM orders"); assertCreateTableAsSelect( "SELECT count(*) x FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey", "SELECT 1"); assertCreateTableAsSelect( "SELECT orderkey FROM orders ORDER BY orderkey LIMIT 10", "SELECT 10"); // this is comment because presto creates a table of varchar(1) and in oracle this unicode occupy 3 char // we should try to get bytes instead of size ?? /* assertCreateTableAsSelect( "SELECT '\u2603' unicode", "SELECT 1"); */ assertCreateTableAsSelect( "SELECT * FROM orders WITH DATA", "SELECT * FROM orders", "SELECT count(*) FROM orders"); assertCreateTableAsSelect( "SELECT * FROM orders WITH NO DATA", "SELECT * FROM orders LIMIT 0", "SELECT 0"); // Tests for CREATE TABLE with UNION ALL: exercises PushTableWriteThroughUnion optimizer assertCreateTableAsSelect( "SELECT orderdate, orderkey, totalprice FROM orders WHERE orderkey % 2 = 0 UNION ALL " + "SELECT orderdate, orderkey, totalprice FROM orders WHERE orderkey % 2 = 1", "SELECT orderdate, orderkey, totalprice FROM orders", "SELECT count(*) FROM orders"); assertCreateTableAsSelect( Session.builder(getSession()).setSystemProperty("redistribute_writes", "true").build(), "SELECT CAST(orderdate AS DATE) orderdate, orderkey, totalprice FROM orders UNION ALL " + "SELECT DATE '2000-01-01', 1234567890, 1.23", "SELECT orderdate, orderkey, totalprice FROM orders UNION ALL " + "SELECT DATE '2000-01-01', 1234567890, 1.23", "SELECT count(*) + 1 FROM orders"); assertCreateTableAsSelect( Session.builder(getSession()).setSystemProperty("redistribute_writes", "false").build(), "SELECT CAST(orderdate AS DATE) orderdate, orderkey, totalprice FROM orders UNION ALL " + "SELECT DATE '2000-01-01', 1234567890, 1.23", "SELECT orderdate, orderkey, totalprice FROM orders UNION ALL " + "SELECT DATE '2000-01-01', 1234567890, 1.23", "SELECT count(*) + 1 FROM orders"); assertExplainAnalyze("EXPLAIN ANALYZE CREATE TABLE " + tableName + " AS SELECT orderstatus FROM orders"); assertQuery("SELECT * from " + tableName, "SELECT orderstatus FROM orders"); assertUpdate("DROP TABLE " + tableName); } @Test @Override public void testCreateTable() { assertUpdate("CREATE TABLE test_create (a bigint, b double, c varchar)"); assertTrue(getQueryRunner().tableExists(getSession(), "test_create")); assertTableColumnNames("test_create", "a", "b", "c"); assertUpdate("DROP TABLE test_create"); assertFalse(getQueryRunner().tableExists(getSession(), "test_create")); assertQueryFails("CREATE TABLE test_create (a bad_type)", ".* Unknown type 'bad_type' for column 'a'"); assertFalse(getQueryRunner().tableExists(getSession(), "test_create")); // Replace test_create_table_if_not_exists with test_create_table_if_not_exist to fetch max size naming on oracle assertUpdate("CREATE TABLE test_create_table_if_not_exist (a bigint, b varchar, c double)"); assertTrue(getQueryRunner().tableExists(getSession(), "test_create_table_if_not_exist")); assertTableColumnNames("test_create_table_if_not_exist", "a", "b", "c"); assertUpdate("CREATE TABLE IF NOT EXISTS test_create_table_if_not_exist (d bigint, e varchar)"); assertTrue(getQueryRunner().tableExists(getSession(), "test_create_table_if_not_exist")); assertTableColumnNames("test_create_table_if_not_exist", "a", "b", "c"); assertUpdate("DROP TABLE test_create_table_if_not_exist"); assertFalse(getQueryRunner().tableExists(getSession(), "test_create_table_if_not_exist")); // Test CREATE TABLE LIKE assertUpdate("CREATE TABLE test_create_original (a bigint, b double, c varchar)"); assertTrue(getQueryRunner().tableExists(getSession(), "test_create_original")); assertTableColumnNames("test_create_original", "a", "b", "c"); assertUpdate("CREATE TABLE test_create_like (LIKE test_create_original, d boolean, e varchar)"); assertTrue(getQueryRunner().tableExists(getSession(), "test_create_like")); assertTableColumnNames("test_create_like", "a", "b", "c", "d", "e"); assertUpdate("DROP TABLE test_create_original"); assertFalse(getQueryRunner().tableExists(getSession(), "test_create_original")); assertUpdate("DROP TABLE test_create_like"); assertFalse(getQueryRunner().tableExists(getSession(), "test_create_like")); } @Test @Override public void testSymbolAliasing() { // Replace tablename to less than 30chars, max size naming on oracle String tableName = "symbol_aliasing" + System.currentTimeMillis(); assertUpdate("CREATE TABLE " + tableName + " AS SELECT 1 foo_1, 2 foo_2_4", 1); assertQuery("SELECT foo_1, foo_2_4 FROM " + tableName, "SELECT 1, 2"); assertUpdate("DROP TABLE " + tableName); } @Test @Override public void testRenameColumn() { // Replace tablename to less than 30chars, max size naming on oracle String tableName = "test_renamecol_" + System.currentTimeMillis(); assertUpdate("CREATE TABLE " + tableName + " AS SELECT 'some value' x", 1); assertUpdate("ALTER TABLE " + tableName + " RENAME COLUMN x TO y"); assertQuery("SELECT y FROM " + tableName, "VALUES 'some value'"); assertUpdate("ALTER TABLE " + tableName + " RENAME COLUMN y TO Z"); // 'Z' is upper-case, not delimited assertQuery( "SELECT z FROM " + tableName, // 'z' is lower-case, not delimited "VALUES 'some value'"); // There should be exactly one column assertQuery("SELECT * FROM " + tableName, "VALUES 'some value'"); assertUpdate("DROP TABLE " + tableName); } @Test @Override public void testQueryLoggingCount() { // table name has more than 30chars,max size naming on oracle. // but as this methods call on private methods we disable it } @Test @Override public void testWrittenStats() { // Replace tablename to fetch max size naming on oracle String tableName = "written_stats_" + System.currentTimeMillis(); String sql = "CREATE TABLE " + tableName + " AS SELECT * FROM nation"; ResultWithQueryId<MaterializedResult> resultResultWithQueryId = getDistributedQueryRunner().executeWithQueryId(getSession(), sql); QueryInfo queryInfo = getDistributedQueryRunner().getCoordinator().getQueryManager().getFullQueryInfo(resultResultWithQueryId.getQueryId()); assertEquals(queryInfo.getQueryStats().getOutputPositions(), 1L); assertEquals(queryInfo.getQueryStats().getWrittenPositions(), 25L); assertTrue(queryInfo.getQueryStats().getLogicalWrittenDataSize().toBytes() > 0L); sql = "INSERT INTO " + tableName + " SELECT * FROM nation LIMIT 10"; resultResultWithQueryId = getDistributedQueryRunner().executeWithQueryId(getSession(), sql); queryInfo = getDistributedQueryRunner().getCoordinator().getQueryManager().getFullQueryInfo(resultResultWithQueryId.getQueryId()); assertEquals(queryInfo.getQueryStats().getOutputPositions(), 1L); assertEquals(queryInfo.getQueryStats().getWrittenPositions(), 10L); assertTrue(queryInfo.getQueryStats().getLogicalWrittenDataSize().toBytes() > 0L); assertUpdate("DROP TABLE " + tableName); } @Test @Override public void testShowColumns() { MaterializedResult actual = computeActual("SHOW COLUMNS FROM orders"); MaterializedResult expectedParametrizedVarchar = resultBuilder(getSession(), VARCHAR, VARCHAR, VARCHAR, VARCHAR) .row("orderkey", "decimal(19,0)", "", "") .row("custkey", "decimal(19,0)", "", "") .row("orderstatus", "varchar(1)", "", "") .row("totalprice", "double", "", "") .row("orderdate", "timestamp(3)", "", "") .row("orderpriority", "varchar(15)", "", "") .row("clerk", "varchar(15)", "", "") .row("shippriority", "decimal(10,0)", "", "") .row("comment", "varchar(79)", "", "") .build(); // Until we migrate all connectors to parametrized varchar we check two options assertTrue(actual.equals(expectedParametrizedVarchar), format("%s does not matches %s", actual, expectedParametrizedVarchar)); } @Override public void testInformationSchemaFiltering() { assertQuery( "SELECT table_name FROM information_schema.tables WHERE table_name = 'orders' LIMIT 1", "SELECT 'orders' table_name"); assertQuery( "SELECT table_name FROM information_schema.columns WHERE data_type = 'decimal(19,0)' AND table_name = 'customer' AND column_name = 'custkey' LIMIT 1", "SELECT 'customer' table_name"); } @Test @Override public void testInsertUnicode() { // unicode not working correctly as one unicode char takes more than one byte } @Test @Override public void testInsertWithCoercion() { assertUpdate("CREATE TABLE test_insert_with_coercion (" + "tinyint_column TINYINT, " + "integer_column INTEGER, " + "decimal_column DECIMAL(5, 3), " + "real_column REAL, " + "char_column CHAR(3), " + "bounded_varchar_column VARCHAR(3), " + "unbounded_varchar_column VARCHAR, " + "date_column DATE)"); assertUpdate("INSERT INTO test_insert_with_coercion (tinyint_column, integer_column, decimal_column, real_column) VALUES (1e0, 2e0, 3e0, 4e0)", 1); assertUpdate("INSERT INTO test_insert_with_coercion (char_column, bounded_varchar_column, unbounded_varchar_column) VALUES (CAST('aa ' AS varchar), CAST('aa ' AS varchar), CAST('aa ' AS varchar))", 1); assertUpdate("INSERT INTO test_insert_with_coercion (char_column, bounded_varchar_column, unbounded_varchar_column) VALUES (NULL, NULL, NULL)", 1); assertUpdate("INSERT INTO test_insert_with_coercion (char_column, bounded_varchar_column, unbounded_varchar_column) VALUES (CAST(NULL AS varchar), CAST(NULL AS varchar), CAST(NULL AS varchar))", 1); // Note this case does not actually require coercion, because the `date_column` ends up as Oracle's DATE, which is mapped to Presto's TIMESTAMP. // The test case is still retained for black box testing purposes. assertUpdate("INSERT INTO test_insert_with_coercion (date_column) VALUES (TIMESTAMP '2019-11-18 22:13:40')", 1); // at oracle date field has time part to assertQuery( "SELECT * FROM test_insert_with_coercion", "VALUES " + "(1, 2, 3, 4, NULL, NULL, NULL, NULL), " + "(NULL, NULL, NULL, NULL, 'aa ', 'aa ', 'aa ', NULL), " + "(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL), " + "(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL), " + "(NULL, NULL, NULL, NULL, NULL, NULL, NULL, TIMESTAMP '2019-11-18 22:13:40')"); // this wont fail //assertQueryFails("INSERT INTO test_insert_with_coercion (integer_column) VALUES (3e9)", "Out of range for integer: 3.0E9"); assertQueryFails("INSERT INTO test_insert_with_coercion (char_column) VALUES ('abcd')", "Cannot truncate non-space characters on INSERT"); assertQueryFails("INSERT INTO test_insert_with_coercion (bounded_varchar_column) VALUES ('abcd')", "Cannot truncate non-space characters on INSERT"); assertUpdate("DROP TABLE test_insert_with_coercion"); } @Override protected Optional<String> filterColumnNameTestData(String columnName) { // table names generated has more than 30chars, max size naming on oracle. return Optional.empty(); } protected abstract SqlExecutor createJdbcSqlExecutor(); }
Drop Oracle specific copy of test Copy was there becase table identifier was too long. After shortening copy of test is not needed.
presto-oracle/src/test/java/io/prestosql/plugin/oracle/BaseTestOracleDistributedQueries.java
Drop Oracle specific copy of test
Java
apache-2.0
944915106b4540140f233b9b32b09f862042868a
0
allanmoso/orientdb,wyzssw/orientdb,alonsod86/orientdb,mmacfadden/orientdb,mbhulin/orientdb,tempbottle/orientdb,cstamas/orientdb,wyzssw/orientdb,cstamas/orientdb,wyzssw/orientdb,cstamas/orientdb,jdillon/orientdb,mbhulin/orientdb,sanyaade-g2g-repos/orientdb,mmacfadden/orientdb,jdillon/orientdb,orientechnologies/orientdb,intfrr/orientdb,tempbottle/orientdb,wouterv/orientdb,redox/OrientDB,wyzssw/orientdb,mmacfadden/orientdb,wouterv/orientdb,sanyaade-g2g-repos/orientdb,mbhulin/orientdb,orientechnologies/orientdb,giastfader/orientdb,joansmith/orientdb,intfrr/orientdb,alonsod86/orientdb,mmacfadden/orientdb,intfrr/orientdb,rprabhat/orientdb,joansmith/orientdb,alonsod86/orientdb,allanmoso/orientdb,wouterv/orientdb,intfrr/orientdb,cstamas/orientdb,mbhulin/orientdb,redox/OrientDB,joansmith/orientdb,rprabhat/orientdb,tempbottle/orientdb,redox/OrientDB,joansmith/orientdb,rprabhat/orientdb,tempbottle/orientdb,allanmoso/orientdb,sanyaade-g2g-repos/orientdb,giastfader/orientdb,sanyaade-g2g-repos/orientdb,alonsod86/orientdb,orientechnologies/orientdb,orientechnologies/orientdb,redox/OrientDB,giastfader/orientdb,rprabhat/orientdb,allanmoso/orientdb,giastfader/orientdb,jdillon/orientdb,wouterv/orientdb
package com.orientechnologies.orient.core; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.MemoryNotificationInfo; import java.lang.management.MemoryPoolMXBean; import java.lang.management.MemoryType; import java.util.ArrayList; import java.util.Collection; import javax.management.Notification; import javax.management.NotificationEmitter; import javax.management.NotificationListener; import com.orientechnologies.common.io.OFileUtils; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.common.profiler.OProfiler; import com.orientechnologies.common.profiler.OProfiler.OProfilerHookValue; import com.orientechnologies.orient.core.OMemoryWatchDog.Listener.TYPE; /** * This memory warning system will call the listener when we exceed the percentage of available memory specified. There should only * be one instance of this object created, since the usage threshold can only be set to one number. */ public class OMemoryWatchDog { private final Collection<Listener> listeners = new ArrayList<Listener>(); private static final MemoryPoolMXBean tenuredGenPool = findTenuredGenPool(); private int alertTimes = 0; public interface Listener { public enum TYPE { OS, JVM } public void memoryUsageLow(TYPE iType, long iUsedMemory, long iMaxMemory); } /** * Create the memory watch dog with the default memory threshold. * * @param iThreshold */ public OMemoryWatchDog(final float iThreshold) { OMemoryWatchDog.setPercentageUsageThreshold(iThreshold); final MemoryMXBean memBean = ManagementFactory.getMemoryMXBean(); final NotificationEmitter memEmitter = (NotificationEmitter) memBean; memEmitter.addNotificationListener(new NotificationListener() { public void handleNotification(Notification n, Object hb) { if (n.getType().equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) { alertTimes++; final long maxMemory = tenuredGenPool.getUsage().getMax(); final long usedMemory = tenuredGenPool.getUsage().getUsed(); OLogManager.instance().warn(this, "Low memory (%s of %s), calling listeners to free memory...", OFileUtils.getSizeAsString(usedMemory), OFileUtils.getSizeAsString(maxMemory)); final long timer = OProfiler.getInstance().startChrono(); try { for (Listener listener : listeners) { listener.memoryUsageLow(TYPE.JVM, usedMemory, maxMemory); } } finally { OProfiler.getInstance().stopChrono("OMemoryWatchDog.freeResources", timer); } } } }, null, null); OProfiler.getInstance().registerHookValue("memory.alerts", new OProfilerHookValue() { public Object getValue() { return alertTimes; } }); } public Collection<Listener> getListeners() { return listeners; } public boolean addListener(Listener listener) { return listeners.add(listener); } public boolean removeListener(Listener listener) { return listeners.remove(listener); } public static void setPercentageUsageThreshold(double percentage) { if (percentage <= 0.0 || percentage > 1.0) { throw new IllegalArgumentException("Percentage not in range"); } long maxMemory = tenuredGenPool.getUsage().getMax(); long warningThreshold = (long) (maxMemory * percentage); tenuredGenPool.setUsageThreshold(warningThreshold); } /** * Tenured Space Pool can be determined by it being of type HEAP and by it being possible to set the usage threshold. */ private static MemoryPoolMXBean findTenuredGenPool() { for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) { // I don't know whether this approach is better, or whether // we should rather check for the pool name "Tenured Gen"? if (pool.getType() == MemoryType.HEAP && pool.isUsageThresholdSupported()) { return pool; } } throw new AssertionError("Could not find tenured space"); } }
core/src/main/java/com/orientechnologies/orient/core/OMemoryWatchDog.java
package com.orientechnologies.orient.core; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.MemoryNotificationInfo; import java.lang.management.MemoryPoolMXBean; import java.lang.management.MemoryType; import java.util.ArrayList; import java.util.Collection; import javax.management.Notification; import javax.management.NotificationEmitter; import javax.management.NotificationListener; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.common.profiler.OProfiler; import com.orientechnologies.common.profiler.OProfiler.OProfilerHookValue; import com.orientechnologies.orient.core.OMemoryWatchDog.Listener.TYPE; /** * This memory warning system will call the listener when we exceed the percentage of available memory specified. There should only * be one instance of this object created, since the usage threshold can only be set to one number. */ public class OMemoryWatchDog { private final Collection<Listener> listeners = new ArrayList<Listener>(); private static final MemoryPoolMXBean tenuredGenPool = findTenuredGenPool(); private int alertTimes = 0; public interface Listener { public enum TYPE { OS, JVM } public void memoryUsageLow(TYPE iType, long iUsedMemory, long iMaxMemory); } /** * Create the memory watch dog with the default memory threshold. * * @param iThreshold */ public OMemoryWatchDog(final float iThreshold) { OMemoryWatchDog.setPercentageUsageThreshold(iThreshold); final MemoryMXBean memBean = ManagementFactory.getMemoryMXBean(); final NotificationEmitter memEmitter = (NotificationEmitter) memBean; memEmitter.addNotificationListener(new NotificationListener() { public void handleNotification(Notification n, Object hb) { if (n.getType().equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) { alertTimes++; long maxMemory = tenuredGenPool.getUsage().getMax(); long usedMemory = tenuredGenPool.getUsage().getUsed(); OLogManager.instance().warn(this, "Low memory caught, calling listeners to free memory..."); final long timer = OProfiler.getInstance().startChrono(); try { for (Listener listener : listeners) { listener.memoryUsageLow(TYPE.JVM, usedMemory, maxMemory); } } finally { OProfiler.getInstance().stopChrono("OMemoryWatchDog.freeResources", timer); } } } }, null, null); OProfiler.getInstance().registerHookValue("memory.alerts", new OProfilerHookValue() { public Object getValue() { return alertTimes; } }); } public Collection<Listener> getListeners() { return listeners; } public boolean addListener(Listener listener) { return listeners.add(listener); } public boolean removeListener(Listener listener) { return listeners.remove(listener); } public static void setPercentageUsageThreshold(double percentage) { if (percentage <= 0.0 || percentage > 1.0) { throw new IllegalArgumentException("Percentage not in range"); } long maxMemory = tenuredGenPool.getUsage().getMax(); long warningThreshold = (long) (maxMemory * percentage); tenuredGenPool.setUsageThreshold(warningThreshold); } /** * Tenured Space Pool can be determined by it being of type HEAP and by it being possible to set the usage threshold. */ private static MemoryPoolMXBean findTenuredGenPool() { for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) { // I don't know whether this approach is better, or whether // we should rather check for the pool name "Tenured Gen"? if (pool.getType() == MemoryType.HEAP && pool.isUsageThresholdSupported()) { return pool; } } throw new AssertionError("Could not find tenured space"); } }
Improved watch dog daemon output
core/src/main/java/com/orientechnologies/orient/core/OMemoryWatchDog.java
Improved watch dog daemon output
Java
apache-2.0
6e31b64dddff0754e8cfd03e6f7a025208174b7a
0
iZettle/dropwizard-metrics-influxdb
package com.izettle.metrics.dw; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.ScheduledReporter; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeName; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.izettle.metrics.influxdb.InfluxDbHttpSender; import com.izettle.metrics.influxdb.InfluxDbReporter; import io.dropwizard.metrics.BaseReporterFactory; import io.dropwizard.util.Duration; import io.dropwizard.validation.ValidationMethod; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; import org.hibernate.validator.constraints.Range; /** * A factory for {@link InfluxDbReporter} instances. * <p/> * <b>Configuration Parameters:</b> * <table> * <tr> * <td>Name</td> * <td>Default</td> * <td>Description</td> * </tr> * <tr> * <td>protocol</td> * <td>http</td> * <td>The protocol (http or https) of the InfluxDb server to report to.</td> * </tr> * <tr> * <td>host</td> * <td>localhost</td> * <td>The hostname of the InfluxDb server to report to.</td> * </tr> * <tr> * <td>port</td> * <td>8086</td> * <td>The port of the InfluxDb server to report to.</td> * </tr> * <tr> * <td>prefix</td> * <td><i>None</i></td> * <td>The prefix for Metric key names to report to InfluxDb.</td> * </tr> * <tr> * <td>tags</td> * <td><i>None</i></td> * <td>tags for all metrics reported to InfluxDb.</td> * </tr> * <tr> * <td>fields</td> * <td>timers = p50, p99, m1_rate<br>meters = m1_rate</td> * <td>fields by metric type to reported to InfluxDb.</td> * </tr> * <tr> * <td>database</td> * <td><i>None</i></td> * <td>The database that metrics will be reported to InfluxDb.</td> * </tr> * <tr> * <td>precision</td> * <td>1m</td> * <td>The precision of timestamps. Does not take into account the quantity, so for example `5m` will be minute precision</td> * <tr> * <td>auth</td> * <td><i>None</i></td> * <td>An auth string of format username:password to authenticate with when reporting to InfluxDb.</td> * </tr> * <tr> * <td>groupGauges</td> * <td><i>None</i></td> * <td>A boolean to signal whether to group gauges when reporting to InfluxDb.</td> * </tr> * <tr> * <td>measurementMappings</td> * <td><i>None</i></td> * <td>A map for measurement mappings to be added, overridden or removed from the defaultMeasurementMappings.</td> * </tr> * <tr> * <td>defaultMeasurementMappings</td> * <td> * health = *.health.*<br> * dao = *.(jdbi|dao).*<br> * resources = *.resources?.*<br> * datasources = io.dropwizard.db.ManagedPooledDataSource.*<br> * clients = org.apache.http.client.HttpClient.*<br> * connections = org.eclipse.jetty.server.HttpConnectionFactory.*<br> * thread_pools = org.eclipse.jetty.util.thread.QueuedThreadPool.*<br> * logs = ch.qos.logback.core.Appender.*<br> * http_server = io.dropwizard.jetty.MutableServletContextHandler.*<br> * raw_sql = org.skife.jdbi.v2.DBI.raw-sql<br> * jvm = ^jvm$<br> * jvm_attribute = jvm\\.attribute.*?<br> * jvm_buffers = jvm\\.buffers\\..*<br> * jvm_classloader = jvm\\.classloader.*<br> * jvm_gc = jvm\\.gc\\..*<br> * jvm_memory = jvm\\.memory\\..*<br> * jvm_threads = jvm\\.threads.*<br> * </td> * <td>A map with default measurement mappings.</td> * </tr> * <tr> * <td>excludes</td> * <td><i>defaultExcludes</i></tr> * <td>A set of pre-calculated metrics like usage and percentage, and unchanging JVM * metrics to exclude by default</td> * </tr> * </table> */ @JsonTypeName("influxdb") public class InfluxDbReporterFactory extends BaseReporterFactory { @NotEmpty private String protocol = "http"; @NotEmpty private String host = "localhost"; @Range(min = 0, max = 49151) private int port = 8086; @NotNull private String prefix = ""; @NotNull private Map<String, String> tags = new HashMap<>(); @NotEmpty private ImmutableMap<String, ImmutableSet<String>> fields = ImmutableMap.of( "timers", ImmutableSet.of("p50", "p99", "m1_rate"), "meters", ImmutableSet.of("m1_rate")); @NotNull private String database = ""; @NotNull private String auth = ""; @NotNull private Duration precision = Duration.minutes(1); private boolean groupGauges = true; private ImmutableMap<String, String> measurementMappings = ImmutableMap.of(); private ImmutableMap<String, String> defaultMeasurementMappings = ImmutableMap.<String, String>builder() .put("health", ".*\\.health.*") .put("auth", ".*\\.auth.*") .put("dao", ".*\\.(jdbi|dao).*") .put("resources", ".*\\.resources?.*") .put("datasources", "io\\.dropwizard\\.db\\.ManagedPooledDataSource.*") .put("clients", "org\\.apache\\.http\\.client\\.HttpClient.*") .put("client_connections", "org\\.apache\\.http\\.conn\\.HttpClientConnectionManager.*") .put("connections", "org\\.eclipse\\.jetty\\.server\\.HttpConnectionFactory.*") .put("thread_pools", "org\\.eclipse\\.jetty\\.util\\.thread\\.QueuedThreadPool.*") .put("logs", "ch\\.qos\\.logback\\.core\\.Appender.*") .put("http_server", "io\\.dropwizard\\.jetty\\.MutableServletContextHandler.*") .put("raw_sql", "org\\.skife\\.jdbi\\.v2\\.DBI\\.raw-sql") .put("jvm", "^jvm$") .put("jvm_attribute", "jvm\\.attribute.*?") .put("jvm_buffers", "jvm\\.buffers\\..*") .put("jvm_classloader", "jvm\\.classloader.*") .put("jvm_gc", "jvm\\.gc\\..*") .put("jvm_memory", "jvm\\.memory\\..*") .put("jvm_threads", "jvm\\.threads.*") .build(); private ImmutableSet<String> excludes = ImmutableSet.<String>builder() .add("ch.qos.logback.core.Appender.debug") .add("ch.qos.logback.core.Appender.trace") .add("io.dropwizard.jetty.MutableServletContextHandler.percent-4xx-15m") .add("io.dropwizard.jetty.MutableServletContextHandler.percent-4xx-1m") .add("io.dropwizard.jetty.MutableServletContextHandler.percent-4xx-5m") .add("io.dropwizard.jetty.MutableServletContextHandler.percent-5xx-15m") .add("io.dropwizard.jetty.MutableServletContextHandler.percent-5xx-1m") .add("io.dropwizard.jetty.MutableServletContextHandler.percent-5xx-5m") .add("jvm.attribute.name") .add("jvm.attribute.vendor") .add("jvm.memory.heap.usage") .add("jvm.memory.non-heap.usage") .add("jvm.memory.pools.Code-Cache.usage") .add("jvm.memory.pools.Compressed-Class-Space.usage") .add("jvm.memory.pools.Metaspace.usage") .add("jvm.memory.pools.PS-Eden-Space.usage") .add("jvm.memory.pools.PS-Old-Gen.usage") .add("jvm.memory.pools.PS-Survivor-Space.usage") .build(); @JsonProperty public String getProtocol() { return protocol; } @JsonProperty public void setProtocol(String protocol) { this.protocol = protocol; } @JsonProperty public String getHost() { return host; } @JsonProperty public void setHost(String host) { this.host = host; } @JsonProperty public int getPort() { return port; } @JsonProperty public void setPort(int port) { this.port = port; } @JsonProperty public String getPrefix() { return prefix; } @JsonProperty public void setPrefix(String prefix) { this.prefix = prefix; } @JsonProperty private Map<String, String> getTags() { return tags; } @JsonProperty public void setTags(Map<String, String> tags) { this.tags = tags; } @JsonProperty public ImmutableMap<String, ImmutableSet<String>> getFields() { return fields; } @JsonProperty public void setFields(ImmutableMap<String, ImmutableSet<String>> fields) { this.fields = fields; } @JsonProperty public String getDatabase() { return database; } @JsonProperty public void setDatabase(String database) { this.database = database; } @JsonProperty public String getAuth() { return auth; } @JsonProperty public void setAuth(String auth) { this.auth = auth; } @JsonProperty public boolean getGroupGauges() { return groupGauges; } @JsonProperty public void setGroupGauges(boolean groupGauges) { this.groupGauges = groupGauges; } @JsonProperty public Duration getPrecision() { return precision; } @JsonProperty public void setPrecision(Duration precision) { this.precision = precision; } @JsonProperty public Map<String, String> getMeasurementMappings() { return measurementMappings; } @JsonProperty public void setMeasurementMappings(ImmutableMap<String, String> measurementMappings) { this.measurementMappings = measurementMappings; } @JsonProperty public Map<String, String> getDefaultMeasurementMappings() { return defaultMeasurementMappings; } @JsonProperty @Override public ImmutableSet<String> getExcludes() { return this.excludes; } @JsonProperty @Override public void setExcludes(ImmutableSet<String> excludes) { this.excludes = excludes; } @JsonProperty public void setDefaultMeasurementMappings(ImmutableMap<String, String> defaultMeasurementMappings) { this.defaultMeasurementMappings = defaultMeasurementMappings; } @Override public ScheduledReporter build(MetricRegistry registry) { try { return builder(registry).build(new InfluxDbHttpSender(protocol, host, port, database, auth, precision.getUnit())); } catch (Exception e) { throw new RuntimeException(e); } } protected Map<String, String> buildMeasurementMappings() { Map<String, String> mappings = new HashMap<>(defaultMeasurementMappings); for (Map.Entry<String, String> entry : measurementMappings.entrySet()) { String mappingKey = entry.getKey(); String mappingValue = entry.getValue(); if (mappingValue.isEmpty()) { mappings.remove(mappingKey); continue; } mappings.put(mappingKey, mappingValue); } return mappings; } @ValidationMethod(message="measurementMappings must be regular expressions") public boolean isMeasurementMappingRegularExpressions() { for (Map.Entry<String, String> entry : buildMeasurementMappings().entrySet()) { try { Pattern.compile(entry.getValue()); } catch(PatternSyntaxException e) { return false; } } return true; } @VisibleForTesting protected InfluxDbReporter.Builder builder(MetricRegistry registry) { return InfluxDbReporter.forRegistry(registry) .convertDurationsTo(getDurationUnit()) .convertRatesTo(getRateUnit()) .includeMeterFields(fields.get("meters")) .includeTimerFields(fields.get("timers")) .filter(getFilter()) .groupGauges(getGroupGauges()) .withTags(getTags()) .measurementMappings(buildMeasurementMappings()); } }
dropwizard-metrics-influxdb/src/main/java/com/izettle/metrics/dw/InfluxDbReporterFactory.java
package com.izettle.metrics.dw; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.ScheduledReporter; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeName; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.izettle.metrics.influxdb.InfluxDbHttpSender; import com.izettle.metrics.influxdb.InfluxDbReporter; import io.dropwizard.metrics.BaseReporterFactory; import io.dropwizard.util.Duration; import io.dropwizard.validation.ValidationMethod; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; import org.hibernate.validator.constraints.Range; /** * A factory for {@link InfluxDbReporter} instances. * <p/> * <b>Configuration Parameters:</b> * <table> * <tr> * <td>Name</td> * <td>Default</td> * <td>Description</td> * </tr> * <tr> * <td>protocol</td> * <td>http</td> * <td>The protocol (http or https) of the InfluxDb server to report to.</td> * </tr> * <tr> * <td>host</td> * <td>localhost</td> * <td>The hostname of the InfluxDb server to report to.</td> * </tr> * <tr> * <td>port</td> * <td>8086</td> * <td>The port of the InfluxDb server to report to.</td> * </tr> * <tr> * <td>prefix</td> * <td><i>None</i></td> * <td>The prefix for Metric key names to report to InfluxDb.</td> * </tr> * <tr> * <td>tags</td> * <td><i>None</i></td> * <td>tags for all metrics reported to InfluxDb.</td> * </tr> * <tr> * <td>fields</td> * <td>timers = p50, p99, m1_rate<br>meters = m1_rate</td> * <td>fields by metric type to reported to InfluxDb.</td> * </tr> * <tr> * <td>database</td> * <td><i>None</i></td> * <td>The database that metrics will be reported to InfluxDb.</td> * </tr> * <tr> * <td>precision</td> * <td>1m</td> * <td>The precision of timestamps. Does not take into account the quantity, so for example `5m` will be minute precision</td> * <tr> * <td>auth</td> * <td><i>None</i></td> * <td>An auth string of format username:password to authenticate with when reporting to InfluxDb.</td> * </tr> * <tr> * <td>groupGauges</td> * <td><i>None</i></td> * <td>A boolean to signal whether to group gauges when reporting to InfluxDb.</td> * </tr> * <tr> * <td>measurementMappings</td> * <td><i>None</i></td> * <td>A map for measurement mappings to be added, overridden or removed from the defaultMeasurementMappings.</td> * </tr> * <tr> * <td>defaultMeasurementMappings</td> * <td> * health = *.health.*<br>dao = *.(jdbi|dao).*<br>resources = *.resources.*<br>datasources = io.dropwizard.db.ManagedPooledDataSource.*<br> * clients = org.apache.http.client.HttpClient.*<br>connections = org.eclipse.jetty.server.HttpConnectionFactory.*<br> * thread_pools = org.eclipse.jetty.util.thread.QueuedThreadPool.*<br>logs = ch.qos.logback.core.Appender.*<br> * http_server = io.dropwizard.jetty.MutableServletContextHandler.*<br>raw_sql = org.skife.jdbi.v2.DBI.raw-sql * </td> * <td>A map with default measurement mappings.</td> * </tr> * </table> */ @JsonTypeName("influxdb") public class InfluxDbReporterFactory extends BaseReporterFactory { @NotEmpty private String protocol = "http"; @NotEmpty private String host = "localhost"; @Range(min = 0, max = 49151) private int port = 8086; @NotNull private String prefix = ""; @NotNull private Map<String, String> tags = new HashMap<>(); @NotEmpty private ImmutableMap<String, ImmutableSet<String>> fields = ImmutableMap.of( "timers", ImmutableSet.of("p50", "p99", "m1_rate"), "meters", ImmutableSet.of("m1_rate")); @NotNull private String database = ""; @NotNull private String auth = ""; @NotNull private Duration precision = Duration.minutes(1); private boolean groupGauges = true; private ImmutableMap<String, String> measurementMappings = ImmutableMap.of(); private ImmutableMap<String, String> defaultMeasurementMappings = ImmutableMap.<String, String>builder() .put("health", ".*\\.health.*") .put("auth", ".*\\.auth.*") .put("dao", ".*\\.(jdbi|dao).*") .put("resources", ".*\\.resources?.*") .put("datasources", "io\\.dropwizard\\.db\\.ManagedPooledDataSource.*") .put("clients", "org\\.apache\\.http\\.client\\.HttpClient.*") .put("client_connections", "org\\.apache\\.http\\.conn\\.HttpClientConnectionManager.*") .put("connections", "org\\.eclipse\\.jetty\\.server\\.HttpConnectionFactory.*") .put("thread_pools", "org\\.eclipse\\.jetty\\.util\\.thread\\.QueuedThreadPool.*") .put("logs", "ch\\.qos\\.logback\\.core\\.Appender.*") .put("http_server", "io\\.dropwizard\\.jetty\\.MutableServletContextHandler.*") .put("raw_sql", "org\\.skife\\.jdbi\\.v2\\.DBI\\.raw-sql") .build(); private ImmutableSet<String> excludes = ImmutableSet.<String>builder() .add("io.dropwizard.jetty.MutableServletContextHandler.percent-4xx-15m") .add("io.dropwizard.jetty.MutableServletContextHandler.percent-4xx-1m") .add("io.dropwizard.jetty.MutableServletContextHandler.percent-4xx-5m") .add("io.dropwizard.jetty.MutableServletContextHandler.percent-5xx-15m") .add("io.dropwizard.jetty.MutableServletContextHandler.percent-5xx-1m") .add("io.dropwizard.jetty.MutableServletContextHandler.percent-5xx-5m") .add("jvm.attribute.name") .add("jvm.attribute.vendor") .add("ch.qos.logback.core.Appender.trace") .add("ch.qos.logback.core.Appender.debug") .add("jvm.memory.heap.usage") .add("jvm.memory.non-heap.usage") .add("jvm.memory.pools.Code-Cache.usage") .add("jvm.memory.pools.Compressed-Class-Space.usage") .add("jvm.memory.pools.Metaspace.usage") .add("jvm.memory.pools.PS-Eden-Space.usage") .add("jvm.memory.pools.PS-Old-Gen.usage") .add("jvm.memory.pools.PS-Survivor-Space.usage") .build(); @JsonProperty public String getProtocol() { return protocol; } @JsonProperty public void setProtocol(String protocol) { this.protocol = protocol; } @JsonProperty public String getHost() { return host; } @JsonProperty public void setHost(String host) { this.host = host; } @JsonProperty public int getPort() { return port; } @JsonProperty public void setPort(int port) { this.port = port; } @JsonProperty public String getPrefix() { return prefix; } @JsonProperty public void setPrefix(String prefix) { this.prefix = prefix; } @JsonProperty private Map<String, String> getTags() { return tags; } @JsonProperty public void setTags(Map<String, String> tags) { this.tags = tags; } @JsonProperty public ImmutableMap<String, ImmutableSet<String>> getFields() { return fields; } @JsonProperty public void setFields(ImmutableMap<String, ImmutableSet<String>> fields) { this.fields = fields; } @JsonProperty public String getDatabase() { return database; } @JsonProperty public void setDatabase(String database) { this.database = database; } @JsonProperty public String getAuth() { return auth; } @JsonProperty public void setAuth(String auth) { this.auth = auth; } @JsonProperty public boolean getGroupGauges() { return groupGauges; } @JsonProperty public void setGroupGauges(boolean groupGauges) { this.groupGauges = groupGauges; } @JsonProperty public Duration getPrecision() { return precision; } @JsonProperty public void setPrecision(Duration precision) { this.precision = precision; } @JsonProperty public Map<String, String> getMeasurementMappings() { return measurementMappings; } @JsonProperty public void setMeasurementMappings(ImmutableMap<String, String> measurementMappings) { this.measurementMappings = measurementMappings; } @JsonProperty public Map<String, String> getDefaultMeasurementMappings() { return defaultMeasurementMappings; } @JsonProperty @Override public ImmutableSet<String> getExcludes() { return this.excludes; } @JsonProperty @Override public void setExcludes(ImmutableSet<String> excludes) { this.excludes = excludes; } @JsonProperty public void setDefaultMeasurementMappings(ImmutableMap<String, String> defaultMeasurementMappings) { this.defaultMeasurementMappings = defaultMeasurementMappings; } @Override public ScheduledReporter build(MetricRegistry registry) { try { return builder(registry).build(new InfluxDbHttpSender(protocol, host, port, database, auth, precision.getUnit())); } catch (Exception e) { throw new RuntimeException(e); } } protected Map<String, String> buildMeasurementMappings() { Map<String, String> mappings = new HashMap<>(defaultMeasurementMappings); for (Map.Entry<String, String> entry : measurementMappings.entrySet()) { String mappingKey = entry.getKey(); String mappingValue = entry.getValue(); if (mappingValue.isEmpty()) { mappings.remove(mappingKey); continue; } mappings.put(mappingKey, mappingValue); } return mappings; } @ValidationMethod(message="measurement mappings must be regular expressions") public boolean isMeasurementMappingRegularExpressions() { for (Map.Entry<String, String> entry : buildMeasurementMappings().entrySet()) { try { Pattern.compile(entry.getValue()); } catch(PatternSyntaxException e) { return false; } } return true; } @VisibleForTesting protected InfluxDbReporter.Builder builder(MetricRegistry registry) { return InfluxDbReporter.forRegistry(registry) .convertDurationsTo(getDurationUnit()) .convertRatesTo(getRateUnit()) .includeMeterFields(fields.get("meters")) .includeTimerFields(fields.get("timers")) .filter(getFilter()) .groupGauges(getGroupGauges()) .withTags(getTags()) .measurementMappings(buildMeasurementMappings()); } }
Map dots to underscores in jvm metrics This makes the measurements more easily queryable in influxdb: $ influx -database development -execute 'show measurements' name: measurements ------------------ name auth client_connections clients connections dao datasources health http_server jvm jvm_buffers jvm_classloader jvm_gc jvm_memory jvm_threads logs raw_sql resources thread_pools
dropwizard-metrics-influxdb/src/main/java/com/izettle/metrics/dw/InfluxDbReporterFactory.java
Map dots to underscores in jvm metrics
Java
apache-2.0
f52940e17f34a43ee30c6d2c54e0cc3b7e010eb4
0
ecki/commons-vfs,seeburger-ag/commons-vfs,mohanaraosv/commons-vfs,mohanaraosv/commons-vfs,seeburger-ag/commons-vfs,apache/commons-vfs,seeburger-ag/commons-vfs,mohanaraosv/commons-vfs,ecki/commons-vfs,apache/commons-vfs
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.vfs2.example; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.StringTokenizer; import org.apache.commons.vfs2.FileContent; import org.apache.commons.vfs2.FileObject; import org.apache.commons.vfs2.FileSystemException; import org.apache.commons.vfs2.FileSystemManager; import org.apache.commons.vfs2.FileType; import org.apache.commons.vfs2.FileUtil; import org.apache.commons.vfs2.Selectors; import org.apache.commons.vfs2.VFS; /** * A simple command-line shell for performing file operations. */ public class Shell { private static final String CVS_ID = "$Id:Shell.java 232419 2005-08-13 07:23:40 +0200 (Sa, 13 Aug 2005) imario $"; private final FileSystemManager mgr; private FileObject cwd; private BufferedReader reader; public static void main(final String[] args) { try { (new Shell()).go(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } System.exit(0); } private Shell() throws FileSystemException { mgr = VFS.getManager(); cwd = mgr.resolveFile(System.getProperty("user.dir")); reader = new BufferedReader(new InputStreamReader(System.in)); } private void go() throws Exception { System.out.println("VFS Shell [" + CVS_ID + "]"); while (true) { final String[] cmd = nextCommand(); if (cmd == null) { return; } if (cmd.length == 0) { continue; } final String cmdName = cmd[0]; if (cmdName.equalsIgnoreCase("exit") || cmdName.equalsIgnoreCase("quit")) { return; } try { handleCommand(cmd); } catch (final Exception e) { System.err.println("Command failed:"); e.printStackTrace(System.err); } } } /** * Handles a command. */ private void handleCommand(final String[] cmd) throws Exception { final String cmdName = cmd[0]; if (cmdName.equalsIgnoreCase("cat")) { cat(cmd); } else if (cmdName.equalsIgnoreCase("cd")) { cd(cmd); } else if (cmdName.equalsIgnoreCase("cp")) { cp(cmd); } else if (cmdName.equalsIgnoreCase("help")) { help(); } else if (cmdName.equalsIgnoreCase("ls")) { ls(cmd); } else if (cmdName.equalsIgnoreCase("pwd")) { pwd(); } else if (cmdName.equalsIgnoreCase("rm")) { rm(cmd); } else if (cmdName.equalsIgnoreCase("touch")) { touch(cmd); } else { System.err.println("Unknown command \"" + cmdName + "\"."); } } /** * Does a 'help' command. */ private void help() { System.out.println("Commands:"); System.out.println("cat <file> Displays the contents of a file."); System.out.println("cd [folder] Changes current folder."); System.out.println("cp <src> <dest> Copies a file or folder."); System.out.println("help Shows this message."); System.out.println("ls [-R] [path] Lists contents of a file or folder."); System.out.println("pwd Displays current folder."); System.out.println("rm <path> Deletes a file or folder."); System.out.println("touch <path> Sets the last-modified time of a file."); System.out.println("exit Exits this program."); System.out.println("quit Exits this program."); } /** * Does an 'rm' command. */ private void rm(final String[] cmd) throws Exception { if (cmd.length < 2) { throw new Exception("USAGE: rm <path>"); } final FileObject file = mgr.resolveFile(cwd, cmd[1]); file.delete(Selectors.SELECT_SELF); } /** * Does a 'cp' command. */ private void cp(final String[] cmd) throws Exception { if (cmd.length < 3) { throw new Exception("USAGE: cp <src> <dest>"); } final FileObject src = mgr.resolveFile(cwd, cmd[1]); FileObject dest = mgr.resolveFile(cwd, cmd[2]); if (dest.exists() && dest.getType() == FileType.FOLDER) { dest = dest.resolveFile(src.getName().getBaseName()); } dest.copyFrom(src, Selectors.SELECT_ALL); } /** * Does a 'cat' command. */ private void cat(final String[] cmd) throws Exception { if (cmd.length < 2) { throw new Exception("USAGE: cat <path>"); } // Locate the file final FileObject file = mgr.resolveFile(cwd, cmd[1]); // Dump the contents to System.out FileUtil.writeContent(file, System.out); System.out.println(); } /** * Does a 'pwd' command. */ private void pwd() { System.out.println("Current folder is " + cwd.getName()); } /** * Does a 'cd' command. * If the taget directory does not exist, a message is printed to <code>System.err</code>. */ private void cd(final String[] cmd) throws Exception { final String path; if (cmd.length > 1) { path = cmd[1]; } else { path = System.getProperty("user.home"); } // Locate and validate the folder FileObject tmp = mgr.resolveFile(cwd, path); if (tmp.exists()) { cwd = tmp; } else { System.out.println("Folder does not exist: " + tmp.getName()); } System.out.println("Current folder is " + cwd.getName()); } /** * Does an 'ls' command. */ private void ls(final String[] cmd) throws FileSystemException { int pos = 1; final boolean recursive; if (cmd.length > pos && cmd[pos].equals("-R")) { recursive = true; pos++; } else { recursive = false; } final FileObject file; if (cmd.length > pos) { file = mgr.resolveFile(cwd, cmd[pos]); } else { file = cwd; } if (file.getType() == FileType.FOLDER) { // List the contents System.out.println("Contents of " + file.getName()); listChildren(file, recursive, ""); } else { // Stat the file System.out.println(file.getName()); final FileContent content = file.getContent(); System.out.println("Size: " + content.getSize() + " bytes."); final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM); final String lastMod = dateFormat.format(new Date(content.getLastModifiedTime())); System.out.println("Last modified: " + lastMod); } } /** * Does a 'touch' command. */ private void touch(final String[] cmd) throws Exception { if (cmd.length < 2) { throw new Exception("USAGE: touch <path>"); } final FileObject file = mgr.resolveFile(cwd, cmd[1]); if (!file.exists()) { file.createFile(); } file.getContent().setLastModifiedTime(System.currentTimeMillis()); } /** * Lists the children of a folder. */ private void listChildren(final FileObject dir, final boolean recursive, final String prefix) throws FileSystemException { final FileObject[] children = dir.getChildren(); for (final FileObject child : children) { System.out.print(prefix); System.out.print(child.getName().getBaseName()); if (child.getType() == FileType.FOLDER) { System.out.println("/"); if (recursive) { listChildren(child, recursive, prefix + " "); } } else { System.out.println(); } } } /** * Returns the next command, split into tokens. */ private String[] nextCommand() throws IOException { System.out.print("> "); final String line = reader.readLine(); if (line == null) { return null; } final ArrayList<String> cmd = new ArrayList<String>(); final StringTokenizer tokens = new StringTokenizer(line); while (tokens.hasMoreTokens()) { cmd.add(tokens.nextToken()); } return cmd.toArray(new String[cmd.size()]); } }
examples/src/main/java/org/apache/commons/vfs2/example/Shell.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.vfs2.example; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.StringTokenizer; import org.apache.commons.vfs2.FileContent; import org.apache.commons.vfs2.FileObject; import org.apache.commons.vfs2.FileSystemException; import org.apache.commons.vfs2.FileSystemManager; import org.apache.commons.vfs2.FileType; import org.apache.commons.vfs2.FileUtil; import org.apache.commons.vfs2.Selectors; import org.apache.commons.vfs2.VFS; /** * A simple command-line shell for performing file operations. */ public class Shell { private static final String CVS_ID = "$Id:Shell.java 232419 2005-08-13 07:23:40 +0200 (Sa, 13 Aug 2005) imario $"; private final FileSystemManager mgr; private FileObject cwd; private BufferedReader reader; public static void main(final String[] args) { try { (new Shell()).go(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } System.exit(0); } private Shell() throws FileSystemException { mgr = VFS.getManager(); cwd = mgr.resolveFile(System.getProperty("user.dir")); reader = new BufferedReader(new InputStreamReader(System.in)); } private void go() throws Exception { System.out.println("VFS Shell [" + CVS_ID + "]"); while (true) { final String[] cmd = nextCommand(); if (cmd == null) { return; } if (cmd.length == 0) { continue; } final String cmdName = cmd[0]; if (cmdName.equalsIgnoreCase("exit") || cmdName.equalsIgnoreCase("quit")) { return; } try { handleCommand(cmd); } catch (final Exception e) { System.err.println("Command failed:"); e.printStackTrace(System.err); } } } /** * Handles a command. */ private void handleCommand(final String[] cmd) throws Exception { final String cmdName = cmd[0]; if (cmdName.equalsIgnoreCase("cat")) { cat(cmd); } else if (cmdName.equalsIgnoreCase("cd")) { cd(cmd); } else if (cmdName.equalsIgnoreCase("cp")) { cp(cmd); } else if (cmdName.equalsIgnoreCase("help")) { help(); } else if (cmdName.equalsIgnoreCase("ls")) { ls(cmd); } else if (cmdName.equalsIgnoreCase("pwd")) { pwd(); } else if (cmdName.equalsIgnoreCase("rm")) { rm(cmd); } else if (cmdName.equalsIgnoreCase("touch")) { touch(cmd); } else { System.err.println("Unknown command \"" + cmdName + "\"."); } } /** * Does a 'help' command. */ private void help() { System.out.println("Commands:"); System.out.println("cat <file> Displays the contents of a file."); System.out.println("cd [folder] Changes current folder."); System.out.println("cp <src> <dest> Copies a file or folder."); System.out.println("help Shows this message."); System.out.println("ls [-R] [path] Lists contents of a file or folder."); System.out.println("pwd Displays current folder."); System.out.println("rm <path> Deletes a file or folder."); System.out.println("touch <path> Sets the last-modified time of a file."); System.out.println("exit Exits this program."); System.out.println("quit Exits this program."); } /** * Does an 'rm' command. */ private void rm(final String[] cmd) throws Exception { if (cmd.length < 2) { throw new Exception("USAGE: rm <path>"); } final FileObject file = mgr.resolveFile(cwd, cmd[1]); file.delete(Selectors.SELECT_SELF); } /** * Does a 'cp' command. */ private void cp(final String[] cmd) throws Exception { if (cmd.length < 3) { throw new Exception("USAGE: cp <src> <dest>"); } final FileObject src = mgr.resolveFile(cwd, cmd[1]); FileObject dest = mgr.resolveFile(cwd, cmd[2]); if (dest.exists() && dest.getType() == FileType.FOLDER) { dest = dest.resolveFile(src.getName().getBaseName()); } dest.copyFrom(src, Selectors.SELECT_ALL); } /** * Does a 'cat' command. */ private void cat(final String[] cmd) throws Exception { if (cmd.length < 2) { throw new Exception("USAGE: cat <path>"); } // Locate the file final FileObject file = mgr.resolveFile(cwd, cmd[1]); // Dump the contents to System.out FileUtil.writeContent(file, System.out); System.out.println(); } /** * Does a 'pwd' command. */ private void pwd() { System.out.println("Current folder is " + cwd.getName()); } /** * Does a 'cd' command. * If the taget directory does not exist, a message is printed to <code>System.err</code>. */ private void cd(final String[] cmd) throws Exception { final String path; if (cmd.length > 1) { path = cmd[1]; } else { path = System.getProperty("user.home"); } // Locate and validate the folder FileObject tmp = mgr.resolveFile(cwd, path); if (tmp.exists()) { cwd = tmp; } else { System.out.println("Folder does not exist: " + tmp.getName()); } System.out.println("Current folder is " + cwd.getName()); } /** * Does an 'ls' command. */ private void ls(final String[] cmd) throws FileSystemException { int pos = 1; final boolean recursive; if (cmd.length > pos && cmd[pos].equals("-R")) { recursive = true; pos++; } else { recursive = false; } final FileObject file; if (cmd.length > pos) { file = mgr.resolveFile(cwd, cmd[pos]); } else { file = cwd; } if (file.getType() == FileType.FOLDER) { // List the contents System.out.println("Contents of " + file.getName()); listChildren(file, recursive, ""); } else { // Stat the file System.out.println(file.getName()); final FileContent content = file.getContent(); System.out.println("Size: " + content.getSize() + " bytes."); final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM); final String lastMod = dateFormat.format(new Date(content.getLastModifiedTime())); System.out.println("Last modified: " + lastMod); } } /** * Does a 'touch' command. */ private void touch(final String[] cmd) throws Exception { if (cmd.length < 2) { throw new Exception("USAGE: touch <path>"); } final FileObject file = mgr.resolveFile(cwd, cmd[1]); if (!file.exists()) { file.createFile(); } file.getContent().setLastModifiedTime(System.currentTimeMillis()); } /** * Lists the children of a folder. */ private void listChildren(final FileObject dir, final boolean recursive, final String prefix) throws FileSystemException { final FileObject[] children = dir.getChildren(); for (final FileObject child : children) { System.out.print(prefix); System.out.print(child.getName().getBaseName()); if (child.getType() == FileType.FOLDER) { System.out.println("/"); if (recursive) { listChildren(child, recursive, prefix + " "); } } else { System.out.println(); } } } /** * Returns the next command, split into tokens. */ private String[] nextCommand() throws IOException { System.out.print("> "); final String line = reader.readLine(); if (line == null) { return null; } final ArrayList<String> cmd = new ArrayList<String>(); final StringTokenizer tokens = new StringTokenizer(line); while (tokens.hasMoreTokens()) { cmd.add(tokens.nextToken()); } return cmd.toArray(new String[cmd.size()]); } }
Checkstyle fix. git-svn-id: c455d203a03ec41bf444183aad31e7cce55db786@1362082 13f79535-47bb-0310-9956-ffa450edef68
examples/src/main/java/org/apache/commons/vfs2/example/Shell.java
Checkstyle fix.
Java
apache-2.0
662c240c2f65be6b9a87b78d1fbb5cad1aca6f86
0
jiachenning/j2objc,hambroperks/j2objc,hambroperks/j2objc,jiachenning/j2objc,Sellegit/j2objc,jiachenning/j2objc,hambroperks/j2objc,Sellegit/j2objc,jiachenning/j2objc,Sellegit/j2objc,Sellegit/j2objc,hambroperks/j2objc,jiachenning/j2objc,hambroperks/j2objc,hambroperks/j2objc,Sellegit/j2objc,hambroperks/j2objc
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.j2objc.testing; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.j2objc.annotations.AutoreleasePool; import com.google.j2objc.annotations.WeakOuter; import junit.framework.Test; import junit.runner.Version; import org.junit.internal.TextListener; import org.junit.runner.Description; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.RunWith; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; import org.junit.runners.JUnit4; import org.junit.runners.Suite; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.lang.annotation.Annotation; import java.util.Arrays; import java.util.Comparator; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.Random; import java.util.Set; /*-[ #include <objc/runtime.h> ]-*/ /** * Runs JUnit test classes. * * Provides a main() function that runs all JUnit tests linked into the executable. * The main() function accepts no arguments since Pulse unit tests are not designed to accept * arguments. Instead the code expects a file called "JUnitTestRunner.properties" to be include * as a resource. * * Any classes derived from {@link Test} (JUnit 3) or {@link Suite} (JUnit 4) are considered * JUnit tests. This behavior can be changed by overriding {@link #isJUnitTestClass}, * {@link #isJUnit3TestClass} or {@link #isJUnit4TestClass}. * * @author iroth@google.com (Ian Roth) */ public class JUnitTestRunner { private static final String PROPERTIES_FILE_NAME = "JUnitTestRunner.properties"; /** * Specifies the output format for tests. */ public enum OutputFormat { JUNIT, // JUnit style output. GTM_UNIT_TESTING // Google Toolkit for Mac unit test output format. } /** * Specifies the sort order for tests. */ public enum SortOrder { ALPHABETICAL, // Sorted alphabetically RANDOM // Sorted randomly (differs with each run) } /** * Specifies whether a pattern includes or excludes test classes. */ public enum TestInclusion { INCLUDE, // Includes test classes matching the pattern EXCLUDE // Excludes test classes matching the pattern } private final PrintStream out; private final Set<String> includePatterns = Sets.newHashSet(); private final Set<String> excludePatterns = Sets.newHashSet(); private final Map<String, String> nameMappings = Maps.newHashMap(); private final Map<String, String> randomNames = Maps.newHashMap(); private final Random random = new Random(System.currentTimeMillis()); private OutputFormat outputFormat = OutputFormat.JUNIT; private SortOrder sortOrder = SortOrder.ALPHABETICAL; public JUnitTestRunner() { this(System.out); } public JUnitTestRunner(PrintStream out) { this.out = out; } public static int main(String[] args) { // Create JUnit test runner. JUnitTestRunner runner = new JUnitTestRunner(); runner.loadPropertiesFromResource(PROPERTIES_FILE_NAME); return runner.run(); } /** * Runs the test classes given in {@param classes}. * @returns Zero if all tests pass, non-zero otherwise. */ public static int run(Class[] classes, RunListener listener) { JUnitCore junitCore = new JUnitCore(); junitCore.addListener(listener); boolean hasError = false; for (@AutoreleasePool Class c : classes) { Result result = junitCore.run(c); hasError = hasError || !result.wasSuccessful(); } return hasError ? 1 : 0; } /** * Runs the test classes that match settings in {@link #PROPERTIES_FILE_NAME}. * @returns Zero if all tests pass, non-zero otherwise. */ public int run() { Class[] classes = (Class[]) getTestClasses().toArray(); sortClasses(classes, sortOrder); RunListener listener = newRunListener(outputFormat); return run(classes, listener); } /** * Returns a new {@link RunListener} instance for the given {@param outputFormat}. */ public RunListener newRunListener(OutputFormat outputFormat) { switch (outputFormat) { case JUNIT: out.println("JUnit version " + Version.id()); return new TextListener(out); case GTM_UNIT_TESTING: return new GtmUnitTestingTextListener(); default: throw new IllegalArgumentException("outputFormat"); } } /** * Sorts the classes given in {@param classes} according to {@param sortOrder}. */ public void sortClasses(Class[] classes, final SortOrder sortOrder) { Arrays.sort(classes, new Comparator<Class>() { public int compare(Class class1, Class class2) { String name1 = getSortKey(class1, sortOrder); String name2 = getSortKey(class2, sortOrder); return name1.compareTo(name2); } }); } private String replaceAll(String value) { for (Map.Entry<String, String> entry : nameMappings.entrySet()) { String pattern = entry.getKey(); String replacement = entry.getValue(); value = value.replaceAll(pattern, replacement); } return value; } private String getSortKey(Class cls, SortOrder sortOrder) { String className = cls.getName(); switch (sortOrder) { case ALPHABETICAL: return replaceAll(className); case RANDOM: String sortKey = randomNames.get(className); if (sortKey == null) { sortKey = Integer.toString(random.nextInt()); randomNames.put(className, sortKey); } return sortKey; default: throw new IllegalArgumentException("sortOrder"); } } /*-[ // Returns true if |cls| conforms to the NSObject protocol. BOOL IsNSObjectClass(Class cls) { while (cls != nil) { if (class_conformsToProtocol(cls, @protocol(NSObject))) { return YES; } // class_conformsToProtocol() does not examine superclasses. cls = class_getSuperclass(cls); } return NO; } ]-*/ /** * Returns the set of all loaded JUnit test classes. */ private native Set<Class> getAllTestClasses() /*-[ int classCount = objc_getClassList(NULL, 0); Class *classes = (Class *)malloc(classCount * sizeof(Class)); objc_getClassList(classes, classCount); id<JavaUtilSet> result = [ComGoogleCommonCollectSets newHashSet]; for (int i = 0; i < classCount; i++) { Class cls = classes[i]; if (IsNSObjectClass(cls)) { IOSClass *javaClass = [IOSClass classWithClass:cls]; if ([self isJUnitTestClassWithIOSClass:javaClass]) { [result addWithId:javaClass]; } } } free(classes); return result; ]-*/; /** * @return true if {@param cls} is either a JUnit 3 or JUnit 4 test. */ protected boolean isJUnitTestClass(Class cls) { return isJUnit3TestClass(cls) || isJUnit4TestSuite(cls) || isJUnit4TestClass(cls); } /** * @return true if {@param cls} derives from {@link Test} and is not part of the * {@link junit.framework} package. */ protected boolean isJUnit3TestClass(Class cls) { return Test.class.isAssignableFrom(cls) && !getPackageName(cls).startsWith("junit.framework") && !getPackageName(cls).startsWith("junit.extensions"); } /** * @return true if {@param cls} derives from {@link Suite} and is not part of the * {@link org.junit} package. */ protected boolean isJUnit4TestSuite(Class cls) { // TODO: implement - check for the RunWith class annotation with a value of Suite.class: // http://www.vogella.com/tutorials/JUnit/article.html#juniteclipse_testsuite return false; } /** * @return true if {@param cls} is {@link JUnit4} annotated. */ protected boolean isJUnit4TestClass(Class cls) { // Need to find test classes, otherwise crashes with b/11790448. if (!cls.getName().endsWith("Test")) { return false; } // Check the annotations. Annotation annotation = cls.getAnnotation(RunWith.class); if (annotation != null) { RunWith runWith = (RunWith) annotation; if (runWith.value().equals(JUnit4.class)) { return true; } } return false; } /** * Returns the name of a class's package or "" for the default package * or (for Foundation classes) no package object. */ private String getPackageName(Class cls) { Package pkg = cls.getPackage(); return pkg != null ? pkg.getName() : ""; } /** * Returns the set of test classes that match settings in {@link #PROPERTIES_FILE_NAME}. */ private Set<Class> getTestClasses() { Set<Class> allTestClasses = getAllTestClasses(); Set<Class> includedClasses = Sets.newHashSet(); if (includePatterns.isEmpty()) { // Include all tests if no include patterns specified. includedClasses = allTestClasses; } else { // Search all tests for tests to include. for (Class testClass : allTestClasses) { for (String includePattern : includePatterns) { if (matchesPattern(testClass, includePattern)) { includedClasses.add(testClass); break; } } } } // Search included tests for tests to exclude. Iterator<Class> includedClassesIterator = includedClasses.iterator(); while (includedClassesIterator.hasNext()) { Class testClass = includedClassesIterator.next(); for (String excludePattern : excludePatterns) { if (matchesPattern(testClass, excludePattern)) { includedClassesIterator.remove(); break; } } } return includedClasses; } private boolean matchesPattern(Class testClass, String pattern) { return testClass.getCanonicalName().contains(pattern); } private void loadProperties(InputStream stream) { Properties properties = new Properties(); try { properties.load(stream); } catch (IOException e) { onError(e); } ClassLoader classLoader = ClassLoader.getSystemClassLoader(); Set<String> propertyNames = properties.stringPropertyNames(); for (String key : propertyNames) { String value = properties.getProperty(key); try { if (key == "outputFormat") { outputFormat = OutputFormat.valueOf(value); } else if (key == "sortOrder") { sortOrder = SortOrder.valueOf(value); } else if (value.equals(TestInclusion.INCLUDE.name())) { includePatterns.add(key); } else if (value.equals(TestInclusion.EXCLUDE.name())) { excludePatterns.add(key); } else { nameMappings.put(key, value); } } catch (IllegalArgumentException e) { onError(e); } } } private void loadPropertiesFromResource(String resourcePath) { try { InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath); if (stream != null) { loadProperties(stream); } else { throw new IOException(String.format("Resource not found: %s", resourcePath)); } } catch (Exception e) { onError(e); } } private void onError(Exception e) { e.printStackTrace(out); } @WeakOuter private class GtmUnitTestingTextListener extends RunListener { private int numTests = 0; private int numFailures = 0; private Failure testFailure; private double testStartTime; @Override public void testRunFinished(Result result) throws Exception { out.printf("Executed %d tests, with %d failures\n", numTests, numFailures); } @Override public void testStarted(Description description) throws Exception { numTests++; testFailure = null; testStartTime = System.currentTimeMillis(); out.printf("Test Case '-[%s]' started.\n", parseDescription(description)); } @Override public void testFinished(Description description) throws Exception { double testEndTime = System.currentTimeMillis(); double elapsedSeconds = 0.001 * (testEndTime - testStartTime); String statusMessage = "passed"; if (testFailure != null) { statusMessage = "failed"; out.print(testFailure.getTrace()); } out.printf("Test Case '-[%s]' %s (%.3f seconds).\n\n", parseDescription(description), statusMessage, elapsedSeconds); } @Override public void testFailure(Failure failure) throws Exception { testFailure = failure; numFailures++; } private String parseDescription(Description description) { String displayName = description.getDisplayName(); int p1 = displayName.indexOf("("); int p2 = displayName.indexOf(")"); if (p1 < 0 || p2 < 0 || p2 <= p1) { return displayName; } String methodName = displayName.substring(0, p1); String className = displayName.substring(p1 + 1, p2); return replaceAll(className) + " " + methodName; } } }
testing/junit-ext/src/java/com/google/j2objc/testing/JUnitTestRunner.java
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.j2objc.testing; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.j2objc.annotations.AutoreleasePool; import com.google.j2objc.annotations.WeakOuter; import junit.framework.Test; import junit.runner.Version; import org.junit.internal.TextListener; import org.junit.runner.Description; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.RunWith; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; import org.junit.runners.JUnit4; import org.junit.runners.Suite; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.lang.annotation.Annotation; import java.util.Arrays; import java.util.Comparator; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.Random; import java.util.Set; /*-[ #include <objc/runtime.h> ]-*/ /** * Runs JUnit test classes. * * Provides a main() function that runs all JUnit tests linked into the executable. * The main() function accepts no arguments since Pulse unit tests are not designed to accept * arguments. Instead the code expects a file called "JUnitTestRunner.properties" to be include * as a resource. * * Any classes derived from {@link Test} (JUnit 3) or {@link Suite} (JUnit 4) are considered * JUnit tests. This behavior can be changed by overriding {@link #isJUnitTestClass}, * {@link #isJUnit3TestClass} or {@link #isJUnit4TestClass}. * * @author iroth@google.com (Ian Roth) */ public class JUnitTestRunner { private static final String PROPERTIES_FILE_NAME = "JUnitTestRunner.properties"; /** * Specifies the output format for tests. */ public enum OutputFormat { JUNIT, // JUnit style output. GTM_UNIT_TESTING // Google Toolkit for Mac unit test output format. } /** * Specifies the sort order for tests. */ public enum SortOrder { ALPHABETICAL, // Sorted alphabetically RANDOM // Sorted randomly (differs with each run) } /** * Specifies whether a pattern includes or excludes test classes. */ public enum TestInclusion { INCLUDE, // Includes test classes matching the pattern EXCLUDE // Excludes test classes matching the pattern } private final PrintStream out; private final Set<String> includePatterns = Sets.newHashSet(); private final Set<String> excludePatterns = Sets.newHashSet(); private final Map<String, String> nameMappings = Maps.newHashMap(); private final Map<String, String> randomNames = Maps.newHashMap(); private final Random random = new Random(System.currentTimeMillis()); private OutputFormat outputFormat = OutputFormat.JUNIT; private SortOrder sortOrder = SortOrder.ALPHABETICAL; public JUnitTestRunner() { this(System.out); } public JUnitTestRunner(PrintStream out) { this.out = out; } public static int main(String[] args) { // Create JUnit test runner. JUnitTestRunner runner = new JUnitTestRunner(); runner.loadPropertiesFromResource(PROPERTIES_FILE_NAME); return runner.run(); } /** * Runs the test classes given in {@param classes}. * @returns Zero if all tests pass, non-zero otherwise. */ public static int run(Class[] classes, RunListener listener) { JUnitCore junitCore = new JUnitCore(); junitCore.addListener(listener); boolean hasError = false; for (@AutoreleasePool Class c : classes) { Result result = junitCore.run(c); hasError = hasError || !result.wasSuccessful(); } return hasError ? 0 : 1; } /** * Runs the test classes that match settings in {@link #PROPERTIES_FILE_NAME}. * @returns Zero if all tests pass, non-zero otherwise. */ public int run() { Class[] classes = (Class[]) getTestClasses().toArray(); sortClasses(classes, sortOrder); RunListener listener = newRunListener(outputFormat); return run(classes, listener); } /** * Returns a new {@link RunListener} instance for the given {@param outputFormat}. */ public RunListener newRunListener(OutputFormat outputFormat) { switch (outputFormat) { case JUNIT: out.println("JUnit version " + Version.id()); return new TextListener(out); case GTM_UNIT_TESTING: return new GtmUnitTestingTextListener(); default: throw new IllegalArgumentException("outputFormat"); } } /** * Sorts the classes given in {@param classes} according to {@param sortOrder}. */ public void sortClasses(Class[] classes, final SortOrder sortOrder) { Arrays.sort(classes, new Comparator<Class>() { public int compare(Class class1, Class class2) { String name1 = getSortKey(class1, sortOrder); String name2 = getSortKey(class2, sortOrder); return name1.compareTo(name2); } }); } private String replaceAll(String value) { for (Map.Entry<String, String> entry : nameMappings.entrySet()) { String pattern = entry.getKey(); String replacement = entry.getValue(); value = value.replaceAll(pattern, replacement); } return value; } private String getSortKey(Class cls, SortOrder sortOrder) { String className = cls.getName(); switch (sortOrder) { case ALPHABETICAL: return replaceAll(className); case RANDOM: String sortKey = randomNames.get(className); if (sortKey == null) { sortKey = Integer.toString(random.nextInt()); randomNames.put(className, sortKey); } return sortKey; default: throw new IllegalArgumentException("sortOrder"); } } /*-[ // Returns true if |cls| conforms to the NSObject protocol. BOOL IsNSObjectClass(Class cls) { while (cls != nil) { if (class_conformsToProtocol(cls, @protocol(NSObject))) { return YES; } // class_conformsToProtocol() does not examine superclasses. cls = class_getSuperclass(cls); } return NO; } ]-*/ /** * Returns the set of all loaded JUnit test classes. */ private native Set<Class> getAllTestClasses() /*-[ int classCount = objc_getClassList(NULL, 0); Class *classes = (Class *)malloc(classCount * sizeof(Class)); objc_getClassList(classes, classCount); id<JavaUtilSet> result = [ComGoogleCommonCollectSets newHashSet]; for (int i = 0; i < classCount; i++) { Class cls = classes[i]; if (IsNSObjectClass(cls)) { IOSClass *javaClass = [IOSClass classWithClass:cls]; if ([self isJUnitTestClassWithIOSClass:javaClass]) { [result addWithId:javaClass]; } } } free(classes); return result; ]-*/; /** * @return true if {@param cls} is either a JUnit 3 or JUnit 4 test. */ protected boolean isJUnitTestClass(Class cls) { return isJUnit3TestClass(cls) || isJUnit4TestSuite(cls) || isJUnit4TestClass(cls); } /** * @return true if {@param cls} derives from {@link Test} and is not part of the * {@link junit.framework} package. */ protected boolean isJUnit3TestClass(Class cls) { return Test.class.isAssignableFrom(cls) && !getPackageName(cls).startsWith("junit.framework") && !getPackageName(cls).startsWith("junit.extensions"); } /** * @return true if {@param cls} derives from {@link Suite} and is not part of the * {@link org.junit} package. */ protected boolean isJUnit4TestSuite(Class cls) { // TODO: implement - check for the RunWith class annotation with a value of Suite.class: // http://www.vogella.com/tutorials/JUnit/article.html#juniteclipse_testsuite return false; } /** * @return true if {@param cls} is {@link JUnit4} annotated. */ protected boolean isJUnit4TestClass(Class cls) { // Need to find test classes, otherwise crashes with b/11790448. if (!cls.getName().endsWith("Test")) { return false; } // Check the annotations. Annotation annotation = cls.getAnnotation(RunWith.class); if (annotation != null) { RunWith runWith = (RunWith) annotation; if (runWith.value().equals(JUnit4.class)) { return true; } } return false; } /** * Returns the name of a class's package or "" for the default package * or (for Foundation classes) no package object. */ private String getPackageName(Class cls) { Package pkg = cls.getPackage(); return pkg != null ? pkg.getName() : ""; } /** * Returns the set of test classes that match settings in {@link #PROPERTIES_FILE_NAME}. */ private Set<Class> getTestClasses() { Set<Class> allTestClasses = getAllTestClasses(); Set<Class> includedClasses = Sets.newHashSet(); if (includePatterns.isEmpty()) { // Include all tests if no include patterns specified. includedClasses = allTestClasses; } else { // Search all tests for tests to include. for (Class testClass : allTestClasses) { for (String includePattern : includePatterns) { if (matchesPattern(testClass, includePattern)) { includedClasses.add(testClass); break; } } } } // Search included tests for tests to exclude. Iterator<Class> includedClassesIterator = includedClasses.iterator(); while (includedClassesIterator.hasNext()) { Class testClass = includedClassesIterator.next(); for (String excludePattern : excludePatterns) { if (matchesPattern(testClass, excludePattern)) { includedClassesIterator.remove(); break; } } } return includedClasses; } private boolean matchesPattern(Class testClass, String pattern) { return testClass.getCanonicalName().contains(pattern); } private void loadProperties(InputStream stream) { Properties properties = new Properties(); try { properties.load(stream); } catch (IOException e) { onError(e); } ClassLoader classLoader = ClassLoader.getSystemClassLoader(); Set<String> propertyNames = properties.stringPropertyNames(); for (String key : propertyNames) { String value = properties.getProperty(key); try { if (key == "outputFormat") { outputFormat = OutputFormat.valueOf(value); } else if (key == "sortOrder") { sortOrder = SortOrder.valueOf(value); } else if (value.equals(TestInclusion.INCLUDE.name())) { includePatterns.add(key); } else if (value.equals(TestInclusion.EXCLUDE.name())) { excludePatterns.add(key); } else { nameMappings.put(key, value); } } catch (IllegalArgumentException e) { onError(e); } } } private void loadPropertiesFromResource(String resourcePath) { try { InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath); if (stream != null) { loadProperties(stream); } else { throw new IOException(String.format("Resource not found: %s", resourcePath)); } } catch (Exception e) { onError(e); } } private void onError(Exception e) { e.printStackTrace(out); } @WeakOuter private class GtmUnitTestingTextListener extends RunListener { private int numTests = 0; private int numFailures = 0; private Failure testFailure; private double testStartTime; @Override public void testRunFinished(Result result) throws Exception { out.printf("Executed %d tests, with %d failures\n", numTests, numFailures); } @Override public void testStarted(Description description) throws Exception { numTests++; testFailure = null; testStartTime = System.currentTimeMillis(); out.printf("Test Case '-[%s]' started.\n", parseDescription(description)); } @Override public void testFinished(Description description) throws Exception { double testEndTime = System.currentTimeMillis(); double elapsedSeconds = 0.001 * (testEndTime - testStartTime); String statusMessage = "passed"; if (testFailure != null) { statusMessage = "failed"; out.print(testFailure.getTrace()); } out.printf("Test Case '-[%s]' %s (%.3f seconds).\n\n", parseDescription(description), statusMessage, elapsedSeconds); } @Override public void testFailure(Failure failure) throws Exception { testFailure = failure; numFailures++; } private String parseDescription(Description description) { String displayName = description.getDisplayName(); int p1 = displayName.indexOf("("); int p2 = displayName.indexOf(")"); if (p1 < 0 || p2 < 0 || p2 <= p1) { return displayName; } String methodName = displayName.substring(0, p1); String className = displayName.substring(p1 + 1, p2); return replaceAll(className) + " " + methodName; } } }
Fixed test runner return code. Change on 2015/01/06 by tball <tball@google.com> ------------- Created by MOE: http://code.google.com/p/moe-java MOE_MIGRATED_REVID=83382062
testing/junit-ext/src/java/com/google/j2objc/testing/JUnitTestRunner.java
Fixed test runner return code. Change on 2015/01/06 by tball <tball@google.com> ------------- Created by MOE: http://code.google.com/p/moe-java MOE_MIGRATED_REVID=83382062
Java
apache-2.0
6e5eca4d3c0803f6b62d8cfaa9ac2a326871760f
0
HubSpot/Singularity,HubSpot/Singularity,hs-jenkins-bot/Singularity,HubSpot/Singularity,hs-jenkins-bot/Singularity,hs-jenkins-bot/Singularity,HubSpot/Singularity,hs-jenkins-bot/Singularity,HubSpot/Singularity,hs-jenkins-bot/Singularity
package com.hubspot.singularity.scheduler; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Optional; import com.google.inject.Inject; import com.hubspot.mesos.Resources; import com.hubspot.mesos.client.MesosClient; import com.hubspot.mesos.json.MesosSlaveMetricsSnapshotObject; import com.hubspot.mesos.json.MesosTaskMonitorObject; import com.hubspot.singularity.ExtendedTaskState; import com.hubspot.singularity.InvalidSingularityTaskIdException; import com.hubspot.singularity.RequestUtilization; import com.hubspot.singularity.SingularityClusterUtilization; import com.hubspot.singularity.SingularityDeleteResult; import com.hubspot.singularity.SingularityDeploy; import com.hubspot.singularity.SingularityDeployStatistics; import com.hubspot.singularity.SingularityPendingRequest; import com.hubspot.singularity.SingularityPendingRequest.PendingType; import com.hubspot.singularity.SingularityRequestWithState; import com.hubspot.singularity.SingularitySlave; import com.hubspot.singularity.SingularitySlaveUsage; import com.hubspot.singularity.SingularitySlaveUsage.ResourceUsageType; import com.hubspot.singularity.SingularityTask; import com.hubspot.singularity.SingularityTaskCleanup; import com.hubspot.singularity.SingularityTaskCurrentUsage; import com.hubspot.singularity.SingularityTaskHistoryUpdate; import com.hubspot.singularity.SingularityTaskId; import com.hubspot.singularity.SingularityTaskUsage; import com.hubspot.singularity.TaskCleanupType; import com.hubspot.singularity.config.SingularityConfiguration; import com.hubspot.singularity.data.DeployManager; import com.hubspot.singularity.data.RequestManager; import com.hubspot.singularity.data.TaskManager; import com.hubspot.singularity.data.UsageManager; import com.hubspot.singularity.sentry.SingularityExceptionNotifier; public class SingularityUsagePoller extends SingularityLeaderOnlyPoller { private static final Logger LOG = LoggerFactory.getLogger(SingularityUsagePoller.class); private final SingularityConfiguration configuration; private final MesosClient mesosClient; private final UsageManager usageManager; private final SingularityUsageHelper usageHelper; private final SingularityExceptionNotifier exceptionNotifier; private final RequestManager requestManager; private final DeployManager deployManager; private final TaskManager taskManager; @Inject SingularityUsagePoller(SingularityConfiguration configuration, SingularityUsageHelper usageHelper, UsageManager usageManager, MesosClient mesosClient, SingularityExceptionNotifier exceptionNotifier, RequestManager requestManager, DeployManager deployManager, TaskManager taskManager) { super(configuration.getCheckUsageEveryMillis(), TimeUnit.MILLISECONDS); this.configuration = configuration; this.usageHelper = usageHelper; this.mesosClient = mesosClient; this.usageManager = usageManager; this.exceptionNotifier = exceptionNotifier; this.requestManager = requestManager; this.deployManager = deployManager; this.taskManager = taskManager; } @Override public void runActionOnPoll() { Map<String, RequestUtilization> utilizationPerRequestId = new HashMap<>(); final long now = System.currentTimeMillis(); long totalMemBytesUsed = 0; long totalMemBytesAvailable = 0; double totalCpuUsed = 0.00; double totalCpuAvailable = 0.00; long totalDiskBytesUsed = 0; long totalDiskBytesAvailable = 0; long currentShuffleCleanupsTotal = 0; if (configuration.isShuffleTasksForOverloadedSlaves()) { currentShuffleCleanupsTotal = taskManager.getCleanupTasks() .stream() .filter((taskCleanup) -> taskCleanup.getCleanupType() == TaskCleanupType.REBALANCE_CPU_USAGE) .count(); } for (SingularitySlave slave : usageHelper.getSlavesToTrackUsageFor()) { Map<ResourceUsageType, Number> longRunningTasksUsage = new HashMap<>(); longRunningTasksUsage.put(ResourceUsageType.MEMORY_BYTES_USED, 0); longRunningTasksUsage.put(ResourceUsageType.CPU_USED, 0); longRunningTasksUsage.put(ResourceUsageType.DISK_BYTES_USED, 0); Optional<Long> memoryMbTotal = Optional.absent(); Optional<Double> cpusTotal = Optional.absent(); Optional<Long> diskMbTotal = Optional.absent(); long memoryMbReservedOnSlave = 0; double cpuReservedOnSlave = 0; long diskMbReservedOnSlave = 0; long memoryBytesUsedOnSlave = 0; double cpusUsedOnSlave = 0; long diskMbUsedOnSlave = 0; try { List<MesosTaskMonitorObject> allTaskUsage = mesosClient.getSlaveResourceUsage(slave.getHost()); MesosSlaveMetricsSnapshotObject slaveMetricsSnapshot = mesosClient.getSlaveMetricsSnapshot(slave.getHost()); double systemMemTotalBytes = 0; double systemMemFreeBytes = 0; double systemLoad1Min = 0; double systemLoad5Min = 0; double systemLoad15Min = 0; double slaveDiskUsed = 0; double slaveDiskTotal = 0; double systemCpusTotal = 0; if (slaveMetricsSnapshot != null) { systemMemTotalBytes = slaveMetricsSnapshot.getSystemMemTotalBytes(); systemMemFreeBytes = slaveMetricsSnapshot.getSystemMemFreeBytes(); systemLoad1Min = slaveMetricsSnapshot.getSystemLoad1Min(); systemLoad5Min = slaveMetricsSnapshot.getSystemLoad5Min(); systemLoad15Min = slaveMetricsSnapshot.getSystemLoad15Min(); slaveDiskUsed = slaveMetricsSnapshot.getSlaveDiskUsed(); slaveDiskTotal = slaveMetricsSnapshot.getSlaveDiskTotal(); systemCpusTotal = slaveMetricsSnapshot.getSystemCpusTotal(); } double systemLoad; switch (configuration.getMesosConfiguration().getScoreUsingSystemLoad()) { case LOAD_1: systemLoad = systemLoad1Min; break; case LOAD_15: systemLoad = systemLoad15Min; break; case LOAD_5: default: systemLoad = systemLoad5Min; break; } boolean slaveOverloaded = systemCpusTotal > 0 && systemLoad / systemCpusTotal > 1.0; double cpuOverage = slaveOverloaded ? systemLoad - systemCpusTotal : 0.0; int shuffledTasks = 0; List<TaskIdWithUsage> possibleTasksToShuffle = new ArrayList<>(); for (MesosTaskMonitorObject taskUsage : allTaskUsage) { String taskId = taskUsage.getSource(); SingularityTaskId task; try { task = SingularityTaskId.valueOf(taskId); } catch (InvalidSingularityTaskIdException e) { LOG.error("Couldn't get SingularityTaskId for {}", taskUsage); continue; } SingularityTaskUsage latestUsage = getUsage(taskUsage); List<SingularityTaskUsage> pastTaskUsages = usageManager.getTaskUsage(taskId); clearOldUsage(taskId); usageManager.saveSpecificTaskUsage(taskId, latestUsage); Optional<SingularityTask> maybeTask = taskManager.getTask(task); if (maybeTask.isPresent()) { Optional<Resources> maybeResources = maybeTask.get().getTaskRequest().getPendingTask().getResources().or(maybeTask.get().getTaskRequest().getDeploy().getResources()); if (maybeResources.isPresent()) { Resources taskResources = maybeResources.get(); double memoryMbReservedForTask = taskResources.getMemoryMb(); double cpuReservedForTask = taskResources.getCpus(); double diskMbReservedForTask = taskResources.getDiskMb(); memoryMbReservedOnSlave += memoryMbReservedForTask; cpuReservedOnSlave += cpuReservedForTask; diskMbReservedOnSlave += diskMbReservedForTask; updateRequestUtilization(utilizationPerRequestId, pastTaskUsages, latestUsage, task, memoryMbReservedForTask, cpuReservedForTask, diskMbReservedForTask); } } memoryBytesUsedOnSlave += latestUsage.getMemoryTotalBytes(); diskMbUsedOnSlave += latestUsage.getDiskTotalBytes(); SingularityTaskCurrentUsage currentUsage = null; if (pastTaskUsages.isEmpty()) { Optional<SingularityTaskHistoryUpdate> maybeStartingUpdate = taskManager.getTaskHistoryUpdate(task, ExtendedTaskState.TASK_STARTING); if (maybeStartingUpdate.isPresent()) { long startTimestampSeconds = TimeUnit.MILLISECONDS.toSeconds(maybeStartingUpdate.get().getTimestamp()); double usedCpusSinceStart = latestUsage.getCpuSeconds() / (latestUsage.getTimestamp() - startTimestampSeconds); if (isLongRunning(task) || isConsideredLongRunning(task)) { updateLongRunningTasksUsage(longRunningTasksUsage, latestUsage.getMemoryTotalBytes(), usedCpusSinceStart, latestUsage.getDiskTotalBytes()); } currentUsage = new SingularityTaskCurrentUsage(latestUsage.getMemoryTotalBytes(), now, usedCpusSinceStart, latestUsage.getDiskTotalBytes()); usageManager.saveCurrentTaskUsage(taskId, currentUsage); cpusUsedOnSlave += usedCpusSinceStart; } } else { SingularityTaskUsage lastUsage = pastTaskUsages.get(pastTaskUsages.size() - 1); double taskCpusUsed = ((latestUsage.getCpuSeconds() - lastUsage.getCpuSeconds()) / (latestUsage.getTimestamp() - lastUsage.getTimestamp())); if (isLongRunning(task) || isConsideredLongRunning(task)) { updateLongRunningTasksUsage(longRunningTasksUsage, latestUsage.getMemoryTotalBytes(), taskCpusUsed, latestUsage.getDiskTotalBytes()); } currentUsage = new SingularityTaskCurrentUsage(latestUsage.getMemoryTotalBytes(), now, taskCpusUsed, latestUsage.getDiskTotalBytes()); usageManager.saveCurrentTaskUsage(taskId, currentUsage); cpusUsedOnSlave += taskCpusUsed; } if (slaveOverloaded && configuration.isShuffleTasksForOverloadedSlaves() && currentUsage != null && currentUsage.getCpusUsed() > 0) { if (isLongRunning(task)) { Optional<SingularityTaskHistoryUpdate> maybeCleanupUpdate = taskManager.getTaskHistoryUpdate(task, ExtendedTaskState.TASK_CLEANING); if (maybeCleanupUpdate.isPresent() && isTaskAlreadyCleanedUpForShuffle(maybeCleanupUpdate.get())) { LOG.trace("Task {} already being cleaned up to spread cpu usage, skipping", taskId); shuffledTasks++; } else { possibleTasksToShuffle.add(new TaskIdWithUsage(task, currentUsage)); } } } } if (slaveOverloaded && configuration.isShuffleTasksForOverloadedSlaves()) { possibleTasksToShuffle.sort((u1, u2) -> Double.compare(u2.getUsage().getCpusUsed(), u1.getUsage().getCpusUsed())); for (TaskIdWithUsage taskIdWithUsage : possibleTasksToShuffle) { if (cpuOverage <= 0 || shuffledTasks > configuration.getMaxTasksToShufflePerHost() || currentShuffleCleanupsTotal >= configuration.getMaxTasksToShuffleTotal()) { LOG.debug("Not shuffling any more tasks (overage: {}, shuffledOnHost: {}, totalShuffleCleanups: {})", cpuOverage, shuffledTasks, currentShuffleCleanupsTotal); break; } LOG.debug("Cleaning up task {} to free up cpu on overloaded host (remaining cpu overage: {})", taskIdWithUsage.getTaskId(), cpuOverage); Optional<String> message = Optional.of(String.format("Load on slave %s is %s / %s, shuffling task to less busy host", slave.getHost(), systemLoad, systemCpusTotal)); taskManager.createTaskCleanup( new SingularityTaskCleanup( Optional.absent(), TaskCleanupType.REBALANCE_CPU_USAGE, System.currentTimeMillis(), taskIdWithUsage.getTaskId(), message, Optional.of(UUID.randomUUID().toString()), Optional.absent(), Optional.absent())); requestManager.addToPendingQueue(new SingularityPendingRequest(taskIdWithUsage.getTaskId().getRequestId(), taskIdWithUsage.getTaskId().getDeployId(), now, Optional.absent(), PendingType.TASK_BOUNCE, Optional.absent(), Optional.absent(), Optional.absent(), message, Optional.of(UUID.randomUUID().toString()))); cpuOverage -= taskIdWithUsage.getUsage().getCpusUsed(); shuffledTasks++; currentShuffleCleanupsTotal++; } } if (!slave.getResources().isPresent() || !slave.getResources().get().getMemoryMegaBytes().isPresent() || !slave.getResources().get().getNumCpus().isPresent()) { LOG.debug("Could not find slave or resources for slave {}", slave.getId()); } else { memoryMbTotal = Optional.of(slave.getResources().get().getMemoryMegaBytes().get().longValue()); cpusTotal = Optional.of(slave.getResources().get().getNumCpus().get().doubleValue()); diskMbTotal = Optional.of(slave.getResources().get().getDiskSpace().get()); } SingularitySlaveUsage slaveUsage = new SingularitySlaveUsage(cpusUsedOnSlave, cpuReservedOnSlave, cpusTotal, memoryBytesUsedOnSlave, memoryMbReservedOnSlave, memoryMbTotal, diskMbUsedOnSlave, diskMbReservedOnSlave, diskMbTotal, longRunningTasksUsage, allTaskUsage.size(), now, systemMemTotalBytes, systemMemFreeBytes, systemCpusTotal, systemLoad1Min, systemLoad5Min, systemLoad15Min, slaveDiskUsed, slaveDiskTotal); List<Long> slaveTimestamps = usageManager.getSlaveUsageTimestamps(slave.getId()); if (slaveTimestamps.size() + 1 > configuration.getNumUsageToKeep()) { usageManager.deleteSpecificSlaveUsage(slave.getId(), slaveTimestamps.get(0)); } if (slaveUsage.getMemoryBytesTotal().isPresent() && slaveUsage.getCpusTotal().isPresent()) { totalMemBytesUsed += slaveUsage.getMemoryBytesUsed(); totalCpuUsed += slaveUsage.getCpusUsed(); totalDiskBytesUsed += slaveUsage.getDiskBytesUsed(); totalMemBytesAvailable += slaveUsage.getMemoryBytesTotal().get(); totalCpuAvailable += slaveUsage.getCpusTotal().get(); totalDiskBytesAvailable += slaveUsage.getDiskBytesTotal().get(); } LOG.debug("Saving slave {} usage {}", slave.getHost(), slaveUsage); usageManager.saveSpecificSlaveUsageAndSetCurrent(slave.getId(), slaveUsage); } catch (Exception e) { String message = String.format("Could not get slave usage for host %s", slave.getHost()); LOG.error(message, e); exceptionNotifier.notify(message, e); } } usageManager.saveClusterUtilization(getClusterUtilization(utilizationPerRequestId, totalMemBytesUsed, totalMemBytesAvailable, totalCpuUsed, totalCpuAvailable, totalDiskBytesUsed, totalDiskBytesAvailable, now)); } private boolean isTaskAlreadyCleanedUpForShuffle(SingularityTaskHistoryUpdate taskHistoryUpdate) { if (taskHistoryUpdate.getStatusMessage().or("").contains(TaskCleanupType.REBALANCE_CPU_USAGE.name())) { return true; } for (SingularityTaskHistoryUpdate previous : taskHistoryUpdate.getPrevious()) { if (previous.getStatusMessage().or("").contains(TaskCleanupType.REBALANCE_CPU_USAGE.name())) { return true; } } return false; } private SingularityTaskUsage getUsage(MesosTaskMonitorObject taskUsage) { double cpuSeconds = taskUsage.getStatistics().getCpusSystemTimeSecs() + taskUsage.getStatistics().getCpusUserTimeSecs(); return new SingularityTaskUsage(taskUsage.getStatistics().getMemTotalBytes(), taskUsage.getStatistics().getTimestampSeconds(), cpuSeconds, taskUsage.getStatistics().getDiskUsedBytes()); } private boolean isLongRunning(SingularityTaskId task) { Optional<SingularityRequestWithState> request = requestManager.getRequest(task.getRequestId()); if (request.isPresent()) { return request.get().getRequest().getRequestType().isLongRunning(); } LOG.warn("Couldn't find request id {} for task {}", task.getRequestId(), task.getId()); return false; } private boolean isConsideredLongRunning(SingularityTaskId task) { final Optional<SingularityDeployStatistics> deployStatistics = deployManager.getDeployStatistics(task.getRequestId(), task.getDeployId()); return deployStatistics.isPresent() && deployStatistics.get().getAverageRuntimeMillis().isPresent() && deployStatistics.get().getAverageRuntimeMillis().get() >= configuration.getConsiderNonLongRunningTaskLongRunningAfterRunningForSeconds(); } private void updateLongRunningTasksUsage(Map<ResourceUsageType, Number> longRunningTasksUsage, long memBytesUsed, double cpuUsed, long diskBytesUsed) { longRunningTasksUsage.compute(ResourceUsageType.MEMORY_BYTES_USED, (k, v) -> (v == null) ? memBytesUsed : v.longValue() + memBytesUsed); longRunningTasksUsage.compute(ResourceUsageType.CPU_USED, (k, v) -> (v == null) ? cpuUsed : v.doubleValue() + cpuUsed); longRunningTasksUsage.compute(ResourceUsageType.DISK_BYTES_USED, (k, v) -> (v == null) ? diskBytesUsed : v.doubleValue() + diskBytesUsed); } private void updateRequestUtilization(Map<String, RequestUtilization> utilizationPerRequestId, List<SingularityTaskUsage> pastTaskUsages, SingularityTaskUsage latestUsage, SingularityTaskId task, double memoryMbReservedForTask, double cpuReservedForTask, double diskMbReservedForTask) { String requestId = task.getRequestId(); RequestUtilization requestUtilization = utilizationPerRequestId.getOrDefault(requestId, new RequestUtilization(requestId, task.getDeployId())); long curMaxMemBytesUsed = 0; long curMinMemBytesUsed = Long.MAX_VALUE; double curMaxCpuUsed = 0; double curMinCpuUsed = Double.MAX_VALUE; long curMaxDiskBytesUsed = 0; long curMinDiskBytesUsed = Long.MAX_VALUE; if (utilizationPerRequestId.containsKey(requestId)) { curMaxMemBytesUsed = requestUtilization.getMaxMemBytesUsed(); curMinMemBytesUsed = requestUtilization.getMinMemBytesUsed(); curMaxCpuUsed = requestUtilization.getMaxCpuUsed(); curMinCpuUsed = requestUtilization.getMinCpuUsed(); curMaxDiskBytesUsed = requestUtilization.getMaxDiskBytesUsed(); curMinDiskBytesUsed = requestUtilization.getMinDiskBytesUsed(); } List<SingularityTaskUsage> pastTaskUsagesCopy = copyUsages(pastTaskUsages, latestUsage, task); int numTasks = pastTaskUsagesCopy.size() - 1; for (int i = 0; i < numTasks; i++) { SingularityTaskUsage olderUsage = pastTaskUsagesCopy.get(i); SingularityTaskUsage newerUsage = pastTaskUsagesCopy.get(i + 1); double cpusUsed = (newerUsage.getCpuSeconds() - olderUsage.getCpuSeconds()) / (newerUsage.getTimestamp() - olderUsage.getTimestamp()); curMaxCpuUsed = Math.max(cpusUsed, curMaxCpuUsed); curMinCpuUsed = Math.min(cpusUsed, curMinCpuUsed); curMaxMemBytesUsed = Math.max(newerUsage.getMemoryTotalBytes(), curMaxMemBytesUsed); curMinMemBytesUsed = Math.min(newerUsage.getMemoryTotalBytes(), curMinMemBytesUsed); curMaxDiskBytesUsed = Math.max(newerUsage.getDiskTotalBytes(), curMaxDiskBytesUsed); curMinDiskBytesUsed = Math.min(newerUsage.getDiskTotalBytes(), curMinDiskBytesUsed); requestUtilization .addCpuUsed(cpusUsed) .addMemBytesUsed(newerUsage.getMemoryTotalBytes()) .addDiskBytesUsed(newerUsage.getDiskTotalBytes()) .incrementTaskCount(); } requestUtilization .addMemBytesReserved((long) (memoryMbReservedForTask * SingularitySlaveUsage.BYTES_PER_MEGABYTE * numTasks)) .addCpuReserved(cpuReservedForTask * numTasks) .addDiskBytesReserved((long) diskMbReservedForTask * SingularitySlaveUsage.BYTES_PER_MEGABYTE * numTasks) .setMaxCpuUsed(curMaxCpuUsed) .setMinCpuUsed(curMinCpuUsed) .setMaxMemBytesUsed(curMaxMemBytesUsed) .setMinMemBytesUsed(curMinMemBytesUsed) .setMaxDiskBytesUsed(curMaxDiskBytesUsed) .setMinDiskBytesUsed(curMinDiskBytesUsed); utilizationPerRequestId.put(requestId, requestUtilization); } private List<SingularityTaskUsage> copyUsages(List<SingularityTaskUsage> pastTaskUsages, SingularityTaskUsage latestUsage, SingularityTaskId task) { List<SingularityTaskUsage> pastTaskUsagesCopy = new ArrayList<>(); pastTaskUsagesCopy.add(new SingularityTaskUsage(0, TimeUnit.MILLISECONDS.toSeconds(task.getStartedAt()), 0, 0)); // to calculate oldest cpu usage pastTaskUsagesCopy.addAll(pastTaskUsages); pastTaskUsagesCopy.add(latestUsage); return pastTaskUsagesCopy; } private SingularityClusterUtilization getClusterUtilization(Map<String, RequestUtilization> utilizationPerRequestId, long totalMemBytesUsed, long totalMemBytesAvailable, double totalCpuUsed, double totalCpuAvailable, long totalDiskBytesUsed, long totalDiskBytesAvailable, long now) { int numRequestsWithUnderUtilizedCpu = 0; int numRequestsWithOverUtilizedCpu = 0; int numRequestsWithUnderUtilizedMemBytes = 0; int numRequestsWithUnderUtilizedDiskBytes = 0; double totalUnderUtilizedCpu = 0; double totalOverUtilizedCpu = 0; long totalUnderUtilizedMemBytes = 0; long totalUnderUtilizedDiskBytes = 0; double maxUnderUtilizedCpu = 0; double maxOverUtilizedCpu = 0; long maxUnderUtilizedMemBytes = 0; long maxUnderUtilizedDiskBytes = 0; String maxUnderUtilizedCpuRequestId = null; String maxOverUtilizedCpuRequestId = null; String maxUnderUtilizedMemBytesRequestId = null; String maxUnderUtilizedDiskBytesRequestId = null; double minUnderUtilizedCpu = Double.MAX_VALUE; double minOverUtilizedCpu = Double.MAX_VALUE; long minUnderUtilizedMemBytes = Long.MAX_VALUE; long minUnderUtilizedDiskBytes = Long.MAX_VALUE; for (RequestUtilization utilization : utilizationPerRequestId.values()) { Optional<SingularityDeploy> maybeDeploy = deployManager.getDeploy(utilization.getRequestId(), utilization.getDeployId()); if (maybeDeploy.isPresent() && maybeDeploy.get().getResources().isPresent()) { String requestId = utilization.getRequestId(); long memoryBytesReserved = (long) (maybeDeploy.get().getResources().get().getMemoryMb() * SingularitySlaveUsage.BYTES_PER_MEGABYTE); double cpuReserved = maybeDeploy.get().getResources().get().getCpus(); long diskBytesReserved = (long) maybeDeploy.get().getResources().get().getDiskMb() * SingularitySlaveUsage.BYTES_PER_MEGABYTE; double unusedCpu = cpuReserved - utilization.getAvgCpuUsed(); long unusedMemBytes = (long) (memoryBytesReserved - utilization.getAvgMemBytesUsed()); long unusedDiskBytes = (long) (diskBytesReserved - utilization.getAvgDiskBytesUsed()); if (unusedCpu > 0) { numRequestsWithUnderUtilizedCpu++; totalUnderUtilizedCpu += unusedCpu; if (unusedCpu > maxUnderUtilizedCpu) { maxUnderUtilizedCpu = unusedCpu; maxUnderUtilizedCpuRequestId = requestId; } minUnderUtilizedCpu = Math.min(unusedCpu, minUnderUtilizedCpu); } else if (unusedCpu < 0) { double overusedCpu = Math.abs(unusedCpu); numRequestsWithOverUtilizedCpu++; totalOverUtilizedCpu += overusedCpu; if (overusedCpu > maxOverUtilizedCpu) { maxOverUtilizedCpu = overusedCpu; maxOverUtilizedCpuRequestId = requestId; } minOverUtilizedCpu = Math.min(overusedCpu, minOverUtilizedCpu); } if (unusedMemBytes > 0) { numRequestsWithUnderUtilizedMemBytes++; totalUnderUtilizedMemBytes += unusedMemBytes; if (unusedMemBytes > maxUnderUtilizedMemBytes) { maxUnderUtilizedMemBytes = unusedMemBytes; maxUnderUtilizedMemBytesRequestId = requestId; } minUnderUtilizedMemBytes = Math.min(unusedMemBytes, minUnderUtilizedMemBytes); } if (unusedDiskBytes > 0) { numRequestsWithUnderUtilizedDiskBytes++; totalUnderUtilizedDiskBytes += unusedDiskBytes; if (unusedDiskBytes > maxUnderUtilizedDiskBytes) { maxUnderUtilizedDiskBytes = unusedDiskBytes; maxUnderUtilizedDiskBytesRequestId = requestId; } minUnderUtilizedDiskBytes = Math.min(unusedDiskBytes, minUnderUtilizedMemBytes); } } } double avgUnderUtilizedCpu = numRequestsWithUnderUtilizedCpu != 0 ? totalUnderUtilizedCpu / numRequestsWithUnderUtilizedCpu : 0; double avgOverUtilizedCpu = numRequestsWithOverUtilizedCpu != 0? totalOverUtilizedCpu / numRequestsWithOverUtilizedCpu : 0; long avgUnderUtilizedMemBytes = numRequestsWithUnderUtilizedMemBytes != 0 ? totalUnderUtilizedMemBytes / numRequestsWithUnderUtilizedMemBytes : 0; long avgUnderUtilizedDiskBytes = numRequestsWithUnderUtilizedDiskBytes != 0 ? totalUnderUtilizedDiskBytes / numRequestsWithUnderUtilizedDiskBytes : 0; return new SingularityClusterUtilization(new ArrayList<>(utilizationPerRequestId.values()), numRequestsWithUnderUtilizedCpu, numRequestsWithOverUtilizedCpu, numRequestsWithUnderUtilizedMemBytes, numRequestsWithUnderUtilizedDiskBytes, totalUnderUtilizedCpu, totalOverUtilizedCpu, totalUnderUtilizedMemBytes, totalUnderUtilizedDiskBytes, avgUnderUtilizedCpu, avgOverUtilizedCpu, avgUnderUtilizedMemBytes, avgUnderUtilizedDiskBytes, maxUnderUtilizedCpu, maxOverUtilizedCpu, maxUnderUtilizedMemBytes, maxUnderUtilizedDiskBytes, maxUnderUtilizedCpuRequestId, maxOverUtilizedCpuRequestId, maxUnderUtilizedMemBytesRequestId, maxUnderUtilizedDiskBytesRequestId, getMin(minUnderUtilizedCpu), getMin(minOverUtilizedCpu), getMin(minUnderUtilizedMemBytes), getMin(minUnderUtilizedDiskBytes), totalMemBytesUsed, totalMemBytesAvailable, totalDiskBytesUsed, totalDiskBytesAvailable, totalCpuUsed, totalCpuAvailable, now); } private double getMin(double value) { return value == Double.MAX_VALUE ? 0 : value; } private long getMin(long value) { return value == Long.MAX_VALUE ? 0 : value; } @VisibleForTesting void clearOldUsage(String taskId) { List<Double> pastTaskUsagePaths = usageManager.getTaskUsagePaths(taskId).stream().map(Double::parseDouble).collect(Collectors.toList()); while (pastTaskUsagePaths.size() + 1 > configuration.getNumUsageToKeep()) { long minSecondsApart = configuration.getUsageIntervalSeconds(); boolean deleted = false; for (int i = 0; i < pastTaskUsagePaths.size() - 1; i++) { if (pastTaskUsagePaths.get(i + 1) - pastTaskUsagePaths.get(i) < minSecondsApart) { SingularityDeleteResult result = usageManager.deleteSpecificTaskUsage(taskId, pastTaskUsagePaths.get(i + 1)); if (result.equals(SingularityDeleteResult.DIDNT_EXIST)) { LOG.warn("Didn't delete taskUsage {} for taskId {}", pastTaskUsagePaths.get(i + 1).toString(), taskId); } deleted = true; pastTaskUsagePaths.remove(pastTaskUsagePaths.get(i + 1)); break; } } if (!deleted) { usageManager.deleteSpecificTaskUsage(taskId, pastTaskUsagePaths.get(0)); pastTaskUsagePaths.remove(pastTaskUsagePaths.get(0)); } } } private static class TaskIdWithUsage { private final SingularityTaskId taskId; private final SingularityTaskCurrentUsage usage; TaskIdWithUsage(SingularityTaskId taskId, SingularityTaskCurrentUsage usage) { this.taskId = taskId; this.usage = usage; } public SingularityTaskId getTaskId() { return taskId; } public SingularityTaskCurrentUsage getUsage() { return usage; } } }
SingularityService/src/main/java/com/hubspot/singularity/scheduler/SingularityUsagePoller.java
package com.hubspot.singularity.scheduler; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Optional; import com.google.inject.Inject; import com.hubspot.mesos.Resources; import com.hubspot.mesos.client.MesosClient; import com.hubspot.mesos.json.MesosSlaveMetricsSnapshotObject; import com.hubspot.mesos.json.MesosTaskMonitorObject; import com.hubspot.singularity.ExtendedTaskState; import com.hubspot.singularity.InvalidSingularityTaskIdException; import com.hubspot.singularity.RequestUtilization; import com.hubspot.singularity.SingularityClusterUtilization; import com.hubspot.singularity.SingularityDeleteResult; import com.hubspot.singularity.SingularityDeploy; import com.hubspot.singularity.SingularityDeployStatistics; import com.hubspot.singularity.SingularityPendingRequest; import com.hubspot.singularity.SingularityPendingRequest.PendingType; import com.hubspot.singularity.SingularityRequestWithState; import com.hubspot.singularity.SingularitySlave; import com.hubspot.singularity.SingularitySlaveUsage; import com.hubspot.singularity.SingularitySlaveUsage.ResourceUsageType; import com.hubspot.singularity.SingularityTask; import com.hubspot.singularity.SingularityTaskCleanup; import com.hubspot.singularity.SingularityTaskCurrentUsage; import com.hubspot.singularity.SingularityTaskHistoryUpdate; import com.hubspot.singularity.SingularityTaskId; import com.hubspot.singularity.SingularityTaskUsage; import com.hubspot.singularity.TaskCleanupType; import com.hubspot.singularity.config.SingularityConfiguration; import com.hubspot.singularity.data.DeployManager; import com.hubspot.singularity.data.RequestManager; import com.hubspot.singularity.data.TaskManager; import com.hubspot.singularity.data.UsageManager; import com.hubspot.singularity.sentry.SingularityExceptionNotifier; public class SingularityUsagePoller extends SingularityLeaderOnlyPoller { private static final Logger LOG = LoggerFactory.getLogger(SingularityUsagePoller.class); private final SingularityConfiguration configuration; private final MesosClient mesosClient; private final UsageManager usageManager; private final SingularityUsageHelper usageHelper; private final SingularityExceptionNotifier exceptionNotifier; private final RequestManager requestManager; private final DeployManager deployManager; private final TaskManager taskManager; @Inject SingularityUsagePoller(SingularityConfiguration configuration, SingularityUsageHelper usageHelper, UsageManager usageManager, MesosClient mesosClient, SingularityExceptionNotifier exceptionNotifier, RequestManager requestManager, DeployManager deployManager, TaskManager taskManager) { super(configuration.getCheckUsageEveryMillis(), TimeUnit.MILLISECONDS); this.configuration = configuration; this.usageHelper = usageHelper; this.mesosClient = mesosClient; this.usageManager = usageManager; this.exceptionNotifier = exceptionNotifier; this.requestManager = requestManager; this.deployManager = deployManager; this.taskManager = taskManager; } @Override public void runActionOnPoll() { Map<String, RequestUtilization> utilizationPerRequestId = new HashMap<>(); final long now = System.currentTimeMillis(); long totalMemBytesUsed = 0; long totalMemBytesAvailable = 0; double totalCpuUsed = 0.00; double totalCpuAvailable = 0.00; long totalDiskBytesUsed = 0; long totalDiskBytesAvailable = 0; long currentShuffleCleanupsTotal = 0; if (configuration.isShuffleTasksForOverloadedSlaves()) { currentShuffleCleanupsTotal = taskManager.getCleanupTasks() .stream() .filter((taskCleanup) -> taskCleanup.getCleanupType() == TaskCleanupType.REBALANCE_CPU_USAGE) .count(); } for (SingularitySlave slave : usageHelper.getSlavesToTrackUsageFor()) { Map<ResourceUsageType, Number> longRunningTasksUsage = new HashMap<>(); longRunningTasksUsage.put(ResourceUsageType.MEMORY_BYTES_USED, 0); longRunningTasksUsage.put(ResourceUsageType.CPU_USED, 0); longRunningTasksUsage.put(ResourceUsageType.DISK_BYTES_USED, 0); Optional<Long> memoryMbTotal = Optional.absent(); Optional<Double> cpusTotal = Optional.absent(); Optional<Long> diskMbTotal = Optional.absent(); long memoryMbReservedOnSlave = 0; double cpuReservedOnSlave = 0; long diskMbReservedOnSlave = 0; long memoryBytesUsedOnSlave = 0; double cpusUsedOnSlave = 0; long diskMbUsedOnSlave = 0; try { List<MesosTaskMonitorObject> allTaskUsage = mesosClient.getSlaveResourceUsage(slave.getHost()); MesosSlaveMetricsSnapshotObject slaveMetricsSnapshot = mesosClient.getSlaveMetricsSnapshot(slave.getHost()); double systemMemTotalBytes = 0; double systemMemFreeBytes = 0; double systemLoad1Min = 0; double systemLoad5Min = 0; double systemLoad15Min = 0; double slaveDiskUsed = 0; double slaveDiskTotal = 0; double systemCpusTotal = 0; if (slaveMetricsSnapshot != null) { systemMemTotalBytes = slaveMetricsSnapshot.getSystemMemTotalBytes(); systemMemFreeBytes = slaveMetricsSnapshot.getSystemMemFreeBytes(); systemLoad1Min = slaveMetricsSnapshot.getSystemLoad1Min(); systemLoad5Min = slaveMetricsSnapshot.getSystemLoad5Min(); systemLoad15Min = slaveMetricsSnapshot.getSystemLoad15Min(); slaveDiskUsed = slaveMetricsSnapshot.getSlaveDiskUsed(); slaveDiskTotal = slaveMetricsSnapshot.getSlaveDiskTotal(); systemCpusTotal = slaveMetricsSnapshot.getSystemCpusTotal(); } double systemLoad; switch (configuration.getMesosConfiguration().getScoreUsingSystemLoad()) { case LOAD_1: systemLoad = systemLoad1Min; break; case LOAD_15: systemLoad = systemLoad15Min; break; case LOAD_5: default: systemLoad = systemLoad5Min; break; } boolean slaveOverloaded = systemCpusTotal > 0 && systemLoad / systemCpusTotal > 1.0; double cpuOverage = slaveOverloaded ? systemLoad - systemCpusTotal : 0.0; int shuffledTasks = 0; List<TaskIdWithUsage> possibleTasksToShuffle = new ArrayList<>(); for (MesosTaskMonitorObject taskUsage : allTaskUsage) { String taskId = taskUsage.getSource(); SingularityTaskId task; try { task = SingularityTaskId.valueOf(taskId); } catch (InvalidSingularityTaskIdException e) { LOG.error("Couldn't get SingularityTaskId for {}", taskUsage); continue; } SingularityTaskUsage latestUsage = getUsage(taskUsage); List<SingularityTaskUsage> pastTaskUsages = usageManager.getTaskUsage(taskId); clearOldUsage(taskId); usageManager.saveSpecificTaskUsage(taskId, latestUsage); Optional<SingularityTask> maybeTask = taskManager.getTask(task); if (maybeTask.isPresent()) { Optional<Resources> maybeResources = maybeTask.get().getTaskRequest().getPendingTask().getResources().or(maybeTask.get().getTaskRequest().getDeploy().getResources()); if (maybeResources.isPresent()) { Resources taskResources = maybeResources.get(); double memoryMbReservedForTask = taskResources.getMemoryMb(); double cpuReservedForTask = taskResources.getCpus(); double diskMbReservedForTask = taskResources.getDiskMb(); memoryMbReservedOnSlave += memoryMbReservedForTask; cpuReservedOnSlave += cpuReservedForTask; diskMbReservedOnSlave += diskMbReservedForTask; updateRequestUtilization(utilizationPerRequestId, pastTaskUsages, latestUsage, task, memoryMbReservedForTask, cpuReservedForTask, diskMbReservedForTask); } } memoryBytesUsedOnSlave += latestUsage.getMemoryTotalBytes(); diskMbUsedOnSlave += latestUsage.getDiskTotalBytes(); SingularityTaskCurrentUsage currentUsage = null; if (pastTaskUsages.isEmpty()) { Optional<SingularityTaskHistoryUpdate> maybeStartingUpdate = taskManager.getTaskHistoryUpdate(task, ExtendedTaskState.TASK_STARTING); if (maybeStartingUpdate.isPresent()) { long startTimestampSeconds = TimeUnit.MILLISECONDS.toSeconds(maybeStartingUpdate.get().getTimestamp()); double usedCpusSinceStart = latestUsage.getCpuSeconds() / (latestUsage.getTimestamp() - startTimestampSeconds); if (isLongRunning(task) || isConsideredLongRunning(task)) { updateLongRunningTasksUsage(longRunningTasksUsage, latestUsage.getMemoryTotalBytes(), usedCpusSinceStart, latestUsage.getDiskTotalBytes()); } currentUsage = new SingularityTaskCurrentUsage(latestUsage.getMemoryTotalBytes(), now, usedCpusSinceStart, latestUsage.getDiskTotalBytes()); usageManager.saveCurrentTaskUsage(taskId, currentUsage); cpusUsedOnSlave += usedCpusSinceStart; } } else { SingularityTaskUsage lastUsage = pastTaskUsages.get(pastTaskUsages.size() - 1); double taskCpusUsed = ((latestUsage.getCpuSeconds() - lastUsage.getCpuSeconds()) / (latestUsage.getTimestamp() - lastUsage.getTimestamp())); if (isLongRunning(task) || isConsideredLongRunning(task)) { updateLongRunningTasksUsage(longRunningTasksUsage, latestUsage.getMemoryTotalBytes(), taskCpusUsed, latestUsage.getDiskTotalBytes()); } currentUsage = new SingularityTaskCurrentUsage(latestUsage.getMemoryTotalBytes(), now, taskCpusUsed, latestUsage.getDiskTotalBytes()); usageManager.saveCurrentTaskUsage(taskId, currentUsage); cpusUsedOnSlave += taskCpusUsed; } if (slaveOverloaded && configuration.isShuffleTasksForOverloadedSlaves() && currentUsage != null && currentUsage.getCpusUsed() > 0) { if (isLongRunning(task)) { Optional<SingularityTaskHistoryUpdate> maybeCleanupUpdate = taskManager.getTaskHistoryUpdate(task, ExtendedTaskState.TASK_CLEANING); if (maybeCleanupUpdate.isPresent() && isTaskAlreadyCleanedUpForShuffle(maybeCleanupUpdate.get())) { LOG.trace("Task {} already being cleaned up to spread cpu usage, skipping", taskId); shuffledTasks++; } else { possibleTasksToShuffle.add(new TaskIdWithUsage(task, currentUsage)); } } } } if (slaveOverloaded && configuration.isShuffleTasksForOverloadedSlaves()) { possibleTasksToShuffle.sort((u1, u2) -> Double.compare(u2.getUsage().getCpusUsed(), u1.getUsage().getCpusUsed())); for (TaskIdWithUsage taskIdWithUsage : possibleTasksToShuffle) { if (cpuOverage <= 0 || shuffledTasks > configuration.getMaxTasksToShufflePerHost() || currentShuffleCleanupsTotal >= configuration.getMaxTasksToShuffleTotal()) { break; } LOG.debug("Cleaning up task {} to free up cpu on overloaded host (remaining cpu overage: {})", taskIdWithUsage.getTaskId(), cpuOverage); Optional<String> message = Optional.of(String.format("Load on slave %s is %s / %s, shuffling task to less busy host", slave.getHost(), systemLoad, systemCpusTotal)); taskManager.createTaskCleanup( new SingularityTaskCleanup( Optional.absent(), TaskCleanupType.REBALANCE_CPU_USAGE, System.currentTimeMillis(), taskIdWithUsage.getTaskId(), message, Optional.of(UUID.randomUUID().toString()), Optional.absent(), Optional.absent())); requestManager.addToPendingQueue(new SingularityPendingRequest(taskIdWithUsage.getTaskId().getRequestId(), taskIdWithUsage.getTaskId().getDeployId(), now, Optional.absent(), PendingType.TASK_BOUNCE, Optional.absent(), Optional.absent(), Optional.absent(), message, Optional.of(UUID.randomUUID().toString()))); cpuOverage -= taskIdWithUsage.getUsage().getCpusUsed(); shuffledTasks++; currentShuffleCleanupsTotal++; } } if (!slave.getResources().isPresent() || !slave.getResources().get().getMemoryMegaBytes().isPresent() || !slave.getResources().get().getNumCpus().isPresent()) { LOG.debug("Could not find slave or resources for slave {}", slave.getId()); } else { memoryMbTotal = Optional.of(slave.getResources().get().getMemoryMegaBytes().get().longValue()); cpusTotal = Optional.of(slave.getResources().get().getNumCpus().get().doubleValue()); diskMbTotal = Optional.of(slave.getResources().get().getDiskSpace().get()); } SingularitySlaveUsage slaveUsage = new SingularitySlaveUsage(cpusUsedOnSlave, cpuReservedOnSlave, cpusTotal, memoryBytesUsedOnSlave, memoryMbReservedOnSlave, memoryMbTotal, diskMbUsedOnSlave, diskMbReservedOnSlave, diskMbTotal, longRunningTasksUsage, allTaskUsage.size(), now, systemMemTotalBytes, systemMemFreeBytes, systemCpusTotal, systemLoad1Min, systemLoad5Min, systemLoad15Min, slaveDiskUsed, slaveDiskTotal); List<Long> slaveTimestamps = usageManager.getSlaveUsageTimestamps(slave.getId()); if (slaveTimestamps.size() + 1 > configuration.getNumUsageToKeep()) { usageManager.deleteSpecificSlaveUsage(slave.getId(), slaveTimestamps.get(0)); } if (slaveUsage.getMemoryBytesTotal().isPresent() && slaveUsage.getCpusTotal().isPresent()) { totalMemBytesUsed += slaveUsage.getMemoryBytesUsed(); totalCpuUsed += slaveUsage.getCpusUsed(); totalDiskBytesUsed += slaveUsage.getDiskBytesUsed(); totalMemBytesAvailable += slaveUsage.getMemoryBytesTotal().get(); totalCpuAvailable += slaveUsage.getCpusTotal().get(); totalDiskBytesAvailable += slaveUsage.getDiskBytesTotal().get(); } LOG.debug("Saving slave {} usage {}", slave.getHost(), slaveUsage); usageManager.saveSpecificSlaveUsageAndSetCurrent(slave.getId(), slaveUsage); } catch (Exception e) { String message = String.format("Could not get slave usage for host %s", slave.getHost()); LOG.error(message, e); exceptionNotifier.notify(message, e); } } usageManager.saveClusterUtilization(getClusterUtilization(utilizationPerRequestId, totalMemBytesUsed, totalMemBytesAvailable, totalCpuUsed, totalCpuAvailable, totalDiskBytesUsed, totalDiskBytesAvailable, now)); } private boolean isTaskAlreadyCleanedUpForShuffle(SingularityTaskHistoryUpdate taskHistoryUpdate) { if (taskHistoryUpdate.getStatusMessage().or("").contains(TaskCleanupType.REBALANCE_CPU_USAGE.name())) { return true; } for (SingularityTaskHistoryUpdate previous : taskHistoryUpdate.getPrevious()) { if (previous.getStatusMessage().or("").contains(TaskCleanupType.REBALANCE_CPU_USAGE.name())) { return true; } } return false; } private SingularityTaskUsage getUsage(MesosTaskMonitorObject taskUsage) { double cpuSeconds = taskUsage.getStatistics().getCpusSystemTimeSecs() + taskUsage.getStatistics().getCpusUserTimeSecs(); return new SingularityTaskUsage(taskUsage.getStatistics().getMemTotalBytes(), taskUsage.getStatistics().getTimestampSeconds(), cpuSeconds, taskUsage.getStatistics().getDiskUsedBytes()); } private boolean isLongRunning(SingularityTaskId task) { Optional<SingularityRequestWithState> request = requestManager.getRequest(task.getRequestId()); if (request.isPresent()) { return request.get().getRequest().getRequestType().isLongRunning(); } LOG.warn("Couldn't find request id {} for task {}", task.getRequestId(), task.getId()); return false; } private boolean isConsideredLongRunning(SingularityTaskId task) { final Optional<SingularityDeployStatistics> deployStatistics = deployManager.getDeployStatistics(task.getRequestId(), task.getDeployId()); return deployStatistics.isPresent() && deployStatistics.get().getAverageRuntimeMillis().isPresent() && deployStatistics.get().getAverageRuntimeMillis().get() >= configuration.getConsiderNonLongRunningTaskLongRunningAfterRunningForSeconds(); } private void updateLongRunningTasksUsage(Map<ResourceUsageType, Number> longRunningTasksUsage, long memBytesUsed, double cpuUsed, long diskBytesUsed) { longRunningTasksUsage.compute(ResourceUsageType.MEMORY_BYTES_USED, (k, v) -> (v == null) ? memBytesUsed : v.longValue() + memBytesUsed); longRunningTasksUsage.compute(ResourceUsageType.CPU_USED, (k, v) -> (v == null) ? cpuUsed : v.doubleValue() + cpuUsed); longRunningTasksUsage.compute(ResourceUsageType.DISK_BYTES_USED, (k, v) -> (v == null) ? diskBytesUsed : v.doubleValue() + diskBytesUsed); } private void updateRequestUtilization(Map<String, RequestUtilization> utilizationPerRequestId, List<SingularityTaskUsage> pastTaskUsages, SingularityTaskUsage latestUsage, SingularityTaskId task, double memoryMbReservedForTask, double cpuReservedForTask, double diskMbReservedForTask) { String requestId = task.getRequestId(); RequestUtilization requestUtilization = utilizationPerRequestId.getOrDefault(requestId, new RequestUtilization(requestId, task.getDeployId())); long curMaxMemBytesUsed = 0; long curMinMemBytesUsed = Long.MAX_VALUE; double curMaxCpuUsed = 0; double curMinCpuUsed = Double.MAX_VALUE; long curMaxDiskBytesUsed = 0; long curMinDiskBytesUsed = Long.MAX_VALUE; if (utilizationPerRequestId.containsKey(requestId)) { curMaxMemBytesUsed = requestUtilization.getMaxMemBytesUsed(); curMinMemBytesUsed = requestUtilization.getMinMemBytesUsed(); curMaxCpuUsed = requestUtilization.getMaxCpuUsed(); curMinCpuUsed = requestUtilization.getMinCpuUsed(); curMaxDiskBytesUsed = requestUtilization.getMaxDiskBytesUsed(); curMinDiskBytesUsed = requestUtilization.getMinDiskBytesUsed(); } List<SingularityTaskUsage> pastTaskUsagesCopy = copyUsages(pastTaskUsages, latestUsage, task); int numTasks = pastTaskUsagesCopy.size() - 1; for (int i = 0; i < numTasks; i++) { SingularityTaskUsage olderUsage = pastTaskUsagesCopy.get(i); SingularityTaskUsage newerUsage = pastTaskUsagesCopy.get(i + 1); double cpusUsed = (newerUsage.getCpuSeconds() - olderUsage.getCpuSeconds()) / (newerUsage.getTimestamp() - olderUsage.getTimestamp()); curMaxCpuUsed = Math.max(cpusUsed, curMaxCpuUsed); curMinCpuUsed = Math.min(cpusUsed, curMinCpuUsed); curMaxMemBytesUsed = Math.max(newerUsage.getMemoryTotalBytes(), curMaxMemBytesUsed); curMinMemBytesUsed = Math.min(newerUsage.getMemoryTotalBytes(), curMinMemBytesUsed); curMaxDiskBytesUsed = Math.max(newerUsage.getDiskTotalBytes(), curMaxDiskBytesUsed); curMinDiskBytesUsed = Math.min(newerUsage.getDiskTotalBytes(), curMinDiskBytesUsed); requestUtilization .addCpuUsed(cpusUsed) .addMemBytesUsed(newerUsage.getMemoryTotalBytes()) .addDiskBytesUsed(newerUsage.getDiskTotalBytes()) .incrementTaskCount(); } requestUtilization .addMemBytesReserved((long) (memoryMbReservedForTask * SingularitySlaveUsage.BYTES_PER_MEGABYTE * numTasks)) .addCpuReserved(cpuReservedForTask * numTasks) .addDiskBytesReserved((long) diskMbReservedForTask * SingularitySlaveUsage.BYTES_PER_MEGABYTE * numTasks) .setMaxCpuUsed(curMaxCpuUsed) .setMinCpuUsed(curMinCpuUsed) .setMaxMemBytesUsed(curMaxMemBytesUsed) .setMinMemBytesUsed(curMinMemBytesUsed) .setMaxDiskBytesUsed(curMaxDiskBytesUsed) .setMinDiskBytesUsed(curMinDiskBytesUsed); utilizationPerRequestId.put(requestId, requestUtilization); } private List<SingularityTaskUsage> copyUsages(List<SingularityTaskUsage> pastTaskUsages, SingularityTaskUsage latestUsage, SingularityTaskId task) { List<SingularityTaskUsage> pastTaskUsagesCopy = new ArrayList<>(); pastTaskUsagesCopy.add(new SingularityTaskUsage(0, TimeUnit.MILLISECONDS.toSeconds(task.getStartedAt()), 0, 0)); // to calculate oldest cpu usage pastTaskUsagesCopy.addAll(pastTaskUsages); pastTaskUsagesCopy.add(latestUsage); return pastTaskUsagesCopy; } private SingularityClusterUtilization getClusterUtilization(Map<String, RequestUtilization> utilizationPerRequestId, long totalMemBytesUsed, long totalMemBytesAvailable, double totalCpuUsed, double totalCpuAvailable, long totalDiskBytesUsed, long totalDiskBytesAvailable, long now) { int numRequestsWithUnderUtilizedCpu = 0; int numRequestsWithOverUtilizedCpu = 0; int numRequestsWithUnderUtilizedMemBytes = 0; int numRequestsWithUnderUtilizedDiskBytes = 0; double totalUnderUtilizedCpu = 0; double totalOverUtilizedCpu = 0; long totalUnderUtilizedMemBytes = 0; long totalUnderUtilizedDiskBytes = 0; double maxUnderUtilizedCpu = 0; double maxOverUtilizedCpu = 0; long maxUnderUtilizedMemBytes = 0; long maxUnderUtilizedDiskBytes = 0; String maxUnderUtilizedCpuRequestId = null; String maxOverUtilizedCpuRequestId = null; String maxUnderUtilizedMemBytesRequestId = null; String maxUnderUtilizedDiskBytesRequestId = null; double minUnderUtilizedCpu = Double.MAX_VALUE; double minOverUtilizedCpu = Double.MAX_VALUE; long minUnderUtilizedMemBytes = Long.MAX_VALUE; long minUnderUtilizedDiskBytes = Long.MAX_VALUE; for (RequestUtilization utilization : utilizationPerRequestId.values()) { Optional<SingularityDeploy> maybeDeploy = deployManager.getDeploy(utilization.getRequestId(), utilization.getDeployId()); if (maybeDeploy.isPresent() && maybeDeploy.get().getResources().isPresent()) { String requestId = utilization.getRequestId(); long memoryBytesReserved = (long) (maybeDeploy.get().getResources().get().getMemoryMb() * SingularitySlaveUsage.BYTES_PER_MEGABYTE); double cpuReserved = maybeDeploy.get().getResources().get().getCpus(); long diskBytesReserved = (long) maybeDeploy.get().getResources().get().getDiskMb() * SingularitySlaveUsage.BYTES_PER_MEGABYTE; double unusedCpu = cpuReserved - utilization.getAvgCpuUsed(); long unusedMemBytes = (long) (memoryBytesReserved - utilization.getAvgMemBytesUsed()); long unusedDiskBytes = (long) (diskBytesReserved - utilization.getAvgDiskBytesUsed()); if (unusedCpu > 0) { numRequestsWithUnderUtilizedCpu++; totalUnderUtilizedCpu += unusedCpu; if (unusedCpu > maxUnderUtilizedCpu) { maxUnderUtilizedCpu = unusedCpu; maxUnderUtilizedCpuRequestId = requestId; } minUnderUtilizedCpu = Math.min(unusedCpu, minUnderUtilizedCpu); } else if (unusedCpu < 0) { double overusedCpu = Math.abs(unusedCpu); numRequestsWithOverUtilizedCpu++; totalOverUtilizedCpu += overusedCpu; if (overusedCpu > maxOverUtilizedCpu) { maxOverUtilizedCpu = overusedCpu; maxOverUtilizedCpuRequestId = requestId; } minOverUtilizedCpu = Math.min(overusedCpu, minOverUtilizedCpu); } if (unusedMemBytes > 0) { numRequestsWithUnderUtilizedMemBytes++; totalUnderUtilizedMemBytes += unusedMemBytes; if (unusedMemBytes > maxUnderUtilizedMemBytes) { maxUnderUtilizedMemBytes = unusedMemBytes; maxUnderUtilizedMemBytesRequestId = requestId; } minUnderUtilizedMemBytes = Math.min(unusedMemBytes, minUnderUtilizedMemBytes); } if (unusedDiskBytes > 0) { numRequestsWithUnderUtilizedDiskBytes++; totalUnderUtilizedDiskBytes += unusedDiskBytes; if (unusedDiskBytes > maxUnderUtilizedDiskBytes) { maxUnderUtilizedDiskBytes = unusedDiskBytes; maxUnderUtilizedDiskBytesRequestId = requestId; } minUnderUtilizedDiskBytes = Math.min(unusedDiskBytes, minUnderUtilizedMemBytes); } } } double avgUnderUtilizedCpu = numRequestsWithUnderUtilizedCpu != 0 ? totalUnderUtilizedCpu / numRequestsWithUnderUtilizedCpu : 0; double avgOverUtilizedCpu = numRequestsWithOverUtilizedCpu != 0? totalOverUtilizedCpu / numRequestsWithOverUtilizedCpu : 0; long avgUnderUtilizedMemBytes = numRequestsWithUnderUtilizedMemBytes != 0 ? totalUnderUtilizedMemBytes / numRequestsWithUnderUtilizedMemBytes : 0; long avgUnderUtilizedDiskBytes = numRequestsWithUnderUtilizedDiskBytes != 0 ? totalUnderUtilizedDiskBytes / numRequestsWithUnderUtilizedDiskBytes : 0; return new SingularityClusterUtilization(new ArrayList<>(utilizationPerRequestId.values()), numRequestsWithUnderUtilizedCpu, numRequestsWithOverUtilizedCpu, numRequestsWithUnderUtilizedMemBytes, numRequestsWithUnderUtilizedDiskBytes, totalUnderUtilizedCpu, totalOverUtilizedCpu, totalUnderUtilizedMemBytes, totalUnderUtilizedDiskBytes, avgUnderUtilizedCpu, avgOverUtilizedCpu, avgUnderUtilizedMemBytes, avgUnderUtilizedDiskBytes, maxUnderUtilizedCpu, maxOverUtilizedCpu, maxUnderUtilizedMemBytes, maxUnderUtilizedDiskBytes, maxUnderUtilizedCpuRequestId, maxOverUtilizedCpuRequestId, maxUnderUtilizedMemBytesRequestId, maxUnderUtilizedDiskBytesRequestId, getMin(minUnderUtilizedCpu), getMin(minOverUtilizedCpu), getMin(minUnderUtilizedMemBytes), getMin(minUnderUtilizedDiskBytes), totalMemBytesUsed, totalMemBytesAvailable, totalDiskBytesUsed, totalDiskBytesAvailable, totalCpuUsed, totalCpuAvailable, now); } private double getMin(double value) { return value == Double.MAX_VALUE ? 0 : value; } private long getMin(long value) { return value == Long.MAX_VALUE ? 0 : value; } @VisibleForTesting void clearOldUsage(String taskId) { List<Double> pastTaskUsagePaths = usageManager.getTaskUsagePaths(taskId).stream().map(Double::parseDouble).collect(Collectors.toList()); while (pastTaskUsagePaths.size() + 1 > configuration.getNumUsageToKeep()) { long minSecondsApart = configuration.getUsageIntervalSeconds(); boolean deleted = false; for (int i = 0; i < pastTaskUsagePaths.size() - 1; i++) { if (pastTaskUsagePaths.get(i + 1) - pastTaskUsagePaths.get(i) < minSecondsApart) { SingularityDeleteResult result = usageManager.deleteSpecificTaskUsage(taskId, pastTaskUsagePaths.get(i + 1)); if (result.equals(SingularityDeleteResult.DIDNT_EXIST)) { LOG.warn("Didn't delete taskUsage {} for taskId {}", pastTaskUsagePaths.get(i + 1).toString(), taskId); } deleted = true; pastTaskUsagePaths.remove(pastTaskUsagePaths.get(i + 1)); break; } } if (!deleted) { usageManager.deleteSpecificTaskUsage(taskId, pastTaskUsagePaths.get(0)); pastTaskUsagePaths.remove(pastTaskUsagePaths.get(0)); } } } private static class TaskIdWithUsage { private final SingularityTaskId taskId; private final SingularityTaskCurrentUsage usage; TaskIdWithUsage(SingularityTaskId taskId, SingularityTaskCurrentUsage usage) { this.taskId = taskId; this.usage = usage; } public SingularityTaskId getTaskId() { return taskId; } public SingularityTaskCurrentUsage getUsage() { return usage; } } }
add logging
SingularityService/src/main/java/com/hubspot/singularity/scheduler/SingularityUsagePoller.java
add logging
Java
apache-2.0
4782aa644a6a3ff99fbc6681186f9a69f39add0f
0
hsjawanda/gae-objectify-utils
/** * */ package com.hsjawanda.gaeobjectify.collections; import static com.google.common.base.Preconditions.checkNotNull; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.googlecode.objectify.Key; import com.googlecode.objectify.Ref; import com.googlecode.objectify.annotation.Entity; import com.hsjawanda.gaeobjectify.data.GaeDataUtil; /** * @author harsh.deep * */ public class EntityCollector<K, V> { private static final int INITIAL_CAPACITY = 3; protected List<V> entityList; protected List<Ref<V>> entityRefs; protected List<Ref<V>> refsToLoad; protected Map<K, V> entityMap; protected KeyGenerator<K, V> keyGen; protected boolean entityMapModified = true; protected boolean hasEntityAnnotation = true; protected boolean refsLoaded = false; Class<V> cls; public static <K, V> EntityCollector<K, V> instance(Class<V> cls, KeyGenerator<K, V> keyGen) { checkNotNull(cls); checkNotNull(keyGen); EntityCollector<K, V> ec = new EntityCollector<>(); ec.cls = cls; ec.keyGen = keyGen; return ec; } public static <K, V> EntityCollector<K, V> instance(Class<V> cls, KeyGenerator<K, V> keyGen, List<Ref<V>> refsToLoad) { EntityCollector<K, V> ec = instance(cls, keyGen); ec.refsToLoad = refsToLoad; return ec; } public void add(V entity) { if (!this.refsLoaded) { loadRefs(); } if (null == entity) return; if (null == this.entityMap) { allocateMap(); } this.entityMap.put(this.keyGen.keyFor(entity), entity); this.entityMapModified = true; } public boolean containsValue(V entity) { if (!this.refsLoaded) { loadRefs(); } if (null != this.entityMap) return this.entityMap.containsValue(entity); return false; } public boolean containsKey(K key) { if (!this.refsLoaded) { loadRefs(); } if (null != this.entityMap) return this.entityMap.containsKey(key); return false; } public boolean isEmpty() { if (!this.refsLoaded) { loadRefs(); } if (null == this.entityMap) return true; return this.entityMap.isEmpty(); } public V removeByKey(K key) { if (!this.refsLoaded) { loadRefs(); } if (null == key || null == this.entityMap) return null; V removedEntity = this.entityMap.remove(key); if (null != removedEntity) { this.entityMapModified = true; } return removedEntity; } public List<Ref<V>> preSaveAction() throws UnsupportedOperationException { if (!this.cls.isAnnotationPresent(Entity.class)) throw new UnsupportedOperationException("The class " + this.cls.getName() + " doesn't have Entity annotation, therefore a List<Ref<" + this.cls.getSimpleName() + ">> can't be generated."); if (!this.refsLoaded) return this.refsToLoad; if (null == this.entityMap || this.entityMap.isEmpty()) return Collections.emptyList(); if (this.entityMapModified) { if (null == this.entityRefs) { this.entityRefs = new ArrayList<>(this.entityMap.size()); } this.entityRefs.clear(); for (K key : this.entityMap.keySet()) { Ref<V> ref = GaeDataUtil.getNullableRefFromPojo(this.entityMap.get(key)); if (null != ref) { this.entityRefs.add(ref); } } this.entityMapModified = false; } return this.entityRefs; } public List<V> asList() { if (!this.refsLoaded) { loadRefs(); } if (null == this.entityMap || this.entityMap.isEmpty()) return Collections.emptyList(); if (null == this.entityList) { this.entityList = new ArrayList<>(this.entityMap.size()); } if (this.entityMapModified) { this.entityList.clear(); for (K key : this.entityMap.keySet()) { this.entityList.add(this.entityMap.get(key)); } this.entityMapModified = false; } return this.entityList; } public Map<K, V> asReadOnlyMap() { if (!this.refsLoaded) { loadRefs(); } return Collections.unmodifiableMap(this.entityMap); } // public void loadFromEntityRefs(List<Ref<V>> refs) { // if (null != refs) { // allocateMap(); // this.entityMap.clear(); // for (Ref<V> ref : refs) { // if (null == ref) { // continue; // } // V entity = ref.get(); // this.entityMap.put(this.keyGen.keyFor(entity), entity); // } // } //// throw new NotImplementedException("Not yet implemented."); // } public void loadFromEntities(List<V> entities) { if (null != entities && entities.size() > 0) { allocateMap(); this.entityMap.clear(); for (V entity : entities) { if (null == entity) { continue; } this.entityMap.put(this.keyGen.keyFor(entity), entity); } } } // protected void refsToLoad(List<Ref<V>> refsToLoad) { // this.refsToLoad = refsToLoad; // } protected void loadRefs() { if (null == this.entityMap) { allocateMap(); } Map<Key<V>, V> entities = GaeDataUtil.getByRefs(this.refsToLoad); for (Key<V> key : entities.keySet()) { V entity = entities.get(key); this.entityMap.put(this.keyGen.keyFor(entity), entity); } this.entityMapModified = true; this.refsLoaded = true; } protected void allocateMap() { if (null == this.entityMap) { this.entityMap = new LinkedHashMap<>(INITIAL_CAPACITY); } } }
src/main/java/com/hsjawanda/gaeobjectify/collections/EntityCollector.java
/** * */ package com.hsjawanda.gaeobjectify.collections; import static com.google.common.base.Preconditions.checkNotNull; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.googlecode.objectify.Key; import com.googlecode.objectify.Ref; import com.googlecode.objectify.annotation.Entity; import com.hsjawanda.gaeobjectify.data.GaeDataUtil; /** * @author harsh.deep * */ public class EntityCollector<K, V> { private static final int INITIAL_CAPACITY = 3; protected List<V> entityList; protected List<Ref<V>> entityRefs; protected List<Ref<V>> refsToLoad; protected Map<K, V> entityMap; protected KeyGenerator<K, V> keyGen; protected boolean entityMapModified = true; protected boolean hasEntityAnnotation = true; protected boolean refsLoaded = false; Class<V> cls; public static <K, V> EntityCollector<K, V> instance(Class<V> cls, KeyGenerator<K, V> keyGen) { checkNotNull(cls); checkNotNull(keyGen); EntityCollector<K, V> ec = new EntityCollector<>(); ec.cls = cls; ec.keyGen = keyGen; return ec; } public static <K, V> EntityCollector<K, V> instance(Class<V> cls, KeyGenerator<K, V> keyGen, List<Ref<V>> refsToLoad) { EntityCollector<K, V> ec = instance(cls, keyGen); ec.refsToLoad = refsToLoad; return ec; } public void add(V entity) { if (null == entity) return; if (!this.refsLoaded) { loadRefs(); } if (null == this.entityMap) { allocateMap(); } this.entityMap.put(this.keyGen.keyFor(entity), entity); this.entityMapModified = true; } public boolean containsValue(V entity) { if (null != this.entityMap) return this.entityMap.containsValue(entity); return false; } public V removeByKey(K key) { if (null == key || null == this.entityMap) return null; if (!this.refsLoaded) { loadRefs(); } V removedEntity = this.entityMap.remove(key); if (null != removedEntity) { this.entityMapModified = true; } return removedEntity; } public List<Ref<V>> preSaveAction() { if (!this.cls.isAnnotationPresent(Entity.class)) throw new UnsupportedOperationException("The class " + this.cls.getName() + " doesn't have Entity annotation, therefore a List<Ref<" + this.cls.getSimpleName() + ">> can't be generated."); if (null == this.entityMap || this.entityMap.isEmpty()) return Collections.emptyList(); if (!this.refsLoaded) return this.refsToLoad; if (this.entityMapModified) { if (null == this.entityRefs) { this.entityRefs = new ArrayList<>(this.entityMap.size()); } this.entityRefs.clear(); for (K key : this.entityMap.keySet()) { Ref<V> ref = GaeDataUtil.getNullableRefFromPojo(this.entityMap.get(key)); if (null != ref) { this.entityRefs.add(ref); } } this.entityMapModified = false; } return this.entityRefs; } public List<V> asList() { if (null == this.entityMap || this.entityMap.isEmpty()) return Collections.emptyList(); if (null == this.entityList) { this.entityList = new ArrayList<>(this.entityMap.size()); } if (!this.refsLoaded) { loadRefs(); } if (this.entityMapModified) { this.entityList.clear(); for (K key : this.entityMap.keySet()) { this.entityList.add(this.entityMap.get(key)); } this.entityMapModified = false; } return this.entityList; } public Map<K, V> asMap() { return Collections.unmodifiableMap(this.entityMap); } public void loadFromEntityRefs(List<Ref<V>> refs) { if (null != refs) { allocateMap(); this.entityMap.clear(); for (Ref<V> ref : refs) { if (null == ref) { continue; } V entity = ref.get(); this.entityMap.put(this.keyGen.keyFor(entity), entity); } } // throw new NotImplementedException("Not yet implemented."); } public void loadFromEntities(List<V> entities) { if (null != entities && entities.size() > 0) { allocateMap(); this.entityMap.clear(); for (V entity : entities) { if (null == entity) { continue; } this.entityMap.put(this.keyGen.keyFor(entity), entity); } } } // protected void refsToLoad(List<Ref<V>> refsToLoad) { // this.refsToLoad = refsToLoad; // } protected void loadRefs() { if (null == this.entityMap) { allocateMap(); } Map<Key<V>, V> entities = GaeDataUtil.getByRefs(this.refsToLoad); for (Key<V> key : entities.keySet()) { V entity = entities.get(key); this.entityMap.put(this.keyGen.keyFor(entity), entity); } this.entityMapModified = true; this.refsLoaded = true; } protected void allocateMap() { if (null == this.entityMap) { this.entityMap = new LinkedHashMap<>(INITIAL_CAPACITY); } } }
Updates to load entities from DS only if needed, and when needed, to do a batch load (more efficient).
src/main/java/com/hsjawanda/gaeobjectify/collections/EntityCollector.java
Updates to load entities from DS only if needed, and when needed, to do a batch load (more efficient).
Java
apache-2.0
b9c23a3312b0211914fc4eea42dd99ddc9754087
0
kenschneider18/zuul,mrohan01/zuul,mrohan01/zuul,luke-grey/zuul-project,mattnelson/zuul,datvikash/zuul,NiteshKant/zuul,jsebastian/zuul,jsebastian/zuul,Fsero/zuul,rspieldenner/zuul,gorcz/zuul,Netflix/zuul,Fsero/zuul,kpacha/zuul,rspieldenner/zuul,jaume-pinyol/zuul,mattnelson/zuul,NiteshKant/zuul,slachiewicz/zuul,jaume-pinyol/zuul,kenschneider18/zuul
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.util; import com.netflix.zuul.context.RequestContext; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Some handy methods for workign with HTTP requests * @author Mikey Cohen * Date: 2/10/12 * Time: 8:22 AM */ public class HTTPRequestUtils { private final static HTTPRequestUtils INSTANCE = new HTTPRequestUtils(); public static final String X_FORWARDED_FOR_HEADER = "x-forwarded-for"; /** * Get the IP address of client making the request. * * Uses the "x-forwarded-for" HTTP header if available, otherwise uses the remote * IP of requester. * * @param request <code>HttpServletRequest</code> * @return <code>String</code> IP address */ public String getClientIP(HttpServletRequest request) { final String xForwardedFor = request.getHeader(X_FORWARDED_FOR_HEADER); String clientIP = null; if (xForwardedFor == null) { clientIP = request.getRemoteAddr(); } else { clientIP = extractClientIpFromXForwardedFor(xForwardedFor); } return clientIP; } /** * Extract the client IP address from an x-forwarded-for header. Returns null if there is no x-forwarded-for header * * @param xForwardedFor a <code>String</code> value * @return a <code>String</code> value */ public final String extractClientIpFromXForwardedFor(String xForwardedFor) { if (xForwardedFor == null) { return null; } xForwardedFor = xForwardedFor.trim(); String tokenized[] = xForwardedFor.split(","); if (tokenized.length == 0) { return null; } else { return tokenized[0].trim(); } } /** * return singleton HTTPRequestUtils object * * @return a <code>HTTPRequestUtils</code> value */ public static HTTPRequestUtils getInstance() { return INSTANCE; } /** * returns the Header value for the given sHeaderName * * @param sHeaderName a <code>String</code> value * @return a <code>String</code> value */ public String getHeaderValue(String sHeaderName) { return RequestContext.getCurrentContext().getRequest().getHeader(sHeaderName); } /** * returns a form value from a given sHeaderName * * @param sHeaderName a <code>String</code> value * @return a <code>String</code> value */ public String getFormValue(String sHeaderName) { return RequestContext.getCurrentContext().getRequest().getParameter(sHeaderName); } /** * returns headers as a Map with String keys and Lists of Strings as values * @return */ public Map<String, List<String>> getRequestHeaderMap() { HttpServletRequest request = RequestContext.getCurrentContext().getRequest(); Map<String,List<String>> headers = new HashMap<String,List<String>>(); Enumeration<String> headerNames = request.getHeaderNames(); if(headerNames != null) { while (headerNames.hasMoreElements()) { String name = headerNames.nextElement().toLowerCase(); String value = request.getHeader(name); List<String> valueList = new ArrayList<String>(); if(headers.containsKey(name)) { headers.get(name).add(value); } valueList.add(value); headers.put(name, valueList); } } return Collections.unmodifiableMap(headers); } /** * returns query params as a Map with String keys and Lists of Strings as values * @return */ public Map<String, List<String>> getQueryParams() { Map<String, List<String>> qp = RequestContext.getCurrentContext().getRequestQueryParams(); if (qp != null) return qp; HttpServletRequest request = RequestContext.getCurrentContext().getRequest(); qp = new HashMap<String, List<String>>(); if (request.getQueryString() == null) return null; StringTokenizer st = new StringTokenizer(request.getQueryString(), "&"); int i; while (st.hasMoreTokens()) { String s = st.nextToken(); i = s.indexOf("="); if (i > 0 && s.length() > i + 1) { String name = s.substring(0, i); String value = s.substring(i + 1); try { name = URLDecoder.decode(name, "UTF-8"); } catch (Exception e) { } try { value = URLDecoder.decode(value, "UTF-8"); } catch (Exception e) { } List<String> valueList = qp.get(name); if (valueList == null) { valueList = new LinkedList<String>(); qp.put(name, valueList); } valueList.add(value); } } RequestContext.getCurrentContext().setRequestQueryParams(qp); return qp; } /** * Checks headers, query string, and form body for a given parameter * * @param sName * @return */ public String getValueFromRequestElements(String sName) { String sValue = null; if (getQueryParams() != null) { final List<String> v = getQueryParams().get(sName); if (v != null && !v.isEmpty()) sValue = v.iterator().next(); } if (sValue != null) return sValue; sValue = getHeaderValue(sName); if (sValue != null) return sValue; sValue = getFormValue(sName); if (sValue != null) return sValue; return null; } /** * return true if the client requested gzip content * * @param contentEncoding a <code>String</code> value * @return true if the content-encoding param containg gzip */ public boolean isGzipped(String contentEncoding) { return contentEncoding.contains("gzip"); } public static class UnitTest { @Test public void detectsGzip() { assertTrue(HTTPRequestUtils.getInstance().isGzipped("gzip")); } @Test public void detectsNonGzip() { assertFalse(HTTPRequestUtils.getInstance().isGzipped("identity")); } @Test public void detectsGzipAmongOtherEncodings() { assertTrue(HTTPRequestUtils.getInstance().isGzipped("gzip, deflate")); } } }
zuul-core/src/main/java/com/netflix/zuul/util/HTTPRequestUtils.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.util; import com.netflix.zuul.context.RequestContext; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import java.net.URLDecoder; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Some handy methods for workign with HTTP requests * @author Mikey Cohen * Date: 2/10/12 * Time: 8:22 AM */ public class HTTPRequestUtils { private final static HTTPRequestUtils INSTANCE = new HTTPRequestUtils(); public static final String X_FORWARDED_FOR_HEADER = "x-forwarded-for"; /** * Get the IP address of client making the request. * * Uses the "x-forwarded-for" HTTP header if available, otherwise uses the remote * IP of requester. * * @param request <code>HttpServletRequest</code> * @return <code>String</code> IP address */ public String getClientIP(HttpServletRequest request) { final String xForwardedFor = request.getHeader(X_FORWARDED_FOR_HEADER); String clientIP = null; if (xForwardedFor == null) { clientIP = request.getRemoteAddr(); } else { clientIP = extractClientIpFromXForwardedFor(xForwardedFor); } return clientIP; } /** * Extract the client IP address from an x-forwarded-for header. Returns null if there is no x-forwarded-for header * * @param xForwardedFor a <code>String</code> value * @return a <code>String</code> value */ public final String extractClientIpFromXForwardedFor(String xForwardedFor) { if (xForwardedFor == null) { return null; } xForwardedFor = xForwardedFor.trim(); String tokenized[] = xForwardedFor.split(","); if (tokenized.length == 0) { return null; } else { return tokenized[0].trim(); } } /** * return singleton HTTPRequestUtils object * * @return a <code>HTTPRequestUtils</code> value */ public static HTTPRequestUtils getInstance() { return INSTANCE; } /** * returns the Header value for the given sHeaderName * * @param sHeaderName a <code>String</code> value * @return a <code>String</code> value */ public String getHeaderValue(String sHeaderName) { return RequestContext.getCurrentContext().getRequest().getHeader(sHeaderName); } /** * returns a form value from a given sHeaderName * * @param sHeaderName a <code>String</code> value * @return a <code>String</code> value */ public String getFormValue(String sHeaderName) { return RequestContext.getCurrentContext().getRequest().getParameter(sHeaderName); } /** * returns query params as a Map with String keys and Lists of Strings as values * @return */ public Map<String, List<String>> getQueryParams() { Map<String, List<String>> qp = RequestContext.getCurrentContext().getRequestQueryParams(); if (qp != null) return qp; HttpServletRequest request = RequestContext.getCurrentContext().getRequest(); qp = new HashMap<String, List<String>>(); if (request.getQueryString() == null) return null; StringTokenizer st = new StringTokenizer(request.getQueryString(), "&"); int i; while (st.hasMoreTokens()) { String s = st.nextToken(); i = s.indexOf("="); if (i > 0 && s.length() > i + 1) { String name = s.substring(0, i); String value = s.substring(i + 1); try { name = URLDecoder.decode(name, "UTF-8"); } catch (Exception e) { } try { value = URLDecoder.decode(value, "UTF-8"); } catch (Exception e) { } List valueList = qp.get(name); if (valueList == null) { valueList = new LinkedList<String>(); qp.put(name, valueList); } valueList.add(value); } } RequestContext.getCurrentContext().setRequestQueryParams(qp); return qp; } /** * Checks headers, query string, and form body for a given parameter * * @param sName * @return */ public String getValueFromRequestElements(String sName) { String sValue = null; if (getQueryParams() != null) { final List<String> v = getQueryParams().get(sName); if (v != null && !v.isEmpty()) sValue = v.iterator().next(); } if (sValue != null) return sValue; sValue = getHeaderValue(sName); if (sValue != null) return sValue; sValue = getFormValue(sName); if (sValue != null) return sValue; return null; } /** * return true if the client requested gzip content * * @param contentEncoding a <code>String</code> value * @return true if the content-encoding param containg gzip */ public boolean isGzipped(String contentEncoding) { return contentEncoding.contains("gzip"); } public static class UnitTest { @Test public void detectsGzip() { assertTrue(HTTPRequestUtils.getInstance().isGzipped("gzip")); } @Test public void detectsNonGzip() { assertFalse(HTTPRequestUtils.getInstance().isGzipped("identity")); } @Test public void detectsGzipAmongOtherEncodings() { assertTrue(HTTPRequestUtils.getInstance().isGzipped("gzip, deflate")); } } }
Add helper method to retrieve headers
zuul-core/src/main/java/com/netflix/zuul/util/HTTPRequestUtils.java
Add helper method to retrieve headers
Java
apache-2.0
d71ea36b7883c2133167fac9cb192f8cae510eab
0
openam-org-ru/org.jsmpp,openam-org-ru/org.jsmpp,amdtelecom/jsmpp,opentelecoms-org/jsmpp,pmoerenhout/jsmpp-1,amdtelecom/jsmpp,opentelecoms-org/jsmpp,pmoerenhout/jsmpp-1
package org.jsmpp.bean; import static org.testng.Assert.assertEquals; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * @author pmoerenhout */ public class DataCodingFactory1100Test { DataCodingFactory1100 factory; @BeforeMethod public void setUp() throws Exception { factory = new DataCodingFactory1100(); } @Test public void testDataCodings1100() { for (byte dataCodingByte = (byte) 0xc0; dataCodingByte < (byte) 0xd0; dataCodingByte++) { DataCoding dataCoding = factory.newInstance(dataCodingByte); assertEquals(dataCoding.getClass(), MessageWaitingDataCoding.class); // assertEquals(Alphabet.parseDataCoding(dataCoding.toByte()), Alphabet.ALPHA_DEFAULT); } } }
jsmpp/src/test/java/org/jsmpp/bean/DataCodingFactory1100Test.java
package org.jsmpp.bean; import static org.testng.Assert.assertEquals; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * @author pmoerenhout */ public class DataCodingFactory1100Test { DataCodingFactory1100 factory; @BeforeMethod public void setUp() throws Exception { factory = new DataCodingFactory1100(); } @Test public void testDataCodings1100() { for (byte dataCodingByte = (byte) 0xc0; dataCodingByte < (byte) 0xd0; dataCodingByte++) { DataCoding dataCoding = factory.newInstance(dataCodingByte); assertEquals(dataCoding.getClass(), MessageWaitingDataCoding.class); assertEquals(Alphabet.parseDataCoding(dataCoding.toByte()), Alphabet.ALPHA_DEFAULT); } } }
Fix testcase.
jsmpp/src/test/java/org/jsmpp/bean/DataCodingFactory1100Test.java
Fix testcase.
Java
apache-2.0
8e7a4b24562654455abea9b1dafbeb203b6a64d6
0
reactor/reactor-core,sdeleuze/reactor-core,sdeleuze/reactor-core,sdeleuze/reactor-core,sdeleuze/reactor-core
/* * Copyright (c) 2011-2016 Pivotal Software Inc, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package reactor.core.util; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import java.util.logging.Level; import java.util.regex.Matcher; /** * Repackaged Logger for internal purposes. Will pick up the existing * logger implementation. Refer to the individual factories for more information. */ public abstract class Logger { public static final int SUBSCRIBE = 0b010000000; public static final int ON_SUBSCRIBE = 0b001000000; public static final int ON_NEXT = 0b000100000; public static final int ON_ERROR = 0b000010000; public static final int ON_COMPLETE = 0b000001000; public static final int REQUEST = 0b000000100; public static final int CANCEL = 0b000000010; public static final int TERMINAL = CANCEL | ON_COMPLETE | ON_ERROR; public static final int ALL = TERMINAL | REQUEST | ON_SUBSCRIBE | ON_NEXT | SUBSCRIBE; private final static LoggerFactory defaultFactory = newDefaultFactory(LoggerFactory.class.getName()); private static final AtomicReferenceFieldUpdater<GlobalExtension, Extension> EXTENSION = PlatformDependent.newAtomicReferenceFieldUpdater(GlobalExtension.class, "extension"); private static LoggerFactory newDefaultFactory(String name) { LoggerFactory f; try { f = new Slf4JLoggerFactory(); f.getLogger(name) .debug("Using Slf4j logging framework"); } catch (Throwable t1) { f = new JdkLoggerFactory(); f.getLogger(name) .debug("Using JDK logging framework"); } return f; } /** * Try getting an appropriate * {@link Logger} whether SLF4J is not present on the classpath or fallback to {@link java.util.logging.Logger}. * * @param name the category or logger name to assign * * @return a new {@link Logger} instance */ public static Logger getLogger(String name) { return defaultFactory.getLogger(name); } /** * Try getting an appropriate * {@link Logger} whether SLF4J is not present on the classpath or fallback to {@link java.util.logging.Logger}. * * @param klass the source {@link Class} to derive the name from. * * @return a new {@link Logger} instance */ public static Logger getLogger(Class<?> klass) { return defaultFactory.getLogger(klass.getName()); } /** * Define a globally set {@link Extension} callback to observe logging statements. * * @param extension the {@link Extension} plugin to provide globally * * @return true if extensions have been successfully enabled */ public static boolean enableExtension(Extension extension) { return EXTENSION.compareAndSet(LoggerFactory.globalExtension, null, extension); } /** * Unsubscribe the passed {@link Extension} reference if currently available globally. * * @param extension the {@link Extension} to unregister * * @return true if successfully unregistered */ public static boolean disableExtension(Extension extension) { if(EXTENSION.compareAndSet(LoggerFactory.globalExtension, extension, null)){ LoggerFactory.globalExtension.cachedExtension = null; return true; } return false; } /** * Format a {@link String} using curly brackets for interpolling * * @param from Origin String * @param arguments objects to interpolate from the passed String * @return the formatted {@link String} */ public static String format(String from, Object... arguments){ if(from != null) { String computed = from; if (arguments != null && arguments.length != 0) { for (Object argument : arguments) { computed = computed.replaceFirst("\\{\\}", Matcher.quoteReplacement(argument.toString())); } } return computed; } return null; } interface LoggerFactory { GlobalExtension globalExtension = new GlobalExtension(); Logger getLogger(String name); } /** * A callback to observe logging statements that can be assigned globally via * {@link Logger#enableExtension(Extension)}. */ @FunctionalInterface public interface Extension { void log(String category, Level level, String msg, Object... arguments); } /** * Return the name of this <code>Logger</code> instance. * @return name of this logger instance */ public abstract String getName(); /** * Is the logger instance enabled for the TRACE level? * * @return True if this Logger is enabled for the TRACE level, * false otherwise. */ public abstract boolean isTraceEnabled(); /** * Log a message at the TRACE level. * * @param msg the message string to be logged */ public abstract void trace(String msg); /** * Log a message at the TRACE level according to the specified format * and arguments. * <p/> * <p>This form avoids superfluous string concatenation when the logger * is disabled for the TRACE level. However, this variant incurs the hidden * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method, * even if this logger is disabled for TRACE.</p> * * @param format the format string * @param arguments a list of 3 or more arguments */ public abstract void trace(String format, Object... arguments); /** * Log an exception (throwable) at the TRACE level with an * accompanying message. * * @param msg the message accompanying the exception * @param t the exception (throwable) to log */ public abstract void trace(String msg, Throwable t); /** * Is the logger instance enabled for the DEBUG level? * * @return True if this Logger is enabled for the DEBUG level, * false otherwise. */ public abstract boolean isDebugEnabled(); /** * Log a message at the DEBUG level. * * @param msg the message string to be logged */ public abstract void debug(String msg); /** * Log a message at the DEBUG level according to the specified format * and arguments. * <p/> * <p>This form avoids superfluous string concatenation when the logger * is disabled for the DEBUG level. However, this variant incurs the hidden * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method, * even if this logger is disabled for DEBUG. </p> * * @param format the format string * @param arguments a list of 3 or more arguments */ public abstract void debug(String format, Object... arguments); /** * Log an exception (throwable) at the DEBUG level with an * accompanying message. * * @param msg the message accompanying the exception * @param t the exception (throwable) to log */ public abstract void debug(String msg, Throwable t); /** * Is the logger instance enabled for the INFO level? * * @return True if this Logger is enabled for the INFO level, * false otherwise. */ public abstract boolean isInfoEnabled(); /** * Log a message at the INFO level. * * @param msg the message string to be logged */ public abstract void info(String msg); /** * Log a message at the INFO level according to the specified format * and arguments. * <p/> * <p>This form avoids superfluous string concatenation when the logger * is disabled for the INFO level. However, this variant incurs the hidden * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method, * even if this logger is disabled for INFO. </p> * * @param format the format string * @param arguments a list of 3 or more arguments */ public abstract void info(String format, Object... arguments); /** * Log an exception (throwable) at the INFO level with an * accompanying message. * * @param msg the message accompanying the exception * @param t the exception (throwable) to log */ public abstract void info(String msg, Throwable t); /** * Is the logger instance enabled for the WARN level? * * @return True if this Logger is enabled for the WARN level, * false otherwise. */ public abstract boolean isWarnEnabled(); /** * Log a message at the WARN level. * * @param msg the message string to be logged */ public abstract void warn(String msg); /** * Log a message at the WARN level according to the specified format * and arguments. * <p/> * <p>This form avoids superfluous string concatenation when the logger * is disabled for the WARN level. However, this variant incurs the hidden * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method, * even if this logger is disabled for WARN. </p> * * @param format the format string * @param arguments a list of 3 or more arguments */ public abstract void warn(String format, Object... arguments); /** * Log an exception (throwable) at the WARN level with an * accompanying message. * * @param msg the message accompanying the exception * @param t the exception (throwable) to log */ public abstract void warn(String msg, Throwable t); /** * Is the logger instance enabled for the ERROR level? * * @return True if this Logger is enabled for the ERROR level, * false otherwise. */ public abstract boolean isErrorEnabled(); /** * Log a message at the ERROR level. * * @param msg the message string to be logged */ public abstract void error(String msg); /** * Log a message at the ERROR level according to the specified format * and arguments. * <p/> * <p>This form avoids superfluous string concatenation when the logger * is disabled for the ERROR level. However, this variant incurs the hidden * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method, * even if this logger is disabled for ERROR. </p> * * @param format the format string * @param arguments a list of 3 or more arguments */ public abstract void error(String format, Object... arguments); /** * Log an exception (throwable) at the ERROR level with an * accompanying message. * * @param msg the message accompanying the exception * @param t the exception (throwable) to log */ public abstract void error(String msg, Throwable t); private static class Slf4JLoggerFactory implements LoggerFactory { @Override public Logger getLogger(String name) { return new Slf4JLogger(org.slf4j.LoggerFactory.getLogger(name)); } } /** * Wrapper over Slf4j Logger */ private static class Slf4JLogger extends Logger { private final org.slf4j.Logger logger; public Slf4JLogger(org.slf4j.Logger logger) { this.logger = logger; } @Override public String getName() { return logger.getName(); } @Override public boolean isTraceEnabled() { return logger.isTraceEnabled(); } @Override public void trace(String msg) { logger.trace(msg); LoggerFactory.globalExtension.log(logger.getName(), Level.FINEST, msg); } @Override public void trace(String format, Object... arguments) { logger.trace(format, arguments); LoggerFactory.globalExtension.log(logger.getName(), Level.FINEST, format, arguments); } @Override public void trace(String msg, Throwable t) { logger.trace(msg, t); LoggerFactory.globalExtension.log(logger.getName(), Level.FINEST, msg, t); } @Override public boolean isDebugEnabled() { return logger.isDebugEnabled(); } @Override public void debug(String msg) { logger.debug(msg); LoggerFactory.globalExtension.log(logger.getName(), Level.FINE, msg); } @Override public void debug(String format, Object... arguments) { logger.debug(format, arguments); LoggerFactory.globalExtension.log(logger.getName(), Level.FINE, format, arguments); } @Override public void debug(String msg, Throwable t) { logger.debug(msg, t); LoggerFactory.globalExtension.log(logger.getName(), Level.FINE, msg, t); } @Override public boolean isInfoEnabled() { return logger.isInfoEnabled(); } @Override public void info(String msg) { logger.info(msg); LoggerFactory.globalExtension.log(logger.getName(), Level.INFO, msg); } @Override public void info(String format, Object... arguments) { logger.info(format, arguments); LoggerFactory.globalExtension.log(logger.getName(), Level.INFO, format, arguments); } @Override public void info(String msg, Throwable t) { logger.info(msg, t); LoggerFactory.globalExtension.log(logger.getName(), Level.INFO, msg, t); } @Override public boolean isWarnEnabled() { return logger.isWarnEnabled(); } @Override public void warn(String msg) { logger.warn(msg); LoggerFactory.globalExtension.log(logger.getName(), Level.WARNING, msg); } @Override public void warn(String format, Object... arguments) { logger.warn(format, arguments); LoggerFactory.globalExtension.log(logger.getName(), Level.WARNING, format, arguments); } @Override public void warn(String msg, Throwable t) { logger.warn(msg, t); LoggerFactory.globalExtension.log(logger.getName(), Level.WARNING, msg, t); } @Override public boolean isErrorEnabled() { return logger.isErrorEnabled(); } @Override public void error(String msg) { logger.error(msg); LoggerFactory.globalExtension.log(logger.getName(), Level.SEVERE, msg); } @Override public void error(String format, Object... arguments) { logger.error(format, arguments); LoggerFactory.globalExtension.log(logger.getName(), Level.SEVERE, format, arguments); } @Override public void error(String msg, Throwable t) { logger.error(msg, t); LoggerFactory.globalExtension.log(logger.getName(), Level.SEVERE, msg, t); } } private static class JdkLoggerFactory implements LoggerFactory { @Override public Logger getLogger(String name) { return new JdkLogger(java.util.logging.Logger.getLogger(name)); } } /** * Wrapper over JDK logger */ private static class JdkLogger extends Logger { private final java.util.logging.Logger logger; public JdkLogger(java.util.logging.Logger logger) { this.logger = logger; } @Override public String getName() { return logger.getName(); } @Override public boolean isTraceEnabled() { return logger.isLoggable(Level.FINEST); } @Override public void trace(String msg) { if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, msg); LoggerFactory.globalExtension.log(logger.getName(), Level.FINEST, msg); } } @Override public void trace(String format, Object... arguments) { if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, format(format, arguments)); LoggerFactory.globalExtension.log(logger.getName(), Level.FINEST, format, arguments); } } @Override public void trace(String msg, Throwable t) { if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, msg, t); LoggerFactory.globalExtension.log(logger.getName(), Level.FINEST, msg, t); } } @Override public boolean isDebugEnabled() { return logger.isLoggable(Level.FINE); } @Override public void debug(String msg) { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, msg); LoggerFactory.globalExtension.log(logger.getName(), Level.FINE, msg); } } @Override public void debug(String format, Object... arguments) { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, format(format, arguments)); LoggerFactory.globalExtension.log(logger.getName(), Level.FINE, format, arguments); } } @Override public void debug(String msg, Throwable t) { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, msg, t); LoggerFactory.globalExtension.log(logger.getName(), Level.FINE, msg, t); } } @Override public boolean isInfoEnabled() { return logger.isLoggable(Level.INFO); } @Override public void info(String msg) { if (logger.isLoggable(Level.INFO)) { logger.log(Level.INFO, msg); LoggerFactory.globalExtension.log(logger.getName(), Level.INFO, msg); } } @Override public void info(String format, Object... arguments) { if (logger.isLoggable(Level.INFO)) { logger.log(Level.INFO, format(format, arguments)); LoggerFactory.globalExtension.log(logger.getName(), Level.INFO, format, arguments); } } @Override public void info(String msg, Throwable t) { if (logger.isLoggable(Level.INFO)) { logger.log(Level.INFO, msg, t); LoggerFactory.globalExtension.log(logger.getName(), Level.INFO, msg, t); } } @Override public boolean isWarnEnabled() { return logger.isLoggable(Level.WARNING); } @Override public void warn(String msg) { if (logger.isLoggable(Level.WARNING)) { logger.log(Level.WARNING, msg); LoggerFactory.globalExtension.log(logger.getName(), Level.WARNING, msg); } } @Override public void warn(String format, Object... arguments) { if (logger.isLoggable(Level.WARNING)) { logger.log(Level.WARNING, format(format, arguments)); LoggerFactory.globalExtension.log(logger.getName(), Level.WARNING, format, arguments); } } @Override public void warn(String msg, Throwable t) { if (logger.isLoggable(Level.WARNING)) { logger.log(Level.WARNING, msg, t); LoggerFactory.globalExtension.log(logger.getName(), Level.WARNING, msg, t); } } @Override public boolean isErrorEnabled() { return logger.isLoggable(Level.SEVERE); } @Override public void error(String msg) { if (logger.isLoggable(Level.SEVERE)) { logger.log(Level.SEVERE, msg); LoggerFactory.globalExtension.log(logger.getName(), Level.SEVERE, msg); } } @Override public void error(String format, Object... arguments) { if (logger.isLoggable(Level.SEVERE)) { logger.log(Level.SEVERE, format(format, arguments)); LoggerFactory.globalExtension.log(logger.getName(), Level.SEVERE, format, arguments); } } @Override public void error(String msg, Throwable t) { if (logger.isLoggable(Level.SEVERE)) { logger.log(Level.SEVERE, msg, t); LoggerFactory.globalExtension.log(logger.getName(), Level.SEVERE, msg, t); } } } private static class GlobalExtension implements Extension { private volatile Extension extension; private Extension cachedExtension; @Override public void log(String category, Level level, String msg, Object... arguments) { if (cachedExtension == null) { cachedExtension = extension; if (cachedExtension == null) { return; } } cachedExtension.log(category, level, msg, arguments); } } }
src/main/java/reactor/core/util/Logger.java
/* * Copyright (c) 2011-2016 Pivotal Software Inc, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package reactor.core.util; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import java.util.logging.Level; import java.util.regex.Matcher; /** * Repackaged Logger for internal purposes. Will pick up the existing * logger implementation. Refer to the individual factories for more information. */ public abstract class Logger { public static final int SUBSCRIBE = 0b010000000; public static final int ON_SUBSCRIBE = 0b001000000; public static final int ON_NEXT = 0b000100000; public static final int ON_ERROR = 0b000010000; public static final int ON_COMPLETE = 0b000001000; public static final int REQUEST = 0b000000100; public static final int CANCEL = 0b000000010; public static final int TERMINAL = CANCEL | ON_COMPLETE | ON_ERROR; public static final int ALL = TERMINAL | REQUEST | ON_SUBSCRIBE | ON_NEXT | SUBSCRIBE; private final static LoggerFactory defaultFactory = newDefaultFactory(LoggerFactory.class.getName()); private static final AtomicReferenceFieldUpdater<GlobalExtension, Extension> EXTENSION = PlatformDependent.newAtomicReferenceFieldUpdater(GlobalExtension.class, "extension"); private static LoggerFactory newDefaultFactory(String name) { LoggerFactory f; try { f = new Slf4JLoggerFactory(); f.getLogger(name) .debug("Using Slf4j logging framework"); } catch (Throwable t1) { f = new JdkLoggerFactory(); f.getLogger(name) .debug("Using JDK logging framework"); } return f; } /** * Try getting an appropriate * {@link Logger} whether SLF4J is not present on the classpath or fallback to {@link java.util.logging.Logger}. * * @param name the category or logger name to assign * * @return a new {@link Logger} instance */ public static Logger getLogger(String name) { return defaultFactory.getLogger(name); } /** * Try getting an appropriate * {@link Logger} whether SLF4J is not present on the classpath or fallback to {@link java.util.logging.Logger}. * * @param klass the source {@link Class} to derive the name from. * * @return a new {@link Logger} instance */ public static Logger getLogger(Class<?> klass) { return defaultFactory.getLogger(klass.getName()); } /** * Define a globally set {@link Extension} callback to observe logging statements. * * @param extension the {@link Extension} plugin to provide globally * * @return true if extensions have been successfully enabled */ public static boolean enableExtension(Extension extension) { return EXTENSION.compareAndSet(LoggerFactory.globalExtension, null, extension); } /** * Unsubscribe the passed {@link Extension} reference if currently available globally. * * @param extension the {@link Extension} to unregister * * @return true if successfully unregistered */ public static boolean disableExtension(Extension extension) { if(EXTENSION.compareAndSet(LoggerFactory.globalExtension, extension, null)){ LoggerFactory.globalExtension.cachedExtension = null; return true; } return false; } /** * Format a {@link String} using curly brackets for interpolling * * @param from Origin String * @param arguments objects to interpolate from the passed String * @return the formatted {@link String} */ public static String format(String from, Object... arguments){ if(from != null) { String computed = from; if (arguments != null && arguments.length != 0) { for (Object argument : arguments) { computed = computed.replaceFirst("\\{\\}", Matcher.quoteReplacement(argument.toString())); } } return computed; } return null; } interface LoggerFactory { GlobalExtension globalExtension = new GlobalExtension(); Logger getLogger(String name); } /** * A callback to observe logging statements that can be assigned globally via * {@link Logger#enableExtension(Extension)}. */ public interface Extension { void log(String category, Level level, String msg, Object... arguments); } /** * Return the name of this <code>Logger</code> instance. * @return name of this logger instance */ public abstract String getName(); /** * Is the logger instance enabled for the TRACE level? * * @return True if this Logger is enabled for the TRACE level, * false otherwise. */ public abstract boolean isTraceEnabled(); /** * Log a message at the TRACE level. * * @param msg the message string to be logged */ public abstract void trace(String msg); /** * Log a message at the TRACE level according to the specified format * and arguments. * <p/> * <p>This form avoids superfluous string concatenation when the logger * is disabled for the TRACE level. However, this variant incurs the hidden * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method, * even if this logger is disabled for TRACE.</p> * * @param format the format string * @param arguments a list of 3 or more arguments */ public abstract void trace(String format, Object... arguments); /** * Log an exception (throwable) at the TRACE level with an * accompanying message. * * @param msg the message accompanying the exception * @param t the exception (throwable) to log */ public abstract void trace(String msg, Throwable t); /** * Is the logger instance enabled for the DEBUG level? * * @return True if this Logger is enabled for the DEBUG level, * false otherwise. */ public abstract boolean isDebugEnabled(); /** * Log a message at the DEBUG level. * * @param msg the message string to be logged */ public abstract void debug(String msg); /** * Log a message at the DEBUG level according to the specified format * and arguments. * <p/> * <p>This form avoids superfluous string concatenation when the logger * is disabled for the DEBUG level. However, this variant incurs the hidden * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method, * even if this logger is disabled for DEBUG. </p> * * @param format the format string * @param arguments a list of 3 or more arguments */ public abstract void debug(String format, Object... arguments); /** * Log an exception (throwable) at the DEBUG level with an * accompanying message. * * @param msg the message accompanying the exception * @param t the exception (throwable) to log */ public abstract void debug(String msg, Throwable t); /** * Is the logger instance enabled for the INFO level? * * @return True if this Logger is enabled for the INFO level, * false otherwise. */ public abstract boolean isInfoEnabled(); /** * Log a message at the INFO level. * * @param msg the message string to be logged */ public abstract void info(String msg); /** * Log a message at the INFO level according to the specified format * and arguments. * <p/> * <p>This form avoids superfluous string concatenation when the logger * is disabled for the INFO level. However, this variant incurs the hidden * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method, * even if this logger is disabled for INFO. </p> * * @param format the format string * @param arguments a list of 3 or more arguments */ public abstract void info(String format, Object... arguments); /** * Log an exception (throwable) at the INFO level with an * accompanying message. * * @param msg the message accompanying the exception * @param t the exception (throwable) to log */ public abstract void info(String msg, Throwable t); /** * Is the logger instance enabled for the WARN level? * * @return True if this Logger is enabled for the WARN level, * false otherwise. */ public abstract boolean isWarnEnabled(); /** * Log a message at the WARN level. * * @param msg the message string to be logged */ public abstract void warn(String msg); /** * Log a message at the WARN level according to the specified format * and arguments. * <p/> * <p>This form avoids superfluous string concatenation when the logger * is disabled for the WARN level. However, this variant incurs the hidden * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method, * even if this logger is disabled for WARN. </p> * * @param format the format string * @param arguments a list of 3 or more arguments */ public abstract void warn(String format, Object... arguments); /** * Log an exception (throwable) at the WARN level with an * accompanying message. * * @param msg the message accompanying the exception * @param t the exception (throwable) to log */ public abstract void warn(String msg, Throwable t); /** * Is the logger instance enabled for the ERROR level? * * @return True if this Logger is enabled for the ERROR level, * false otherwise. */ public abstract boolean isErrorEnabled(); /** * Log a message at the ERROR level. * * @param msg the message string to be logged */ public abstract void error(String msg); /** * Log a message at the ERROR level according to the specified format * and arguments. * <p/> * <p>This form avoids superfluous string concatenation when the logger * is disabled for the ERROR level. However, this variant incurs the hidden * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method, * even if this logger is disabled for ERROR. </p> * * @param format the format string * @param arguments a list of 3 or more arguments */ public abstract void error(String format, Object... arguments); /** * Log an exception (throwable) at the ERROR level with an * accompanying message. * * @param msg the message accompanying the exception * @param t the exception (throwable) to log */ public abstract void error(String msg, Throwable t); private static class Slf4JLoggerFactory implements LoggerFactory { @Override public Logger getLogger(String name) { return new Slf4JLogger(org.slf4j.LoggerFactory.getLogger(name)); } } /** * Wrapper over Slf4j Logger */ private static class Slf4JLogger extends Logger { private final org.slf4j.Logger logger; public Slf4JLogger(org.slf4j.Logger logger) { this.logger = logger; } @Override public String getName() { return logger.getName(); } @Override public boolean isTraceEnabled() { return logger.isTraceEnabled(); } @Override public void trace(String msg) { logger.trace(msg); LoggerFactory.globalExtension.log(logger.getName(), Level.FINEST, msg); } @Override public void trace(String format, Object... arguments) { logger.trace(format, arguments); LoggerFactory.globalExtension.log(logger.getName(), Level.FINEST, format, arguments); } @Override public void trace(String msg, Throwable t) { logger.trace(msg, t); LoggerFactory.globalExtension.log(logger.getName(), Level.FINEST, msg, t); } @Override public boolean isDebugEnabled() { return logger.isDebugEnabled(); } @Override public void debug(String msg) { logger.debug(msg); LoggerFactory.globalExtension.log(logger.getName(), Level.FINE, msg); } @Override public void debug(String format, Object... arguments) { logger.debug(format, arguments); LoggerFactory.globalExtension.log(logger.getName(), Level.FINE, format, arguments); } @Override public void debug(String msg, Throwable t) { logger.debug(msg, t); LoggerFactory.globalExtension.log(logger.getName(), Level.FINE, msg, t); } @Override public boolean isInfoEnabled() { return logger.isInfoEnabled(); } @Override public void info(String msg) { logger.info(msg); LoggerFactory.globalExtension.log(logger.getName(), Level.INFO, msg); } @Override public void info(String format, Object... arguments) { logger.info(format, arguments); LoggerFactory.globalExtension.log(logger.getName(), Level.INFO, format, arguments); } @Override public void info(String msg, Throwable t) { logger.info(msg, t); LoggerFactory.globalExtension.log(logger.getName(), Level.INFO, msg, t); } @Override public boolean isWarnEnabled() { return logger.isWarnEnabled(); } @Override public void warn(String msg) { logger.warn(msg); LoggerFactory.globalExtension.log(logger.getName(), Level.WARNING, msg); } @Override public void warn(String format, Object... arguments) { logger.warn(format, arguments); LoggerFactory.globalExtension.log(logger.getName(), Level.WARNING, format, arguments); } @Override public void warn(String msg, Throwable t) { logger.warn(msg, t); LoggerFactory.globalExtension.log(logger.getName(), Level.WARNING, msg, t); } @Override public boolean isErrorEnabled() { return logger.isErrorEnabled(); } @Override public void error(String msg) { logger.error(msg); LoggerFactory.globalExtension.log(logger.getName(), Level.SEVERE, msg); } @Override public void error(String format, Object... arguments) { logger.error(format, arguments); LoggerFactory.globalExtension.log(logger.getName(), Level.SEVERE, format, arguments); } @Override public void error(String msg, Throwable t) { logger.error(msg, t); LoggerFactory.globalExtension.log(logger.getName(), Level.SEVERE, msg, t); } } private static class JdkLoggerFactory implements LoggerFactory { @Override public Logger getLogger(String name) { return new JdkLogger(java.util.logging.Logger.getLogger(name)); } } /** * Wrapper over JDK logger */ private static class JdkLogger extends Logger { private final java.util.logging.Logger logger; public JdkLogger(java.util.logging.Logger logger) { this.logger = logger; } @Override public String getName() { return logger.getName(); } @Override public boolean isTraceEnabled() { return logger.isLoggable(Level.FINEST); } @Override public void trace(String msg) { if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, msg); LoggerFactory.globalExtension.log(logger.getName(), Level.FINEST, msg); } } @Override public void trace(String format, Object... arguments) { if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, format(format, arguments)); LoggerFactory.globalExtension.log(logger.getName(), Level.FINEST, format, arguments); } } @Override public void trace(String msg, Throwable t) { if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, msg, t); LoggerFactory.globalExtension.log(logger.getName(), Level.FINEST, msg, t); } } @Override public boolean isDebugEnabled() { return logger.isLoggable(Level.FINE); } @Override public void debug(String msg) { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, msg); LoggerFactory.globalExtension.log(logger.getName(), Level.FINE, msg); } } @Override public void debug(String format, Object... arguments) { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, format(format, arguments)); LoggerFactory.globalExtension.log(logger.getName(), Level.FINE, format, arguments); } } @Override public void debug(String msg, Throwable t) { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, msg, t); LoggerFactory.globalExtension.log(logger.getName(), Level.FINE, msg, t); } } @Override public boolean isInfoEnabled() { return logger.isLoggable(Level.INFO); } @Override public void info(String msg) { if (logger.isLoggable(Level.INFO)) { logger.log(Level.INFO, msg); LoggerFactory.globalExtension.log(logger.getName(), Level.INFO, msg); } } @Override public void info(String format, Object... arguments) { if (logger.isLoggable(Level.INFO)) { logger.log(Level.INFO, format(format, arguments)); LoggerFactory.globalExtension.log(logger.getName(), Level.INFO, format, arguments); } } @Override public void info(String msg, Throwable t) { if (logger.isLoggable(Level.INFO)) { logger.log(Level.INFO, msg, t); LoggerFactory.globalExtension.log(logger.getName(), Level.INFO, msg, t); } } @Override public boolean isWarnEnabled() { return logger.isLoggable(Level.WARNING); } @Override public void warn(String msg) { if (logger.isLoggable(Level.WARNING)) { logger.log(Level.WARNING, msg); LoggerFactory.globalExtension.log(logger.getName(), Level.WARNING, msg); } } @Override public void warn(String format, Object... arguments) { if (logger.isLoggable(Level.WARNING)) { logger.log(Level.WARNING, format(format, arguments)); LoggerFactory.globalExtension.log(logger.getName(), Level.WARNING, format, arguments); } } @Override public void warn(String msg, Throwable t) { if (logger.isLoggable(Level.WARNING)) { logger.log(Level.WARNING, msg, t); LoggerFactory.globalExtension.log(logger.getName(), Level.WARNING, msg, t); } } @Override public boolean isErrorEnabled() { return logger.isLoggable(Level.SEVERE); } @Override public void error(String msg) { if (logger.isLoggable(Level.SEVERE)) { logger.log(Level.SEVERE, msg); LoggerFactory.globalExtension.log(logger.getName(), Level.SEVERE, msg); } } @Override public void error(String format, Object... arguments) { if (logger.isLoggable(Level.SEVERE)) { logger.log(Level.SEVERE, format(format, arguments)); LoggerFactory.globalExtension.log(logger.getName(), Level.SEVERE, format, arguments); } } @Override public void error(String msg, Throwable t) { if (logger.isLoggable(Level.SEVERE)) { logger.log(Level.SEVERE, msg, t); LoggerFactory.globalExtension.log(logger.getName(), Level.SEVERE, msg, t); } } } private static class GlobalExtension implements Extension { private volatile Extension extension; private Extension cachedExtension; @Override public void log(String category, Level level, String msg, Object... arguments) { if (cachedExtension == null) { cachedExtension = extension; if (cachedExtension == null) { return; } } cachedExtension.log(category, level, msg, arguments); } } }
tweaks
src/main/java/reactor/core/util/Logger.java
tweaks
Java
apache-2.0
8247b33ab513cb064e6ea0399648d0e96991573a
0
etnetera/jmeter,etnetera/jmeter,apache/jmeter,etnetera/jmeter,ham1/jmeter,ham1/jmeter,benbenw/jmeter,etnetera/jmeter,benbenw/jmeter,apache/jmeter,ham1/jmeter,apache/jmeter,apache/jmeter,apache/jmeter,ham1/jmeter,etnetera/jmeter,benbenw/jmeter,benbenw/jmeter,ham1/jmeter
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.jmeter.gui.action; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.HeadlessException; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.InputMap; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRootPane; import javax.swing.JScrollPane; import javax.swing.UIManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import org.apache.jmeter.gui.GuiPackage; import org.apache.jmeter.gui.action.template.Template; import org.apache.jmeter.gui.action.template.TemplateManager; import org.apache.jmeter.swing.HtmlPane; import org.apache.jmeter.util.JMeterUtils; import org.apache.jmeter.util.TemplateUtil; import org.apache.jorphan.gui.ComponentUtil; import org.apache.jorphan.gui.JLabeledChoice; import org.apache.jorphan.gui.JLabeledTextField; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import freemarker.template.Configuration; import freemarker.template.TemplateException; /** * Dialog used for Templates selection * @since 2.10 */ public class SelectTemplatesDialog extends JDialog implements ChangeListener, ActionListener, HyperlinkListener { // NOSONAR Ignore inheritence warning private static final long serialVersionUID = 1; // Minimal dimensions for dialog box private static final int MINIMAL_BOX_WIDTH = 500; private static final int MINIMAL_BOX_HEIGHT = 300; private static final Font FONT_DEFAULT = UIManager.getDefaults().getFont("TextField.font"); //$NON-NLS-1$ private static final Font FONT_SMALL = new Font("SansSerif", Font.PLAIN, (int) Math.round(FONT_DEFAULT.getSize() * 0.8)); //$NON-NLS-1$ private static final Logger log = LoggerFactory.getLogger(SelectTemplatesDialog.class); private final JLabeledChoice templateList = new JLabeledChoice(JMeterUtils.getResString("template_choose"), false); //$NON-NLS-1$ private final HtmlPane helpDoc = new HtmlPane(); private final JButton reloadTemplateButton = new JButton(JMeterUtils.getResString("template_reload")); //$NON-NLS-1$ private final JButton applyTemplateButton = new JButton(); private final JButton cancelButton = new JButton(JMeterUtils.getResString("cancel")); //$NON-NLS-1$ private final JButton previous = new JButton(JMeterUtils.getResString("previous")); //$NON-NLS-1$ private final JButton validateButton = new JButton(JMeterUtils.getResString("validate_threadgroup")); //$NON-NLS-1$ private Map<String, JLabeledTextField> parametersTextFields = new LinkedHashMap<>(); private JPanel actionBtnBar = new JPanel(new FlowLayout()); public SelectTemplatesDialog() { super((JFrame) null, JMeterUtils.getResString("template_title"), true); //$NON-NLS-1$ init(); } @Override protected JRootPane createRootPane() { JRootPane rootPane = new JRootPane(); // Hide Window on ESC Action escapeAction = new AbstractAction("ESCAPE") { //$NON-NLS-1$ /** * */ private static final long serialVersionUID = -6543764044868772971L; @Override public void actionPerformed(ActionEvent actionEvent) { setVisible(false); } }; // Do search on Enter Action enterAction = new AbstractAction("ENTER") { //$NON-NLS-1$ private static final long serialVersionUID = -3661361497864527363L; @Override public void actionPerformed(final ActionEvent actionEvent) { checkDirtyAndLoad(actionEvent); } }; ActionMap actionMap = rootPane.getActionMap(); actionMap.put(escapeAction.getValue(Action.NAME), escapeAction); actionMap.put(enterAction.getValue(Action.NAME), enterAction); InputMap inputMap = rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); inputMap.put(KeyStrokes.ESC, escapeAction.getValue(Action.NAME)); inputMap.put(KeyStrokes.ENTER, enterAction.getValue(Action.NAME)); return rootPane; } /** * Check if existing Test Plan has been modified and ask user * what he wants to do if test plan is dirty. * Also ask user for parameters in case of customizable templates. * @param actionEvent {@link ActionEvent} */ private void checkDirtyAndLoad(final ActionEvent actionEvent) throws HeadlessException { final String selectedTemplate = templateList.getText(); final Template template = TemplateManager.getInstance().getTemplateByName(selectedTemplate); if (template == null) { return; } templateList.setValues(TemplateManager.getInstance().getTemplateNames()); // reload the templates before loading final boolean isTestPlan = template.isTestPlan(); // Check if the user wants to drop any changes if (isTestPlan && !checkDirty(actionEvent)) { return; } ActionRouter.getInstance().doActionNow(new ActionEvent(actionEvent.getSource(), actionEvent.getID(), ActionNames.STOP_THREAD)); final File parent = template.getParent(); File fileToCopy = parent != null ? new File(parent, template.getFileName()) : new File(JMeterUtils.getJMeterHome(), template.getFileName()); replaceTemplateParametersAndLoad(actionEvent, template, isTestPlan, fileToCopy); } /** * @param actionEvent {@link ActionEvent} * @param template {@link Template} definition * @param isTestPlan If it's a full test plan or a part * @param templateFile Template file to load */ void replaceTemplateParametersAndLoad(final ActionEvent actionEvent, final Template template, final boolean isTestPlan, File templateFile) { File temporaryGeneratedFile = null; try { // handle customized templates (the .jmx.fmkr files) if (template.getParameters() != null && !template.getParameters().isEmpty()) { File jmxFile = new File(templateFile.getAbsolutePath()); Map<String, String> userParameters = getUserParameters(); Configuration templateCfg = TemplateUtil.getTemplateConfig(); try { temporaryGeneratedFile = File.createTempFile(template.getName(), ".output"); templateFile = temporaryGeneratedFile; TemplateUtil.processTemplate(jmxFile, temporaryGeneratedFile, templateCfg, userParameters); } catch (IOException | TemplateException ex) { log.error("Error generating output file {} from template {}", temporaryGeneratedFile, jmxFile, ex); return; } } Load.loadProjectFile(actionEvent, templateFile, !isTestPlan, false); this.dispose(); } finally { if (temporaryGeneratedFile != null && !temporaryGeneratedFile.delete()) { log.warn("Could not delete generated output file {} from template {}", temporaryGeneratedFile, templateFile); } } } /** * @param actionEvent {@link ActionEvent} * @return true if plan is not dirty or has been saved */ private boolean checkDirty(final ActionEvent actionEvent) { ActionRouter.getInstance().doActionNow(new ActionEvent(actionEvent.getSource(), actionEvent.getID(), ActionNames.CHECK_DIRTY)); GuiPackage guiPackage = GuiPackage.getInstance(); if (guiPackage.isDirty()) { // Check if the user wants to create from template int response = JOptionPane.showConfirmDialog(GuiPackage.getInstance().getMainFrame(), JMeterUtils.getResString("cancel_new_from_template"), // $NON-NLS-1$ JMeterUtils.getResString("template_load?"), // $NON-NLS-1$ JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (response == JOptionPane.YES_OPTION) { ActionRouter.getInstance().doActionNow(new ActionEvent(actionEvent.getSource(), actionEvent.getID(), ActionNames.SAVE)); return true; } if (response == JOptionPane.CLOSED_OPTION || response == JOptionPane.CANCEL_OPTION) { return false; // Don't clear the plan } } return true; } private Map<String, String> getUserParameters(){ Map<String, String> userParameters = new LinkedHashMap<>(); for (Entry<String, JLabeledTextField> entry : parametersTextFields.entrySet()) { userParameters.put(entry.getKey(), entry.getValue().getText()); } return userParameters; } private void init() { // WARNING: called from ctor so must not be overridden (i.e. must be private or final) templateList.setValues(TemplateManager.getInstance().getTemplateNames()); templateList.addChangeListener(this); reloadTemplateButton.addActionListener(this); reloadTemplateButton.setFont(FONT_SMALL); helpDoc.setContentType("text/html"); //$NON-NLS-1$ helpDoc.setEditable(false); helpDoc.addHyperlinkListener(this); applyTemplateButton.addActionListener(this); cancelButton.addActionListener(this); previous.addActionListener(this); validateButton.addActionListener(this); // allow to reset the JDialog if the user click on the close button while // it was displaying templates parameters this.addWindowListener(new WindowAdapter(){ @Override public void windowClosing(WindowEvent evt){ resetJDialog(false); dispose(); } }); this.setContentPane(templateSelectionPanel()); this.pack(); this.setMinimumSize(new Dimension(MINIMAL_BOX_WIDTH, MINIMAL_BOX_HEIGHT)); ComponentUtil.centerComponentInWindow(this, 50); // center position and 50% of screen size populateTemplatePage(); } private JPanel templateSelectionPanel() { JPanel panel = new JPanel(new BorderLayout()); JScrollPane scroller = new JScrollPane(); scroller.setViewportView(helpDoc); JPanel templateBar = new JPanel(new BorderLayout()); templateBar.add(templateList, BorderLayout.CENTER); JPanel reloadBtnBar = new JPanel(); reloadBtnBar.add(reloadTemplateButton); templateBar.add(reloadBtnBar, BorderLayout.EAST); // Bottom buttons bar actionBtnBar.add(applyTemplateButton); actionBtnBar.add(cancelButton); panel.add(templateBar, BorderLayout.NORTH); panel.add(scroller, BorderLayout.CENTER); panel.add(actionBtnBar, BorderLayout.SOUTH); return panel; } /** * Do search * @param e {@link ActionEvent} */ @Override public void actionPerformed(ActionEvent e) { final Object source = e.getSource(); if (source == cancelButton) { resetJDialog(false); this.dispose(); } else if (source == applyTemplateButton) { String selectedTemplate = templateList.getText(); Template template = TemplateManager.getInstance().getTemplateByName(selectedTemplate); if (hasParameters(template)) { this.setContentPane(configureParametersPanel(template.getParameters())); this.revalidate(); } else { checkDirtyAndLoad(e); } } else if (source == reloadTemplateButton) { resetJDialog(true); } else if (source == previous) { resetJDialog(false); } else if (source == validateButton) { checkDirtyAndLoad(e); resetJDialog(false); } } /** * * @param template {@link Template} * @return true if template has not parameter */ private boolean hasParameters(Template template) { return !(template.getParameters() == null || template.getParameters().isEmpty()); } @Override public void stateChanged(ChangeEvent event) { populateTemplatePage(); } private void resetJDialog(boolean reloadTemplates) { if(reloadTemplates) { TemplateManager.getInstance().reset(); } templateList.setValues(TemplateManager.getInstance().getTemplateNames()); // reload templates this.setContentPane(templateSelectionPanel()); this.revalidate(); } private void populateTemplatePage() { String selectedTemplate = templateList.getText(); Template template = TemplateManager.getInstance().getTemplateByName(selectedTemplate); helpDoc.setText(template.getDescription()); applyTemplateButton.setText(template.isTestPlan() ? JMeterUtils.getResString("template_create_from") : JMeterUtils.getResString("template_merge_from") ); } /** * @param parameters {@link Map} parameters map * @return JPanel from parameters */ private JPanel configureParametersPanel(Map<String, String> parameters) { JPanel panel = new JPanel(new BorderLayout()); JPanel northPanel = new JPanel(new FlowLayout()); JLabel label = new JLabel(JMeterUtils.getResString("template_fill_parameters")); label.setPreferredSize(new Dimension(150,35)); northPanel.add(label); panel.add(northPanel, BorderLayout.NORTH); parametersTextFields.clear(); GridBagConstraints gbc = new GridBagConstraints(); initConstraints(gbc); int parameterCount = 0; JPanel gridbagpanel = new JPanel(new GridBagLayout()); for (Entry<String, String> entry : parameters.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); JLabeledTextField paramLabel = new JLabeledTextField(key + " : "); paramLabel.setText(value); parametersTextFields.put(key, paramLabel); gbc.gridy = parameterCount++; List<JComponent> listedParamLabel = paramLabel.getComponentList(); gridbagpanel.add(listedParamLabel.get(0), gbc.clone()); gbc.gridx = 1; gridbagpanel.add(listedParamLabel.get(1), gbc.clone()); gbc.gridx = 0; } JPanel actionBtnBarParameterPanel = new JPanel(new FlowLayout()); actionBtnBarParameterPanel.add(validateButton); actionBtnBarParameterPanel.add(cancelButton); actionBtnBarParameterPanel.add(previous); JScrollPane scroller = new JScrollPane(gridbagpanel); panel.add(scroller, BorderLayout.CENTER); panel.add(actionBtnBarParameterPanel, BorderLayout.SOUTH); return panel; } private void initConstraints(GridBagConstraints gbc) { gbc.anchor = GridBagConstraints.WEST; gbc.insets = new Insets(0,0,5,0); gbc.fill = GridBagConstraints.NONE; gbc.gridheight = 1; gbc.gridwidth = 1; gbc.gridx = 0; gbc.gridy = 0; gbc.weightx = 0; gbc.weighty = 0; } @Override public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED && java.awt.Desktop.isDesktopSupported()) { try { java.awt.Desktop.getDesktop().browse(e.getURL().toURI()); } catch (Exception ex) { log.error("Error opening URL in browser: {}", e.getURL()); } } } }
src/core/org/apache/jmeter/gui/action/SelectTemplatesDialog.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.jmeter.gui.action; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.HeadlessException; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.InputMap; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRootPane; import javax.swing.JScrollPane; import javax.swing.UIManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import org.apache.jmeter.gui.GuiPackage; import org.apache.jmeter.gui.action.template.Template; import org.apache.jmeter.gui.action.template.TemplateManager; import org.apache.jmeter.swing.HtmlPane; import org.apache.jmeter.util.JMeterUtils; import org.apache.jmeter.util.TemplateUtil; import org.apache.jorphan.gui.ComponentUtil; import org.apache.jorphan.gui.JLabeledChoice; import org.apache.jorphan.gui.JLabeledTextField; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import freemarker.template.Configuration; import freemarker.template.TemplateException; /** * Dialog used for Templates selection * @since 2.10 */ public class SelectTemplatesDialog extends JDialog implements ChangeListener, ActionListener, HyperlinkListener { // NOSONAR Ignore inheritence warning private static final long serialVersionUID = 1; // Minimal dimensions for dialog box private static final int MINIMAL_BOX_WIDTH = 500; private static final int MINIMAL_BOX_HEIGHT = 300; private static final Font FONT_DEFAULT = UIManager.getDefaults().getFont("TextField.font"); //$NON-NLS-1$ private static final Font FONT_SMALL = new Font("SansSerif", Font.PLAIN, (int) Math.round(FONT_DEFAULT.getSize() * 0.8)); //$NON-NLS-1$ private static final Logger log = LoggerFactory.getLogger(SelectTemplatesDialog.class); private final JLabeledChoice templateList = new JLabeledChoice(JMeterUtils.getResString("template_choose"), false); //$NON-NLS-1$ private final HtmlPane helpDoc = new HtmlPane(); private final JButton reloadTemplateButton = new JButton(JMeterUtils.getResString("template_reload")); //$NON-NLS-1$ private final JButton applyTemplateButton = new JButton(); private final JButton cancelButton = new JButton(JMeterUtils.getResString("cancel")); //$NON-NLS-1$ private final JButton previous = new JButton(JMeterUtils.getResString("previous")); //$NON-NLS-1$ private final JButton validateButton = new JButton(JMeterUtils.getResString("validate_threadgroup")); //$NON-NLS-1$ private Map<String, JLabeledTextField> parametersTextFields = new LinkedHashMap<>(); private JPanel actionBtnBar = new JPanel(new FlowLayout()); public SelectTemplatesDialog() { super((JFrame) null, JMeterUtils.getResString("template_title"), true); //$NON-NLS-1$ init(); } @Override protected JRootPane createRootPane() { JRootPane rootPane = new JRootPane(); // Hide Window on ESC Action escapeAction = new AbstractAction("ESCAPE") { //$NON-NLS-1$ /** * */ private static final long serialVersionUID = -6543764044868772971L; @Override public void actionPerformed(ActionEvent actionEvent) { setVisible(false); } }; // Do search on Enter Action enterAction = new AbstractAction("ENTER") { //$NON-NLS-1$ private static final long serialVersionUID = -3661361497864527363L; @Override public void actionPerformed(final ActionEvent actionEvent) { checkDirtyAndLoad(actionEvent); } }; ActionMap actionMap = rootPane.getActionMap(); actionMap.put(escapeAction.getValue(Action.NAME), escapeAction); actionMap.put(enterAction.getValue(Action.NAME), enterAction); InputMap inputMap = rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); inputMap.put(KeyStrokes.ESC, escapeAction.getValue(Action.NAME)); inputMap.put(KeyStrokes.ENTER, enterAction.getValue(Action.NAME)); return rootPane; } /** * Check if existing Test Plan has been modified and ask user * what he wants to do if test plan is dirty. * Also ask user for parameters in case of customizable templates. * @param actionEvent {@link ActionEvent} */ private void checkDirtyAndLoad(final ActionEvent actionEvent) throws HeadlessException { final String selectedTemplate = templateList.getText(); final Template template = TemplateManager.getInstance().getTemplateByName(selectedTemplate); if (template == null) { return; } templateList.setValues(TemplateManager.getInstance().reset().getTemplateNames()); // reload the templates before loading final boolean isTestPlan = template.isTestPlan(); // Check if the user wants to drop any changes if (isTestPlan && !checkDirty(actionEvent)) { return; } ActionRouter.getInstance().doActionNow(new ActionEvent(actionEvent.getSource(), actionEvent.getID(), ActionNames.STOP_THREAD)); final File parent = template.getParent(); File fileToCopy = parent != null ? new File(parent, template.getFileName()) : new File(JMeterUtils.getJMeterHome(), template.getFileName()); replaceTemplateParametersAndLoad(actionEvent, template, isTestPlan, fileToCopy); } /** * @param actionEvent {@link ActionEvent} * @param template {@link Template} definition * @param isTestPlan If it's a full test plan or a part * @param templateFile Template file to load */ void replaceTemplateParametersAndLoad(final ActionEvent actionEvent, final Template template, final boolean isTestPlan, File templateFile) { File temporaryGeneratedFile = null; try { // handle customized templates (the .jmx.fmkr files) if (template.getParameters() != null && !template.getParameters().isEmpty()) { File jmxFile = new File(templateFile.getAbsolutePath()); Map<String, String> userParameters = getUserParameters(); Configuration templateCfg = TemplateUtil.getTemplateConfig(); try { temporaryGeneratedFile = File.createTempFile(template.getName(), ".output"); templateFile = temporaryGeneratedFile; TemplateUtil.processTemplate(jmxFile, temporaryGeneratedFile, templateCfg, userParameters); } catch (IOException | TemplateException ex) { log.error("Error generating output file {} from template {}", temporaryGeneratedFile, jmxFile, ex); return; } } Load.loadProjectFile(actionEvent, templateFile, !isTestPlan, false); this.dispose(); } finally { if (temporaryGeneratedFile != null && !temporaryGeneratedFile.delete()) { log.warn("Could not delete generated output file {} from template {}", temporaryGeneratedFile, templateFile); } } } /** * @param actionEvent {@link ActionEvent} * @return true if plan is not dirty or has been saved */ private boolean checkDirty(final ActionEvent actionEvent) { ActionRouter.getInstance().doActionNow(new ActionEvent(actionEvent.getSource(), actionEvent.getID(), ActionNames.CHECK_DIRTY)); GuiPackage guiPackage = GuiPackage.getInstance(); if (guiPackage.isDirty()) { // Check if the user wants to create from template int response = JOptionPane.showConfirmDialog(GuiPackage.getInstance().getMainFrame(), JMeterUtils.getResString("cancel_new_from_template"), // $NON-NLS-1$ JMeterUtils.getResString("template_load?"), // $NON-NLS-1$ JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (response == JOptionPane.YES_OPTION) { ActionRouter.getInstance().doActionNow(new ActionEvent(actionEvent.getSource(), actionEvent.getID(), ActionNames.SAVE)); return true; } if (response == JOptionPane.CLOSED_OPTION || response == JOptionPane.CANCEL_OPTION) { return false; // Don't clear the plan } } return true; } private Map<String, String> getUserParameters(){ Map<String, String> userParameters = new LinkedHashMap<>(); for (Entry<String, JLabeledTextField> entry : parametersTextFields.entrySet()) { userParameters.put(entry.getKey(), entry.getValue().getText()); } return userParameters; } private void init() { // WARNING: called from ctor so must not be overridden (i.e. must be private or final) templateList.setValues(TemplateManager.getInstance().getTemplateNames()); templateList.addChangeListener(this); reloadTemplateButton.addActionListener(this); reloadTemplateButton.setFont(FONT_SMALL); helpDoc.setContentType("text/html"); //$NON-NLS-1$ helpDoc.setEditable(false); helpDoc.addHyperlinkListener(this); applyTemplateButton.addActionListener(this); cancelButton.addActionListener(this); previous.addActionListener(this); validateButton.addActionListener(this); // allow to reset the JDialog if the user click on the close button while // it was displaying templates parameters this.addWindowListener(new WindowAdapter(){ @Override public void windowClosing(WindowEvent evt){ resetJDialog(); dispose(); } }); this.setContentPane(templateSelectionPanel()); this.pack(); this.setMinimumSize(new Dimension(MINIMAL_BOX_WIDTH, MINIMAL_BOX_HEIGHT)); ComponentUtil.centerComponentInWindow(this, 50); // center position and 50% of screen size populateTemplatePage(); } private JPanel templateSelectionPanel() { JPanel panel = new JPanel(new BorderLayout()); JScrollPane scroller = new JScrollPane(); scroller.setViewportView(helpDoc); JPanel templateBar = new JPanel(new BorderLayout()); templateBar.add(templateList, BorderLayout.CENTER); JPanel reloadBtnBar = new JPanel(); reloadBtnBar.add(reloadTemplateButton); templateBar.add(reloadBtnBar, BorderLayout.EAST); // Bottom buttons bar actionBtnBar.add(applyTemplateButton); actionBtnBar.add(cancelButton); panel.add(templateBar, BorderLayout.NORTH); panel.add(scroller, BorderLayout.CENTER); panel.add(actionBtnBar, BorderLayout.SOUTH); return panel; } /** * Do search * @param e {@link ActionEvent} */ @Override public void actionPerformed(ActionEvent e) { final Object source = e.getSource(); if (source == cancelButton) { resetJDialog(); this.dispose(); } else if (source == applyTemplateButton) { String selectedTemplate = templateList.getText(); Template template = TemplateManager.getInstance().getTemplateByName(selectedTemplate); if (hasParameters(template)) { this.setContentPane(configureParametersPanel(template.getParameters())); this.revalidate(); } else { checkDirtyAndLoad(e); } } else if (source == reloadTemplateButton || source == previous) { resetJDialog(); } else if (source == validateButton) { checkDirtyAndLoad(e); resetJDialog(); } } /** * * @param template {@link Template} * @return true if template has not parameter */ private boolean hasParameters(Template template) { return !(template.getParameters() == null || template.getParameters().isEmpty()); } @Override public void stateChanged(ChangeEvent event) { populateTemplatePage(); } private void resetJDialog() { templateList.setValues(TemplateManager.getInstance().reset().getTemplateNames()); // reload templates this.setContentPane(templateSelectionPanel()); this.revalidate(); } private void populateTemplatePage() { String selectedTemplate = templateList.getText(); Template template = TemplateManager.getInstance().getTemplateByName(selectedTemplate); helpDoc.setText(template.getDescription()); applyTemplateButton.setText(template.isTestPlan() ? JMeterUtils.getResString("template_create_from") : JMeterUtils.getResString("template_merge_from") ); } /** * @param parameters {@link Map} parameters map * @return JPanel from parameters */ private JPanel configureParametersPanel(Map<String, String> parameters) { JPanel panel = new JPanel(new BorderLayout()); JPanel northPanel = new JPanel(new FlowLayout()); JLabel label = new JLabel(JMeterUtils.getResString("template_fill_parameters")); label.setPreferredSize(new Dimension(150,35)); northPanel.add(label); panel.add(northPanel, BorderLayout.NORTH); parametersTextFields.clear(); GridBagConstraints gbc = new GridBagConstraints(); initConstraints(gbc); int parameterCount = 0; JPanel gridbagpanel = new JPanel(new GridBagLayout()); for (Entry<String, String> entry : parameters.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); JLabeledTextField paramLabel = new JLabeledTextField(key + " : "); paramLabel.setText(value); parametersTextFields.put(key, paramLabel); gbc.gridy = parameterCount++; List<JComponent> listedParamLabel = paramLabel.getComponentList(); gridbagpanel.add(listedParamLabel.get(0), gbc.clone()); gbc.gridx = 1; gridbagpanel.add(listedParamLabel.get(1), gbc.clone()); gbc.gridx = 0; } JPanel actionBtnBarParameterPanel = new JPanel(new FlowLayout()); actionBtnBarParameterPanel.add(validateButton); actionBtnBarParameterPanel.add(cancelButton); actionBtnBarParameterPanel.add(previous); JScrollPane scroller = new JScrollPane(gridbagpanel); panel.add(scroller, BorderLayout.CENTER); panel.add(actionBtnBarParameterPanel, BorderLayout.SOUTH); return panel; } private void initConstraints(GridBagConstraints gbc) { gbc.anchor = GridBagConstraints.WEST; gbc.insets = new Insets(0,0,5,0); gbc.fill = GridBagConstraints.NONE; gbc.gridheight = 1; gbc.gridwidth = 1; gbc.gridx = 0; gbc.gridy = 0; gbc.weightx = 0; gbc.weighty = 0; } @Override public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED && java.awt.Desktop.isDesktopSupported()) { try { java.awt.Desktop.getDesktop().browse(e.getURL().toURI()); } catch (Exception ex) { log.error("Error opening URL in browser: {}", e.getURL()); } } } }
Bug 62870 - Templates : Add ability to provide parameters Avoid resetting templates when not necessary Bugzilla Id: 62870 git-svn-id: https://svn.apache.org/repos/asf/jmeter/trunk@1848039 13f79535-47bb-0310-9956-ffa450edef68 Former-commit-id: 13ec5eebec23529417fa4df83837178e300c6494
src/core/org/apache/jmeter/gui/action/SelectTemplatesDialog.java
Bug 62870 - Templates : Add ability to provide parameters
Java
apache-2.0
4def6b0cbaabcd2d8f3877aeaaca5c6af3d26a33
0
apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
/* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.core.executor.sql.execute; import com.google.common.eventbus.EventBus; import io.shardingsphere.core.constant.SQLType; import io.shardingsphere.core.event.ShardingEventBusInstance; import io.shardingsphere.core.executor.ShardingExecuteCallback; import io.shardingsphere.core.executor.ShardingGroupExecuteCallback; import io.shardingsphere.core.event.executor.sql.SQLExecutionEvent; import io.shardingsphere.core.event.executor.sql.SQLExecutionEventFactory; import io.shardingsphere.core.executor.sql.SQLExecuteUnit; import io.shardingsphere.core.executor.sql.execute.threadlocal.ExecutorDataMap; import io.shardingsphere.core.executor.sql.execute.threadlocal.ExecutorExceptionHandler; import lombok.RequiredArgsConstructor; import java.sql.SQLException; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * Statement execute callback interface. * * @author gaohongtao * @author zhangliang * * @param <T> class type of return value */ @RequiredArgsConstructor public abstract class SQLExecuteCallback<T> implements ShardingExecuteCallback<SQLExecuteUnit, T>, ShardingGroupExecuteCallback<SQLExecuteUnit, T> { private final SQLType sqlType; private final boolean isExceptionThrown; private final Map<String, Object> dataMap; private final EventBus shardingEventBus = ShardingEventBusInstance.getInstance(); @Override public final T execute(final SQLExecuteUnit sqlExecuteUnit) throws SQLException { return execute0(sqlExecuteUnit); } @Override public final Collection<T> execute(final Collection<SQLExecuteUnit> sqlExecuteUnits) throws SQLException { Collection<T> result = new LinkedList<>(); for (SQLExecuteUnit each : sqlExecuteUnits) { result.add(execute0(each)); } return result; } private T execute0(final SQLExecuteUnit sqlExecuteUnit) throws SQLException { ExecutorExceptionHandler.setExceptionThrown(isExceptionThrown); ExecutorDataMap.setDataMap(dataMap); List<SQLExecutionEvent> events = new LinkedList<>(); for (List<Object> each : sqlExecuteUnit.getRouteUnit().getSqlUnit().getParameterSets()) { SQLExecutionEvent event = SQLExecutionEventFactory.createEvent(sqlType, sqlExecuteUnit, each, sqlExecuteUnit.getStatement().getConnection().getMetaData().getURL()); events.add(event); shardingEventBus.post(event); } try { T result = executeSQL(sqlExecuteUnit); for (SQLExecutionEvent each : events) { each.setExecuteSuccess(); shardingEventBus.post(each); } return result; } catch (final SQLException ex) { for (SQLExecutionEvent each : events) { each.setExecuteFailure(ex); shardingEventBus.post(each); } ExecutorExceptionHandler.handleException(ex); return null; } } protected abstract T executeSQL(SQLExecuteUnit sqlExecuteUnit) throws SQLException; }
sharding-core/src/main/java/io/shardingsphere/core/executor/sql/execute/SQLExecuteCallback.java
/* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.core.executor.sql.execute; import com.google.common.eventbus.EventBus; import io.shardingsphere.core.constant.SQLType; import io.shardingsphere.core.event.ShardingEventBusInstance; import io.shardingsphere.core.executor.ShardingExecuteCallback; import io.shardingsphere.core.executor.ShardingGroupExecuteCallback; import io.shardingsphere.core.event.executor.sql.SQLExecutionEvent; import io.shardingsphere.core.event.executor.sql.SQLExecutionEventFactory; import io.shardingsphere.core.executor.sql.SQLExecuteUnit; import io.shardingsphere.core.executor.sql.execute.threadlocal.ExecutorDataMap; import io.shardingsphere.core.executor.sql.execute.threadlocal.ExecutorExceptionHandler; import lombok.RequiredArgsConstructor; import java.sql.SQLException; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * Statement execute callback interface. * * @author gaohongtao * @author zhangliang * * @param <T> class type of return value */ @RequiredArgsConstructor public abstract class SQLExecuteCallback<T> implements ShardingExecuteCallback<SQLExecuteUnit, T>, ShardingGroupExecuteCallback<SQLExecuteUnit, T> { private final SQLType sqlType; private final boolean isExceptionThrown; private final Map<String, Object> dataMap; private final EventBus shardingEventBus = ShardingEventBusInstance.getInstance(); @Override public final T execute(final SQLExecuteUnit sqlExecuteUnit) throws SQLException { return execute0(sqlExecuteUnit); } @Override public final Collection<T> execute(final Collection<SQLExecuteUnit> sqlExecuteUnits) throws SQLException { Collection<T> result = new LinkedList<>(); for (SQLExecuteUnit each : sqlExecuteUnits) { result.add(execute0(each)); } return result; } private T execute0(final SQLExecuteUnit sqlExecuteUnit) throws SQLException { ExecutorExceptionHandler.setExceptionThrown(isExceptionThrown); ExecutorDataMap.setDataMap(dataMap); List<SQLExecutionEvent> events = new LinkedList<>(); for (List<Object> each : sqlExecuteUnit.getRouteUnit().getSqlUnit().getParameterSets()) { SQLExecutionEvent event = SQLExecutionEventFactory.createEvent(sqlType, sqlExecuteUnit, each, sqlExecuteUnit.getStatement().getConnection().getMetaData().getURL()); events.add(event); shardingEventBus.post(event); } try { T result = executeSQL(sqlExecuteUnit); for (SQLExecutionEvent each : events) { each.setExecuteSuccess(); shardingEventBus.post(each); } return result; } catch (final SQLException ex) { for (SQLExecutionEvent each : events) { each.setExecuteFailure(ex); shardingEventBus.post(each); ExecutorExceptionHandler.handleException(ex); } return null; } } protected abstract T executeSQL(SQLExecuteUnit sqlExecuteUnit) throws SQLException; }
#1172, refine
sharding-core/src/main/java/io/shardingsphere/core/executor/sql/execute/SQLExecuteCallback.java
#1172, refine
Java
apache-2.0
555a2c2a75f047fb1b1826f9ed7f0ecda90e9722
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.console; import com.intellij.execution.ExecutionException; import com.intellij.execution.ExecutionManager; import com.intellij.execution.Executor; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.configurations.JavaParameters; import com.intellij.execution.executors.DefaultRunExecutor; import com.intellij.execution.impl.ConsoleViewImpl; import com.intellij.execution.process.*; import com.intellij.execution.ui.ConsoleView; import com.intellij.execution.ui.ConsoleViewContentType; import com.intellij.execution.ui.RunContentDescriptor; import com.intellij.execution.ui.actions.CloseAction; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.ActionToolbar; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JdkUtil; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.Consumer; import com.intellij.util.io.BaseOutputReader; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.runner.DefaultGroovyScriptRunner; import org.jetbrains.plugins.groovy.runner.GroovyScriptRunConfiguration; import org.jetbrains.plugins.groovy.runner.GroovyScriptRunner; import javax.swing.*; import java.awt.*; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; import static org.jetbrains.plugins.groovy.console.GroovyConsoleUtilKt.getWorkingDirectory; public class GroovyConsole { public static final Key<GroovyConsole> GROOVY_CONSOLE = Key.create("Groovy console key"); private static final Logger LOG = Logger.getInstance(GroovyConsole.class); private static final Charset UTF_8 = Charset.forName("UTF-8"); private static final Executor defaultExecutor = DefaultRunExecutor.getRunExecutorInstance(); private final Project myProject; private final RunContentDescriptor myContentDescriptor; private final ConsoleView myConsoleView; private final ProcessHandler myProcessHandler; public GroovyConsole(Project project, RunContentDescriptor descriptor, ConsoleView view, ProcessHandler handler) { myProject = project; myContentDescriptor = descriptor; myConsoleView = view; myProcessHandler = handler; } private void doExecute(@NotNull String command) { for (String line : command.trim().split("\n")) { myConsoleView.print("> ", ConsoleViewContentType.USER_INPUT); myConsoleView.print(line, ConsoleViewContentType.USER_INPUT); myConsoleView.print("\n", ConsoleViewContentType.NORMAL_OUTPUT); } ApplicationManager.getApplication().executeOnPooledThread( () -> send(myProcessHandler, StringUtil.replace(command, "\n", "###\\n")) ); } public void execute(@NotNull String command) { if (!StringUtil.isEmptyOrSpaces(command)) doExecute(command); ExecutionManager.getInstance(myProject).getContentManager().toFrontRunContent(defaultExecutor, myContentDescriptor); } public void stop() { myProcessHandler.destroyProcess(); // use force } private static void send(@NotNull ProcessHandler processHandler, @NotNull String command) { final OutputStream outputStream = processHandler.getProcessInput(); assert outputStream != null : "output stream is null"; final Charset charset = processHandler instanceof BaseOSProcessHandler ? ((BaseOSProcessHandler)processHandler).getCharset() : null; byte[] bytes = (command + "\n").getBytes(charset != null ? charset : UTF_8); try { outputStream.write(bytes); outputStream.flush(); } catch (IOException ignored) { LOG.warn(ignored); } } public static void getOrCreateConsole(@NotNull final Project project, @NotNull final VirtualFile contentFile, @NotNull final Consumer<? super GroovyConsole> callback) { final GroovyConsole existingConsole = contentFile.getUserData(GROOVY_CONSOLE); if (existingConsole != null) return; final Consumer<Module> initializer = module -> { final GroovyConsole console = createConsole(project, contentFile, module); if (console != null) { callback.consume(console); } }; final Module module = GroovyConsoleStateService.getInstance(project).getSelectedModule(contentFile); if (module == null || module.isDisposed()) { // if not, then select module, then run initializer GroovyConsoleUtil.selectModuleAndRun(project, initializer); } else { // if module for console is already selected, then use it for creation initializer.consume(module); } } @Nullable public static GroovyConsole createConsole(@NotNull final Project project, @NotNull final VirtualFile contentFile, @NotNull Module module) { final ProcessHandler processHandler = createProcessHandler(module); if (processHandler == null) return null; final GroovyConsoleStateService consoleStateService = GroovyConsoleStateService.getInstance(project); consoleStateService.setFileModule(contentFile, module); final String title = consoleStateService.getSelectedModuleTitle(contentFile); final ConsoleViewImpl consoleView = new GroovyConsoleView(project); final RunContentDescriptor descriptor = new RunContentDescriptor(consoleView, processHandler, new JPanel(new BorderLayout()), title); final GroovyConsole console = new GroovyConsole(project, descriptor, consoleView, processHandler); // must call getComponent before createConsoleActions() final JComponent consoleViewComponent = consoleView.getComponent(); final DefaultActionGroup actionGroup = new DefaultActionGroup(); actionGroup.add(new BuildAndRestartConsoleAction(module, project, defaultExecutor, descriptor, restarter(project, contentFile))); actionGroup.addSeparator(); actionGroup.addAll(consoleView.createConsoleActions()); actionGroup.add(new CloseAction(defaultExecutor, descriptor, project) { @Override public void actionPerformed(@NotNull AnActionEvent e) { processHandler.destroyProcess(); // use force super.actionPerformed(e); } }); final ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar("GroovyConsole", actionGroup, false); toolbar.setTargetComponent(consoleViewComponent); final JComponent ui = descriptor.getComponent(); ui.add(consoleViewComponent, BorderLayout.CENTER); ui.add(toolbar.getComponent(), BorderLayout.WEST); processHandler.addProcessListener(new ProcessAdapter() { @Override public void processTerminated(@NotNull ProcessEvent event) { if (contentFile.getUserData(GROOVY_CONSOLE) == console) { // process terminated either by closing file or by close action contentFile.putUserData(GROOVY_CONSOLE, null); } } }); contentFile.putUserData(GROOVY_CONSOLE, console); consoleView.attachToProcess(processHandler); processHandler.startNotify(); ExecutionManager.getInstance(project).getContentManager().showRunContent(defaultExecutor, descriptor); return console; } private static ProcessHandler createProcessHandler(Module module) { try { final JavaParameters javaParameters = createJavaParameters(module); final GeneralCommandLine commandLine = javaParameters.toCommandLine(); return new OSProcessHandler(commandLine) { @Override public boolean isSilentlyDestroyOnClose() { return true; } @NotNull @Override protected BaseOutputReader.Options readerOptions() { return BaseOutputReader.Options.forMostlySilentProcess(); } }; } catch (ExecutionException e) { LOG.warn(e); return null; } } private static JavaParameters createJavaParameters(@NotNull Module module) throws ExecutionException { JavaParameters res = GroovyScriptRunConfiguration.createJavaParametersWithSdk(module); DefaultGroovyScriptRunner.configureGenericGroovyRunner(res, module, "groovy.ui.GroovyMain", !GroovyConsoleUtil.hasGroovyAll(module), true, true, false); res.getProgramParametersList().addAll("-p", GroovyScriptRunner.getPathInConf("console.groovy")); res.setWorkingDirectory(getWorkingDirectory(module)); res.setUseDynamicClasspath(true); if (useArgsFile(res)) { res.setArgFile(true); } return res; } private static boolean useArgsFile(@NotNull JavaParameters res) { Sdk jdk = res.getJdk(); if (jdk == null) { return false; } String rootPath = jdk.getHomePath(); if (rootPath == null) { return false; } return JdkUtil.isModularRuntime(rootPath); } private static Consumer<Module> restarter(final Project project, final VirtualFile file) { return module -> createConsole(project, file, module); } }
plugins/groovy/src/org/jetbrains/plugins/groovy/console/GroovyConsole.java
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.console; import com.intellij.execution.ExecutionException; import com.intellij.execution.ExecutionManager; import com.intellij.execution.Executor; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.configurations.JavaParameters; import com.intellij.execution.executors.DefaultRunExecutor; import com.intellij.execution.impl.ConsoleViewImpl; import com.intellij.execution.process.*; import com.intellij.execution.ui.ConsoleView; import com.intellij.execution.ui.ConsoleViewContentType; import com.intellij.execution.ui.RunContentDescriptor; import com.intellij.execution.ui.actions.CloseAction; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.ActionToolbar; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.Consumer; import com.intellij.util.io.BaseOutputReader; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.runner.DefaultGroovyScriptRunner; import org.jetbrains.plugins.groovy.runner.GroovyScriptRunConfiguration; import org.jetbrains.plugins.groovy.runner.GroovyScriptRunner; import javax.swing.*; import java.awt.*; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; import static org.jetbrains.plugins.groovy.console.GroovyConsoleUtilKt.getWorkingDirectory; public class GroovyConsole { public static final Key<GroovyConsole> GROOVY_CONSOLE = Key.create("Groovy console key"); private static final Logger LOG = Logger.getInstance(GroovyConsole.class); private static final Charset UTF_8 = Charset.forName("UTF-8"); private static final Executor defaultExecutor = DefaultRunExecutor.getRunExecutorInstance(); private final Project myProject; private final RunContentDescriptor myContentDescriptor; private final ConsoleView myConsoleView; private final ProcessHandler myProcessHandler; public GroovyConsole(Project project, RunContentDescriptor descriptor, ConsoleView view, ProcessHandler handler) { myProject = project; myContentDescriptor = descriptor; myConsoleView = view; myProcessHandler = handler; } private void doExecute(@NotNull String command) { for (String line : command.trim().split("\n")) { myConsoleView.print("> ", ConsoleViewContentType.USER_INPUT); myConsoleView.print(line, ConsoleViewContentType.USER_INPUT); myConsoleView.print("\n", ConsoleViewContentType.NORMAL_OUTPUT); } ApplicationManager.getApplication().executeOnPooledThread( () -> send(myProcessHandler, StringUtil.replace(command, "\n", "###\\n")) ); } public void execute(@NotNull String command) { if (!StringUtil.isEmptyOrSpaces(command)) doExecute(command); ExecutionManager.getInstance(myProject).getContentManager().toFrontRunContent(defaultExecutor, myContentDescriptor); } public void stop() { myProcessHandler.destroyProcess(); // use force } private static void send(@NotNull ProcessHandler processHandler, @NotNull String command) { final OutputStream outputStream = processHandler.getProcessInput(); assert outputStream != null : "output stream is null"; final Charset charset = processHandler instanceof BaseOSProcessHandler ? ((BaseOSProcessHandler)processHandler).getCharset() : null; byte[] bytes = (command + "\n").getBytes(charset != null ? charset : UTF_8); try { outputStream.write(bytes); outputStream.flush(); } catch (IOException ignored) { LOG.warn(ignored); } } public static void getOrCreateConsole(@NotNull final Project project, @NotNull final VirtualFile contentFile, @NotNull final Consumer<? super GroovyConsole> callback) { final GroovyConsole existingConsole = contentFile.getUserData(GROOVY_CONSOLE); if (existingConsole != null) return; final Consumer<Module> initializer = module -> { final GroovyConsole console = createConsole(project, contentFile, module); if (console != null) { callback.consume(console); } }; final Module module = GroovyConsoleStateService.getInstance(project).getSelectedModule(contentFile); if (module == null || module.isDisposed()) { // if not, then select module, then run initializer GroovyConsoleUtil.selectModuleAndRun(project, initializer); } else { // if module for console is already selected, then use it for creation initializer.consume(module); } } @Nullable public static GroovyConsole createConsole(@NotNull final Project project, @NotNull final VirtualFile contentFile, @NotNull Module module) { final ProcessHandler processHandler = createProcessHandler(module); if (processHandler == null) return null; final GroovyConsoleStateService consoleStateService = GroovyConsoleStateService.getInstance(project); consoleStateService.setFileModule(contentFile, module); final String title = consoleStateService.getSelectedModuleTitle(contentFile); final ConsoleViewImpl consoleView = new GroovyConsoleView(project); final RunContentDescriptor descriptor = new RunContentDescriptor(consoleView, processHandler, new JPanel(new BorderLayout()), title); final GroovyConsole console = new GroovyConsole(project, descriptor, consoleView, processHandler); // must call getComponent before createConsoleActions() final JComponent consoleViewComponent = consoleView.getComponent(); final DefaultActionGroup actionGroup = new DefaultActionGroup(); actionGroup.add(new BuildAndRestartConsoleAction(module, project, defaultExecutor, descriptor, restarter(project, contentFile))); actionGroup.addSeparator(); actionGroup.addAll(consoleView.createConsoleActions()); actionGroup.add(new CloseAction(defaultExecutor, descriptor, project) { @Override public void actionPerformed(@NotNull AnActionEvent e) { processHandler.destroyProcess(); // use force super.actionPerformed(e); } }); final ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar("GroovyConsole", actionGroup, false); toolbar.setTargetComponent(consoleViewComponent); final JComponent ui = descriptor.getComponent(); ui.add(consoleViewComponent, BorderLayout.CENTER); ui.add(toolbar.getComponent(), BorderLayout.WEST); processHandler.addProcessListener(new ProcessAdapter() { @Override public void processTerminated(@NotNull ProcessEvent event) { if (contentFile.getUserData(GROOVY_CONSOLE) == console) { // process terminated either by closing file or by close action contentFile.putUserData(GROOVY_CONSOLE, null); } } }); contentFile.putUserData(GROOVY_CONSOLE, console); consoleView.attachToProcess(processHandler); processHandler.startNotify(); ExecutionManager.getInstance(project).getContentManager().showRunContent(defaultExecutor, descriptor); return console; } private static ProcessHandler createProcessHandler(Module module) { try { final JavaParameters javaParameters = createJavaParameters(module); final GeneralCommandLine commandLine = javaParameters.toCommandLine(); return new OSProcessHandler(commandLine) { @Override public boolean isSilentlyDestroyOnClose() { return true; } @NotNull @Override protected BaseOutputReader.Options readerOptions() { return BaseOutputReader.Options.forMostlySilentProcess(); } }; } catch (ExecutionException e) { LOG.warn(e); return null; } } private static JavaParameters createJavaParameters(@NotNull Module module) throws ExecutionException { JavaParameters res = GroovyScriptRunConfiguration.createJavaParametersWithSdk(module); DefaultGroovyScriptRunner.configureGenericGroovyRunner(res, module, "groovy.ui.GroovyMain", !GroovyConsoleUtil.hasGroovyAll(module), true, true, false); res.getProgramParametersList().addAll("-p", GroovyScriptRunner.getPathInConf("console.groovy")); res.setWorkingDirectory(getWorkingDirectory(module)); res.setUseDynamicClasspath(true); return res; } private static Consumer<Module> restarter(final Project project, final VirtualFile file) { return module -> createConsole(project, file, module); } }
[groovy] use args file command line shortening for Java 9+ in Console (IDEA-215543) GitOrigin-RevId: 5cb75db36494f91cb48d02c7be924720557cd9a3
plugins/groovy/src/org/jetbrains/plugins/groovy/console/GroovyConsole.java
[groovy] use args file command line shortening for Java 9+ in Console (IDEA-215543)
Java
apache-2.0
86121641aef44ed3bfb9b0901e0f4c47bda5a883
0
flowersinthesand/spheres-sandbox
package com.github.flowersinthesand.spheres; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class DefaultApp implements App, AppInside { private final Options options; private final Bridge bridge; private final Protocol protocol; private ConcurrentMap<String, Socket> sockets = new ConcurrentHashMap<>(); private ConcurrentMap<Socket, SessionBase> sessions = new ConcurrentHashMap<>(); private Actions<Void> closeActions = new ConcurrentActions<>(new Actions.Options().once(true).memory(true)); DefaultApp(Options options) { this.options = options; bridge = options.bridge(); protocol = options.protocol(); } @Override public void install() { closeAction(new VoidAction() { @Override public void on() { for (Socket socket : sockets.values()) { socket.close(); } } }); httpAction(new Action<HttpExchange>() { @Override public void on(HttpExchange http) { protocol.on(http); } }); webSocketAction(new Action<WebSocket>() { @Override public void on(WebSocket ws) { protocol.on(ws); } }); socketAction(new Action<Socket>() { @Override public void on(final Socket socket) { sockets.put(socket.id(), socket); socket.closeAction(new VoidAction() { @Override public void on() { sockets.remove(socket.id()); } }); protocol.on(socket); } }); sessionAction(new Action<SessionBase>() { @Override public void on(SessionBase session) { final Socket socket = session.unwrap(Socket.class); sessions.put(socket, session); socket.closeAction(new VoidAction() { @Override public void on() { sessions.remove(socket); } }); } }); for (Object comp : new Object[] { bridge, protocol }) { if (comp instanceof AppInsideAware) { ((AppInsideAware) comp).setAppInside(this); } if (comp instanceof Initable) { ((Initable) comp).init(); } } } @Override public Options options() { return options; } @Override public ConcurrentMap<String, Socket> sockets() { return sockets; } @SuppressWarnings("unchecked") @Override public App all(Action<? extends SessionBase> action) { for (Socket socket : sockets.values()) { ((Action<SessionBase>) action).on(sessions.get(socket)); } return this; } @SuppressWarnings("unchecked") @Override public App byId(String id, Action<? extends SessionBase> action) { Socket socket = sockets.get(id); if (socket != null) { ((Action<SessionBase>) action).on(sessions.get(socket)); } return this; } @SuppressWarnings("unchecked") @Override public App byTag(String name, Action<? extends SessionBase> action) { for (Socket socket : sockets.values()) { if (socket.tags().contains(name)) { ((Action<SessionBase>) action).on(sessions.get(socket)); } } return this; } @Override public App httpAction(Action<HttpExchange> action) { bridge.httpActions().add(action); return this; } @Override public App webSocketAction(Action<WebSocket> action) { bridge.webSocketActions().add(action); return this; } @Override public App socketAction(Action<Socket> action) { protocol.socketActions().add(action); return this; } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public App sessionAction(Action<? extends SessionBase> action) { protocol.sessionActions().add((Action) action); return this; } @Override public App closeAction(Action<Void> action) { closeActions.add(action); return this; } @Override public void close() { closeActions.fire(); } }
src/main/java/com/github/flowersinthesand/spheres/DefaultApp.java
package com.github.flowersinthesand.spheres; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class DefaultApp implements App, AppInside { private final Options options; private final Bridge bridge; private final Protocol protocol; private ConcurrentMap<String, Socket> sockets = new ConcurrentHashMap<>(); private ConcurrentMap<Socket, SessionBase> sessions = new ConcurrentHashMap<>(); private Actions<Void> closeActions = new ConcurrentActions<>(new Actions.Options().once(true).memory(true)); public DefaultApp(Options options) { this.options = options; bridge = options.bridge(); protocol = options.protocol(); } @Override public void install() { closeAction(new VoidAction() { @Override public void on() { for (Socket socket : sockets.values()) { socket.close(); } } }); httpAction(new Action<HttpExchange>() { @Override public void on(HttpExchange http) { protocol.on(http); } }); webSocketAction(new Action<WebSocket>() { @Override public void on(WebSocket ws) { protocol.on(ws); } }); socketAction(new Action<Socket>() { @Override public void on(final Socket socket) { sockets.put(socket.id(), socket); socket.closeAction(new VoidAction() { @Override public void on() { sockets.remove(socket.id()); } }); protocol.on(socket); } }); sessionAction(new Action<SessionBase>() { @Override public void on(SessionBase session) { final Socket socket = session.unwrap(Socket.class); sessions.put(socket, session); socket.closeAction(new VoidAction() { @Override public void on() { sessions.remove(socket); } }); } }); for (Object comp : new Object[] { bridge, protocol }) { if (comp instanceof AppInsideAware) { ((AppInsideAware) comp).setAppInside(this); } if (comp instanceof Initable) { ((Initable) comp).init(); } } } @Override public Options options() { return options; } @Override public ConcurrentMap<String, Socket> sockets() { return sockets; } @SuppressWarnings("unchecked") @Override public App all(Action<? extends SessionBase> action) { for (Socket socket : sockets.values()) { ((Action<SessionBase>) action).on(sessions.get(socket)); } return this; } @SuppressWarnings("unchecked") @Override public App byId(String id, Action<? extends SessionBase> action) { Socket socket = sockets.get(id); if (socket != null) { ((Action<SessionBase>) action).on(sessions.get(socket)); } return this; } @SuppressWarnings("unchecked") @Override public App byTag(String name, Action<? extends SessionBase> action) { for (Socket socket : sockets.values()) { if (socket.tags().contains(name)) { ((Action<SessionBase>) action).on(sessions.get(socket)); } } return this; } @Override public App httpAction(Action<HttpExchange> action) { bridge.httpActions().add(action); return this; } @Override public App webSocketAction(Action<WebSocket> action) { bridge.webSocketActions().add(action); return this; } @Override public App socketAction(Action<Socket> action) { protocol.socketActions().add(action); return this; } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public App sessionAction(Action<? extends SessionBase> action) { protocol.sessionActions().add((Action) action); return this; } @Override public App closeAction(Action<Void> action) { closeActions.add(action); return this; } @Override public void close() { closeActions.fire(); } }
Hide constructor
src/main/java/com/github/flowersinthesand/spheres/DefaultApp.java
Hide constructor
Java
bsd-2-clause
f0650920148daa8280563a30ed2e306670a14ee7
0
ratan12/Atarashii,ratan12/Atarashii,AnimeNeko/Atarashii,AnimeNeko/Atarashii
package net.somethingdreadful.MAL.sql; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.crashlytics.android.Crashlytics; import net.somethingdreadful.MAL.MALDateTools; import net.somethingdreadful.MAL.api.MALApi; import net.somethingdreadful.MAL.api.response.Anime; import net.somethingdreadful.MAL.api.response.Manga; import net.somethingdreadful.MAL.api.response.RecordStub; import net.somethingdreadful.MAL.api.response.User; import java.util.ArrayList; import java.util.HashMap; public class DatabaseManager { MALSqlHelper malSqlHelper; SQLiteDatabase dbRead; public DatabaseManager(Context context) { if (malSqlHelper == null) malSqlHelper = MALSqlHelper.getHelper(context); } public synchronized SQLiteDatabase getDBWrite() { return malSqlHelper.getWritableDatabase(); } public SQLiteDatabase getDBRead() { if (dbRead == null) dbRead = malSqlHelper.getReadableDatabase(); return dbRead; } public void saveAnimeList(ArrayList<Anime> list, String username) { Integer userId = getUserId(username); if (list != null && list.size() > 0 && userId != null) { try { getDBWrite().beginTransaction(); for (Anime anime : list) saveAnime(anime, true, userId); getDBWrite().setTransactionSuccessful(); } catch (Exception e) { Crashlytics.log(Log.ERROR, "MALX", "DatabaseManager.saveAnimeList(): " + e.getMessage()); } finally { getDBWrite().endTransaction(); } } } public void saveAnime(Anime anime, boolean IGF, String username) { Integer userId; if (username.equals("")) userId = 0; else userId = getUserId(username); saveAnime(anime, IGF, userId); } public void saveAnime(Anime anime, boolean IGF, int userId) { ContentValues cv = new ContentValues(); cv.put(MALSqlHelper.COLUMN_ID, anime.getId()); cv.put("recordName", anime.getTitle()); cv.put("recordType", anime.getType()); cv.put("imageUrl", anime.getImageUrl()); cv.put("recordStatus", anime.getStatus()); cv.put("episodesTotal", anime.getEpisodes()); if (!IGF) { cv.put("synopsis", anime.getSynopsis()); cv.put("memberScore", anime.getMembersScore()); cv.put("classification", anime.getClassification()); cv.put("membersCount", anime.getMembersCount()); cv.put("favoritedCount", anime.getFavoritedCount()); cv.put("popularityRank", anime.getPopularityRank()); cv.put("rank", anime.getRank()); cv.put("listedId", anime.getListedId()); } // don't use replace it replaces synopsis with null even when we don't put it in the ContentValues int updateResult = getDBWrite().update(MALSqlHelper.TABLE_ANIME, cv, MALSqlHelper.COLUMN_ID + " = ?", new String[]{Integer.toString(anime.getId())}); if (updateResult == 0) { Long insertResult = getDBWrite().insert(MALSqlHelper.TABLE_ANIME, null, cv); if (insertResult > 0) { anime.setId(insertResult.intValue()); } } if (anime.getId() > 0) { // save/update relations if saving was successful if (!IGF) { if (anime.getGenres() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_ANIME_GENRES, "anime_id = ?", new String[]{String.valueOf(anime.getId())}); for (String genre : anime.getGenres()) { Integer genreId = getGenreId(genre); if (genreId != null) { ContentValues gcv = new ContentValues(); gcv.put("anime_id", anime.getId()); gcv.put("genre_id", genreId); getDBWrite().insert(MALSqlHelper.TABLE_ANIME_GENRES, null, gcv); } } } if (anime.getTags() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_ANIME_TAGS, "anime_id = ?", new String[]{String.valueOf(anime.getId())}); for (String tag : anime.getTags()) { Integer tagId = getTagId(tag); if (tagId != null) { ContentValues gcv = new ContentValues(); gcv.put("anime_id", anime.getId()); gcv.put("tag_id", tagId); getDBWrite().replace(MALSqlHelper.TABLE_ANIME_TAGS, null, gcv); } } } saveAnimeToAnimeRelation(anime.getAlternativeVersions(), anime.getId(), MALSqlHelper.RELATION_TYPE_ALTERNATIVE); saveAnimeToAnimeRelation(anime.getCharacterAnime(), anime.getId(), MALSqlHelper.RELATION_TYPE_CHARACTER); saveAnimeToAnimeRelation(anime.getPrequels(), anime.getId(), MALSqlHelper.RELATION_TYPE_PREQUEL); saveAnimeToAnimeRelation(anime.getSequels(), anime.getId(), MALSqlHelper.RELATION_TYPE_SEQUEL); saveAnimeToAnimeRelation(anime.getSideStories(), anime.getId(), MALSqlHelper.RELATION_TYPE_SIDE_STORY); saveAnimeToAnimeRelation(anime.getSpinOffs(), anime.getId(), MALSqlHelper.RELATION_TYPE_SPINOFF); saveAnimeToAnimeRelation(anime.getSummaries(), anime.getId(), MALSqlHelper.RELATION_TYPE_SUMMARY); if (anime.getMangaAdaptions() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_ANIME_MANGA_RELATIONS, "anime_id = ? AND relationType = ?", new String[]{String.valueOf(anime.getId()), MALSqlHelper.RELATION_TYPE_ADAPTATION}); for (RecordStub mangaStub : anime.getMangaAdaptions()) { saveAnimeToMangaRelation(anime.getId(), mangaStub, MALSqlHelper.RELATION_TYPE_ADAPTATION); } } if (anime.getParentStory() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_ANIME_MANGA_RELATIONS, "anime_id = ? AND relationType = ?", new String[]{String.valueOf(anime.getId()), MALSqlHelper.RELATION_TYPE_PARENT_STORY}); saveAnimeToAnimeRelation(anime.getId(), anime.getParentStory(), MALSqlHelper.RELATION_TYPE_PARENT_STORY); } if (anime.getOtherTitles() != null) { if (anime.getOtherTitlesEnglish() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_ANIME_OTHER_TITLES, "anime_id = ? and titleType = ?", new String[]{String.valueOf(anime.getId()), MALSqlHelper.TITLE_TYPE_ENGLISH}); for (String title : anime.getOtherTitlesEnglish()) { saveAnimeOtherTitle(anime.getId(), title, MALSqlHelper.TITLE_TYPE_ENGLISH); } } if (anime.getOtherTitlesJapanese() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_ANIME_OTHER_TITLES, "anime_id = ? and titleType = ?", new String[]{String.valueOf(anime.getId()), MALSqlHelper.TITLE_TYPE_JAPANESE}); for (String title : anime.getOtherTitlesJapanese()) { saveAnimeOtherTitle(anime.getId(), title, MALSqlHelper.TITLE_TYPE_JAPANESE); } } if (anime.getOtherTitlesSynonyms() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_ANIME_OTHER_TITLES, "anime_id = ? and titleType = ?", new String[]{String.valueOf(anime.getId()), MALSqlHelper.TITLE_TYPE_SYNONYM}); for (String title : anime.getOtherTitlesSynonyms()) { saveAnimeOtherTitle(anime.getId(), title, MALSqlHelper.TITLE_TYPE_SYNONYM); } } } } // update animelist if user id is provided if (userId > 0) { ContentValues alcv = new ContentValues(); alcv.put("profile_id", userId); alcv.put("anime_id", anime.getId()); alcv.put("status", anime.getWatchedStatus()); alcv.put("score", anime.getScore()); alcv.put("watched", anime.getWatchedEpisodes()); alcv.put("dirty", anime.getDirty()); if (anime.getLastUpdate() != null) alcv.put("lastUpdate", anime.getLastUpdate().getTime()); getDBWrite().replace(MALSqlHelper.TABLE_ANIMELIST, null, alcv); } } } public void saveAnimeToAnimeRelation(ArrayList<RecordStub> record, int id, String relationType) { if (record != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_ANIME_ANIME_RELATIONS, "anime_id = ? AND relationType = ?", new String[]{String.valueOf(id), relationType}); for (RecordStub stub : record) { saveAnimeToAnimeRelation(id, stub, relationType); } } } public Anime getAnime(Integer id, String username) { Anime result = null; Cursor cursor = getDBRead().rawQuery("SELECT a.*, al.score AS myScore, al.status AS myStatus, al.watched AS episodesWatched, al.dirty, al.lastUpdate" + " FROM animelist al INNER JOIN anime a ON al.anime_id = a." + MALSqlHelper.COLUMN_ID + " WHERE al.profile_id = ? AND a." + MALSqlHelper.COLUMN_ID + " = ?", new String[]{getUserId(username).toString(), id.toString()}); if (cursor.moveToFirst()) { result = Anime.fromCursor(cursor); result.setGenres(getAnimeGenres(result.getId())); result.setTags(getAnimeTags(result.getId())); result.setAlternativeVersions(getAnimeToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_ALTERNATIVE)); result.setCharacterAnime(getAnimeToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_CHARACTER)); result.setPrequels(getAnimeToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_PREQUEL)); result.setSequels(getAnimeToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_SEQUEL)); result.setSideStories(getAnimeToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_SIDE_STORY)); result.setSpinOffs(getAnimeToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_SPINOFF)); result.setSummaries(getAnimeToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_SUMMARY)); result.setMangaAdaptions(getAnimeToMangaRelations(result.getId(), MALSqlHelper.RELATION_TYPE_ADAPTATION)); ArrayList<RecordStub> parentStory = getAnimeToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_PARENT_STORY); if (parentStory != null && parentStory.size() > 0) { result.setParentStory(parentStory.get(0)); } HashMap<String, ArrayList<String>> otherTitles = new HashMap<String, ArrayList<String>>(); otherTitles.put("english", getAnimeOtherTitles(result.getId(), MALSqlHelper.TITLE_TYPE_ENGLISH)); otherTitles.put("japanese", getAnimeOtherTitles(result.getId(), MALSqlHelper.TITLE_TYPE_JAPANESE)); otherTitles.put("synonyms", getAnimeOtherTitles(result.getId(), MALSqlHelper.TITLE_TYPE_SYNONYM)); result.setOtherTitles(otherTitles); } cursor.close(); return result; } private boolean deleteAnime(Integer id) { return getDBWrite().delete(MALSqlHelper.TABLE_ANIME, MALSqlHelper.COLUMN_ID + " = ?", new String[]{id.toString()}) == 1; } public boolean deleteAnimeFromAnimelist(Integer id, String username) { boolean result = false; Integer userId = getUserId(username); if (userId != 0) { result = getDBWrite().delete(MALSqlHelper.TABLE_ANIMELIST, "profile_id = ? AND anime_id = ?", new String[]{userId.toString(), id.toString()}) == 1; if (result) { boolean isUsed = false; /* check if this record is used for other relations and delete if it's not to keep the database * still used relations can be: * - animelist of other user * - record is related to other anime or manga (e.g. as sequel or adaptation) */ // used in other animelist? isUsed = recordExists(MALSqlHelper.TABLE_ANIMELIST, "anime_id", id.toString()); if (!isUsed) { // no need to check more if its already used // used as related record of other anime? isUsed = recordExists(MALSqlHelper.TABLE_ANIME_ANIME_RELATIONS, "related_id", id.toString()); } if (!isUsed) { // no need to check more if its already used // used as related record of an manga? isUsed = recordExists(MALSqlHelper.TABLE_MANGA_ANIME_RELATIONS, "related_id", id.toString()); } if (!isUsed) {// its not used anymore, delete it deleteAnime(id); } } } return result; } // delete all anime records without relations, because they're "dead" records public void cleanupAnimeTable() { getDBWrite().rawQuery("DELETE FROM anime WHERE " + MALSqlHelper.COLUMN_ID + " NOT IN (SELECT DISTINCT anime_id FROM " + MALSqlHelper.TABLE_ANIMELIST + ") AND " + MALSqlHelper.COLUMN_ID + " NOT IN (SELECT DISTINCT related_id FROM " + MALSqlHelper.TABLE_ANIME_ANIME_RELATIONS + ") AND " + MALSqlHelper.COLUMN_ID + " NOT IN (SELECT DISTINCT related_id FROM " + MALSqlHelper.TABLE_MANGA_ANIME_RELATIONS + ")", null); } public ArrayList<Anime> getAnimeList(String listType, String username) { if (listType == "") return getAnimeList(getUserId(username), "", false); else return getAnimeList(getUserId(username), listType, false); } public ArrayList<Anime> getDirtyAnimeList(String username) { return getAnimeList(getUserId(username), "", true); } private ArrayList<Anime> getAnimeList(int userId, String listType, boolean dirtyOnly) { ArrayList<Anime> result = null; Cursor cursor; try { ArrayList<String> selArgs = new ArrayList<String>(); selArgs.add(String.valueOf(userId)); if (listType != "") { selArgs.add(listType); } cursor = getDBRead().rawQuery("SELECT a.*, al.score AS myScore, al.status AS myStatus, al.watched AS episodesWatched, al.dirty, al.lastUpdate" + " FROM animelist al INNER JOIN anime a ON al.anime_id = a." + MALSqlHelper.COLUMN_ID + " WHERE al.profile_id = ? " + (listType != "" ? " AND al.status = ? " : "") + (dirtyOnly ? " AND al.dirty = 1 " : "") + " ORDER BY a.recordName COLLATE NOCASE", selArgs.toArray(new String[selArgs.size()])); if (cursor.moveToFirst()) { result = new ArrayList<Anime>(); do { result.add(Anime.fromCursor(cursor)); } while (cursor.moveToNext()); } cursor.close(); } catch (SQLException e) { Crashlytics.log(Log.ERROR, "MALX", "DatabaseManager.getAnimeList(): " + e.getMessage()); } return result; } public void saveMangaList(ArrayList<Manga> list, String username) { Integer userId = getUserId(username); if (list != null && list.size() > 0 && userId != null) { try { getDBWrite().beginTransaction(); for (Manga manga : list) saveManga(manga, true, userId); getDBWrite().setTransactionSuccessful(); } catch (Exception e) { Crashlytics.log(Log.ERROR, "MALX", "DatabaseManager.saveMangaList(): " + e.getMessage()); } finally { getDBWrite().endTransaction(); } } } public void saveManga(Manga manga, boolean ignoreSynopsis, String username) { Integer userId; if (username.equals("")) userId = 0; else userId = getUserId(username); saveManga(manga, ignoreSynopsis, userId); } public void saveManga(Manga manga, boolean ignoreSynopsis, int userId) { ContentValues cv = new ContentValues(); cv.put(MALSqlHelper.COLUMN_ID, manga.getId()); cv.put("recordName", manga.getTitle()); cv.put("recordType", manga.getType()); cv.put("imageUrl", manga.getImageUrl()); cv.put("recordStatus", manga.getStatus()); cv.put("volumesTotal", manga.getVolumes()); cv.put("chaptersTotal", manga.getChapters()); if (!ignoreSynopsis) { cv.put("synopsis", manga.getSynopsis()); cv.put("membersCount", manga.getMembersCount()); cv.put("memberScore", manga.getMembersScore()); cv.put("favoritedCount", manga.getFavoritedCount()); cv.put("popularityRank", manga.getPopularityRank()); cv.put("rank", manga.getRank()); cv.put("listedId", manga.getListedId()); } // don't use replace it replaces synopsis with null even when we don't put it in the ContentValues int updateResult = getDBWrite().update(MALSqlHelper.TABLE_MANGA, cv, MALSqlHelper.COLUMN_ID + " = ?", new String[]{Integer.toString(manga.getId())}); if (updateResult == 0) { Long insertResult = getDBWrite().insert(MALSqlHelper.TABLE_MANGA, null, cv); if (insertResult > 0) { manga.setId(insertResult.intValue()); } } if (manga.getId() > 0) { // save/update relations if saving was successful if (!ignoreSynopsis) { // only on DetailView! if (manga.getGenres() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_MANGA_GENRES, "manga_id = ?", new String[]{String.valueOf(manga.getId())}); for (String genre : manga.getGenres()) { Integer genreId = getGenreId(genre); if (genreId != null) { ContentValues gcv = new ContentValues(); gcv.put("manga_id", manga.getId()); gcv.put("genre_id", genreId); getDBWrite().replace(MALSqlHelper.TABLE_MANGA_GENRES, null, gcv); } } } if (manga.getTags() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_MANGA_TAGS, "manga_id = ?", new String[]{String.valueOf(manga.getId())}); for (String tag : manga.getTags()) { Integer tagId = getTagId(tag); if (tagId != null) { ContentValues gcv = new ContentValues(); gcv.put("manga_id", manga.getId()); gcv.put("tag_id", tagId); getDBWrite().replace(MALSqlHelper.TABLE_MANGA_TAGS, null, gcv); } } } if (manga.getAlternativeVersions() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_MANGA_MANGA_RELATIONS, "manga_id = ? AND relationType = ?", new String[]{String.valueOf(manga.getId()), MALSqlHelper.RELATION_TYPE_ALTERNATIVE}); for (RecordStub mangaStub : manga.getAlternativeVersions()) { saveMangaToMangaRelation(manga.getId(), mangaStub, MALSqlHelper.RELATION_TYPE_ALTERNATIVE); } } if (manga.getRelatedManga() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_MANGA_MANGA_RELATIONS, "manga_id = ? AND relationType = ?", new String[]{String.valueOf(manga.getId()), MALSqlHelper.RELATION_TYPE_RELATED}); for (RecordStub mangaStub : manga.getRelatedManga()) { saveMangaToMangaRelation(manga.getId(), mangaStub, MALSqlHelper.RELATION_TYPE_RELATED); } } if (manga.getAnimeAdaptations() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_MANGA_ANIME_RELATIONS, "manga_id = ? AND relationType = ?", new String[]{String.valueOf(manga.getId()), MALSqlHelper.RELATION_TYPE_ADAPTATION}); for (RecordStub animeStub : manga.getAnimeAdaptations()) { saveMangaToAnimeRelation(manga.getId(), animeStub, MALSqlHelper.RELATION_TYPE_ADAPTATION); } } if (manga.getOtherTitles() != null) { if (manga.getOtherTitlesEnglish() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_MANGA_OTHER_TITLES, "manga_id = ? and titleType = ?", new String[]{String.valueOf(manga.getId()), MALSqlHelper.TITLE_TYPE_ENGLISH}); for (String title : manga.getOtherTitlesEnglish()) { saveMangaOtherTitle(manga.getId(), title, MALSqlHelper.TITLE_TYPE_ENGLISH); } } if (manga.getOtherTitlesJapanese() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_MANGA_OTHER_TITLES, "manga_id = ? and titleType = ?", new String[]{String.valueOf(manga.getId()), MALSqlHelper.TITLE_TYPE_JAPANESE}); for (String title : manga.getOtherTitlesJapanese()) { saveMangaOtherTitle(manga.getId(), title, MALSqlHelper.TITLE_TYPE_JAPANESE); } } if (manga.getOtherTitlesSynonyms() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_MANGA_OTHER_TITLES, "manga_id = ? and titleType = ?", new String[]{String.valueOf(manga.getId()), MALSqlHelper.TITLE_TYPE_SYNONYM}); for (String title : manga.getOtherTitlesSynonyms()) { saveMangaOtherTitle(manga.getId(), title, MALSqlHelper.TITLE_TYPE_SYNONYM); } } } } // update mangalist if user id is provided if (userId > 0) { ContentValues mlcv = new ContentValues(); mlcv.put("profile_id", userId); mlcv.put("manga_id", manga.getId()); mlcv.put("status", manga.getReadStatus()); mlcv.put("score", manga.getScore()); mlcv.put("volumesRead", manga.getVolumesRead()); mlcv.put("chaptersRead", manga.getChaptersRead()); mlcv.put("dirty", manga.getDirty()); if (manga.getLastUpdate() != null) mlcv.put("lastUpdate", manga.getLastUpdate().getTime()); getDBWrite().replace(MALSqlHelper.TABLE_MANGALIST, null, mlcv); } } } public Manga getManga(Integer id, String username) { Manga result = null; Cursor cursor = getDBRead().rawQuery("SELECT m.*, ml.score AS myScore, ml.status AS myStatus, ml.chaptersRead, ml.volumesRead, ml.dirty, ml.lastUpdate" + " FROM mangalist ml INNER JOIN manga m ON ml.manga_id = m." + MALSqlHelper.COLUMN_ID + " WHERE ml.profile_id = ? and m." + MALSqlHelper.COLUMN_ID + " = ?", new String[]{getUserId(username).toString(), id.toString()}); if (cursor.moveToFirst()) { result = Manga.fromCursor(cursor); result.setGenres(getMangaGenres(result.getId())); result.setTags(getMangaTags(result.getId())); result.setAlternativeVersions(getMangaToMangaRelations(result.getId(), MALSqlHelper.RELATION_TYPE_ALTERNATIVE)); result.setRelatedManga(getMangaToMangaRelations(result.getId(), MALSqlHelper.RELATION_TYPE_RELATED)); result.setAnimeAdaptations(getMangaToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_ADAPTATION)); HashMap<String, ArrayList<String>> otherTitles = new HashMap<String, ArrayList<String>>(); otherTitles.put("english", getMangaOtherTitles(result.getId(), MALSqlHelper.TITLE_TYPE_ENGLISH)); otherTitles.put("japanese", getMangaOtherTitles(result.getId(), MALSqlHelper.TITLE_TYPE_JAPANESE)); otherTitles.put("synonyms", getMangaOtherTitles(result.getId(), MALSqlHelper.TITLE_TYPE_SYNONYM)); result.setOtherTitles(otherTitles); } cursor.close(); return result; } private boolean deleteManga(Integer id) { return getDBWrite().delete(MALSqlHelper.TABLE_MANGA, MALSqlHelper.COLUMN_ID + " = ?", new String[]{id.toString()}) == 1; } public boolean deleteMangaFromMangalist(Integer id, String username) { boolean result = false; Integer userId = getUserId(username); if (userId != 0) { result = getDBWrite().delete(MALSqlHelper.TABLE_MANGALIST, "profile_id = ? AND manga_id = ?", new String[]{userId.toString(), id.toString()}) == 1; if (result) { boolean isUsed = false; /* check if this record is used for other relations and delete if it's not to keep the database * still used relations can be: * - mangalist of other user * - record is related to other anime or manga (e.g. as sequel or adaptation) */ // used in other mangalist? isUsed = recordExists(MALSqlHelper.TABLE_MANGALIST, "manga_id", id.toString()); if (!isUsed) { // no need to check more if its already used // used as related record of other manga? isUsed = recordExists(MALSqlHelper.TABLE_MANGA_MANGA_RELATIONS, "related_id", id.toString()); } if (!isUsed) { // no need to check more if its already used // used as related record of an anime? isUsed = recordExists(MALSqlHelper.TABLE_ANIME_MANGA_RELATIONS, "related_id", id.toString()); } if (!isUsed) {// its not used anymore, delete it deleteManga(id); } } } return result; } // delete all manga records without relations, because they're "dead" records public void cleanupMangaTable() { getDBWrite().rawQuery("DELETE FROM manga WHERE " + MALSqlHelper.COLUMN_ID + " NOT IN (SELECT DISTINCT manga_id FROM " + MALSqlHelper.TABLE_MANGALIST + ") AND " + MALSqlHelper.COLUMN_ID + " NOT IN (SELECT DISTINCT related_id FROM " + MALSqlHelper.TABLE_MANGA_MANGA_RELATIONS + ") AND " + MALSqlHelper.COLUMN_ID + " NOT IN (SELECT DISTINCT related_id FROM " + MALSqlHelper.TABLE_ANIME_MANGA_RELATIONS + ")", null); } public ArrayList<Manga> getMangaList(String listType, String username) { if (listType == "") return getMangaList(getUserId(username), "", false); else return getMangaList(getUserId(username), listType, false); } public ArrayList<Manga> getDirtyMangaList(String username) { return getMangaList(getUserId(username), "", true); } private ArrayList<Manga> getMangaList(int userId, String listType, boolean dirtyOnly) { ArrayList<Manga> result = null; Cursor cursor; try { ArrayList<String> selArgs = new ArrayList<String>(); selArgs.add(String.valueOf(userId)); if (listType != "") { selArgs.add(listType); } cursor = getDBRead().rawQuery("SELECT m.*, ml.score AS myScore, ml.status AS myStatus, ml.chaptersRead, ml.volumesRead, ml.dirty, ml.lastUpdate" + " FROM mangalist ml INNER JOIN manga m ON ml.manga_id = m." + MALSqlHelper.COLUMN_ID + " WHERE ml.profile_id = ? " + (listType != "" ? " AND ml.status = ? " : "") + (dirtyOnly ? " AND ml.dirty = 1 " : "") + " ORDER BY m.recordName COLLATE NOCASE", selArgs.toArray(new String[selArgs.size()])); if (cursor.moveToFirst()) { result = new ArrayList<Manga>(); do { result.add(Manga.fromCursor(cursor)); } while (cursor.moveToNext()); } cursor.close(); } catch (SQLException e) { Crashlytics.log(Log.ERROR, "MALX", "DatabaseManager.getMangaList(): " + e.getMessage()); } return result; } public void saveUser(User user, Boolean profile) { ContentValues cv = new ContentValues(); cv.put("username", user.getName()); if (user.getProfile().getAvatarUrl().equals("http://cdn.myanimelist.net/images/questionmark_50.gif")) cv.put("avatar_url", "http://cdn.myanimelist.net/images/na.gif"); else cv.put("avatar_url", user.getProfile().getAvatarUrl()); if (user.getProfile().getDetails().getLastOnline() != null) { String lastOnline = MALDateTools.parseMALDateToISO8601String(user.getProfile().getDetails().getLastOnline()); cv.put("last_online", lastOnline.equals("") ? user.getProfile().getDetails().getLastOnline() : lastOnline); } else cv.putNull("last_online"); if (profile) { if (user.getProfile().getDetails().getBirthday() != null) { String birthday = MALDateTools.parseMALDateToISO8601String(user.getProfile().getDetails().getBirthday()); cv.put("birthday", birthday.equals("") ? user.getProfile().getDetails().getBirthday() : birthday); } else cv.putNull("birthday"); cv.put("location", user.getProfile().getDetails().getLocation()); cv.put("website", user.getProfile().getDetails().getWebsite()); cv.put("comments", user.getProfile().getDetails().getComments()); cv.put("forum_posts", user.getProfile().getDetails().getForumPosts()); cv.put("gender", user.getProfile().getDetails().getGender()); if (user.getProfile().getDetails().getJoinDate() != null) { String joindate = MALDateTools.parseMALDateToISO8601String(user.getProfile().getDetails().getJoinDate()); cv.put("join_date", joindate.equals("") ? user.getProfile().getDetails().getJoinDate() : joindate); } else cv.putNull("join_date"); cv.put("access_rank", user.getProfile().getDetails().getAccessRank()); cv.put("anime_list_views", user.getProfile().getDetails().getAnimeListViews()); cv.put("manga_list_views", user.getProfile().getDetails().getMangaListViews()); cv.put("anime_time_days", user.getProfile().getAnimeStats().getTimeDays()); cv.put("anime_watching", user.getProfile().getAnimeStats().getWatching()); cv.put("anime_completed", user.getProfile().getAnimeStats().getCompleted()); cv.put("anime_on_hold", user.getProfile().getAnimeStats().getOnHold()); cv.put("anime_dropped", user.getProfile().getAnimeStats().getDropped()); cv.put("anime_plan_to_watch", user.getProfile().getAnimeStats().getPlanToWatch()); cv.put("anime_total_entries", user.getProfile().getAnimeStats().getTotalEntries()); cv.put("manga_time_days", user.getProfile().getMangaStats().getTimeDays()); cv.put("manga_reading", user.getProfile().getMangaStats().getReading()); cv.put("manga_completed", user.getProfile().getMangaStats().getCompleted()); cv.put("manga_on_hold", user.getProfile().getMangaStats().getOnHold()); cv.put("manga_dropped", user.getProfile().getMangaStats().getDropped()); cv.put("manga_plan_to_read", user.getProfile().getMangaStats().getPlanToRead()); cv.put("manga_total_entries", user.getProfile().getMangaStats().getTotalEntries()); } // don't use replace it alters the autoincrement _id field! int updateResult = getDBWrite().update(MALSqlHelper.TABLE_PROFILE, cv, "username = ?", new String[]{user.getName()}); if (updateResult > 0) {// updated row user.setId(getUserId(user.getName())); } else { Long insertResult = getDBWrite().insert(MALSqlHelper.TABLE_PROFILE, null, cv); user.setId(insertResult.intValue()); } } public void saveUserFriends(Integer userId, ArrayList<User> friends) { if (userId == null || friends == null) { return; } SQLiteDatabase db = getDBWrite(); db.beginTransaction(); try { db.delete(MALSqlHelper.TABLE_FRIENDLIST, "profile_id = ?", new String[]{userId.toString()}); for (User friend : friends) { ContentValues cv = new ContentValues(); cv.put("profile_id", userId); cv.put("friend_id", friend.getId()); db.insert(MALSqlHelper.TABLE_FRIENDLIST, null, cv); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } public User getProfile(String name) { User result = null; Cursor cursor; try { cursor = getDBRead().query(MALSqlHelper.TABLE_PROFILE, null, "username = ?", new String[]{name}, null, null, null); if (cursor.moveToFirst()) result = User.fromCursor(cursor); cursor.close(); } catch (SQLException e) { Crashlytics.log(Log.ERROR, "MALX", "DatabaseManager.getProfile(): " + e.getMessage()); } return result; } public ArrayList<User> getFriendList(String username) { ArrayList<User> friendlist = new ArrayList<User>(); Cursor cursor = getDBRead().rawQuery("SELECT p1.* FROM " + MALSqlHelper.TABLE_PROFILE + " AS p1" + // for result rows " INNER JOIN " + MALSqlHelper.TABLE_PROFILE + " AS p2" + // for getting user id to given name " INNER JOIN " + MALSqlHelper.TABLE_FRIENDLIST + " AS fl ON fl.profile_id = p2." + MALSqlHelper.COLUMN_ID + // for user<>friend relation " WHERE p2.username = ? AND p1." + MALSqlHelper.COLUMN_ID + " = fl.friend_id ORDER BY p1.username COLLATE NOCASE", new String[]{username}); if (cursor.moveToFirst()) { do { friendlist.add(User.fromCursor(cursor)); } while (cursor.moveToNext()); } cursor.close(); return friendlist; } public void saveFriendList(ArrayList<User> friendlist, String username) { for (User friend : friendlist) { saveUser(friend, false); } Integer userId = getUserId(username); saveUserFriends(userId, friendlist); } private Integer getGenreId(String genre) { return getRecordId(MALSqlHelper.TABLE_GENRES, MALSqlHelper.COLUMN_ID, "recordName", genre); } private Integer getTagId(String tag) { return getRecordId(MALSqlHelper.TABLE_TAGS, MALSqlHelper.COLUMN_ID, "recordName", tag); } private Integer getUserId(String username) { if (username == null || username.equals("")) return 0; Integer id = getRecordId(MALSqlHelper.TABLE_PROFILE, MALSqlHelper.COLUMN_ID, "username", username); if (id == null) { id = 0; } return id; } private Integer getRecordId(String table, String idField, String searchField, String value) { Integer result = null; Cursor cursor = getDBRead().query(table, new String[]{idField}, searchField + " = ?", new String[]{value}, null, null, null); if (cursor.moveToFirst()) { result = cursor.getInt(0); } cursor.close(); if (result == null) { ContentValues cv = new ContentValues(); cv.put(searchField, value); Long addResult = getDBWrite().insert(table, null, cv); if (addResult > -1) { result = addResult.intValue(); } } return result; } public ArrayList<String> getAnimeGenres(Integer animeId) { ArrayList<String> result = null; Cursor cursor = getDBRead().rawQuery("SELECT g.recordName FROM " + MALSqlHelper.TABLE_GENRES + " g " + "INNER JOIN " + MALSqlHelper.TABLE_ANIME_GENRES + " ag ON ag.genre_id = g." + MALSqlHelper.COLUMN_ID + " WHERE ag.anime_id = ? ORDER BY g.recordName COLLATE NOCASE", new String[]{animeId.toString()}); if (cursor.moveToFirst()) { result = new ArrayList<String>(); do { result.add(cursor.getString(0)); } while (cursor.moveToNext()); } cursor.close(); return result; } public ArrayList<String> getAnimeTags(Integer animeId) { ArrayList<String> result = null; Cursor cursor = getDBRead().rawQuery("SELECT t.recordName FROM " + MALSqlHelper.TABLE_TAGS + " t " + "INNER JOIN " + MALSqlHelper.TABLE_ANIME_TAGS + " at ON at.tag_id = t." + MALSqlHelper.COLUMN_ID + " WHERE at.anime_id = ? ORDER BY t.recordName COLLATE NOCASE", new String[]{animeId.toString()}); if (cursor.moveToFirst()) { result = new ArrayList<String>(); do { result.add(cursor.getString(0)); } while (cursor.moveToNext()); } cursor.close(); return result; } public ArrayList<String> getMangaGenres(Integer mangaId) { ArrayList<String> result = null; Cursor cursor = getDBRead().rawQuery("SELECT g.recordName FROM " + MALSqlHelper.TABLE_GENRES + " g " + "INNER JOIN " + MALSqlHelper.TABLE_MANGA_GENRES + " mg ON mg.genre_id = g." + MALSqlHelper.COLUMN_ID + " WHERE mg.manga_id = ? ORDER BY g.recordName COLLATE NOCASE", new String[]{mangaId.toString()}); if (cursor.moveToFirst()) { result = new ArrayList<String>(); do { result.add(cursor.getString(0)); } while (cursor.moveToNext()); } cursor.close(); return result; } public ArrayList<String> getMangaTags(Integer mangaId) { ArrayList<String> result = null; Cursor cursor = getDBRead().rawQuery("SELECT t.recordName FROM " + MALSqlHelper.TABLE_TAGS + " t " + "INNER JOIN " + MALSqlHelper.TABLE_MANGA_TAGS + " mt ON mt.tag_id = t." + MALSqlHelper.COLUMN_ID + " WHERE mt.manga_id = ? ORDER BY t.recordName COLLATE NOCASE", new String[]{mangaId.toString()}); if (cursor.moveToFirst()) { result = new ArrayList<String>(); do { result.add(cursor.getString(0)); } while (cursor.moveToNext()); } cursor.close(); return result; } private boolean recordExists(String table, String searchField, String searchValue) { boolean result = false; Cursor cursor = getDBRead().query(table, null, searchField + " = ?", new String[]{searchValue}, null, null, null); if (cursor.moveToFirst()) { result = true; } cursor.close(); return result; } /* Storing relations is a little more complicated as we need to look if the related anime is * stored in the database, if not we need to create a new record before storing the information. * This record then only has the few informations that are available in the relation object * returned by the API (only id and title) */ private void saveAnimeToAnimeRelation(int animeId, RecordStub relatedAnime, String relationType) { if (relatedAnime.getId() == 0) { Crashlytics.log(Log.ERROR, "MALX", "DatabaseManager.saveAnimeToAnimeRelation(): error saving relation: anime id must not be 0; title: " + relatedAnime.getTitle()); return; } boolean relatedRecordExists; if (!recordExists(MALSqlHelper.TABLE_ANIME, MALSqlHelper.COLUMN_ID, String.valueOf(relatedAnime.getId()))) { ContentValues cv = new ContentValues(); cv.put(MALSqlHelper.COLUMN_ID, relatedAnime.getId()); cv.put("recordName", relatedAnime.getTitle()); relatedRecordExists = getDBWrite().insert(MALSqlHelper.TABLE_ANIME, null, cv) > 0; } else { relatedRecordExists = true; } if (relatedRecordExists) { ContentValues cv = new ContentValues(); cv.put("anime_id", animeId); cv.put("related_id", relatedAnime.getId()); cv.put("relationType", relationType); getDBWrite().replace(MALSqlHelper.TABLE_ANIME_ANIME_RELATIONS, null, cv); } } private void saveAnimeToMangaRelation(int animeId, RecordStub relatedManga, String relationType) { if (relatedManga.getId() == 0) { Crashlytics.log(Log.ERROR, "MALX", "DatabaseManager.saveAnimeToMangaRelation(): error saving relation: manga id must not be 0; title: " + relatedManga.getTitle()); return; } boolean relatedRecordExists; if (!recordExists(MALSqlHelper.TABLE_MANGA, MALSqlHelper.COLUMN_ID, String.valueOf(relatedManga.getId()))) { ContentValues cv = new ContentValues(); cv.put(MALSqlHelper.COLUMN_ID, relatedManga.getId()); cv.put("recordName", relatedManga.getTitle()); relatedRecordExists = getDBWrite().insert(MALSqlHelper.TABLE_MANGA, null, cv) > 0; } else { relatedRecordExists = true; } if (relatedRecordExists) { ContentValues cv = new ContentValues(); cv.put("anime_id", animeId); cv.put("related_id", relatedManga.getId()); cv.put("relationType", relationType); getDBWrite().replace(MALSqlHelper.TABLE_ANIME_MANGA_RELATIONS, null, cv); } } private void saveMangaToMangaRelation(int mangaId, RecordStub relatedManga, String relationType) { if (relatedManga.getId() == 0) { Crashlytics.log(Log.ERROR, "MALX", "DatabaseManager.saveMangaToMangaRelation(): error saving relation: manga id must not be 0; title: " + relatedManga.getTitle()); return; } boolean relatedRecordExists; if (!recordExists(MALSqlHelper.TABLE_MANGA, MALSqlHelper.COLUMN_ID, String.valueOf(relatedManga.getId()))) { ContentValues cv = new ContentValues(); cv.put(MALSqlHelper.COLUMN_ID, relatedManga.getId()); cv.put("recordName", relatedManga.getTitle()); relatedRecordExists = getDBWrite().insert(MALSqlHelper.TABLE_MANGA, null, cv) > 0; } else { relatedRecordExists = true; } if (relatedRecordExists) { ContentValues cv = new ContentValues(); cv.put("manga_id", mangaId); cv.put("related_id", relatedManga.getId()); cv.put("relationType", relationType); getDBWrite().replace(MALSqlHelper.TABLE_MANGA_MANGA_RELATIONS, null, cv); } } private void saveMangaToAnimeRelation(int mangaId, RecordStub relatedAnime, String relationType) { if (relatedAnime.getId() == 0) { Crashlytics.log(Log.ERROR, "MALX", "DatabaseManager.saveMangaToAnimeRelation(): error saving relation: anime id must not be 0; title: " + relatedAnime.getTitle()); return; } boolean relatedRecordExists; if (!recordExists(MALSqlHelper.TABLE_ANIME, MALSqlHelper.COLUMN_ID, String.valueOf(relatedAnime.getId()))) { ContentValues cv = new ContentValues(); cv.put(MALSqlHelper.COLUMN_ID, relatedAnime.getId()); cv.put("recordName", relatedAnime.getTitle()); relatedRecordExists = getDBWrite().insert(MALSqlHelper.TABLE_ANIME, null, cv) > 0; } else { relatedRecordExists = true; } if (relatedRecordExists) { ContentValues cv = new ContentValues(); cv.put("manga_id", mangaId); cv.put("related_id", relatedAnime.getId()); cv.put("relationType", relationType); getDBWrite().replace(MALSqlHelper.TABLE_MANGA_ANIME_RELATIONS, null, cv); } } private ArrayList<RecordStub> getAnimeToAnimeRelations(Integer animeId, String relationType) { ArrayList<RecordStub> result = null; Cursor cursor = getDBRead().rawQuery("SELECT a." + MALSqlHelper.COLUMN_ID + ", a.recordName FROM " + MALSqlHelper.TABLE_ANIME + " a " + "INNER JOIN " + MALSqlHelper.TABLE_ANIME_ANIME_RELATIONS + " ar ON a." + MALSqlHelper.COLUMN_ID + " = ar.related_id " + "WHERE ar.anime_id = ? AND ar.relationType = ? ORDER BY a.recordName COLLATE NOCASE", new String[]{animeId.toString(), relationType}); if (cursor.moveToFirst()) { result = new ArrayList<RecordStub>(); do { RecordStub animeStub = new RecordStub(); animeStub.setId(cursor.getInt(0), MALApi.ListType.ANIME); animeStub.setTitle(cursor.getString(1)); result.add(animeStub); } while (cursor.moveToNext()); } cursor.close(); return result; } private ArrayList<RecordStub> getAnimeToMangaRelations(Integer animeId, String relationType) { ArrayList<RecordStub> result = null; Cursor cursor = getDBRead().rawQuery("SELECT m." + MALSqlHelper.COLUMN_ID + ", m.recordName FROM " + MALSqlHelper.TABLE_MANGA + " m " + "INNER JOIN " + MALSqlHelper.TABLE_ANIME_MANGA_RELATIONS + " ar ON m." + MALSqlHelper.COLUMN_ID + " = ar.related_id " + "WHERE ar.anime_id = ? AND ar.relationType = ? ORDER BY m.recordName COLLATE NOCASE", new String[]{animeId.toString(), relationType}); if (cursor.moveToFirst()) { result = new ArrayList<RecordStub>(); do { RecordStub mangaStub = new RecordStub(); mangaStub.setId(cursor.getInt(0), MALApi.ListType.MANGA); mangaStub.setTitle(cursor.getString(1)); result.add(mangaStub); } while (cursor.moveToNext()); } cursor.close(); return result; } private ArrayList<RecordStub> getMangaToMangaRelations(Integer mangaId, String relationType) { ArrayList<RecordStub> result = null; Cursor cursor = getDBRead().rawQuery("SELECT m." + MALSqlHelper.COLUMN_ID + ", m.recordName FROM " + MALSqlHelper.TABLE_MANGA + " m " + "INNER JOIN " + MALSqlHelper.TABLE_MANGA_MANGA_RELATIONS + " mr ON m." + MALSqlHelper.COLUMN_ID + " = mr.related_id " + "WHERE mr.manga_id = ? AND mr.relationType = ? ORDER BY m.recordName COLLATE NOCASE", new String[]{mangaId.toString(), relationType}); if (cursor.moveToFirst()) { result = new ArrayList<RecordStub>(); do { RecordStub mangaStub = new RecordStub(); mangaStub.setId(cursor.getInt(0), MALApi.ListType.MANGA); mangaStub.setTitle(cursor.getString(1)); result.add(mangaStub); } while (cursor.moveToNext()); } cursor.close(); return result; } private ArrayList<RecordStub> getMangaToAnimeRelations(Integer mangaId, String relationType) { ArrayList<RecordStub> result = null; Cursor cursor = getDBRead().rawQuery("SELECT a." + MALSqlHelper.COLUMN_ID + ", a.recordName FROM " + MALSqlHelper.TABLE_ANIME + " a " + "INNER JOIN " + MALSqlHelper.TABLE_MANGA_ANIME_RELATIONS + " mr ON a." + MALSqlHelper.COLUMN_ID + " = mr.related_id " + "WHERE mr.manga_id = ? AND mr.relationType = ? ORDER BY a.recordName COLLATE NOCASE", new String[]{mangaId.toString(), relationType}); if (cursor.moveToFirst()) { result = new ArrayList<RecordStub>(); do { RecordStub animeStub = new RecordStub(); animeStub.setId(cursor.getInt(0), MALApi.ListType.ANIME); animeStub.setTitle(cursor.getString(1)); result.add(animeStub); } while (cursor.moveToNext()); } cursor.close(); return result; } private void saveAnimeOtherTitle(int animeId, String title, String titleType) { ContentValues cv = new ContentValues(); cv.put("anime_id", animeId); cv.put("titleType", titleType); cv.put("title", title); getDBWrite().replace(MALSqlHelper.TABLE_ANIME_OTHER_TITLES, null, cv); } private void saveMangaOtherTitle(int mangaId, String title, String titleType) { ContentValues cv = new ContentValues(); cv.put("manga_id", mangaId); cv.put("titleType", titleType); cv.put("title", title); getDBWrite().replace(MALSqlHelper.TABLE_MANGA_OTHER_TITLES, null, cv); } private ArrayList<String> getAnimeOtherTitles(Integer animeId, String titleType) { ArrayList<String> result = null; Cursor cursor = getDBRead().query(MALSqlHelper.TABLE_ANIME_OTHER_TITLES, new String[]{"title"}, "anime_id = ? AND titleType = ?", new String[]{animeId.toString(), titleType}, null, null, "title COLLATE NOCASE"); if (cursor.moveToFirst()) { result = new ArrayList<String>(); do { result.add(cursor.getString(0)); } while (cursor.moveToNext()); } cursor.close(); return result; } private ArrayList<String> getMangaOtherTitles(Integer mangaId, String titleType) { ArrayList<String> result = null; Cursor cursor = getDBRead().query(MALSqlHelper.TABLE_MANGA_OTHER_TITLES, new String[]{"title"}, "manga_id = ? AND titleType = ?", new String[]{mangaId.toString(), titleType}, null, null, "title COLLATE NOCASE"); if (cursor.moveToFirst()) { result = new ArrayList<String>(); do { result.add(cursor.getString(0)); } while (cursor.moveToNext()); } cursor.close(); return result; } }
Atarashii/src/net/somethingdreadful/MAL/sql/DatabaseManager.java
package net.somethingdreadful.MAL.sql; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.crashlytics.android.Crashlytics; import net.somethingdreadful.MAL.MALDateTools; import net.somethingdreadful.MAL.api.MALApi; import net.somethingdreadful.MAL.api.response.Anime; import net.somethingdreadful.MAL.api.response.Manga; import net.somethingdreadful.MAL.api.response.RecordStub; import net.somethingdreadful.MAL.api.response.User; import java.util.ArrayList; import java.util.HashMap; public class DatabaseManager { MALSqlHelper malSqlHelper; SQLiteDatabase dbRead; public DatabaseManager(Context context) { if (malSqlHelper == null) malSqlHelper = MALSqlHelper.getHelper(context); } public synchronized SQLiteDatabase getDBWrite() { return malSqlHelper.getWritableDatabase(); } public SQLiteDatabase getDBRead() { if (dbRead == null) dbRead = malSqlHelper.getReadableDatabase(); return dbRead; } public void saveAnimeList(ArrayList<Anime> list, String username) { Integer userId = getUserId(username); if (list != null && list.size() > 0 && userId != null) { try { getDBWrite().beginTransaction(); for (Anime anime : list) saveAnime(anime, true, userId); getDBWrite().setTransactionSuccessful(); } catch (Exception e) { Crashlytics.log(Log.ERROR, "MALX", "DatabaseManager.saveAnimeList(): " + e.getMessage()); } finally { getDBWrite().endTransaction(); } } } public void saveAnime(Anime anime, boolean IGF, String username) { Integer userId; if (username.equals("")) userId = 0; else userId = getUserId(username); saveAnime(anime, IGF, userId); } public void saveAnime(Anime anime, boolean IGF, int userId) { ContentValues cv = new ContentValues(); cv.put(MALSqlHelper.COLUMN_ID, anime.getId()); cv.put("recordName", anime.getTitle()); cv.put("recordType", anime.getType()); cv.put("imageUrl", anime.getImageUrl()); cv.put("recordStatus", anime.getStatus()); cv.put("episodesTotal", anime.getEpisodes()); if (!IGF) { cv.put("synopsis", anime.getSynopsis()); cv.put("memberScore", anime.getMembersScore()); cv.put("classification", anime.getClassification()); cv.put("membersCount", anime.getMembersCount()); cv.put("favoritedCount", anime.getFavoritedCount()); cv.put("popularityRank", anime.getPopularityRank()); cv.put("rank", anime.getRank()); cv.put("listedId", anime.getListedId()); } // don't use replace it replaces synopsis with null even when we don't put it in the ContentValues int updateResult = getDBWrite().update(MALSqlHelper.TABLE_ANIME, cv, MALSqlHelper.COLUMN_ID + " = ?", new String[]{Integer.toString(anime.getId())}); if (updateResult == 0) { Long insertResult = getDBWrite().insert(MALSqlHelper.TABLE_ANIME, null, cv); if (insertResult > 0) { anime.setId(insertResult.intValue()); } } if (anime.getId() > 0) { // save/update relations if saving was successful if (!IGF) { if (anime.getGenres() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_ANIME_GENRES, "anime_id = ?", new String[]{String.valueOf(anime.getId())}); for (String genre : anime.getGenres()) { Integer genreId = getGenreId(genre); if (genreId != null) { ContentValues gcv = new ContentValues(); gcv.put("anime_id", anime.getId()); gcv.put("genre_id", genreId); getDBWrite().insert(MALSqlHelper.TABLE_ANIME_GENRES, null, gcv); } } } if (anime.getTags() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_ANIME_TAGS, "anime_id = ?", new String[]{String.valueOf(anime.getId())}); for (String tag : anime.getTags()) { Integer tagId = getTagId(tag); if (tagId != null) { ContentValues gcv = new ContentValues(); gcv.put("anime_id", anime.getId()); gcv.put("tag_id", tagId); getDBWrite().replace(MALSqlHelper.TABLE_ANIME_TAGS, null, gcv); } } } saveAnimeAnimeRelation(anime.getAlternativeVersions(), anime.getId(), MALSqlHelper.RELATION_TYPE_ALTERNATIVE); saveAnimeAnimeRelation(anime.getCharacterAnime(), anime.getId(), MALSqlHelper.RELATION_TYPE_CHARACTER); saveAnimeAnimeRelation(anime.getPrequels(), anime.getId(), MALSqlHelper.RELATION_TYPE_PREQUEL); saveAnimeAnimeRelation(anime.getSequels(), anime.getId(), MALSqlHelper.RELATION_TYPE_SEQUEL); saveAnimeAnimeRelation(anime.getSideStories(), anime.getId(), MALSqlHelper.RELATION_TYPE_SIDE_STORY); saveAnimeAnimeRelation(anime.getSpinOffs(), anime.getId(), MALSqlHelper.RELATION_TYPE_SPINOFF); saveAnimeAnimeRelation(anime.getSummaries(), anime.getId(), MALSqlHelper.RELATION_TYPE_SUMMARY); if (anime.getMangaAdaptions() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_ANIME_MANGA_RELATIONS, "anime_id = ? AND relationType = ?", new String[]{String.valueOf(anime.getId()), MALSqlHelper.RELATION_TYPE_ADAPTATION}); for (RecordStub mangaStub : anime.getMangaAdaptions()) { saveAnimeToMangaRelation(anime.getId(), mangaStub, MALSqlHelper.RELATION_TYPE_ADAPTATION); } } if (anime.getParentStory() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_ANIME_MANGA_RELATIONS, "anime_id = ? AND relationType = ?", new String[]{String.valueOf(anime.getId()), MALSqlHelper.RELATION_TYPE_PARENT_STORY}); saveAnimeToAnimeRelation(anime.getId(), anime.getParentStory(), MALSqlHelper.RELATION_TYPE_PARENT_STORY); } if (anime.getOtherTitles() != null) { if (anime.getOtherTitlesEnglish() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_ANIME_OTHER_TITLES, "anime_id = ? and titleType = ?", new String[]{String.valueOf(anime.getId()), MALSqlHelper.TITLE_TYPE_ENGLISH}); for (String title : anime.getOtherTitlesEnglish()) { saveAnimeOtherTitle(anime.getId(), title, MALSqlHelper.TITLE_TYPE_ENGLISH); } } if (anime.getOtherTitlesJapanese() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_ANIME_OTHER_TITLES, "anime_id = ? and titleType = ?", new String[]{String.valueOf(anime.getId()), MALSqlHelper.TITLE_TYPE_JAPANESE}); for (String title : anime.getOtherTitlesJapanese()) { saveAnimeOtherTitle(anime.getId(), title, MALSqlHelper.TITLE_TYPE_JAPANESE); } } if (anime.getOtherTitlesSynonyms() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_ANIME_OTHER_TITLES, "anime_id = ? and titleType = ?", new String[]{String.valueOf(anime.getId()), MALSqlHelper.TITLE_TYPE_SYNONYM}); for (String title : anime.getOtherTitlesSynonyms()) { saveAnimeOtherTitle(anime.getId(), title, MALSqlHelper.TITLE_TYPE_SYNONYM); } } } } // update animelist if user id is provided if (userId > 0) { ContentValues alcv = new ContentValues(); alcv.put("profile_id", userId); alcv.put("anime_id", anime.getId()); alcv.put("status", anime.getWatchedStatus()); alcv.put("score", anime.getScore()); alcv.put("watched", anime.getWatchedEpisodes()); alcv.put("dirty", anime.getDirty()); if (anime.getLastUpdate() != null) alcv.put("lastUpdate", anime.getLastUpdate().getTime()); getDBWrite().replace(MALSqlHelper.TABLE_ANIMELIST, null, alcv); } } } public void saveAnimeAnimeRelation(ArrayList<RecordStub> record, int id, String type) { if (record != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_ANIME_ANIME_RELATIONS, "anime_id = ? AND relationType = ?", new String[]{String.valueOf(id), type}); for (RecordStub stub : record) { saveAnimeToAnimeRelation(id, stub, type); } } } public Anime getAnime(Integer id, String username) { Anime result = null; Cursor cursor = getDBRead().rawQuery("SELECT a.*, al.score AS myScore, al.status AS myStatus, al.watched AS episodesWatched, al.dirty, al.lastUpdate" + " FROM animelist al INNER JOIN anime a ON al.anime_id = a." + MALSqlHelper.COLUMN_ID + " WHERE al.profile_id = ? AND a." + MALSqlHelper.COLUMN_ID + " = ?", new String[]{getUserId(username).toString(), id.toString()}); if (cursor.moveToFirst()) { result = Anime.fromCursor(cursor); result.setGenres(getAnimeGenres(result.getId())); result.setTags(getAnimeTags(result.getId())); result.setAlternativeVersions(getAnimeToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_ALTERNATIVE)); result.setCharacterAnime(getAnimeToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_CHARACTER)); result.setPrequels(getAnimeToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_PREQUEL)); result.setSequels(getAnimeToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_SEQUEL)); result.setSideStories(getAnimeToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_SIDE_STORY)); result.setSpinOffs(getAnimeToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_SPINOFF)); result.setSummaries(getAnimeToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_SUMMARY)); result.setMangaAdaptions(getAnimeToMangaRelations(result.getId(), MALSqlHelper.RELATION_TYPE_ADAPTATION)); ArrayList<RecordStub> parentStory = getAnimeToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_PARENT_STORY); if (parentStory != null && parentStory.size() > 0) { result.setParentStory(parentStory.get(0)); } HashMap<String, ArrayList<String>> otherTitles = new HashMap<String, ArrayList<String>>(); otherTitles.put("english", getAnimeOtherTitles(result.getId(), MALSqlHelper.TITLE_TYPE_ENGLISH)); otherTitles.put("japanese", getAnimeOtherTitles(result.getId(), MALSqlHelper.TITLE_TYPE_JAPANESE)); otherTitles.put("synonyms", getAnimeOtherTitles(result.getId(), MALSqlHelper.TITLE_TYPE_SYNONYM)); result.setOtherTitles(otherTitles); } cursor.close(); return result; } private boolean deleteAnime(Integer id) { return getDBWrite().delete(MALSqlHelper.TABLE_ANIME, MALSqlHelper.COLUMN_ID + " = ?", new String[]{id.toString()}) == 1; } public boolean deleteAnimeFromAnimelist(Integer id, String username) { boolean result = false; Integer userId = getUserId(username); if (userId != 0) { result = getDBWrite().delete(MALSqlHelper.TABLE_ANIMELIST, "profile_id = ? AND anime_id = ?", new String[]{userId.toString(), id.toString()}) == 1; if (result) { boolean isUsed = false; /* check if this record is used for other relations and delete if it's not to keep the database * still used relations can be: * - animelist of other user * - record is related to other anime or manga (e.g. as sequel or adaptation) */ // used in other animelist? isUsed = recordExists(MALSqlHelper.TABLE_ANIMELIST, "anime_id", id.toString()); if (!isUsed) { // no need to check more if its already used // used as related record of other anime? isUsed = recordExists(MALSqlHelper.TABLE_ANIME_ANIME_RELATIONS, "related_id", id.toString()); } if (!isUsed) { // no need to check more if its already used // used as related record of an manga? isUsed = recordExists(MALSqlHelper.TABLE_MANGA_ANIME_RELATIONS, "related_id", id.toString()); } if (!isUsed) {// its not used anymore, delete it deleteAnime(id); } } } return result; } // delete all anime records without relations, because they're "dead" records public void cleanupAnimeTable() { getDBWrite().rawQuery("DELETE FROM anime WHERE " + MALSqlHelper.COLUMN_ID + " NOT IN (SELECT DISTINCT anime_id FROM " + MALSqlHelper.TABLE_ANIMELIST + ") AND " + MALSqlHelper.COLUMN_ID + " NOT IN (SELECT DISTINCT related_id FROM " + MALSqlHelper.TABLE_ANIME_ANIME_RELATIONS + ") AND " + MALSqlHelper.COLUMN_ID + " NOT IN (SELECT DISTINCT related_id FROM " + MALSqlHelper.TABLE_MANGA_ANIME_RELATIONS + ")", null); } public ArrayList<Anime> getAnimeList(String listType, String username) { if (listType == "") return getAnimeList(getUserId(username), "", false); else return getAnimeList(getUserId(username), listType, false); } public ArrayList<Anime> getDirtyAnimeList(String username) { return getAnimeList(getUserId(username), "", true); } private ArrayList<Anime> getAnimeList(int userId, String listType, boolean dirtyOnly) { ArrayList<Anime> result = null; Cursor cursor; try { ArrayList<String> selArgs = new ArrayList<String>(); selArgs.add(String.valueOf(userId)); if (listType != "") { selArgs.add(listType); } cursor = getDBRead().rawQuery("SELECT a.*, al.score AS myScore, al.status AS myStatus, al.watched AS episodesWatched, al.dirty, al.lastUpdate" + " FROM animelist al INNER JOIN anime a ON al.anime_id = a." + MALSqlHelper.COLUMN_ID + " WHERE al.profile_id = ? " + (listType != "" ? " AND al.status = ? " : "") + (dirtyOnly ? " AND al.dirty = 1 " : "") + " ORDER BY a.recordName COLLATE NOCASE", selArgs.toArray(new String[selArgs.size()])); if (cursor.moveToFirst()) { result = new ArrayList<Anime>(); do { result.add(Anime.fromCursor(cursor)); } while (cursor.moveToNext()); } cursor.close(); } catch (SQLException e) { Crashlytics.log(Log.ERROR, "MALX", "DatabaseManager.getAnimeList(): " + e.getMessage()); } return result; } public void saveMangaList(ArrayList<Manga> list, String username) { Integer userId = getUserId(username); if (list != null && list.size() > 0 && userId != null) { try { getDBWrite().beginTransaction(); for (Manga manga : list) saveManga(manga, true, userId); getDBWrite().setTransactionSuccessful(); } catch (Exception e) { Crashlytics.log(Log.ERROR, "MALX", "DatabaseManager.saveMangaList(): " + e.getMessage()); } finally { getDBWrite().endTransaction(); } } } public void saveManga(Manga manga, boolean ignoreSynopsis, String username) { Integer userId; if (username.equals("")) userId = 0; else userId = getUserId(username); saveManga(manga, ignoreSynopsis, userId); } public void saveManga(Manga manga, boolean ignoreSynopsis, int userId) { ContentValues cv = new ContentValues(); cv.put(MALSqlHelper.COLUMN_ID, manga.getId()); cv.put("recordName", manga.getTitle()); cv.put("recordType", manga.getType()); cv.put("imageUrl", manga.getImageUrl()); cv.put("recordStatus", manga.getStatus()); cv.put("volumesTotal", manga.getVolumes()); cv.put("chaptersTotal", manga.getChapters()); if (!ignoreSynopsis) { cv.put("synopsis", manga.getSynopsis()); cv.put("membersCount", manga.getMembersCount()); cv.put("memberScore", manga.getMembersScore()); cv.put("favoritedCount", manga.getFavoritedCount()); cv.put("popularityRank", manga.getPopularityRank()); cv.put("rank", manga.getRank()); cv.put("listedId", manga.getListedId()); } // don't use replace it replaces synopsis with null even when we don't put it in the ContentValues int updateResult = getDBWrite().update(MALSqlHelper.TABLE_MANGA, cv, MALSqlHelper.COLUMN_ID + " = ?", new String[]{Integer.toString(manga.getId())}); if (updateResult == 0) { Long insertResult = getDBWrite().insert(MALSqlHelper.TABLE_MANGA, null, cv); if (insertResult > 0) { manga.setId(insertResult.intValue()); } } if (manga.getId() > 0) { // save/update relations if saving was successful if (!ignoreSynopsis) { // only on DetailView! if (manga.getGenres() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_MANGA_GENRES, "manga_id = ?", new String[]{String.valueOf(manga.getId())}); for (String genre : manga.getGenres()) { Integer genreId = getGenreId(genre); if (genreId != null) { ContentValues gcv = new ContentValues(); gcv.put("manga_id", manga.getId()); gcv.put("genre_id", genreId); getDBWrite().replace(MALSqlHelper.TABLE_MANGA_GENRES, null, gcv); } } } if (manga.getTags() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_MANGA_TAGS, "manga_id = ?", new String[]{String.valueOf(manga.getId())}); for (String tag : manga.getTags()) { Integer tagId = getTagId(tag); if (tagId != null) { ContentValues gcv = new ContentValues(); gcv.put("manga_id", manga.getId()); gcv.put("tag_id", tagId); getDBWrite().replace(MALSqlHelper.TABLE_MANGA_TAGS, null, gcv); } } } if (manga.getAlternativeVersions() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_MANGA_MANGA_RELATIONS, "manga_id = ? AND relationType = ?", new String[]{String.valueOf(manga.getId()), MALSqlHelper.RELATION_TYPE_ALTERNATIVE}); for (RecordStub mangaStub : manga.getAlternativeVersions()) { saveMangaToMangaRelation(manga.getId(), mangaStub, MALSqlHelper.RELATION_TYPE_ALTERNATIVE); } } if (manga.getRelatedManga() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_MANGA_MANGA_RELATIONS, "manga_id = ? AND relationType = ?", new String[]{String.valueOf(manga.getId()), MALSqlHelper.RELATION_TYPE_RELATED}); for (RecordStub mangaStub : manga.getRelatedManga()) { saveMangaToMangaRelation(manga.getId(), mangaStub, MALSqlHelper.RELATION_TYPE_RELATED); } } if (manga.getAnimeAdaptations() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_MANGA_ANIME_RELATIONS, "manga_id = ? AND relationType = ?", new String[]{String.valueOf(manga.getId()), MALSqlHelper.RELATION_TYPE_ADAPTATION}); for (RecordStub animeStub : manga.getAnimeAdaptations()) { saveMangaToAnimeRelation(manga.getId(), animeStub, MALSqlHelper.RELATION_TYPE_ADAPTATION); } } if (manga.getOtherTitles() != null) { if (manga.getOtherTitlesEnglish() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_MANGA_OTHER_TITLES, "manga_id = ? and titleType = ?", new String[]{String.valueOf(manga.getId()), MALSqlHelper.TITLE_TYPE_ENGLISH}); for (String title : manga.getOtherTitlesEnglish()) { saveMangaOtherTitle(manga.getId(), title, MALSqlHelper.TITLE_TYPE_ENGLISH); } } if (manga.getOtherTitlesJapanese() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_MANGA_OTHER_TITLES, "manga_id = ? and titleType = ?", new String[]{String.valueOf(manga.getId()), MALSqlHelper.TITLE_TYPE_JAPANESE}); for (String title : manga.getOtherTitlesJapanese()) { saveMangaOtherTitle(manga.getId(), title, MALSqlHelper.TITLE_TYPE_JAPANESE); } } if (manga.getOtherTitlesSynonyms() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_MANGA_OTHER_TITLES, "manga_id = ? and titleType = ?", new String[]{String.valueOf(manga.getId()), MALSqlHelper.TITLE_TYPE_SYNONYM}); for (String title : manga.getOtherTitlesSynonyms()) { saveMangaOtherTitle(manga.getId(), title, MALSqlHelper.TITLE_TYPE_SYNONYM); } } } } // update mangalist if user id is provided if (userId > 0) { ContentValues mlcv = new ContentValues(); mlcv.put("profile_id", userId); mlcv.put("manga_id", manga.getId()); mlcv.put("status", manga.getReadStatus()); mlcv.put("score", manga.getScore()); mlcv.put("volumesRead", manga.getVolumesRead()); mlcv.put("chaptersRead", manga.getChaptersRead()); mlcv.put("dirty", manga.getDirty()); if (manga.getLastUpdate() != null) mlcv.put("lastUpdate", manga.getLastUpdate().getTime()); getDBWrite().replace(MALSqlHelper.TABLE_MANGALIST, null, mlcv); } } } public Manga getManga(Integer id, String username) { Manga result = null; Cursor cursor = getDBRead().rawQuery("SELECT m.*, ml.score AS myScore, ml.status AS myStatus, ml.chaptersRead, ml.volumesRead, ml.dirty, ml.lastUpdate" + " FROM mangalist ml INNER JOIN manga m ON ml.manga_id = m." + MALSqlHelper.COLUMN_ID + " WHERE ml.profile_id = ? and m." + MALSqlHelper.COLUMN_ID + " = ?", new String[]{getUserId(username).toString(), id.toString()}); if (cursor.moveToFirst()) { result = Manga.fromCursor(cursor); result.setGenres(getMangaGenres(result.getId())); result.setTags(getMangaTags(result.getId())); result.setAlternativeVersions(getMangaToMangaRelations(result.getId(), MALSqlHelper.RELATION_TYPE_ALTERNATIVE)); result.setRelatedManga(getMangaToMangaRelations(result.getId(), MALSqlHelper.RELATION_TYPE_RELATED)); result.setAnimeAdaptations(getMangaToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_ADAPTATION)); HashMap<String, ArrayList<String>> otherTitles = new HashMap<String, ArrayList<String>>(); otherTitles.put("english", getMangaOtherTitles(result.getId(), MALSqlHelper.TITLE_TYPE_ENGLISH)); otherTitles.put("japanese", getMangaOtherTitles(result.getId(), MALSqlHelper.TITLE_TYPE_JAPANESE)); otherTitles.put("synonyms", getMangaOtherTitles(result.getId(), MALSqlHelper.TITLE_TYPE_SYNONYM)); result.setOtherTitles(otherTitles); } cursor.close(); return result; } private boolean deleteManga(Integer id) { return getDBWrite().delete(MALSqlHelper.TABLE_MANGA, MALSqlHelper.COLUMN_ID + " = ?", new String[]{id.toString()}) == 1; } public boolean deleteMangaFromMangalist(Integer id, String username) { boolean result = false; Integer userId = getUserId(username); if (userId != 0) { result = getDBWrite().delete(MALSqlHelper.TABLE_MANGALIST, "profile_id = ? AND manga_id = ?", new String[]{userId.toString(), id.toString()}) == 1; if (result) { boolean isUsed = false; /* check if this record is used for other relations and delete if it's not to keep the database * still used relations can be: * - mangalist of other user * - record is related to other anime or manga (e.g. as sequel or adaptation) */ // used in other mangalist? isUsed = recordExists(MALSqlHelper.TABLE_MANGALIST, "manga_id", id.toString()); if (!isUsed) { // no need to check more if its already used // used as related record of other manga? isUsed = recordExists(MALSqlHelper.TABLE_MANGA_MANGA_RELATIONS, "related_id", id.toString()); } if (!isUsed) { // no need to check more if its already used // used as related record of an anime? isUsed = recordExists(MALSqlHelper.TABLE_ANIME_MANGA_RELATIONS, "related_id", id.toString()); } if (!isUsed) {// its not used anymore, delete it deleteManga(id); } } } return result; } // delete all manga records without relations, because they're "dead" records public void cleanupMangaTable() { getDBWrite().rawQuery("DELETE FROM manga WHERE " + MALSqlHelper.COLUMN_ID + " NOT IN (SELECT DISTINCT manga_id FROM " + MALSqlHelper.TABLE_MANGALIST + ") AND " + MALSqlHelper.COLUMN_ID + " NOT IN (SELECT DISTINCT related_id FROM " + MALSqlHelper.TABLE_MANGA_MANGA_RELATIONS + ") AND " + MALSqlHelper.COLUMN_ID + " NOT IN (SELECT DISTINCT related_id FROM " + MALSqlHelper.TABLE_ANIME_MANGA_RELATIONS + ")", null); } public ArrayList<Manga> getMangaList(String listType, String username) { if (listType == "") return getMangaList(getUserId(username), "", false); else return getMangaList(getUserId(username), listType, false); } public ArrayList<Manga> getDirtyMangaList(String username) { return getMangaList(getUserId(username), "", true); } private ArrayList<Manga> getMangaList(int userId, String listType, boolean dirtyOnly) { ArrayList<Manga> result = null; Cursor cursor; try { ArrayList<String> selArgs = new ArrayList<String>(); selArgs.add(String.valueOf(userId)); if (listType != "") { selArgs.add(listType); } cursor = getDBRead().rawQuery("SELECT m.*, ml.score AS myScore, ml.status AS myStatus, ml.chaptersRead, ml.volumesRead, ml.dirty, ml.lastUpdate" + " FROM mangalist ml INNER JOIN manga m ON ml.manga_id = m." + MALSqlHelper.COLUMN_ID + " WHERE ml.profile_id = ? " + (listType != "" ? " AND ml.status = ? " : "") + (dirtyOnly ? " AND ml.dirty = 1 " : "") + " ORDER BY m.recordName COLLATE NOCASE", selArgs.toArray(new String[selArgs.size()])); if (cursor.moveToFirst()) { result = new ArrayList<Manga>(); do { result.add(Manga.fromCursor(cursor)); } while (cursor.moveToNext()); } cursor.close(); } catch (SQLException e) { Crashlytics.log(Log.ERROR, "MALX", "DatabaseManager.getMangaList(): " + e.getMessage()); } return result; } public void saveUser(User user, Boolean profile) { ContentValues cv = new ContentValues(); cv.put("username", user.getName()); if (user.getProfile().getAvatarUrl().equals("http://cdn.myanimelist.net/images/questionmark_50.gif")) cv.put("avatar_url", "http://cdn.myanimelist.net/images/na.gif"); else cv.put("avatar_url", user.getProfile().getAvatarUrl()); if (user.getProfile().getDetails().getLastOnline() != null) { String lastOnline = MALDateTools.parseMALDateToISO8601String(user.getProfile().getDetails().getLastOnline()); cv.put("last_online", lastOnline.equals("") ? user.getProfile().getDetails().getLastOnline() : lastOnline); } else cv.putNull("last_online"); if (profile) { if (user.getProfile().getDetails().getBirthday() != null) { String birthday = MALDateTools.parseMALDateToISO8601String(user.getProfile().getDetails().getBirthday()); cv.put("birthday", birthday.equals("") ? user.getProfile().getDetails().getBirthday() : birthday); } else cv.putNull("birthday"); cv.put("location", user.getProfile().getDetails().getLocation()); cv.put("website", user.getProfile().getDetails().getWebsite()); cv.put("comments", user.getProfile().getDetails().getComments()); cv.put("forum_posts", user.getProfile().getDetails().getForumPosts()); cv.put("gender", user.getProfile().getDetails().getGender()); if (user.getProfile().getDetails().getJoinDate() != null) { String joindate = MALDateTools.parseMALDateToISO8601String(user.getProfile().getDetails().getJoinDate()); cv.put("join_date", joindate.equals("") ? user.getProfile().getDetails().getJoinDate() : joindate); } else cv.putNull("join_date"); cv.put("access_rank", user.getProfile().getDetails().getAccessRank()); cv.put("anime_list_views", user.getProfile().getDetails().getAnimeListViews()); cv.put("manga_list_views", user.getProfile().getDetails().getMangaListViews()); cv.put("anime_time_days", user.getProfile().getAnimeStats().getTimeDays()); cv.put("anime_watching", user.getProfile().getAnimeStats().getWatching()); cv.put("anime_completed", user.getProfile().getAnimeStats().getCompleted()); cv.put("anime_on_hold", user.getProfile().getAnimeStats().getOnHold()); cv.put("anime_dropped", user.getProfile().getAnimeStats().getDropped()); cv.put("anime_plan_to_watch", user.getProfile().getAnimeStats().getPlanToWatch()); cv.put("anime_total_entries", user.getProfile().getAnimeStats().getTotalEntries()); cv.put("manga_time_days", user.getProfile().getMangaStats().getTimeDays()); cv.put("manga_reading", user.getProfile().getMangaStats().getReading()); cv.put("manga_completed", user.getProfile().getMangaStats().getCompleted()); cv.put("manga_on_hold", user.getProfile().getMangaStats().getOnHold()); cv.put("manga_dropped", user.getProfile().getMangaStats().getDropped()); cv.put("manga_plan_to_read", user.getProfile().getMangaStats().getPlanToRead()); cv.put("manga_total_entries", user.getProfile().getMangaStats().getTotalEntries()); } // don't use replace it alters the autoincrement _id field! int updateResult = getDBWrite().update(MALSqlHelper.TABLE_PROFILE, cv, "username = ?", new String[]{user.getName()}); if (updateResult > 0) {// updated row user.setId(getUserId(user.getName())); } else { Long insertResult = getDBWrite().insert(MALSqlHelper.TABLE_PROFILE, null, cv); user.setId(insertResult.intValue()); } } public void saveUserFriends(Integer userId, ArrayList<User> friends) { if (userId == null || friends == null) { return; } SQLiteDatabase db = getDBWrite(); db.beginTransaction(); try { db.delete(MALSqlHelper.TABLE_FRIENDLIST, "profile_id = ?", new String[]{userId.toString()}); for (User friend : friends) { ContentValues cv = new ContentValues(); cv.put("profile_id", userId); cv.put("friend_id", friend.getId()); db.insert(MALSqlHelper.TABLE_FRIENDLIST, null, cv); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } public User getProfile(String name) { User result = null; Cursor cursor; try { cursor = getDBRead().query(MALSqlHelper.TABLE_PROFILE, null, "username = ?", new String[]{name}, null, null, null); if (cursor.moveToFirst()) result = User.fromCursor(cursor); cursor.close(); } catch (SQLException e) { Crashlytics.log(Log.ERROR, "MALX", "DatabaseManager.getProfile(): " + e.getMessage()); } return result; } public ArrayList<User> getFriendList(String username) { ArrayList<User> friendlist = new ArrayList<User>(); Cursor cursor = getDBRead().rawQuery("SELECT p1.* FROM " + MALSqlHelper.TABLE_PROFILE + " AS p1" + // for result rows " INNER JOIN " + MALSqlHelper.TABLE_PROFILE + " AS p2" + // for getting user id to given name " INNER JOIN " + MALSqlHelper.TABLE_FRIENDLIST + " AS fl ON fl.profile_id = p2." + MALSqlHelper.COLUMN_ID + // for user<>friend relation " WHERE p2.username = ? AND p1." + MALSqlHelper.COLUMN_ID + " = fl.friend_id ORDER BY p1.username COLLATE NOCASE", new String[]{username}); if (cursor.moveToFirst()) { do { friendlist.add(User.fromCursor(cursor)); } while (cursor.moveToNext()); } cursor.close(); return friendlist; } public void saveFriendList(ArrayList<User> friendlist, String username) { for (User friend : friendlist) { saveUser(friend, false); } Integer userId = getUserId(username); saveUserFriends(userId, friendlist); } private Integer getGenreId(String genre) { return getRecordId(MALSqlHelper.TABLE_GENRES, MALSqlHelper.COLUMN_ID, "recordName", genre); } private Integer getTagId(String tag) { return getRecordId(MALSqlHelper.TABLE_TAGS, MALSqlHelper.COLUMN_ID, "recordName", tag); } private Integer getUserId(String username) { if (username == null || username.equals("")) return 0; Integer id = getRecordId(MALSqlHelper.TABLE_PROFILE, MALSqlHelper.COLUMN_ID, "username", username); if (id == null) { id = 0; } return id; } private Integer getRecordId(String table, String idField, String searchField, String value) { Integer result = null; Cursor cursor = getDBRead().query(table, new String[]{idField}, searchField + " = ?", new String[]{value}, null, null, null); if (cursor.moveToFirst()) { result = cursor.getInt(0); } cursor.close(); if (result == null) { ContentValues cv = new ContentValues(); cv.put(searchField, value); Long addResult = getDBWrite().insert(table, null, cv); if (addResult > -1) { result = addResult.intValue(); } } return result; } public ArrayList<String> getAnimeGenres(Integer animeId) { ArrayList<String> result = null; Cursor cursor = getDBRead().rawQuery("SELECT g.recordName FROM " + MALSqlHelper.TABLE_GENRES + " g " + "INNER JOIN " + MALSqlHelper.TABLE_ANIME_GENRES + " ag ON ag.genre_id = g." + MALSqlHelper.COLUMN_ID + " WHERE ag.anime_id = ? ORDER BY g.recordName COLLATE NOCASE", new String[]{animeId.toString()}); if (cursor.moveToFirst()) { result = new ArrayList<String>(); do { result.add(cursor.getString(0)); } while (cursor.moveToNext()); } cursor.close(); return result; } public ArrayList<String> getAnimeTags(Integer animeId) { ArrayList<String> result = null; Cursor cursor = getDBRead().rawQuery("SELECT t.recordName FROM " + MALSqlHelper.TABLE_TAGS + " t " + "INNER JOIN " + MALSqlHelper.TABLE_ANIME_TAGS + " at ON at.tag_id = t." + MALSqlHelper.COLUMN_ID + " WHERE at.anime_id = ? ORDER BY t.recordName COLLATE NOCASE", new String[]{animeId.toString()}); if (cursor.moveToFirst()) { result = new ArrayList<String>(); do { result.add(cursor.getString(0)); } while (cursor.moveToNext()); } cursor.close(); return result; } public ArrayList<String> getMangaGenres(Integer mangaId) { ArrayList<String> result = null; Cursor cursor = getDBRead().rawQuery("SELECT g.recordName FROM " + MALSqlHelper.TABLE_GENRES + " g " + "INNER JOIN " + MALSqlHelper.TABLE_MANGA_GENRES + " mg ON mg.genre_id = g." + MALSqlHelper.COLUMN_ID + " WHERE mg.manga_id = ? ORDER BY g.recordName COLLATE NOCASE", new String[]{mangaId.toString()}); if (cursor.moveToFirst()) { result = new ArrayList<String>(); do { result.add(cursor.getString(0)); } while (cursor.moveToNext()); } cursor.close(); return result; } public ArrayList<String> getMangaTags(Integer mangaId) { ArrayList<String> result = null; Cursor cursor = getDBRead().rawQuery("SELECT t.recordName FROM " + MALSqlHelper.TABLE_TAGS + " t " + "INNER JOIN " + MALSqlHelper.TABLE_MANGA_TAGS + " mt ON mt.tag_id = t." + MALSqlHelper.COLUMN_ID + " WHERE mt.manga_id = ? ORDER BY t.recordName COLLATE NOCASE", new String[]{mangaId.toString()}); if (cursor.moveToFirst()) { result = new ArrayList<String>(); do { result.add(cursor.getString(0)); } while (cursor.moveToNext()); } cursor.close(); return result; } private boolean recordExists(String table, String searchField, String searchValue) { boolean result = false; Cursor cursor = getDBRead().query(table, null, searchField + " = ?", new String[]{searchValue}, null, null, null); if (cursor.moveToFirst()) { result = true; } cursor.close(); return result; } /* Storing relations is a little more complicated as we need to look if the related anime is * stored in the database, if not we need to create a new record before storing the information. * This record then only has the few informations that are available in the relation object * returned by the API (only id and title) */ private void saveAnimeToAnimeRelation(int animeId, RecordStub relatedAnime, String relationType) { if (relatedAnime.getId() == 0) { Crashlytics.log(Log.ERROR, "MALX", "DatabaseManager.saveAnimeToAnimeRelation(): error saving relation: anime id must not be 0; title: " + relatedAnime.getTitle()); return; } boolean relatedRecordExists; if (!recordExists(MALSqlHelper.TABLE_ANIME, MALSqlHelper.COLUMN_ID, String.valueOf(relatedAnime.getId()))) { ContentValues cv = new ContentValues(); cv.put(MALSqlHelper.COLUMN_ID, relatedAnime.getId()); cv.put("recordName", relatedAnime.getTitle()); relatedRecordExists = getDBWrite().insert(MALSqlHelper.TABLE_ANIME, null, cv) > 0; } else { relatedRecordExists = true; } if (relatedRecordExists) { ContentValues cv = new ContentValues(); cv.put("anime_id", animeId); cv.put("related_id", relatedAnime.getId()); cv.put("relationType", relationType); getDBWrite().replace(MALSqlHelper.TABLE_ANIME_ANIME_RELATIONS, null, cv); } } private void saveAnimeToMangaRelation(int animeId, RecordStub relatedManga, String relationType) { if (relatedManga.getId() == 0) { Crashlytics.log(Log.ERROR, "MALX", "DatabaseManager.saveAnimeToMangaRelation(): error saving relation: manga id must not be 0; title: " + relatedManga.getTitle()); return; } boolean relatedRecordExists; if (!recordExists(MALSqlHelper.TABLE_MANGA, MALSqlHelper.COLUMN_ID, String.valueOf(relatedManga.getId()))) { ContentValues cv = new ContentValues(); cv.put(MALSqlHelper.COLUMN_ID, relatedManga.getId()); cv.put("recordName", relatedManga.getTitle()); relatedRecordExists = getDBWrite().insert(MALSqlHelper.TABLE_MANGA, null, cv) > 0; } else { relatedRecordExists = true; } if (relatedRecordExists) { ContentValues cv = new ContentValues(); cv.put("anime_id", animeId); cv.put("related_id", relatedManga.getId()); cv.put("relationType", relationType); getDBWrite().replace(MALSqlHelper.TABLE_ANIME_MANGA_RELATIONS, null, cv); } } private void saveMangaToMangaRelation(int mangaId, RecordStub relatedManga, String relationType) { if (relatedManga.getId() == 0) { Crashlytics.log(Log.ERROR, "MALX", "DatabaseManager.saveMangaToMangaRelation(): error saving relation: manga id must not be 0; title: " + relatedManga.getTitle()); return; } boolean relatedRecordExists; if (!recordExists(MALSqlHelper.TABLE_MANGA, MALSqlHelper.COLUMN_ID, String.valueOf(relatedManga.getId()))) { ContentValues cv = new ContentValues(); cv.put(MALSqlHelper.COLUMN_ID, relatedManga.getId()); cv.put("recordName", relatedManga.getTitle()); relatedRecordExists = getDBWrite().insert(MALSqlHelper.TABLE_MANGA, null, cv) > 0; } else { relatedRecordExists = true; } if (relatedRecordExists) { ContentValues cv = new ContentValues(); cv.put("manga_id", mangaId); cv.put("related_id", relatedManga.getId()); cv.put("relationType", relationType); getDBWrite().replace(MALSqlHelper.TABLE_MANGA_MANGA_RELATIONS, null, cv); } } private void saveMangaToAnimeRelation(int mangaId, RecordStub relatedAnime, String relationType) { if (relatedAnime.getId() == 0) { Crashlytics.log(Log.ERROR, "MALX", "DatabaseManager.saveMangaToAnimeRelation(): error saving relation: anime id must not be 0; title: " + relatedAnime.getTitle()); return; } boolean relatedRecordExists; if (!recordExists(MALSqlHelper.TABLE_ANIME, MALSqlHelper.COLUMN_ID, String.valueOf(relatedAnime.getId()))) { ContentValues cv = new ContentValues(); cv.put(MALSqlHelper.COLUMN_ID, relatedAnime.getId()); cv.put("recordName", relatedAnime.getTitle()); relatedRecordExists = getDBWrite().insert(MALSqlHelper.TABLE_ANIME, null, cv) > 0; } else { relatedRecordExists = true; } if (relatedRecordExists) { ContentValues cv = new ContentValues(); cv.put("manga_id", mangaId); cv.put("related_id", relatedAnime.getId()); cv.put("relationType", relationType); getDBWrite().replace(MALSqlHelper.TABLE_MANGA_ANIME_RELATIONS, null, cv); } } private ArrayList<RecordStub> getAnimeToAnimeRelations(Integer animeId, String relationType) { ArrayList<RecordStub> result = null; Cursor cursor = getDBRead().rawQuery("SELECT a." + MALSqlHelper.COLUMN_ID + ", a.recordName FROM " + MALSqlHelper.TABLE_ANIME + " a " + "INNER JOIN " + MALSqlHelper.TABLE_ANIME_ANIME_RELATIONS + " ar ON a." + MALSqlHelper.COLUMN_ID + " = ar.related_id " + "WHERE ar.anime_id = ? AND ar.relationType = ? ORDER BY a.recordName COLLATE NOCASE", new String[]{animeId.toString(), relationType}); if (cursor.moveToFirst()) { result = new ArrayList<RecordStub>(); do { RecordStub animeStub = new RecordStub(); animeStub.setId(cursor.getInt(0), MALApi.ListType.ANIME); animeStub.setTitle(cursor.getString(1)); result.add(animeStub); } while (cursor.moveToNext()); } cursor.close(); return result; } private ArrayList<RecordStub> getAnimeToMangaRelations(Integer animeId, String relationType) { ArrayList<RecordStub> result = null; Cursor cursor = getDBRead().rawQuery("SELECT m." + MALSqlHelper.COLUMN_ID + ", m.recordName FROM " + MALSqlHelper.TABLE_MANGA + " m " + "INNER JOIN " + MALSqlHelper.TABLE_ANIME_MANGA_RELATIONS + " ar ON m." + MALSqlHelper.COLUMN_ID + " = ar.related_id " + "WHERE ar.anime_id = ? AND ar.relationType = ? ORDER BY m.recordName COLLATE NOCASE", new String[]{animeId.toString(), relationType}); if (cursor.moveToFirst()) { result = new ArrayList<RecordStub>(); do { RecordStub mangaStub = new RecordStub(); mangaStub.setId(cursor.getInt(0), MALApi.ListType.MANGA); mangaStub.setTitle(cursor.getString(1)); result.add(mangaStub); } while (cursor.moveToNext()); } cursor.close(); return result; } private ArrayList<RecordStub> getMangaToMangaRelations(Integer mangaId, String relationType) { ArrayList<RecordStub> result = null; Cursor cursor = getDBRead().rawQuery("SELECT m." + MALSqlHelper.COLUMN_ID + ", m.recordName FROM " + MALSqlHelper.TABLE_MANGA + " m " + "INNER JOIN " + MALSqlHelper.TABLE_MANGA_MANGA_RELATIONS + " mr ON m." + MALSqlHelper.COLUMN_ID + " = mr.related_id " + "WHERE mr.manga_id = ? AND mr.relationType = ? ORDER BY m.recordName COLLATE NOCASE", new String[]{mangaId.toString(), relationType}); if (cursor.moveToFirst()) { result = new ArrayList<RecordStub>(); do { RecordStub mangaStub = new RecordStub(); mangaStub.setId(cursor.getInt(0), MALApi.ListType.MANGA); mangaStub.setTitle(cursor.getString(1)); result.add(mangaStub); } while (cursor.moveToNext()); } cursor.close(); return result; } private ArrayList<RecordStub> getMangaToAnimeRelations(Integer mangaId, String relationType) { ArrayList<RecordStub> result = null; Cursor cursor = getDBRead().rawQuery("SELECT a." + MALSqlHelper.COLUMN_ID + ", a.recordName FROM " + MALSqlHelper.TABLE_ANIME + " a " + "INNER JOIN " + MALSqlHelper.TABLE_MANGA_ANIME_RELATIONS + " mr ON a." + MALSqlHelper.COLUMN_ID + " = mr.related_id " + "WHERE mr.manga_id = ? AND mr.relationType = ? ORDER BY a.recordName COLLATE NOCASE", new String[]{mangaId.toString(), relationType}); if (cursor.moveToFirst()) { result = new ArrayList<RecordStub>(); do { RecordStub animeStub = new RecordStub(); animeStub.setId(cursor.getInt(0), MALApi.ListType.ANIME); animeStub.setTitle(cursor.getString(1)); result.add(animeStub); } while (cursor.moveToNext()); } cursor.close(); return result; } private void saveAnimeOtherTitle(int animeId, String title, String titleType) { ContentValues cv = new ContentValues(); cv.put("anime_id", animeId); cv.put("titleType", titleType); cv.put("title", title); getDBWrite().replace(MALSqlHelper.TABLE_ANIME_OTHER_TITLES, null, cv); } private void saveMangaOtherTitle(int mangaId, String title, String titleType) { ContentValues cv = new ContentValues(); cv.put("manga_id", mangaId); cv.put("titleType", titleType); cv.put("title", title); getDBWrite().replace(MALSqlHelper.TABLE_MANGA_OTHER_TITLES, null, cv); } private ArrayList<String> getAnimeOtherTitles(Integer animeId, String titleType) { ArrayList<String> result = null; Cursor cursor = getDBRead().query(MALSqlHelper.TABLE_ANIME_OTHER_TITLES, new String[]{"title"}, "anime_id = ? AND titleType = ?", new String[]{animeId.toString(), titleType}, null, null, "title COLLATE NOCASE"); if (cursor.moveToFirst()) { result = new ArrayList<String>(); do { result.add(cursor.getString(0)); } while (cursor.moveToNext()); } cursor.close(); return result; } private ArrayList<String> getMangaOtherTitles(Integer mangaId, String titleType) { ArrayList<String> result = null; Cursor cursor = getDBRead().query(MALSqlHelper.TABLE_MANGA_OTHER_TITLES, new String[]{"title"}, "manga_id = ? AND titleType = ?", new String[]{mangaId.toString(), titleType}, null, null, "title COLLATE NOCASE"); if (cursor.moveToFirst()) { result = new ArrayList<String>(); do { result.add(cursor.getString(0)); } while (cursor.moveToNext()); } cursor.close(); return result; } }
Rename saveAnimeAnimeRelation to saveAnimeToAnimeRelation (DatabaseManager)
Atarashii/src/net/somethingdreadful/MAL/sql/DatabaseManager.java
Rename saveAnimeAnimeRelation to saveAnimeToAnimeRelation (DatabaseManager)
Java
bsd-2-clause
8cd878f1d41e98acbee1b7cdacb1c5c4cac9f452
0
sebastianscatularo/javadns,sebastianscatularo/javadns
org/xbill/DNS/utils/hmacSigner.java
// Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org) package org.xbill.DNS.utils; import java.io.*; /** * A pure java implementation of the HMAC-MD5 secure hash algorithm * * @author Brian Wellington */ public class hmacSigner { private byte [] ipad, opad; private ByteArrayOutputStream bytes; private static final byte IPAD = 0x36; private static final byte OPAD = 0x5c; private static final byte PADLEN = 64; /** If true, all digested bytes will be printed */ public static boolean verbose = false; /** * Creates a new HMAC instance * @param key The secret key */ public hmacSigner(byte [] key) { int i; if (key.length > PADLEN) key = md5.compute(key); ipad = new byte[PADLEN]; opad = new byte[PADLEN]; for (i = 0; i < key.length; i++) { ipad[i] = (byte) (key[i] ^ IPAD); opad[i] = (byte) (key[i] ^ OPAD); } for (; i < PADLEN; i++) { ipad[i] = IPAD; opad[i] = OPAD; } bytes = new ByteArrayOutputStream(); try { bytes.write(ipad); } catch (IOException e) { } if (verbose) System.err.println(hexdump.dump("key", key)); } /** * Adds data to the current hash * @param b The data * @param offset The index at which to start adding to the hash * @param length The number of bytes to hash */ public void addData(byte [] b, int offset, int length) { if (length < 0 || offset + length > b.length) { if (verbose) System.err.println("Invalid parameters"); return; } if (verbose) System.err.println(hexdump.dump("partial add", b, offset, length)); bytes.write(b, offset, length); } /** * Adds data to the current hash * @param b The data */ public void addData(byte [] b) { if (verbose) System.err.println(hexdump.dump("add", b)); try { bytes.write(b); } catch (IOException e) { } } /** * Signs the data (computes the secure hash) * @return An array with the signature */ public byte [] sign() { byte [] output = md5.compute(bytes.toByteArray()); bytes = new ByteArrayOutputStream(); try { bytes.write(opad); bytes.write(output); } catch (IOException e) { } byte [] b = md5.compute(bytes.toByteArray()); if (verbose) System.err.println(hexdump.dump("sig", b)); return b; } /** * Verifies the data (computes the secure hash and compares it to the input) * @param signature The signature to compare against * @return true if the signature matched, false otherwise */ public boolean verify(byte [] signature) { if (verbose) System.err.println(hexdump.dump("ver", signature)); return (byteArrayCompare(signature, sign())); } /** * Resets the HMAC object for further use */ public void clear() { bytes = new ByteArrayOutputStream(); try { bytes.write(ipad); } catch (IOException e) { } } private static boolean byteArrayCompare(byte [] b1, byte [] b2) { if (b1.length != b2.length) return false; for (int i = 0; i < b1.length; i++) if (b1[i] != b2[i]) return false; return true; } }
No longer used; HMAC is better.
org/xbill/DNS/utils/hmacSigner.java
No longer used; HMAC is better.
Java
bsd-2-clause
74b9414b69e7fd3afa65fc5e0cbcbc3c4138cd6d
0
biovoxxel/imagej,biovoxxel/imagej,TehSAUCE/imagej,biovoxxel/imagej,TehSAUCE/imagej,TehSAUCE/imagej
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2012 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of any organization. * #L% */ package imagej.updater.core; import imagej.updater.util.AbstractProgressable; import java.io.IOException; import java.util.List; /** * Abstract base class for ImageJ upload mechanisms. * * @author Johannes Schindelin */ public abstract class AbstractUploader extends AbstractProgressable implements IUploader { // TODO: Convert this class to use a subinterface of IPlugin. // The Uploader annotation interface methods will need to migrate here. // See ticket #993: http://trac.imagej.net/ticket/993 protected String uploadDir; protected int total; protected long timestamp; @Override public abstract void upload(List<Uploadable> files, List<String> locks) throws IOException; @Override public void calculateTotalSize(final List<Uploadable> sources) { total = 0; for (final Uploadable source : sources) total += (int) source.getFilesize(); } @Override public boolean login(final FilesUploader uploader) { uploadDir = uploader.getUploadDirectory(); return true; // no login required; override this if login _is_ required! } @Override public void logout() { // no logout required; override this if logout _is_ required! } @Override public long getTimestamp() { return timestamp; } }
core/updater/core/src/main/java/imagej/updater/core/AbstractUploader.java
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2012 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of any organization. * #L% */ package imagej.updater.core; import imagej.updater.util.AbstractProgressable; import java.io.IOException; import java.util.List; /** * Abstract base class for ImageJ upload mechanisms. * * @author Johannes Schindelin */ public abstract class AbstractUploader extends AbstractProgressable implements IUploader { // TODO: Convert this class to use a subinterface of IPlugin. // The Uploader annotation interface methods will need to migrate here. // See ticket #993: http://trac.imagej.net/ticket/993 protected String uploadDir; protected int total; protected long timestamp; @Override public abstract void upload(List<Uploadable> files, List<String> locks) throws IOException; @Override public void calculateTotalSize(final List<Uploadable> sources) { total = 0; for (final Uploadable source : sources) total += (int) source.getFilesize(); } @Override public boolean login(final FilesUploader uploader) { uploadDir = uploader.getUploadDirectory(); return true; // no login required; override this if login _is_ required! } @Override public void logout() {} @Override public long getTimestamp() { return timestamp; } }
Add comment to empty method body This fixes an Eclipse warning.
core/updater/core/src/main/java/imagej/updater/core/AbstractUploader.java
Add comment to empty method body
Java
bsd-3-clause
5a5343fdbf890aa8066d16169635d876a35ff026
0
BaseXdb/basex,dimitarp/basex,dimitarp/basex,dimitarp/basex,dimitarp/basex,dimitarp/basex,BaseXdb/basex,BaseXdb/basex,dimitarp/basex,BaseXdb/basex,BaseXdb/basex,dimitarp/basex,BaseXdb/basex,BaseXdb/basex,dimitarp/basex,dimitarp/basex,BaseXdb/basex,BaseXdb/basex,dimitarp/basex,BaseXdb/basex,dimitarp/basex,BaseXdb/basex,BaseXdb/basex,dimitarp/basex
package org.basex.query.ast; import static org.basex.query.func.Function.*; import static org.basex.query.QueryError.*; import org.basex.core.cmd.*; import org.basex.query.expr.*; import org.basex.query.expr.List; import org.basex.query.expr.constr.*; import org.basex.query.expr.gflwor.*; import org.basex.query.expr.index.*; import org.basex.query.expr.path.*; import org.basex.query.func.*; import org.basex.query.value.item.*; import org.basex.query.value.node.*; import org.basex.query.value.seq.*; import org.basex.query.var.*; import org.junit.Test; /** * Checks query rewritings. * * @author BaseX Team 2005-20, BSD License * @author Christian Gruen */ public final class RewritingsTest extends QueryPlanTest { /** Input file. */ private static final String FILE = "src/test/resources/input.xml"; /** Checks if the count function is pre-compiled. */ @Test public void preEval() { check("count(1)", 1, exists(Int.class)); execute(new CreateDB(NAME, "<xml><a x='y'>1</a><a>2 3</a><a/></xml>")); check("count(//a)", 3, exists(Int.class)); check("count(/xml/a)", 3, exists(Int.class)); check("count(//text())", 2, exists(Int.class)); check("count(//*)", 4, exists(Int.class)); check("count(//node())", 6, exists(Int.class)); check("count(//comment())", 0, exists(Int.class)); check("count(/self::document-node())", 1, exists(Int.class)); } /** Checks if descendant-or-self::node() steps are rewritten. */ @Test public void mergeDesc() { execute(new CreateDB(NAME, "<a><b>B</b><b><c>C</c></b></a>")); check("//*", null, "//@axis = 'descendant'"); check("//(b, *)", null, exists(IterPath.class), "//@axis = 'descendant'"); check("//(b | *)", null, exists(IterPath.class), "//@axis = 'descendant'"); check("//(b | *)[text()]", null, exists(IterPath.class), empty(Union.class), "//@axis = 'descendant'"); check("//(b, *)[1]", null, "not(//@axis = 'descendant')"); } /** Checks if descendant steps are rewritten to child steps. */ @Test public void descToChild() { execute(new CreateDB(NAME, "<a><b>B</b><b><c>C</c></b></a>")); check("descendant::a", null, "//@axis = 'child'"); check("descendant::b", null, "//@axis = 'child'"); check("descendant::c", null, "//@axis = 'child'"); check("descendant::*", null, "not(//@axis = 'child')"); } /** Checks EBV optimizations. */ @Test public void optimizeEbv() { query("not(<a/>[b])", true); query("empty(<a/>[b])", true); query("exists(<a/>[b])", false); query("not(<a/>[b = 'c'])", true); query("empty(<a/>[b = 'c'])", true); query("exists(<a/>[b = 'c'])", false); query("let $n := <n/> where $n[<a><b/><b/></a>/*] return $n", "<n/>"); check("empty(<a>X</a>[text()])", null, "//@axis = 'child'"); check("exists(<a>X</a>[text()])", null, "//@axis = 'child'"); check("boolean(<a>X</a>[text()])", null, "//@axis = 'child'"); check("not(<a>X</a>[text()])", null, "//@axis = 'child'"); check("if(<a>X</a>[text()]) then 1 else 2", null, "//@axis = 'child'"); check("<a>X</a>[text()] and <a/>", null, "//@axis = 'child'"); check("<a>X</a>[text()] or <a/>", null, "//Bln = 'true'"); check("<a>X</a>[text()] or <a/>[text()]", null, "//@axis = 'child'"); check("for $a in <a>X</a> where $a[text()] return $a", null, "//@axis = 'child'"); check("empty(<a>X</a>/.[text()])", null, "//@axis = 'child'"); } /** Checks if iterative evaluation of XPaths is used if no duplicates occur. */ @Test public void gh1001() { execute(new CreateDB(NAME, "<a id='0' x:id='' x='' xmlns:x='x'><b id='1'/><c id='2'/>" + "<d id='3'/><e id='4'/></a>")); check("(/a/*/../*) ! name()", "b\nc\nd\ne", empty(IterPath.class)); check("(exactly-one(/a/b)/../*) ! name()", "b\nc\nd\ne", exists(IterPath.class)); check("(/a/*/following::*) ! name()", "c\nd\ne", empty(IterPath.class)); check("(exactly-one(/a/b)/following::*) ! name()", "c\nd\ne", exists(IterPath.class)); check("(/a/*/following-sibling::*) ! name()", "c\nd\ne", empty(IterPath.class)); check("(exactly-one(/a/b)/following-sibling::*) ! name()", "c\nd\ne", exists(IterPath.class)); check("(/*/@id/../*) ! name()", "b\nc\nd\ne", empty(IterPath.class)); check("(exactly-one(/a)/@id/../*) ! name()", "b\nc\nd\ne", exists(IterPath.class)); } /** Checks OR optimizations. */ @Test public void or() { check("('' or '')", false, empty(Or.class)); check("('x' or 'x' = 'x')", true, empty(Or.class)); check("(false() or <x/> = 'x')", false, empty(Or.class)); check("(true() or <x/> = 'x')", true, empty(Or.class)); check("('x' = 'x' or <x/> = 'x')", true, empty(Or.class)); // {@link CmpG} rewritings check("let $x := <x/> return ($x = 'x' or $x = 'y')", false, empty(Or.class)); check("let $x := <x>x</x> return ($x = 'x' or $x = 'y')", true, empty(Or.class)); } /** Checks AND optimizations. */ @Test public void and() { check("('x' and 'y')", true, empty(And.class)); check("('x' and 'x' = 'x')", true, empty(And.class)); check("(true() and <x>x</x> = 'x')", true, empty(And.class)); check("(false() and <x>x</x> = 'x')", false, empty(And.class)); check("('x' = 'x' and <x>x</x> = 'x')", true, empty(And.class)); } /** Checks {@link CmpIR} optimizations. */ @Test public void cmpIR() { final Class<CmpIR> cmpir = CmpIR.class; check("(1, 2)[. = 1] = 1 to 2", true, exists(cmpir)); check("(1, 2)[. = 3] = 1 to 2", false, exists(cmpir)); check("(1, 2)[. = 3] = 1 to 2", false, exists(cmpir)); // do not rewrite equality comparisons against single integers check("(1, 2)[. = 1] = 1", true, empty(cmpir)); // rewrite to positional test check("(1 to 5)[let $p := position() return $p = 2]", 2, empty(cmpir), empty(Let.class), empty(POSITION)); check("1[let $p := position() return $p = 0]", "", empty()); check("1[let $p := position() return $p = (-5 to -1)]", "", empty()); } /** Checks {@link CmpR} optimizations. */ @Test public void cmpR() { final Class<CmpR> cmpr = CmpR.class; check("<a>5</a>[text() > 1 and text() < 9]", "<a>5</a>", count(cmpr, 1)); check("<a>5</a>[text() > 1 and text() < 9 and <b/>]", "<a>5</a>", count(cmpr, 1)); check("<a>5</a>[text() > 1 and . < 9]", "<a>5</a>", count(cmpr, 2)); // GH-1744 check("<a>5</a>[text() < 5 or text() > 5]", "", count(cmpr, 2)); check("<a>5</a>[text() > 5 or text() < 5]", "", count(cmpr, 2)); check("<a>5</a>[5 > text() or 5 < text()]", "", count(cmpr, 2)); check("<a>5</a>[5 < text() or 5 > text()]", "", count(cmpr, 2)); check("<a>5</a>[text() > 800000000]", "", exists(cmpr)); check("<a>5</a>[text() < -800000000]", "", exists(cmpr)); check("<a>5</a>[text() <= -800000000]", "", exists(cmpr)); check("exists(<x>1234567890.12345678</x>[. = 1234567890.1234567])", true, empty(cmpr)); check("exists(<x>123456789012345678</x> [. = 123456789012345679])", true, empty(cmpr)); check("<a>5</a>[text() > 8000000000000000000]", "", empty(cmpr)); check("<a>5</a>[text() < -8000000000000000000]", "", empty(cmpr)); check("(1, 1234567890.12345678)[. = 1234567890.1234567]", "", empty(cmpr)); check("(1, 123456789012345678 )[. = 123456789012345679]", "", empty(cmpr)); // rewrite equality comparisons check("(0, 1)[. = 1] >= 1.0", true, exists(cmpr)); check("(0, 1)[. = 1] >= 1e0", true, exists(cmpr)); check("(0e0, 1e0)[. = 1] >= 1", true, exists(cmpr)); check("(0e0, 1e0)[. = 1] >= 1e0", true, exists(cmpr)); check("<_>1.1</_> >= 1.1", true, exists(cmpr)); // do not rewrite decimal/double comparisons check("(0e0, 1e0)[. = 1] >= 1.0", true, empty(cmpr)); check("(0.0, 1.0)[. = 1] >= 1e0", true, empty(cmpr)); // do not rewrite equality comparisons check("(0, 1)[. = 1] = 1.0", true, empty(cmpr)); check("(0, 1)[. = 1] = 1e0", true, empty(cmpr)); check("(0e0, 1e0)[. = 1] = 1", true, empty(cmpr)); check("(0e0, 1e0)[. = 1] = 1.0", true, empty(cmpr)); check("(0e0, 1e0)[. = 1] = 1e0", true, empty(cmpr)); check("<_>1.1</_> = 1.1", true, empty(cmpr)); // suppressed rewritings check("random:double() = 2", false, empty(cmpr)); check("(0.1, 1.1)[. != 0] = 1.3", false, empty(cmpr)); check("('x', 'y')[. = 'x'] = 'x'", true, empty(cmpr)); check("('x', 'x')[. != 'x'] = 1.3", false, empty(cmpr)); check("(0.1, 1.1)[. = 1.1] = 1.1", true, empty(cmpr)); // rewrite to positional test check("1[let $p := position() return $p = 0.0]", "", empty()); } /** Checks {@link CmpSR} optimizations. */ @Test public void cmpSR() { check("<a>5</a>[text() > '1' and text() < '9']", "<a>5</a>", count(CmpSR.class, 1)); check("<a>5</a>[text() > '1' and text() < '9' and <b/>]", "<a>5</a>", count(CmpSR.class, 1)); check("<a>5</a>[text() > '1' and . < '9']", "<a>5</a>", count(CmpSR.class, 2)); } /** Checks string-length optimizations. */ @Test public void stringLength() { check("<a/>[string-length() > -1]", "<a/>", empty(IterFilter.class)); check("<a/>[string-length() != -1]", "<a/>", empty(IterFilter.class)); check("<a/>[string-length() ge 0]", "<a/>", empty(IterFilter.class)); check("<a/>[string-length() ne 1.1]", "<a/>", empty(IterFilter.class)); check("<a/>[string-length() < 0]", "", empty(IterFilter.class)); check("<a/>[string-length() <= -1]", "", empty(IterFilter.class)); check("<a/>[string-length() eq -1]", "", empty(IterFilter.class)); check("<a/>[string-length() eq 1.1]", "", empty(IterFilter.class)); check("<a/>[string-length() > 0]", "", exists(STRING)); check("<a/>[string-length() >= 0.5]", "", exists(STRING)); check("<a/>[string-length() ne 0]", "", exists(STRING)); check("<a/>[string-length() < 0.5]", "<a/>", exists(STRING)); check("<a/>[string-length() <= 0.5]", "<a/>", exists(STRING)); check("<a/>[string-length() eq 0]", "<a/>", exists(STRING)); check("<a/>[string-length() gt 1]", "", exists(STRING_LENGTH)); check("<a/>[string-length() = <a>1</a>]", "", exists(STRING_LENGTH)); } /** Checks count optimizations. */ @Test public void count() { // static occurrence: zero-or-one String count = "count(<_>1</_>[. = 1])"; // static result: no need to evaluate count check(count + " < 0", false, root(Bln.class)); check(count + " <= -.1", false, root(Bln.class)); check(count + " >= 0", true, root(Bln.class)); check(count + " > -0.1", true, root(Bln.class)); check(count + " = 1.1", false, root(Bln.class)); check(count + " != 1.1", true, root(Bln.class)); check(count + " = -1", false, root(Bln.class)); check(count + " != -1", true, root(Bln.class)); // rewrite to empty/exists (faster) check(count + " > 0", true, root(EXISTS)); check(count + " >= 1", true, root(EXISTS)); check(count + " != 0", true, root(EXISTS)); check(count + " < 1", false, root(EMPTY)); check(count + " <= 0", false, root(EMPTY)); check(count + " = 0", false, root(EMPTY)); // zero-or-one result: no need to evaluate count check(count + " < 2", true, root(Bln.class)); check(count + " <= 1", true, root(Bln.class)); check(count + " != 2", true, root(Bln.class)); check(count + " > 1", false, root(Bln.class)); check(count + " >= 2", false, root(Bln.class)); check(count + " = 2", false, root(Bln.class)); // no rewritings possible check(count + " != 1", false, exists(COUNT)); check(count + " = 1", true, exists(COUNT)); // one-or-more results: no need to evaluate count count = "count((1, <_>1</_>[. = 1]))"; check(count + " > 0", true, root(Bln.class)); check(count + " >= 1", true, root(Bln.class)); check(count + " != 0", true, root(Bln.class)); check(count + " < 1", false, root(Bln.class)); check(count + " <= 0", false, root(Bln.class)); check(count + " = 0", false, root(Bln.class)); // no rewritings possible check(count + " = 1", false, exists(COUNT)); check(count + " = 2", true, exists(COUNT)); } /** Checks that empty sequences are eliminated and that singleton lists are flattened. */ @Test public void list() { check("((), <x/>, ())", "<x/>", empty(List.class), empty(Empty.class), exists(CElem.class)); } /** Checks that expressions marked as non-deterministic will not be rewritten. */ @Test public void nonDeterministic() { check("count((# basex:non-deterministic #) { <x/> })", 1, exists(COUNT)); } /** Ensures that fn:doc with URLs will not be rewritten. */ @Test public void doc() { check("<a>{ doc('" + FILE + "') }</a>//x", "", exists(DBNode.class)); check("if(<x>1</x> = 1) then 2 else doc('" + FILE + "')", 2, exists(DBNode.class)); check("if(<x>1</x> = 1) then 2 else doc('http://abc.de/')", 2, exists(DOC)); check("if(<x>1</x> = 1) then 2 else collection('http://abc.de/')", 2, exists(COLLECTION)); } /** Positional predicates. */ @Test public void pos() { // check if positional predicates are pre-evaluated check("'a'[1]", "a", exists(Str.class)); check("'a'[position() = 1]", "a", "exists(QueryPlan/Str)"); check("'a'[position() = 1 to 2]", "a", "exists(QueryPlan/Str)"); check("'a'[position() > 0]", "a", "exists(QueryPlan/Str)"); check("'a'[position() < 2]", "a", "exists(QueryPlan/Str)"); check("'a'[position() >= 1]", "a", "exists(QueryPlan/Str)"); check("'a'[position() <= 1]", "a", "exists(QueryPlan/Str)"); // check if positional predicates are rewritten to utility functions check("for $i in (1, 2) return 'a'[$i]", "a", exists(_UTIL_ITEM)); check("for $i in (1, 2) return 'a'[position() = $i]", "a", exists(_UTIL_ITEM)); check("for $i in (1, 2) return 'a'[position() = $i to $i]", "a", exists(_UTIL_ITEM)); check("for $i in (1, 2) return 'a'[position() = $i to $i+1]", "a", exists(_UTIL_RANGE)); check("for $i in (1, 2) return 'a'[position() = $i to 1]", "a", exists(_UTIL_RANGE)); check("for $i in (1, 2) return 'a'[position() >= $i]", "a", exists(_UTIL_RANGE)); check("for $i in (1, 2) return 'a'[position() > $i]", "", exists(_UTIL_RANGE)); check("for $i in (1, 2) return 'a'[position() <= $i]", "a\na", exists(_UTIL_RANGE)); check("for $i in (1, 2) return 'a'[position() < $i]", "a", exists(_UTIL_RANGE)); // check if positional predicates are rewritten to utility functions final String seq = " (1, 1.1, 1.9, 2) "; check("for $i in" + seq + "return ('a', 'b')[$i]", "a\nb", exists(_UTIL_ITEM)); check("for $i in" + seq + "return ('a', 'b')[position() = $i]", "a\nb", exists(_UTIL_ITEM)); check("for $i in" + seq + "return ('a', 'b')[position() >= $i]", "a\nb\nb\nb\nb", exists(_UTIL_RANGE)); check("for $i in" + seq + "return ('a', 'b')[position() > $i]", "b\nb\nb", exists(_UTIL_RANGE)); check("for $i in" + seq + "return ('a', 'b')[position() <= $i]", "a\na\na\na\nb", exists(_UTIL_RANGE)); check("for $i in" + seq + "return ('a', 'b')[position() < $i]", "a\na\na", exists(_UTIL_RANGE)); // check if multiple positional predicates are rewritten to utility functions check("for $i in" + seq + "return ('a', 'b')[$i][$i]", "a", count(_UTIL_ITEM, 2)); check("for $i in" + seq + "return ('a', 'b')[position() = $i][position() = $i]", "a", count(_UTIL_ITEM, 2)); check("for $i in" + seq + "return ('a', 'b')[position() < $i][position() < $i]", "a\na\na", count(_UTIL_RANGE, 2)); // check if positional predicates are merged and rewritten to utility functions check("for $i in" + seq + "return ('a', 'b')[position() = $i and position() = $i]", "a\nb", exists(_UTIL_ITEM)); check("for $i in" + seq + "return ('a', 'b')[position() >= $i and position() <= $i]", "a\nb", exists(_UTIL_RANGE)); check("for $i in" + seq + "return ('a', 'b')[position() <= $i and position() >= $i]", "a\nb", exists(_UTIL_RANGE)); check("for $i in" + seq + "return ('a', 'b')[position() > $i and position() < $i]", "", exists(_UTIL_RANGE)); check("for $i in" + seq + "return ('a', 'b')[position() < $i and position() > $i]", "", exists(_UTIL_RANGE)); // no rewriting possible (conflicting positional predicates) check("for $i in" + seq + "return ('a', 'b')[position() = $i and position() = $i+1]", "", exists(CachedFilter.class)); check("for $i in" + seq + "return ('a', 'b')[position() >= $i and position() > $i]", "b\nb\nb", exists(CachedFilter.class)); check("for $i in" + seq + "return ('a', 'b')[position() >= $i and position() >= $i+1]", "b", exists(CachedFilter.class)); check("for $i in" + seq + "return ('a', 'b')[position() < $i and position() < $i+1]", "a\na\na", exists(CachedFilter.class)); check("(<a/>, <b/>)[last()]", "<b/>", count(_UTIL_LAST, 1)); check("(<a/>, <b/>)[position() > 1 and position() < 3]", "<b/>", count(_UTIL_LAST, 1)); check("(<a/>, <b/>)[position() > 1 and position() < 3 and <b/>]", "<b/>", count(_UTIL_LAST, 1)); check("(<a/>, <b/>)[position() > 1 and position() < 4]", "<b/>", count(_UTIL_LAST, 1)); } /** Predicates. */ @Test public void preds() { // context value: rewrite if root is of type string or node check("('s', 't')[.]", "s\nt", exists(ContextValue.class)); check("<a/>[.]", "<a/>", exists(CElem.class), empty(ContextValue.class)); check("<a/>[.][.]", "<a/>", exists(CElem.class), empty(ContextValue.class)); check("<a/>/self::*[.][.]", "<a/>", empty(ContextValue.class)); check("<a/>/self::*[.][.]", "<a/>", empty(ContextValue.class)); check("('a', 'b')[position()[position() ! .]]", "a\nb", count(POSITION, 2)); check("('a', 'b')[. ! position()]", "a", exists("*[contains(name(), 'Map')]")); check("(1, 0)[.]", 1, exists(ContextValue.class)); error("true#0[.]", EBV_X_X); error("(true#0, false#0)[.]", EBV_X_X); // map expression check("'s'['s' ! <a/>]", "s", empty(IterMap.class)); check("'s'['s' ! <a/>]", "s", root(Str.class)); check("'s'['x' ! <a/> ! <b/>]", "s", root(Str.class)); check("'s'['x' ! (<a/>, <b/>) ! <b/>]", "s", root(Str.class)); check("'s'['x' ! <a>{ . }</a>[. = 'x']]", "s", empty(IterMap.class), root(If.class)); // path expression check("let $a := <a/> return $a[$a/self::a]", "<a/>", count(VarRef.class, 1)); check("let $a := <a/> return $a[$a]", "<a/>", empty(VarRef.class)); } /** Comparison expressions. */ @Test public void cmpG() { check("count(let $s := (0, 1 to 99999) return $s[. = $s])", 100000, exists(CmpHashG.class)); } /** Checks OR optimizations. */ @Test public void gh1519() { query("declare function local:replicate($seq, $n, $out) {" + " if($n eq 0) then $out " + " else ( " + " let $out2 := if($n mod 2 eq 0) then $out else ($out, $seq) " + " return local:replicate(($seq, $seq), $n idiv 2, $out2) " + " )" + "};" + "let $n := 1000000000 " + "return ( " + " count(local:replicate((1, 2, 3), $n, ())) eq 3 * $n, " + " count(local:replicate((1, 2, 3), $n, ())) = 3 * $n " + ")", "true\ntrue"); } /** Checks simplification of empty path expressions. */ @Test public void gh1587() { check("document {}/..", "", empty(CDoc.class)); check("function() { document {}/.. }()", "", empty(CDoc.class)); check("declare function local:f() { document {}/.. }; local:f()", "", empty(CDoc.class)); } /** * Remove redundant self steps. */ @Test public void selfSteps() { check("<a/>/.", "<a/>", root(CElem.class)); check("<a/>/./././.", "<a/>", root(CElem.class)); check("<a/>[.]", "<a/>", root(CElem.class)); check("<a/>/self::element()", "<a/>", root(CElem.class)); check("attribute a { 0 }/self::attribute()", "a=\"0\"", root(CAttr.class)); check("<a/>/self::*", "<a/>", root(CElem.class)); } /** Static optimizations of paths without results (see also gh1630). */ @Test public void emptyPath() { // check combination of axis and node test and axis check("<e a='A'/>/attribute::text()", "", empty()); check("<e a='A'/>/attribute::attribute()", "a=\"A\"", exists(IterPath.class)); check("<e a='A'/>/ancestor::text()", "", empty()); check("<e a='A'/>/parent::text()", "", empty()); check("<e a='A'/>/parent::*", "", exists(IterPath.class)); check("attribute a { 0 }/child::attribute()", "", empty()); check("<e a='A'/>/attribute::a/child::attribute()", "", empty()); // check step after expression that yields document nodes check("document { <a/> }/self::*", "", empty()); check("document { <a/> }/self::*", "", empty()); check("document { <a/> }/self::text()", "", empty()); check("document { <a/> }/child::document-node()", "", empty()); check("document { <a/> }/child::attribute()", "", empty()); check("document { <a/> }/child::*", "<a/>", exists(IterPath.class)); check("document { <a/> }/descendant-or-self::attribute()", "", empty()); check("document { <a/> }/parent::node()", "", empty()); check("document { <a/> }/ancestor::node()", "", empty()); check("document { <a/> }/following::node()", "", empty()); check("document { <a/> }/preceding-sibling::node()", "", empty()); // skip further tests if previous node type is unknown, or if current test accepts all nodes check("(<a/>, <_>1</_>[. = 0])/node()", "", exists(IterStep.class)); // check step after any other expression check("<a/>/self::text()", "", empty()); check("comment {}/child::node()", "", empty()); check("text { 0 }/child::node()", "", empty()); check("attribute a { 0 }/following-sibling::node()", "", empty()); check("attribute a { 0 }/preceding-sibling::node()", "", empty()); check("comment { }/following-sibling::node()", "", exists(IterPath.class)); check("comment { }/preceding-sibling::node()", "", exists(IterStep.class)); check("attribute a { 0 }/child::node()", "", empty()); check("attribute a { 0 }/descendant::*", "", empty()); check("attribute a { 0 }/self::*", "", empty()); // namespaces check("(<a/>, comment{})/child::namespace-node()", "", empty()); check("(<a/>, comment{})/descendant::namespace-node()", "", empty()); check("(<a/>, comment{})/attribute::namespace-node()", "", empty()); check("(<a/>, comment{})/self::namespace-node()", "", exists(IterStep.class)); check("(<a/>, comment{})/descendant-or-self::namespace-node()", "", exists(IterStep.class)); } /** Casts. */ @Test public void gh1795() { check("for $n in 1 to 3 return xs:integer($n)[. = 1]", 1, empty(Cast.class)); check("('a', 'b') ! xs:string(.)", "a\nb", empty(Cast.class), root(StrSeq.class)); check("xs:string(''[. = <_/>])", "", empty(Cast.class), root(If.class)); check("xs:string(<_/>[. = '']) = ''", true, empty(Cast.class), root(CmpSimpleG.class)); check("xs:double(<_>1</_>) + 2", 3, empty(Cast.class), type(Arith.class, "xs:double")); check("(1, 2) ! (xs:byte(.)) ! (xs:integer(.) + 2)", "3\n4", count(Cast.class, 1), type(Arith.class, "xs:integer")); error("(if(<_>!</_> = 'a') then 'b') cast as xs:string", INVTYPE_X_X_X); } /** Type promotions. */ @Test public void gh1801() { check("map { xs:string(<_/>): '' } instance of map(xs:string, xs:string)", true); check("map { string(<_/>): '' } instance of map(xs:string, xs:string)", true); } /** Casts. */ @Test public void typeCheck() { check("declare function local:a($e) as xs:string? { local:b($e) }; " + "declare function local:b($e) as xs:string? { $e }; local:a(<_>X</_>)", "X", count(TypeCheck.class, 1)); check("declare function local:a($e) as xs:string? { local:b($e) }; " + "declare function local:b($e) as xs:string* { $e }; local:a(<_>X</_>)", "X", count(TypeCheck.class, 1)); check("declare function local:a($e) as xs:string* { local:b($e) }; " + "declare function local:b($e) as xs:string? { $e }; local:a(<_>X</_>)", "X", count(TypeCheck.class, 1)); } /** GH1694. */ @Test public void gh1694() { check("count(1)", 1, exists(Int.class)); execute(new CreateDB(NAME, "<_/>")); final String query = "declare function local:b($e) as xs:string { $e };\n" + "declare function local:a($db) {\n" + " let $ids := local:b(db:open($db))\n" + " return db:open('" + NAME + "')[*[1] = $ids]\n" + "};\n" + "local:a('" + NAME + "')"; query(query, "<_/>"); } /** GH1726. */ @Test public void gh1726() { final String query = "let $xml := if((1, 0)[.]) then ( " + " element a { element b { } update { } } " + ") else ( " + " error() " + ") " + "let $b := $xml/* " + "return ($b, $b/..)"; query(query, "<b/>\n<a>\n<b/>\n</a>"); } /** GH1723. */ @Test public void gh1723() { check("count(<a/>)", 1, root(Int.class)); check("count(<a/>/<b/>)", 1, root(Int.class)); check("count(<a/>/<b/>/<c/>/<d/>)", 1, root(Int.class)); } /** GH1733. */ @Test public void gh1733() { check("(<a/>, <b/>)/1", "1\n1", root(SingletonSeq.class)); check("<a/>/1", 1, root(Int.class)); check("<a/>/<a/>", "<a/>", root(CElem.class)); check("(<a/>/map { 1:2 })?1", 2, root(Int.class)); check("<a/>/self::a/count(.)", 1, root("ItemMap")); // no rewriting possible check("(<a/>, <b/>)/<c/>", "<c/>\n<c/>", root(MixedPath.class)); } /** GH1741. */ @Test public void gh1741() { check("<a/>/<b/>[1]", "<b/>", root(CElem.class)); check("<a/>/.[1]", "<a/>", root(CElem.class)); check("<doc><x/><y/></doc>/*/..[1] ! name()", "doc", empty(ItrPos.class)); check("<a/>/<b/>[2]", "", empty()); check("<a/>/.[2]", "", empty()); check("<doc><x/><y/></doc>/*/..[2] ! name()", "", empty()); } /** GH1737: combined kind tests. */ @Test public void gh1737() { // merge identical steps, rewrite to iterative path check("<a/>/(* | *)", "", root(IterPath.class), empty(Union.class)); check("<a/>/(*, *)", "", root(IterPath.class), empty(List.class)); // rewrite to single union node test, rewrite to iterative path check("<a/>/(a | b)", "", root(IterPath.class), empty(Union.class)); check("<a/>/(a, b)", "", root(IterPath.class), empty(List.class)); // merge descendant-or-self step, rewrite to iterative path check("<a/>//(a | b)", "", root(IterPath.class), empty(Union.class)); check("<a/>/(a, b)", "", root(IterPath.class), empty(List.class)); // rewrite to single union node test, rewrite to iterative path check("<a/>/(a | b)[text()]", "", root(IterPath.class), empty(Union.class)); check("<a/>/(a, b)[text()]", "", root(IterPath.class), empty(List.class)); check("<_><a>x</a><b/></_>/(a, b)[text()]", "<a>x</a>", root(IterPath.class), empty(List.class)); // rewrite to union expression check("<a/>/(*, @*)", "", root(MixedPath.class), exists(Union.class)); } /** GH1761: merge adjacent steps in path expressions. */ @Test public void gh1761() { // merge self steps check("<a/>/self::*/self::a", "<a/>", count(IterStep.class, 1)); check("<a/>/self::*/self::b", "", count(IterStep.class, 1)); check("<a/>/self::a/self::*", "<a/>", count(IterStep.class, 1)); check("<a/>/self::a/self::node()", "<a/>", count(IterStep.class, 1)); // merge descendant and self steps check("document { <a/> }//self::a", "<a/>", count(IterStep.class, 1)); check("document { <a/> }//*/self::a", "<a/>", count(IterStep.class, 1)); // combined kind tests check("document { <a/>, <b/> }/(a, b)/self::a", "<a/>", count(IterStep.class, 1)); check("document { <a/>, <b/> }/a/(self::a, self::b)", "<a/>", count(IterStep.class, 1)); check("document { <a/>, <b/> }/(a, b)/(self::b, self::a)", "<a/>\n<b/>", count(IterStep.class, 1)); } /** GH1762: merge steps and predicates with self steps. */ @Test public void gh1762() { // merge self steps check("<a/>/self::*[self::a]", "<a/>", count(IterStep.class, 1)); check("<a/>/self::*[self::b]", "", count(IterStep.class, 1)); check("<a/>/self::a[self::*]", "<a/>", count(IterStep.class, 1)); check("<a/>/self::a[self::node()]", "<a/>", count(IterStep.class, 1)); // nested predicates check("<a/>/self::a[self::a[self::a[self::a]]]", "<a/>", count(IterStep.class, 1)); // combined kind test check("document { <a/>, <b/> }/a[self::a | self::b]", "<a/>", count(IterStep.class, 1)); } /** Path tests. */ @Test public void gh1729() { check("let $x := 'g' return <g/> ! self::g[name() = $x]", "<g/>", empty(CachedPath.class)); } /** Path tests. */ @Test public void gh1752() { check("'1' ! json:parse(.)/descendant::*[text()] = 1", true, empty(IterMap.class)); } /** Static typing of computed maps. */ @Test public void gh1766() { check("let $map := map { 'c': 'x' } return count($map?(('a', 'b')))", 0, type(For.class, "xs:string")); } /** Rewrite boolean comparisons. */ @Test public void gh1775() { check("(false(), true()) ! (. = true())", "false\ntrue", root(BlnSeq.class)); check("(false(), true()) ! (. != false())", "false\ntrue", root(BlnSeq.class)); check("(false(), true()) ! (. = false())", "true\nfalse", exists(NOT)); check("(false(), true()) ! (. != true())", "true\nfalse", exists(NOT)); } /** Merge predicates. */ @Test public void gh1777() { check("(5, 6, 7)[. > 5][. < 7]", 6, count(CmpIR.class, 1)); check("('a', 'b')[2][2]", "", empty()); check("('a', 'b')[1][1]", "a", root(Str.class)); check("for $n in <x a='1'/>/@* where $n >= 1 where $n <= 2 return $n", "a=\"1\"", root(IterPath.class), count(CmpR.class, 1)); check("for $n in <x a='1'/>/@* where data($n) >= 1 where data($n) <= 2 return $n", "a=\"1\"", root(IterPath.class), count(CmpR.class, 1)); check("for $n in <x a='1'/>/@* where $n/data() >= 1 where $n/data() <= 2 return $n", "a=\"1\"", root(IterPath.class), count(CmpR.class, 1)); } /** Merge conjunctions. */ @Test public void gh1776() { check("for $n in (1, 2, 3) where $n != 2 and $n != 3 return $n", 1, exists(NOT), exists(IntSeq.class)); check("<_>A</_>[. = <a>A</a> and . = 'A']", "<_>A</_>", exists(NOT), exists(List.class)); check("(<a/>, <b/>, <c/>)[name() = 'a' and name() = 'b']", "", exists(NOT), exists(StrSeq.class)); } /** Merge of consecutive operations. */ @Test public void gh1778() { check("(1 to 3)[. = 1 or . != 2 or . = 3 or . != 4]", "1\n2\n3", count(IntSeq.class, 2)); check("for $n in (<a/>, <b/>, <c/>) " + "where name($n) != 'a' where $n = '' where name($n) != 'b' " + "return $n", "<c/>", exists(NOT), exists(StrSeq.class)); check("for $n in (<a/>, <b/>, <c/>) " + "where name($n) != 'a' and $n = '' and name($n) != 'b' " + "return $n", "<c/>", exists(NOT), exists(StrSeq.class)); } /** EBV checks. */ @Test public void gh1769ebv() { check("if((<a/>, <b/>)) then 1 else 2", 1, root(Int.class)); check("if(data(<a/>)) then 1 else 2", 2, exists(DATA)); } /** Remove redundant atomizations. */ @Test public void gh1769data() { check("data(<_>1</_>) + 2", 3, empty(DATA)); check("string-join(data(<_>X</_>))", "X", empty(DATA)); check("data(data(<_>X</_>))", "X", count(DATA, 1)); check("<x>A</x>[data() = 'A']", "<x>A</x>", empty(DATA), count(ContextValue.class, 1)); check("<x>A</x>[data() ! data() ! data() = 'A']", "<x>A</x>", empty(DATA), count(ContextValue.class, 1)); check("<x>A</x>[data() = 'A']", "<x>A</x>", empty(DATA)); check("<A>A</A> ! data() = data(<A>B</A>)", false, empty(DATA)); } /** Remove redundant atomizations. */ @Test public void gh1769string() { check("('a', 'b')[string() = 'a']", "a", empty(STRING)); check("('a', 'b')[string(.) = 'b']", "b", empty(STRING)); check("<x>A</x>[string() = 'A']", "<x>A</x>", empty(STRING)); check("<x>A</x>[string(.) = 'A']", "<x>A</x>", empty(STRING)); check("<A>A</A> ! string() = data(<A>B</A>)", false, empty(STRING)); check("max(<_>1</_> ! string(@a))", "", root(ItemMap.class)); check("max((<_>1</_>, <_>2</_>) ! string(@a))", "", root(MAX)); check("min(<_ _='A'/>/@_ ! string())", "A", root(MIN)); check("string(<_>1</_>[.= 1]) = <_>1</_>", true, exists(STRING)); } /** Remove redundant atomizations. */ @Test public void gh1769number() { check("(0e0, 1e0)[number() = 1]", 1, empty(NUMBER)); check("(0e0, 1e0)[number(.) = 1]", 1, empty(NUMBER)); check("<_>1</_>[number() = 1]", "<_>1</_>", empty(NUMBER)); check("<_>1</_>[number(.) = 1]", "<_>1</_>", empty(NUMBER)); check("number(<_>1</_>) + 2", 3, empty(NUMBER)); check("(1e0, 2e0) ! (number() + 1)", "2\n3", empty(NUMBER)); check("for $v in (1e0, 2e0) return number($v) + 1", "2\n3", empty(NUMBER)); check("for $n in (10000000000000000, 1) return number($n) = 10000000000000001", "true\nfalse", exists(NUMBER)); } /** Inlining of where clauses. */ @Test public void gh1782() { check("1 ! (for $a in (1, 2) where $a = last() return $a)", 1, exists(GFLWOR.class)); check("(3, 4) ! (for $a in (1, 2) where . = $a return $a)", "", exists(GFLWOR.class)); } /** Rewriting of positional tests that might yield an error. */ @Test public void gh1783() { execute(new Close()); error("(position() = 3) = (position() = 3)", NOCTX_X); error(". = .", NOCTX_X); } /** Pre-evaluate predicates in filter expressions. */ @Test public void gh1785() { check("<a/>[self::node()]", "<a/>", root(CElem.class)); check("<a/>[self::*]", "<a/>", root(CElem.class)); check("<a/>[self::*[name(..) = 'a']]", "", root(IterFilter.class)); check("<a/>[self::text()]", "", empty()); } /** Better typing of functions with context arguments. */ @Test public void gh1787() { check("path(<a/>) instance of xs:string", true, root(Bln.class)); check("<a/>[path() instance of xs:string]", "<a/>", root(CElem.class)); check("<a/>[name() = 'a']", "<a/>", exists(CmpSimpleG.class)); check("node-name(prof:void(()))", "", root(_PROF_VOID)); check("prefix-from-QName(prof:void(()))", "", root(_PROF_VOID)); } /** Rewrite name tests to self steps. */ @Test public void gh1770() { check("<a/>[node-name() eq xs:QName('a')]", "<a/>", exists(SingleIterPath.class)); check("<a/>[local-name() eq 'a']", "<a/>", exists(SingleIterPath.class)); check("<a/>[local-name() = ('a', 'b', '')]", "<a/>", exists(SingleIterPath.class)); check("<a/>[local-name() = 'a' or local-name() = 'b']", "<a/>", exists(SingleIterPath.class)); check("<a/>[node-name() = (xs:QName('a'), xs:QName('b'))]", "<a/>", exists(SingleIterPath.class)); check("<a/>[local-name() = ('', '', '')]", "", empty()); check("(<a/>, <b/>)[. = '!'][local-name() = 'a']", "", empty(LOCAL_NAME)); check("comment {}[local-name() = '']", "<!---->", root(CComm.class)); check("text { 'a' }[local-name() = '']", "a", root(CTxt.class)); final String prolog = "declare default element namespace 'A'; "; check(prolog + "<a/>[node-name() eq QName('A', 'a')]", "<a xmlns=\"A\"/>", exists(SingleIterPath.class)); check(prolog + "<a/>[namespace-uri() eq 'A']", "<a xmlns=\"A\"/>", exists(SingleIterPath.class)); // no rewritings check("<a/>[local-name() != 'a']", "", exists(LOCAL_NAME)); check("<a/>[local-name() = <_>a</_>]", "<a/>", exists(LOCAL_NAME)); check("<a/>[node-name() = xs:QName(<_>a</_>)]", "<a/>", exists(NODE_NAME)); check("parse-xml('<a/>')[name(*) = 'a']", "<a/>", exists(Function.NAME)); } /** Functions with database access. */ @Test public void gh1788() { execute(new CreateDB(NAME, "<x>A</x>")); check("db:text('" + NAME + "', 'A')/parent::x", "<x>A</x>", exists(_DB_TEXT)); check("db:text('" + NAME + "', 'A')/parent::unknown", "", empty()); } /** Inline context in filter expressions. */ @Test public void gh1792() { check("1[. = 0]", "", empty()); check("1[. * .]", 1, root(Int.class)); check("2[. * . = 4]", 2, root(Int.class)); check("2[number()]", "", empty()); check("1[count(.)]", 1, root(Int.class)); check("1[count(.)]", 1, root(Int.class)); check("1[.[.[.[.[.[.[.[.[. = 1]]]]]]]]]", 1, root(Int.class)); check("1[1[1[1[1[1[1[1[1[1 = .]]]]]]]]]", 1, root(Int.class)); check("''[string()]", "", empty()); check("'a'[string()]", "a", root(Str.class)); check("'a'[string(.)]", "a", root(Str.class)); check("'a'[string-length() = 1]", "a", root(Str.class)); check("'a'[string-length(.) = 1]", "a", root(Str.class)); check("' '[normalize-space()]", "", empty()); check("''[data()]", "", empty()); check("<_/>[data()]", "", root(IterFilter.class)); check("(1, 2)[. = 3]", "", root(IterFilter.class)); } /** Type checks. */ @Test public void gh1791() { check("function() as xs:double { <x>1</x> }() + 2", 3, empty(TypeCheck.class)); check("declare function local:_() as xs:string { <x>A</x> }; local:_() = 'A'", true, empty(TypeCheck.class)); check("declare function local:f($s as xs:string) { tokenize($s) };\n" + "<x/> ! local:f(.)", "", empty(TypeCheck.class)); } /** Unary expression. */ @Test public void gh1796() { check("-xs:byte(-128) instance of xs:byte", false, empty(Unary.class), empty(Cast.class)); check("for $i in -128 return --xs:byte($i) instance of xs:byte", false, empty(Unary.class), empty(Cast.class)); check("let $i := -128 return --xs:byte($i) instance of xs:byte", false, empty(Unary.class), empty(Cast.class)); check("--xs:byte(<_>-128</_>)", -128, empty(Unary.class), count(Cast.class, 2)); } /** Promote to expression. */ @Test public void gh1798() { check("<a>1</a> promote to xs:string", 1, root(TypeCheck.class)); check("(1, 2) promote to xs:double+", "1\n2", empty(TypeCheck.class), root(ItemSeq.class), count(Dbl.class, 2)); error("<a/> promote to empty-sequence()", INVPROMOTE_X_X_X); error("(1, 2) promote to xs:byte+", INVPROMOTE_X_X_X); } /** Treats and promotions, error messages. */ @Test public void gh1799() { error("'a' promote to node()", INVPROMOTE_X_X_X); error("'a' treat as node()", NOTREAT_X_X_X); } /** Merge of operations with fn:not. */ @Test public void gh1805() { check("<_/>[not(. = ('A', 'B'))][not(. = ('C', 'D'))]", "<_/>", count(CmpHashG.class, 1)); check("<_/>[. != 'A'][. != 'B'][. != 'C'][. != 'D']", "<_/>", count(CmpHashG.class, 1)); check("(3, 4)[not(. = 1) and not(. = (2, 3))]", 4, count(NOT, 1), count(CmpHashG.class, 1)); check("(3, 4)[not(. = (2, 3)) and . != 1]", 4, count(NOT, 1), count(CmpHashG.class, 1)); check("(3, 4)[not(. = (2, 3)) and not(. = (1, 4))]", "", count(NOT, 1), count(CmpHashG.class, 1)); } /** Comparisons with empty strings. */ @Test public void gh1803() { check("<a/>[namespace-uri() eq '']", "<a/>", exists(NOT), empty(STRING)); check("<a/>[local-name() eq '']", "", exists(NOT), empty(STRING)); check("attribute { 'a' } { '' }[local-name() = '']", "", exists(NOT), empty(STRING)); check("let $x := (<a/>, <a/>) where $x[. eq ''] return $x", "<a/>\n<a/>", exists(NOT), exists(DATA)); check("string(<_/>) != ''", false, root(BOOLEAN)); check("string(<_/>) = ''", true, root(NOT), exists(DATA)); check("string(<_/>) <= ''", true, root(NOT), exists(DATA)); check("string(<_/>) >= ''", true, root(Bln.class)); check("string(<_/>) < ''", false, root(Bln.class)); check("('', 'a')[string() != '']", "a", root(IterFilter.class), empty(CmpG.class)); check("('', 'a')[string() = '']", "", root(IterFilter.class), exists(NOT)); } /** Comparisons with simple map operands. */ @Test public void gh1804() { // rewritings in comparisons check("<_>A</_> ! text() = 'A'", true, exists(IterPath.class), empty(IterMap.class)); check("<_>A</_> ! text() = 'A'", true, exists(IterPath.class), empty(IterMap.class)); check("let $a := <_>A</_> return $a ! text() = $a ! text()", true, count(IterPath.class, 2), empty(IterMap.class)); // EBV rewritings check("<a><b/></a>[b ! ..]", "<a>\n<b/>\n</a>", exists(CachedPath.class), empty(IterMap.class)); // do not rewrite absolute paths check("<a>a</a>/string() ! <x>{ . }</x>/text() = 'a'", true, exists(IterMap.class)); } /** Rewrite if to where. */ public void gh1806() { check("let $a := <_/> return if ($a = '') then $a else ()", "<_/>", empty(If.class), exists(Where.class)); check("for $a in (1, 2) return if ($a = 3) then $a else ()", "", empty(If.class), exists(Where.class), root(IterFilter.class)); check("for $t in ('a', 'b') return if($t) then $t else ()", "a\nb", root(IterFilter.class), exists(ContextValue.class)); check("for $t in ('a', 'b') return $t[$t]", "a\nb", root(IterFilter.class), exists(ContextValue.class)); } /** If expression with empty branches. */ @Test public void gh1809() { check("if(<_>1</_>[. = 1]) then () else ()", "", empty()); check("if(prof:void(1)) then () else ()", "", root(_PROF_VOID), count(_PROF_VOID, 1)); } /** EBV simplifications: if, switch, typeswitch. */ @Test public void gh1813() { // if expression check("(1, 2) ! boolean(if(.) then 'a' else <a/>)", "true\ntrue", root(SingletonSeq.class)); check("(1 to 2) ! boolean(if(.) then '' else ())", "false\nfalse", root(SingletonSeq.class)); check("boolean(if(random:double()) then '' else 0)", "false", root(List.class), exists(_PROF_VOID)); check("(1, 2)[if(.) then 0.0e0 else 0.0]", "", empty()); check("(1, 2)[if(.) then '' else xs:anyURI('')]", "", empty()); // no rewriting of numbers > 0 check("(1, 2) ! boolean(if(.) then 'a' else 1)", "true\ntrue", exists(If.class)); // switch expression check("for $i in (1 to 3)\n" + "return if(switch($i)\n" + " case 1 return 0\n" + " case 2 return ''\n" + " default return ()\n" + ") then 'fail' else ''", "\n\n", root(SingletonSeq.class)); // typeswitch expression check("for $i in ('a', 1)\n" + "return if(typeswitch($i)\n" + " case xs:integer return 0\n" + " case xs:string return ''\n" + " default return ()\n" + ") then 'fail' else ''", "\n", root(SingletonSeq.class)); } /** Simple map, index rewritings. */ @Test public void gh1814() { execute(new CreateDB(NAME, "<x><y><z>A</z></y></x>")); check("exists(x[y/z = 'A'])", true, exists(ValueAccess.class)); check("exists(x[y ! z = 'A'])", true, exists(ValueAccess.class)); } /** Typing: data references. */ @Test public void gh1816() { execute(new CreateDB(NAME, "<x><y/></x>")); check("x/z", "", empty()); check("(x, y)/z", "", empty()); check("(x | y)/z", "", empty()); check("(if(random:double()) then x else y)/z", "", empty()); check("(let $_ := random:double() return x)/z", "", empty()); check("((# bla #) { x })/z", "", empty()); check("(switch (random:double())\n" + " case 1 return ()\n" + " default return x\n" + ")/z", "", empty()); check("(x, prof:void(()))/z", "", empty()); check("(x | prof:void(()))/z", "", empty()); check("(if(random:double()) then x)/z", "", empty()); } /** List to union in root of path expression. */ @Test public void gh1817() { check("<a/>[(b, c)/d]", "", empty(List.class), count(IterPath.class, 1)); // do not rewrite paths that yield no nodes check("(<a/>, <b/>)/name()", "a\nb", exists(List.class)); check("let $_ := <_/> return ($_, $_)/0", "0\n0", exists(SingletonSeq.class)); } /** List to union. */ @Test public void gh1818() { check("<a/>[b, text()]", "", exists(Union.class), count(SingleIterPath.class, 2)); // union expression will be further rewritten to single path check("<a/>[b, c]", "", empty(List.class), count(SingleIterPath.class, 1)); check("<a/>[(b, c) = '']", "", empty(List.class), count(SingleIterPath.class, 1)); check("<a/>[(b, c) = (b, c)]", "", empty(List.class), count(SingleIterPath.class, 2)); } /** FLWOR, no results, non-deterministic expressions. */ @Test public void gh1819() { check("for $_ in () return <x/>", "", empty()); check("for $_ in prof:void(1) return 1", "", root(_PROF_VOID)); check("let $_ := 1 return <x/>", "<x/>", root(CElem.class)); check("let $_ := prof:void(1) return 1", 1, root(List.class), exists(_PROF_VOID)); check("for $_ in 1 to 2 return 3", "3\n3", root(SingletonSeq.class)); check("for $_ in 1 to 2 return ()", "", empty()); // skip rewriting check("for $_ in 1 to 2 return <a/>", "<a/>\n<a/>", root(GFLWOR.class)); check("for $_ in 1 to 2 return prof:void(1)", "", root(GFLWOR.class)); } /** Merge and/or expressions. */ @Test public void gh1820() { // OR: merge check("(<_/>, <_/>) = 'a' or (<_/>, <_/>) = 'b'", false, empty(Or.class)); check("(<_/>, <_/>) = 'a' or (<_/>, <_/>) = ('b', 'c')", false, empty(Or.class)); check("<_>1</_>[. = 1 or . = (2, 3)]", "<_>1</_>", empty(Or.class), exists(CmpG.class)); check("<_>1</_>[not(. = 1) or . != (2, 3)]", "<_>1</_>", empty(Or.class)); check("exists(let $x := <a><b>c</b><b>d</b></a> return $x[b = 'c' or b = 'd'])", true, count(CmpHashG.class, 1)); // OR: no merge check("<_>1</_>[not(. = 1) or not(. = (2, 3))]", "<_>1</_>", exists(Or.class)); check("<_>1</_>[. = 1 or not(. != (2, 3))]", "<_>1</_>", exists(Or.class)); check("<_>1</_>[not(. = 1) or . = (2, 3)]", "", exists(Or.class)); check("<_>1</_>[. = 1 or not(. = (2, 3))]", "<_>1</_>", exists(Or.class)); check("<_>a</_>[. = 'a' or . != 'b']", "<_>a</_>", exists(Or.class)); check("<_>a</_>[. = 'a' or .. != 'b']", "<_>a</_>", exists(Or.class)); // AND: merge check("(<_/>, <_/>) = 'a' and (<_/>, <_/>) = 'b'", false, empty(And.class)); check("<_>1</_>[not(. = 1) and not(. = (2, 3))]", "", exists(CmpG.class), empty(CmpSimpleG.class)); check("not((<_/>, <_/>) != 'a') and not((<_/>, <_/>) != 'b')", false, exists(CmpG.class), empty(CmpSimpleG.class)); // AND: no merge check("(<_/>, <_/>) = 'a' and (<_/>, <_/>) = ('b', 'c')", false, exists(And.class)); check("exists(let $x := <a><b>c</b><b>d</b></a> return $x[b = 'c' and b = 'd'])", true, count(CmpG.class, 2)); check("<_>1</_>[. = 1 and . = (2, 3)]", "", exists(CmpG.class), exists(CmpSimpleG.class)); check("<_>1</_>[not(. = 1) and . = (2, 3)]", "", exists(CmpG.class), exists(CmpSimpleG.class)); check("<_>1</_>[. = 1 and not(. = (2, 3))]", "<_>1</_>", exists(CmpG.class), exists(CmpSimpleG.class)); check("(<_/>, <_/>) = '' and (<_/>, <_/>) = 'a'", false, exists(And.class)); } /** Map/array lookups: better typing. */ @Test public void gh1825() { check("[ 1 ](<_>1</_>) instance of xs:integer", true, root(Bln.class)); check("map { 'a': 2 }(<_>a</_>) instance of xs:integer?", true, root(Bln.class)); check("map { 1: 2 }(<_/>) instance of xs:integer?", true, root(Bln.class)); check("map { 1: (2, 'a') }(<_/>) instance of xs:anyAtomicType*", true, root(Bln.class)); } /** Rewriting of positional predicate. */ @Test public void gh1827() { check("declare function local:f($pos) { (1, 2)[position() < $pos] };\n" + "local:f(1)", "", empty()); } /** Merge fn:empty and fn:exist functions. */ @Test public void gh1829() { check("exists(<a/>/a) or exists(<b/>/b)", false, root(BOOLEAN), empty(Or.class), empty(EXISTS), exists(Union.class)); check("for $i in 1 to 2 return exists($i[. = 1]) or exists($i[. = 2])", "true\ntrue", empty(Or.class), count(EXISTS, 1)); check("<a/>/a or <b/>/b", false, root(BOOLEAN), empty(Or.class), exists(Union.class)); check("<a/>[a or b]", "", empty(Or.class), count(SingleIterPath.class, 1)); check("<a/>[empty(b)][empty(c)]", "<a/>", count(EMPTY, 1), count(SingleIterPath.class, 1)); check("<a/>[empty((b, c))]", "<a/>", count(SingleIterPath.class, 1)); check("for $a in (<b/>, <c/>) return <a/>[empty(($a[. = 'a'], $a[. = 'b']))]", "<a/>\n<a/>", count(IterFilter.class, 2)); // no rewritings query("for $a in 1 to 2 return <a/>[empty(($a[. = 1], $a[. = 1]))]", "<a/>"); check("exists(<a/>/a) and exists(<b/>/b)", false, exists(And.class)); check("for $i in 1 to 2 return exists($i[. = 1]) and exists($i[. = 2])", "false\nfalse", exists(And.class)); check("<a/>/a and <b/>/b", false, exists(And.class)); check("<a/>[a and b]", "", count(SingleIterPath.class, 2)); check("<a/>[empty(b) or empty(c)]", "<a/>", exists(Or.class)); } /** Documents with different default namespaces. */ @Test public void gh1831() { execute(new CreateDB(NAME)); execute(new Add("a.xml", "<x xmlns='x'/>")); execute(new Add("b.xml", "<x/>")); query("x", "<x/>"); } /** Equality tests on QNames. */ @Test public void gh1823() { query("declare namespace p = 'U';\n" + "prefix-from-QName(QName('U', 'a')[. = xs:QName(<_>p:a</_>)]) or\n" + "prefix-from-QName(QName('U', 'p:a')[. = xs:QName(<_>p:a</_>)])", true); query("let $f := function($a) { string($a) }\n" + "return distinct-values(($f(QName('U', 'l')), $f(QName('U', 'p:l'))))", "l\np:l"); } /** Static typing, maps. */ @Test public void gh1834() { query("declare function local:f() as map(xs:string, xs:string) {" + " map:entry(<e/> ! string(), '')" + "}; local:f()?*", ""); query("declare function local:f() as map(xs:string, xs:string) {" + " map:put(map {}, <e/> ! string(), '')" + "}; local:f()?*", ""); } /** Set Expressions: Merge operands. */ @Test public void gh1838() { check("<_><a/></_>/(* union *[b])", "<a/>", empty(Union.class), empty(SingleIterPath.class), count(IterStep.class, 1)); check("<_><a/></_>/(* intersect *[b])", "", empty(Intersect.class), count(SingleIterPath.class, 1), count(IterStep.class, 2)); check("<_><a/></_>/(* except *[b])", "<a/>", empty(Except.class), exists(EMPTY), count(SingleIterPath.class, 1)); check("<_><a/></_>/*/(.[self::a] union .[self::b])", "<a/>", empty(Union.class)); check("<_><a/></_>/*/(.[self::a] intersect .[self::b])", "", empty(Intersect.class)); check("<_><a/></_>/*/(.[self::a] except .[self::b])", "<a/>", empty(Except.class), exists(EMPTY)); check("<_><a/></_>/(.[b][c] union .[d])", "", empty(Union.class), exists(And.class), exists(Or.class)); check("<_><a/></_>/(.[b][c] intersect .[d])", "", empty(Intersect.class), empty(And.class)); check("<_><a/></_>/(.[b][c] except .[d])", "", empty(Except.class), exists(EMPTY), empty(And.class)); // no optimization check("<_><a/></_>/(a union a/*[b])", "<a/>", exists(Union.class)); check("<_><a/></_>/(a union a/<b/>)", "<a/>\n<b/>", exists(Union.class)); check("<_><a/></_>/(a union self::a)", "<a/>", exists(Union.class)); check("<_><a/></_>/(a[1] union a[2])", "<a/>", exists(Union.class)); check("<_/>/(<b/>[*] union <c/>[*])", "", exists(Union.class)); } /** Distinct integer sequences. */ @Test public void gh1841() { check("<_/>[position() = (1, 1)]", "<_/>", root(CElem.class)); check("<_/>[position() = (1, 2, 1)]", "<_/>", count(Int.class, 2)); } }
basex-core/src/test/java/org/basex/query/ast/RewritingsTest.java
package org.basex.query.ast; import static org.basex.query.func.Function.*; import static org.basex.query.QueryError.*; import org.basex.core.cmd.*; import org.basex.query.expr.*; import org.basex.query.expr.List; import org.basex.query.expr.constr.*; import org.basex.query.expr.gflwor.*; import org.basex.query.expr.index.*; import org.basex.query.expr.path.*; import org.basex.query.func.*; import org.basex.query.value.item.*; import org.basex.query.value.node.*; import org.basex.query.value.seq.*; import org.basex.query.var.*; import org.junit.Test; /** * Checks query rewritings. * * @author BaseX Team 2005-20, BSD License * @author Christian Gruen */ public final class RewritingsTest extends QueryPlanTest { /** Input file. */ private static final String FILE = "src/test/resources/input.xml"; /** Checks if the count function is pre-compiled. */ @Test public void preEval() { check("count(1)", 1, exists(Int.class)); execute(new CreateDB(NAME, "<xml><a x='y'>1</a><a>2 3</a><a/></xml>")); check("count(//a)", 3, exists(Int.class)); check("count(/xml/a)", 3, exists(Int.class)); check("count(//text())", 2, exists(Int.class)); check("count(//*)", 4, exists(Int.class)); check("count(//node())", 6, exists(Int.class)); check("count(//comment())", 0, exists(Int.class)); check("count(/self::document-node())", 1, exists(Int.class)); } /** Checks if descendant-or-self::node() steps are rewritten. */ @Test public void mergeDesc() { execute(new CreateDB(NAME, "<a><b>B</b><b><c>C</c></b></a>")); check("//*", null, "//@axis = 'descendant'"); check("//(b, *)", null, exists(IterPath.class), "//@axis = 'descendant'"); check("//(b | *)", null, exists(IterPath.class), "//@axis = 'descendant'"); check("//(b | *)[text()]", null, exists(IterPath.class), empty(Union.class), "//@axis = 'descendant'"); check("//(b, *)[1]", null, "not(//@axis = 'descendant')"); } /** Checks if descendant steps are rewritten to child steps. */ @Test public void descToChild() { execute(new CreateDB(NAME, "<a><b>B</b><b><c>C</c></b></a>")); check("descendant::a", null, "//@axis = 'child'"); check("descendant::b", null, "//@axis = 'child'"); check("descendant::c", null, "//@axis = 'child'"); check("descendant::*", null, "not(//@axis = 'child')"); } /** Checks EBV optimizations. */ @Test public void optimizeEbv() { query("not(<a/>[b])", true); query("empty(<a/>[b])", true); query("exists(<a/>[b])", false); query("not(<a/>[b = 'c'])", true); query("empty(<a/>[b = 'c'])", true); query("exists(<a/>[b = 'c'])", false); query("let $n := <n/> where $n[<a><b/><b/></a>/*] return $n", "<n/>"); check("empty(<a>X</a>[text()])", null, "//@axis = 'child'"); check("exists(<a>X</a>[text()])", null, "//@axis = 'child'"); check("boolean(<a>X</a>[text()])", null, "//@axis = 'child'"); check("not(<a>X</a>[text()])", null, "//@axis = 'child'"); check("if(<a>X</a>[text()]) then 1 else 2", null, "//@axis = 'child'"); check("<a>X</a>[text()] and <a/>", null, "//@axis = 'child'"); check("<a>X</a>[text()] or <a/>", null, "//Bln = 'true'"); check("<a>X</a>[text()] or <a/>[text()]", null, "//@axis = 'child'"); check("for $a in <a>X</a> where $a[text()] return $a", null, "//@axis = 'child'"); check("empty(<a>X</a>/.[text()])", null, "//@axis = 'child'"); } /** Checks if iterative evaluation of XPaths is used if no duplicates occur. */ @Test public void gh1001() { execute(new CreateDB(NAME, "<a id='0' x:id='' x='' xmlns:x='x'><b id='1'/><c id='2'/>" + "<d id='3'/><e id='4'/></a>")); check("(/a/*/../*) ! name()", "b\nc\nd\ne", empty(IterPath.class)); check("(exactly-one(/a/b)/../*) ! name()", "b\nc\nd\ne", exists(IterPath.class)); check("(/a/*/following::*) ! name()", "c\nd\ne", empty(IterPath.class)); check("(exactly-one(/a/b)/following::*) ! name()", "c\nd\ne", exists(IterPath.class)); check("(/a/*/following-sibling::*) ! name()", "c\nd\ne", empty(IterPath.class)); check("(exactly-one(/a/b)/following-sibling::*) ! name()", "c\nd\ne", exists(IterPath.class)); check("(/*/@id/../*) ! name()", "b\nc\nd\ne", empty(IterPath.class)); check("(exactly-one(/a)/@id/../*) ! name()", "b\nc\nd\ne", exists(IterPath.class)); } /** Checks OR optimizations. */ @Test public void or() { check("('' or '')", false, empty(Or.class)); check("('x' or 'x' = 'x')", true, empty(Or.class)); check("(false() or <x/> = 'x')", false, empty(Or.class)); check("(true() or <x/> = 'x')", true, empty(Or.class)); check("('x' = 'x' or <x/> = 'x')", true, empty(Or.class)); // {@link CmpG} rewritings check("let $x := <x/> return ($x = 'x' or $x = 'y')", false, empty(Or.class)); check("let $x := <x>x</x> return ($x = 'x' or $x = 'y')", true, empty(Or.class)); } /** Checks AND optimizations. */ @Test public void and() { check("('x' and 'y')", true, empty(And.class)); check("('x' and 'x' = 'x')", true, empty(And.class)); check("(true() and <x>x</x> = 'x')", true, empty(And.class)); check("(false() and <x>x</x> = 'x')", false, empty(And.class)); check("('x' = 'x' and <x>x</x> = 'x')", true, empty(And.class)); } /** Checks {@link CmpIR} optimizations. */ @Test public void cmpIR() { final Class<CmpIR> cmpir = CmpIR.class; check("(1, 2)[. = 1] = 1 to 2", true, exists(cmpir)); check("(1, 2)[. = 3] = 1 to 2", false, exists(cmpir)); check("(1, 2)[. = 3] = 1 to 2", false, exists(cmpir)); // do not rewrite equality comparisons against single integers check("(1, 2)[. = 1] = 1", true, empty(cmpir)); // rewrite to positional test check("(1 to 5)[let $p := position() return $p = 2]", 2, empty(cmpir), empty(Let.class), empty(POSITION)); check("1[let $p := position() return $p = 0]", "", empty()); check("1[let $p := position() return $p = (-5 to -1)]", "", empty()); } /** Checks {@link CmpR} optimizations. */ @Test public void cmpR() { final Class<CmpR> cmpr = CmpR.class; check("<a>5</a>[text() > 1 and text() < 9]", "<a>5</a>", count(cmpr, 1)); check("<a>5</a>[text() > 1 and text() < 9 and <b/>]", "<a>5</a>", count(cmpr, 1)); check("<a>5</a>[text() > 1 and . < 9]", "<a>5</a>", count(cmpr, 2)); // GH-1744 check("<a>5</a>[text() < 5 or text() > 5]", "", count(cmpr, 2)); check("<a>5</a>[text() > 5 or text() < 5]", "", count(cmpr, 2)); check("<a>5</a>[5 > text() or 5 < text()]", "", count(cmpr, 2)); check("<a>5</a>[5 < text() or 5 > text()]", "", count(cmpr, 2)); check("<a>5</a>[text() > 800000000]", "", exists(cmpr)); check("<a>5</a>[text() < -800000000]", "", exists(cmpr)); check("<a>5</a>[text() <= -800000000]", "", exists(cmpr)); check("exists(<x>1234567890.12345678</x>[. = 1234567890.1234567])", true, empty(cmpr)); check("exists(<x>123456789012345678</x> [. = 123456789012345679])", true, empty(cmpr)); check("<a>5</a>[text() > 8000000000000000000]", "", empty(cmpr)); check("<a>5</a>[text() < -8000000000000000000]", "", empty(cmpr)); check("(1, 1234567890.12345678)[. = 1234567890.1234567]", "", empty(cmpr)); check("(1, 123456789012345678 )[. = 123456789012345679]", "", empty(cmpr)); // rewrite equality comparisons check("(0, 1)[. = 1] >= 1.0", true, exists(cmpr)); check("(0, 1)[. = 1] >= 1e0", true, exists(cmpr)); check("(0e0, 1e0)[. = 1] >= 1", true, exists(cmpr)); check("(0e0, 1e0)[. = 1] >= 1e0", true, exists(cmpr)); check("<_>1.1</_> >= 1.1", true, exists(cmpr)); // do not rewrite decimal/double comparisons check("(0e0, 1e0)[. = 1] >= 1.0", true, empty(cmpr)); check("(0.0, 1.0)[. = 1] >= 1e0", true, empty(cmpr)); // do not rewrite equality comparisons check("(0, 1)[. = 1] = 1.0", true, empty(cmpr)); check("(0, 1)[. = 1] = 1e0", true, empty(cmpr)); check("(0e0, 1e0)[. = 1] = 1", true, empty(cmpr)); check("(0e0, 1e0)[. = 1] = 1.0", true, empty(cmpr)); check("(0e0, 1e0)[. = 1] = 1e0", true, empty(cmpr)); check("<_>1.1</_> = 1.1", true, empty(cmpr)); // suppressed rewritings check("random:double() = 2", false, empty(cmpr)); check("(0.1, 1.1)[. != 0] = 1.3", false, empty(cmpr)); check("('x', 'y')[. = 'x'] = 'x'", true, empty(cmpr)); check("('x', 'x')[. != 'x'] = 1.3", false, empty(cmpr)); check("(0.1, 1.1)[. = 1.1] = 1.1", true, empty(cmpr)); // rewrite to positional test check("1[let $p := position() return $p = 0.0]", "", empty()); } /** Checks {@link CmpSR} optimizations. */ @Test public void cmpSR() { check("<a>5</a>[text() > '1' and text() < '9']", "<a>5</a>", count(CmpSR.class, 1)); check("<a>5</a>[text() > '1' and text() < '9' and <b/>]", "<a>5</a>", count(CmpSR.class, 1)); check("<a>5</a>[text() > '1' and . < '9']", "<a>5</a>", count(CmpSR.class, 2)); } /** Checks string-length optimizations. */ @Test public void stringLength() { check("<a/>[string-length() > -1]", "<a/>", empty(IterFilter.class)); check("<a/>[string-length() != -1]", "<a/>", empty(IterFilter.class)); check("<a/>[string-length() ge 0]", "<a/>", empty(IterFilter.class)); check("<a/>[string-length() ne 1.1]", "<a/>", empty(IterFilter.class)); check("<a/>[string-length() < 0]", "", empty(IterFilter.class)); check("<a/>[string-length() <= -1]", "", empty(IterFilter.class)); check("<a/>[string-length() eq -1]", "", empty(IterFilter.class)); check("<a/>[string-length() eq 1.1]", "", empty(IterFilter.class)); check("<a/>[string-length() > 0]", "", exists(STRING)); check("<a/>[string-length() >= 0.5]", "", exists(STRING)); check("<a/>[string-length() ne 0]", "", exists(STRING)); check("<a/>[string-length() < 0.5]", "<a/>", exists(STRING)); check("<a/>[string-length() <= 0.5]", "<a/>", exists(STRING)); check("<a/>[string-length() eq 0]", "<a/>", exists(STRING)); check("<a/>[string-length() gt 1]", "", exists(STRING_LENGTH)); check("<a/>[string-length() = <a>1</a>]", "", exists(STRING_LENGTH)); } /** Checks count optimizations. */ @Test public void count() { // static occurrence: zero-or-one String count = "count(<_>1</_>[. = 1])"; // static result: no need to evaluate count check(count + " < 0", false, root(Bln.class)); check(count + " <= -.1", false, root(Bln.class)); check(count + " >= 0", true, root(Bln.class)); check(count + " > -0.1", true, root(Bln.class)); check(count + " = 1.1", false, root(Bln.class)); check(count + " != 1.1", true, root(Bln.class)); check(count + " = -1", false, root(Bln.class)); check(count + " != -1", true, root(Bln.class)); // rewrite to empty/exists (faster) check(count + " > 0", true, root(EXISTS)); check(count + " >= 1", true, root(EXISTS)); check(count + " != 0", true, root(EXISTS)); check(count + " < 1", false, root(EMPTY)); check(count + " <= 0", false, root(EMPTY)); check(count + " = 0", false, root(EMPTY)); // zero-or-one result: no need to evaluate count check(count + " < 2", true, root(Bln.class)); check(count + " <= 1", true, root(Bln.class)); check(count + " != 2", true, root(Bln.class)); check(count + " > 1", false, root(Bln.class)); check(count + " >= 2", false, root(Bln.class)); check(count + " = 2", false, root(Bln.class)); // no rewritings possible check(count + " != 1", false, exists(COUNT)); check(count + " = 1", true, exists(COUNT)); // one-or-more results: no need to evaluate count count = "count((1, <_>1</_>[. = 1]))"; check(count + " > 0", true, root(Bln.class)); check(count + " >= 1", true, root(Bln.class)); check(count + " != 0", true, root(Bln.class)); check(count + " < 1", false, root(Bln.class)); check(count + " <= 0", false, root(Bln.class)); check(count + " = 0", false, root(Bln.class)); // no rewritings possible check(count + " = 1", false, exists(COUNT)); check(count + " = 2", true, exists(COUNT)); } /** Checks that empty sequences are eliminated and that singleton lists are flattened. */ @Test public void list() { check("((), <x/>, ())", "<x/>", empty(List.class), empty(Empty.class), exists(CElem.class)); } /** Checks that expressions marked as non-deterministic will not be rewritten. */ @Test public void nonDeterministic() { check("count((# basex:non-deterministic #) { <x/> })", 1, exists(COUNT)); } /** Ensures that fn:doc with URLs will not be rewritten. */ @Test public void doc() { check("<a>{ doc('" + FILE + "') }</a>//x", "", exists(DBNode.class)); check("if(<x>1</x> = 1) then 2 else doc('" + FILE + "')", 2, exists(DBNode.class)); check("if(<x>1</x> = 1) then 2 else doc('http://abc.de/')", 2, exists(DOC)); check("if(<x>1</x> = 1) then 2 else collection('http://abc.de/')", 2, exists(COLLECTION)); } /** Positional predicates. */ @Test public void pos() { // check if positional predicates are pre-evaluated check("'a'[1]", "a", exists(Str.class)); check("'a'[position() = 1]", "a", "exists(QueryPlan/Str)"); check("'a'[position() = 1 to 2]", "a", "exists(QueryPlan/Str)"); check("'a'[position() > 0]", "a", "exists(QueryPlan/Str)"); check("'a'[position() < 2]", "a", "exists(QueryPlan/Str)"); check("'a'[position() >= 1]", "a", "exists(QueryPlan/Str)"); check("'a'[position() <= 1]", "a", "exists(QueryPlan/Str)"); // check if positional predicates are rewritten to utility functions check("for $i in (1, 2) return 'a'[$i]", "a", exists(_UTIL_ITEM)); check("for $i in (1, 2) return 'a'[position() = $i]", "a", exists(_UTIL_ITEM)); check("for $i in (1, 2) return 'a'[position() = $i to $i]", "a", exists(_UTIL_ITEM)); check("for $i in (1, 2) return 'a'[position() = $i to $i+1]", "a", exists(_UTIL_RANGE)); check("for $i in (1, 2) return 'a'[position() = $i to 1]", "a", exists(_UTIL_RANGE)); check("for $i in (1, 2) return 'a'[position() >= $i]", "a", exists(_UTIL_RANGE)); check("for $i in (1, 2) return 'a'[position() > $i]", "", exists(_UTIL_RANGE)); check("for $i in (1, 2) return 'a'[position() <= $i]", "a\na", exists(_UTIL_RANGE)); check("for $i in (1, 2) return 'a'[position() < $i]", "a", exists(_UTIL_RANGE)); // check if positional predicates are rewritten to utility functions final String seq = " (1, 1.1, 1.9, 2) "; check("for $i in" + seq + "return ('a', 'b')[$i]", "a\nb", exists(_UTIL_ITEM)); check("for $i in" + seq + "return ('a', 'b')[position() = $i]", "a\nb", exists(_UTIL_ITEM)); check("for $i in" + seq + "return ('a', 'b')[position() >= $i]", "a\nb\nb\nb\nb", exists(_UTIL_RANGE)); check("for $i in" + seq + "return ('a', 'b')[position() > $i]", "b\nb\nb", exists(_UTIL_RANGE)); check("for $i in" + seq + "return ('a', 'b')[position() <= $i]", "a\na\na\na\nb", exists(_UTIL_RANGE)); check("for $i in" + seq + "return ('a', 'b')[position() < $i]", "a\na\na", exists(_UTIL_RANGE)); // check if multiple positional predicates are rewritten to utility functions check("for $i in" + seq + "return ('a', 'b')[$i][$i]", "a", count(_UTIL_ITEM, 2)); check("for $i in" + seq + "return ('a', 'b')[position() = $i][position() = $i]", "a", count(_UTIL_ITEM, 2)); check("for $i in" + seq + "return ('a', 'b')[position() < $i][position() < $i]", "a\na\na", count(_UTIL_RANGE, 2)); // check if positional predicates are merged and rewritten to utility functions check("for $i in" + seq + "return ('a', 'b')[position() = $i and position() = $i]", "a\nb", exists(_UTIL_ITEM)); check("for $i in" + seq + "return ('a', 'b')[position() >= $i and position() <= $i]", "a\nb", exists(_UTIL_RANGE)); check("for $i in" + seq + "return ('a', 'b')[position() <= $i and position() >= $i]", "a\nb", exists(_UTIL_RANGE)); check("for $i in" + seq + "return ('a', 'b')[position() > $i and position() < $i]", "", exists(_UTIL_RANGE)); check("for $i in" + seq + "return ('a', 'b')[position() < $i and position() > $i]", "", exists(_UTIL_RANGE)); // no rewriting possible (conflicting positional predicates) check("for $i in" + seq + "return ('a', 'b')[position() = $i and position() = $i+1]", "", exists(CachedFilter.class)); check("for $i in" + seq + "return ('a', 'b')[position() >= $i and position() > $i]", "b\nb\nb", exists(CachedFilter.class)); check("for $i in" + seq + "return ('a', 'b')[position() >= $i and position() >= $i+1]", "b", exists(CachedFilter.class)); check("for $i in" + seq + "return ('a', 'b')[position() < $i and position() < $i+1]", "a\na\na", exists(CachedFilter.class)); check("(<a/>, <b/>)[last()]", "<b/>", count(_UTIL_LAST, 1)); check("(<a/>, <b/>)[position() > 1 and position() < 3]", "<b/>", count(_UTIL_LAST, 1)); check("(<a/>, <b/>)[position() > 1 and position() < 3 and <b/>]", "<b/>", count(_UTIL_LAST, 1)); check("(<a/>, <b/>)[position() > 1 and position() < 4]", "<b/>", count(_UTIL_LAST, 1)); } /** Predicates. */ @Test public void preds() { // context value: rewrite if root is of type string or node check("('s', 't')[.]", "s\nt", exists(ContextValue.class)); check("<a/>[.]", "<a/>", exists(CElem.class), empty(ContextValue.class)); check("<a/>[.][.]", "<a/>", exists(CElem.class), empty(ContextValue.class)); check("<a/>/self::*[.][.]", "<a/>", empty(ContextValue.class)); check("<a/>/self::*[.][.]", "<a/>", empty(ContextValue.class)); check("('a', 'b')[position()[position() ! .]]", "a\nb", count(POSITION, 2)); check("('a', 'b')[. ! position()]", "a", exists("*[contains(name(), 'Map')]")); check("(1, 0)[.]", 1, exists(ContextValue.class)); error("true#0[.]", EBV_X_X); error("(true#0, false#0)[.]", EBV_X_X); // map expression check("'s'['s' ! <a/>]", "s", empty(IterMap.class)); check("'s'['s' ! <a/>]", "s", root(Str.class)); check("'s'['x' ! <a/> ! <b/>]", "s", root(Str.class)); check("'s'['x' ! (<a/>, <b/>) ! <b/>]", "s", root(Str.class)); check("'s'['x' ! <a>{ . }</a>[. = 'x']]", "s", empty(IterMap.class), root(If.class)); // path expression check("let $a := <a/> return $a[$a/self::a]", "<a/>", count(VarRef.class, 1)); check("let $a := <a/> return $a[$a]", "<a/>", empty(VarRef.class)); } /** Comparison expressions. */ @Test public void cmpG() { check("count(let $s := (0, 1 to 99999) return $s[. = $s])", 100000, exists(CmpHashG.class)); } /** Checks OR optimizations. */ @Test public void gh1519() { query("declare function local:replicate($seq, $n, $out) {" + " if($n eq 0) then $out " + " else ( " + " let $out2 := if($n mod 2 eq 0) then $out else ($out, $seq) " + " return local:replicate(($seq, $seq), $n idiv 2, $out2) " + " )" + "};" + "let $n := 1000000000 " + "return ( " + " count(local:replicate((1, 2, 3), $n, ())) eq 3 * $n, " + " count(local:replicate((1, 2, 3), $n, ())) = 3 * $n " + ")", "true\ntrue"); } /** Checks simplification of empty path expressions. */ @Test public void gh1587() { check("document {}/..", "", empty(CDoc.class)); check("function() { document {}/.. }()", "", empty(CDoc.class)); check("declare function local:f() { document {}/.. }; local:f()", "", empty(CDoc.class)); } /** * Remove redundant self steps. */ @Test public void selfSteps() { check("<a/>/.", "<a/>", root(CElem.class)); check("<a/>/./././.", "<a/>", root(CElem.class)); check("<a/>[.]", "<a/>", root(CElem.class)); check("<a/>/self::element()", "<a/>", root(CElem.class)); check("attribute a { 0 }/self::attribute()", "a=\"0\"", root(CAttr.class)); check("<a/>/self::*", "<a/>", root(CElem.class)); } /** Static optimizations of paths without results (see also gh1630). */ @Test public void emptyPath() { // check combination of axis and node test and axis check("<e a='A'/>/attribute::text()", "", empty()); check("<e a='A'/>/attribute::attribute()", "a=\"A\"", exists(IterPath.class)); check("<e a='A'/>/ancestor::text()", "", empty()); check("<e a='A'/>/parent::text()", "", empty()); check("<e a='A'/>/parent::*", "", exists(IterPath.class)); check("attribute a { 0 }/child::attribute()", "", empty()); check("<e a='A'/>/attribute::a/child::attribute()", "", empty()); // check step after expression that yields document nodes check("document { <a/> }/self::*", "", empty()); check("document { <a/> }/self::*", "", empty()); check("document { <a/> }/self::text()", "", empty()); check("document { <a/> }/child::document-node()", "", empty()); check("document { <a/> }/child::attribute()", "", empty()); check("document { <a/> }/child::*", "<a/>", exists(IterPath.class)); check("document { <a/> }/descendant-or-self::attribute()", "", empty()); check("document { <a/> }/parent::node()", "", empty()); check("document { <a/> }/ancestor::node()", "", empty()); check("document { <a/> }/following::node()", "", empty()); check("document { <a/> }/preceding-sibling::node()", "", empty()); // skip further tests if previous node type is unknown, or if current test accepts all nodes check("(<a/>, <_>1</_>[. = 0])/node()", "", exists(IterStep.class)); // check step after any other expression check("<a/>/self::text()", "", empty()); check("comment {}/child::node()", "", empty()); check("text { 0 }/child::node()", "", empty()); check("attribute a { 0 }/following-sibling::node()", "", empty()); check("attribute a { 0 }/preceding-sibling::node()", "", empty()); check("comment { }/following-sibling::node()", "", exists(IterPath.class)); check("comment { }/preceding-sibling::node()", "", exists(IterStep.class)); check("attribute a { 0 }/child::node()", "", empty()); check("attribute a { 0 }/descendant::*", "", empty()); check("attribute a { 0 }/self::*", "", empty()); // namespaces check("(<a/>, comment{})/child::namespace-node()", "", empty()); check("(<a/>, comment{})/descendant::namespace-node()", "", empty()); check("(<a/>, comment{})/attribute::namespace-node()", "", empty()); check("(<a/>, comment{})/self::namespace-node()", "", exists(IterStep.class)); check("(<a/>, comment{})/descendant-or-self::namespace-node()", "", exists(IterStep.class)); } /** Casts. */ @Test public void gh1795() { check("for $n in 1 to 3 return xs:integer($n)[. = 1]", 1, empty(Cast.class)); check("('a', 'b') ! xs:string(.)", "a\nb", empty(Cast.class), root(StrSeq.class)); check("xs:string(''[. = <_/>])", "", empty(Cast.class), root(If.class)); check("xs:string(<_/>[. = '']) = ''", true, empty(Cast.class), root(CmpSimpleG.class)); check("xs:double(<_>1</_>) + 2", 3, empty(Cast.class), type(Arith.class, "xs:double")); check("(1, 2) ! (xs:byte(.)) ! (xs:integer(.) + 2)", "3\n4", count(Cast.class, 1), type(Arith.class, "xs:integer")); error("(if(<_>!</_> = 'a') then 'b') cast as xs:string", INVTYPE_X_X_X); } /** Type promotions. */ @Test public void gh1801() { check("map { xs:string(<_/>): '' } instance of map(xs:string, xs:string)", true); check("map { string(<_/>): '' } instance of map(xs:string, xs:string)", true); } /** Casts. */ @Test public void typeCheck() { check("declare function local:a($e) as xs:string? { local:b($e) }; " + "declare function local:b($e) as xs:string? { $e }; local:a(<_>X</_>)", "X", count(TypeCheck.class, 1)); check("declare function local:a($e) as xs:string? { local:b($e) }; " + "declare function local:b($e) as xs:string* { $e }; local:a(<_>X</_>)", "X", count(TypeCheck.class, 1)); check("declare function local:a($e) as xs:string* { local:b($e) }; " + "declare function local:b($e) as xs:string? { $e }; local:a(<_>X</_>)", "X", count(TypeCheck.class, 1)); } /** GH1694. */ @Test public void gh1694() { check("count(1)", 1, exists(Int.class)); execute(new CreateDB(NAME, "<_/>")); final String query = "declare function local:b($e) as xs:string { $e };\n" + "declare function local:a($db) {\n" + " let $ids := local:b(db:open($db))\n" + " return db:open('" + NAME + "')[*[1] = $ids]\n" + "};\n" + "local:a('" + NAME + "')"; query(query, "<_/>"); } /** GH1726. */ @Test public void gh1726() { final String query = "let $xml := if((1, 0)[.]) then ( " + " element a { element b { } update { } } " + ") else ( " + " error() " + ") " + "let $b := $xml/* " + "return ($b, $b/..)"; query(query, "<b/>\n<a>\n<b/>\n</a>"); } /** GH1723. */ @Test public void gh1723() { check("count(<a/>)", 1, root(Int.class)); check("count(<a/>/<b/>)", 1, root(Int.class)); check("count(<a/>/<b/>/<c/>/<d/>)", 1, root(Int.class)); } /** GH1733. */ @Test public void gh1733() { check("(<a/>, <b/>)/1", "1\n1", root(SingletonSeq.class)); check("<a/>/1", 1, root(Int.class)); check("<a/>/<a/>", "<a/>", root(CElem.class)); check("(<a/>/map { 1:2 })?1", 2, root(Int.class)); check("<a/>/self::a/count(.)", 1, root("ItemMap")); // no rewriting possible check("(<a/>, <b/>)/<c/>", "<c/>\n<c/>", root(MixedPath.class)); } /** GH1741. */ @Test public void gh1741() { check("<a/>/<b/>[1]", "<b/>", root(CElem.class)); check("<a/>/.[1]", "<a/>", root(CElem.class)); check("<doc><x/><y/></doc>/*/..[1] ! name()", "doc", empty(ItrPos.class)); check("<a/>/<b/>[2]", "", empty()); check("<a/>/.[2]", "", empty()); check("<doc><x/><y/></doc>/*/..[2] ! name()", "", empty()); } /** GH1737: combined kind tests. */ @Test public void gh1737() { // merge identical steps, rewrite to iterative path check("<a/>/(* | *)", "", root(IterPath.class), empty(Union.class)); check("<a/>/(*, *)", "", root(IterPath.class), empty(List.class)); // rewrite to single union node test, rewrite to iterative path check("<a/>/(a | b)", "", root(IterPath.class), empty(Union.class)); check("<a/>/(a, b)", "", root(IterPath.class), empty(List.class)); // merge descendant-or-self step, rewrite to iterative path check("<a/>//(a | b)", "", root(IterPath.class), empty(Union.class)); check("<a/>/(a, b)", "", root(IterPath.class), empty(List.class)); // rewrite to single union node test, rewrite to iterative path check("<a/>/(a | b)[text()]", "", root(IterPath.class), empty(Union.class)); check("<a/>/(a, b)[text()]", "", root(IterPath.class), empty(List.class)); check("<_><a>x</a><b/></_>/(a, b)[text()]", "<a>x</a>", root(IterPath.class), empty(List.class)); // rewrite to union expression check("<a/>/(*, @*)", "", root(MixedPath.class), exists(Union.class)); } /** GH1761: merge adjacent steps in path expressions. */ @Test public void gh1761() { // merge self steps check("<a/>/self::*/self::a", "<a/>", count(IterStep.class, 1)); check("<a/>/self::*/self::b", "", count(IterStep.class, 1)); check("<a/>/self::a/self::*", "<a/>", count(IterStep.class, 1)); check("<a/>/self::a/self::node()", "<a/>", count(IterStep.class, 1)); // merge descendant and self steps check("document { <a/> }//self::a", "<a/>", count(IterStep.class, 1)); check("document { <a/> }//*/self::a", "<a/>", count(IterStep.class, 1)); // combined kind tests check("document { <a/>, <b/> }/(a, b)/self::a", "<a/>", count(IterStep.class, 1)); check("document { <a/>, <b/> }/a/(self::a, self::b)", "<a/>", count(IterStep.class, 1)); check("document { <a/>, <b/> }/(a, b)/(self::b, self::a)", "<a/>\n<b/>", count(IterStep.class, 1)); } /** GH1762: merge steps and predicates with self steps. */ @Test public void gh1762() { // merge self steps check("<a/>/self::*[self::a]", "<a/>", count(IterStep.class, 1)); check("<a/>/self::*[self::b]", "", count(IterStep.class, 1)); check("<a/>/self::a[self::*]", "<a/>", count(IterStep.class, 1)); check("<a/>/self::a[self::node()]", "<a/>", count(IterStep.class, 1)); // nested predicates check("<a/>/self::a[self::a[self::a[self::a]]]", "<a/>", count(IterStep.class, 1)); // combined kind test check("document { <a/>, <b/> }/a[self::a | self::b]", "<a/>", count(IterStep.class, 1)); } /** Path tests. */ @Test public void gh1729() { check("let $x := 'g' return <g/> ! self::g[name() = $x]", "<g/>", empty(CachedPath.class)); } /** Path tests. */ @Test public void gh1752() { check("'1' ! json:parse(.)/descendant::*[text()] = 1", true, empty(IterMap.class)); } /** Static typing of computed maps. */ @Test public void gh1766() { check("let $map := map { 'c': 'x' } return count($map?(('a', 'b')))", 0, type(For.class, "xs:string")); } /** Rewrite boolean comparisons. */ @Test public void gh1775() { check("(false(), true()) ! (. = true())", "false\ntrue", root(BlnSeq.class)); check("(false(), true()) ! (. != false())", "false\ntrue", root(BlnSeq.class)); check("(false(), true()) ! (. = false())", "true\nfalse", exists(NOT)); check("(false(), true()) ! (. != true())", "true\nfalse", exists(NOT)); } /** Merge predicates. */ @Test public void gh1777() { check("(5, 6, 7)[. > 5][. < 7]", 6, count(CmpIR.class, 1)); check("('a', 'b')[2][2]", "", empty()); check("('a', 'b')[1][1]", "a", root(Str.class)); check("for $n in <x a='1'/>/@* where $n >= 1 where $n <= 2 return $n", "a=\"1\"", root(IterPath.class), count(CmpR.class, 1)); check("for $n in <x a='1'/>/@* where data($n) >= 1 where data($n) <= 2 return $n", "a=\"1\"", root(IterPath.class), count(CmpR.class, 1)); check("for $n in <x a='1'/>/@* where $n/data() >= 1 where $n/data() <= 2 return $n", "a=\"1\"", root(IterPath.class), count(CmpR.class, 1)); } /** Merge conjunctions. */ @Test public void gh1776() { check("for $n in (1, 2, 3) where $n != 2 and $n != 3 return $n", 1, exists(NOT), exists(IntSeq.class)); check("<_>A</_>[. = <a>A</a> and . = 'A']", "<_>A</_>", exists(NOT), exists(List.class)); check("(<a/>, <b/>, <c/>)[name() = 'a' and name() = 'b']", "", exists(NOT), exists(StrSeq.class)); } /** Merge of consecutive operations. */ @Test public void gh1778() { check("(1 to 3)[. = 1 or . != 2 or . = 3 or . != 4]", "1\n2\n3", count(IntSeq.class, 2)); check("for $n in (<a/>, <b/>, <c/>) " + "where name($n) != 'a' where $n = '' where name($n) != 'b' " + "return $n", "<c/>", exists(NOT), exists(StrSeq.class)); check("for $n in (<a/>, <b/>, <c/>) " + "where name($n) != 'a' and $n = '' and name($n) != 'b' " + "return $n", "<c/>", exists(NOT), exists(StrSeq.class)); } /** EBV checks. */ @Test public void gh1769ebv() { check("if((<a/>, <b/>)) then 1 else 2", 1, root(Int.class)); check("if(data(<a/>)) then 1 else 2", 2, exists(DATA)); } /** Remove redundant atomizations. */ @Test public void gh1769data() { check("data(<_>1</_>) + 2", 3, empty(DATA)); check("string-join(data(<_>X</_>))", "X", empty(DATA)); check("data(data(<_>X</_>))", "X", count(DATA, 1)); check("<x>A</x>[data() = 'A']", "<x>A</x>", empty(DATA), count(ContextValue.class, 1)); check("<x>A</x>[data() ! data() ! data() = 'A']", "<x>A</x>", empty(DATA), count(ContextValue.class, 1)); check("<x>A</x>[data() = 'A']", "<x>A</x>", empty(DATA)); check("<A>A</A> ! data() = data(<A>B</A>)", false, empty(DATA)); } /** Remove redundant atomizations. */ @Test public void gh1769string() { check("('a', 'b')[string() = 'a']", "a", empty(STRING)); check("('a', 'b')[string(.) = 'b']", "b", empty(STRING)); check("<x>A</x>[string() = 'A']", "<x>A</x>", empty(STRING)); check("<x>A</x>[string(.) = 'A']", "<x>A</x>", empty(STRING)); check("<A>A</A> ! string() = data(<A>B</A>)", false, empty(STRING)); check("max(<_>1</_> ! string(@a))", "", root(ItemMap.class)); check("max((<_>1</_>, <_>2</_>) ! string(@a))", "", root(MAX)); check("min(<_ _='A'/>/@_ ! string())", "A", root(MIN)); check("string(<_>1</_>[.= 1]) = <_>1</_>", true, exists(STRING)); } /** Remove redundant atomizations. */ @Test public void gh1769number() { check("(0e0, 1e0)[number() = 1]", 1, empty(NUMBER)); check("(0e0, 1e0)[number(.) = 1]", 1, empty(NUMBER)); check("<_>1</_>[number() = 1]", "<_>1</_>", empty(NUMBER)); check("<_>1</_>[number(.) = 1]", "<_>1</_>", empty(NUMBER)); check("number(<_>1</_>) + 2", 3, empty(NUMBER)); check("(1e0, 2e0) ! (number() + 1)", "2\n3", empty(NUMBER)); check("for $v in (1e0, 2e0) return number($v) + 1", "2\n3", empty(NUMBER)); check("for $n in (10000000000000000, 1) return number($n) = 10000000000000001", "true\nfalse", exists(NUMBER)); } /** Inlining of where clauses. */ @Test public void gh1782() { check("1 ! (for $a in (1, 2) where $a = last() return $a)", 1, exists(GFLWOR.class)); check("(3, 4) ! (for $a in (1, 2) where . = $a return $a)", "", exists(GFLWOR.class)); } /** Rewriting of positional tests that might yield an error. */ @Test public void gh1783() { execute(new Close()); error("(position() = 3) = (position() = 3)", NOCTX_X); error(". = .", NOCTX_X); } /** Pre-evaluate predicates in filter expressions. */ @Test public void gh1785() { check("<a/>[self::node()]", "<a/>", root(CElem.class)); check("<a/>[self::*]", "<a/>", root(CElem.class)); check("<a/>[self::*[name(..) = 'a']]", "", root(IterFilter.class)); check("<a/>[self::text()]", "", empty()); } /** Better typing of functions with context arguments. */ @Test public void gh1787() { check("path(<a/>) instance of xs:string", true, root(Bln.class)); check("<a/>[path() instance of xs:string]", "<a/>", root(CElem.class)); check("<a/>[name() = 'a']", "<a/>", exists(CmpSimpleG.class)); check("node-name(prof:void(()))", "", root(_PROF_VOID)); check("prefix-from-QName(prof:void(()))", "", root(_PROF_VOID)); } /** Rewrite name tests to self steps. */ @Test public void gh1770() { check("<a/>[node-name() eq xs:QName('a')]", "<a/>", exists(SingleIterPath.class)); check("<a/>[local-name() eq 'a']", "<a/>", exists(SingleIterPath.class)); check("<a/>[local-name() = ('a', 'b', '')]", "<a/>", exists(SingleIterPath.class)); check("<a/>[local-name() = 'a' or local-name() = 'b']", "<a/>", exists(SingleIterPath.class)); check("<a/>[node-name() = (xs:QName('a'), xs:QName('b'))]", "<a/>", exists(SingleIterPath.class)); check("<a/>[local-name() = ('', '', '')]", "", empty()); check("(<a/>, <b/>)[. = '!'][local-name() = 'a']", "", empty(LOCAL_NAME)); check("comment {}[local-name() = '']", "<!---->", root(CComm.class)); check("text { 'a' }[local-name() = '']", "a", root(CTxt.class)); final String prolog = "declare default element namespace 'A'; "; check(prolog + "<a/>[node-name() eq QName('A', 'a')]", "<a xmlns=\"A\"/>", exists(SingleIterPath.class)); check(prolog + "<a/>[namespace-uri() eq 'A']", "<a xmlns=\"A\"/>", exists(SingleIterPath.class)); // no rewritings check("<a/>[local-name() != 'a']", "", exists(LOCAL_NAME)); check("<a/>[local-name() = <_>a</_>]", "<a/>", exists(LOCAL_NAME)); check("<a/>[node-name() = xs:QName(<_>a</_>)]", "<a/>", exists(NODE_NAME)); check("parse-xml('<a/>')[name(*) = 'a']", "<a/>", exists(Function.NAME)); } /** Functions with database access. */ @Test public void gh1788() { execute(new CreateDB(NAME, "<x>A</x>")); check("db:text('" + NAME + "', 'A')/parent::x", "<x>A</x>", exists(_DB_TEXT)); check("db:text('" + NAME + "', 'A')/parent::unknown", "", empty()); } /** Inline context in filter expressions. */ @Test public void gh1792() { check("1[. = 0]", "", empty()); check("1[. * .]", 1, root(Int.class)); check("2[. * . = 4]", 2, root(Int.class)); check("2[number()]", "", empty()); check("1[count(.)]", 1, root(Int.class)); check("1[count(.)]", 1, root(Int.class)); check("1[.[.[.[.[.[.[.[.[. = 1]]]]]]]]]", 1, root(Int.class)); check("1[1[1[1[1[1[1[1[1[1 = .]]]]]]]]]", 1, root(Int.class)); check("''[string()]", "", empty()); check("'a'[string()]", "a", root(Str.class)); check("'a'[string(.)]", "a", root(Str.class)); check("'a'[string-length() = 1]", "a", root(Str.class)); check("'a'[string-length(.) = 1]", "a", root(Str.class)); check("' '[normalize-space()]", "", empty()); check("''[data()]", "", empty()); check("<_/>[data()]", "", root(IterFilter.class)); check("(1, 2)[. = 3]", "", root(IterFilter.class)); } /** Type checks. */ @Test public void gh1791() { check("function() as xs:double { <x>1</x> }() + 2", 3, empty(TypeCheck.class)); check("declare function local:_() as xs:string { <x>A</x> }; local:_() = 'A'", true, empty(TypeCheck.class)); check("declare function local:f($s as xs:string) { tokenize($s) };\n" + "<x/> ! local:f(.)", "", empty(TypeCheck.class)); } /** Unary expression. */ @Test public void gh1796() { check("-xs:byte(-128) instance of xs:byte", false, empty(Unary.class), empty(Cast.class)); check("for $i in -128 return --xs:byte($i) instance of xs:byte", false, empty(Unary.class), empty(Cast.class)); check("let $i := -128 return --xs:byte($i) instance of xs:byte", false, empty(Unary.class), empty(Cast.class)); check("--xs:byte(<_>-128</_>)", -128, empty(Unary.class), count(Cast.class, 2)); } /** Promote to expression. */ @Test public void gh1798() { check("<a>1</a> promote to xs:string", 1, root(TypeCheck.class)); check("(1,2) promote to xs:double+", "1\n2", empty(TypeCheck.class), root(ItemSeq.class), count(Dbl.class, 2)); error("<a/> promote to empty-sequence()", INVPROMOTE_X_X_X); error("(1,2) promote to xs:byte+", INVPROMOTE_X_X_X); } /** Treats and promotions, error messages. */ @Test public void gh1799() { error("'a' promote to node()", INVPROMOTE_X_X_X); error("'a' treat as node()", NOTREAT_X_X_X); } /** Merge of operations with fn:not. */ @Test public void gh1805() { check("<_/>[not(. = ('A', 'B'))][not(. = ('C', 'D'))]", "<_/>", count(CmpHashG.class, 1)); check("<_/>[. != 'A'][. != 'B'][. != 'C'][. != 'D']", "<_/>", count(CmpHashG.class, 1)); check("(3, 4)[not(. = 1) and not(. = (2, 3))]", 4, count(NOT, 1), count(CmpHashG.class, 1)); check("(3, 4)[not(. = (2, 3)) and . != 1]", 4, count(NOT, 1), count(CmpHashG.class, 1)); check("(3, 4)[not(. = (2, 3)) and not(. = (1,4))]", "", count(NOT, 1), count(CmpHashG.class, 1)); } /** Comparisons with empty strings. */ @Test public void gh1803() { check("<a/>[namespace-uri() eq '']", "<a/>", exists(NOT), empty(STRING)); check("<a/>[local-name() eq '']", "", exists(NOT), empty(STRING)); check("attribute { 'a' } { '' }[local-name() = '']", "", exists(NOT), empty(STRING)); check("let $x := (<a/>, <a/>) where $x[. eq ''] return $x", "<a/>\n<a/>", exists(NOT), exists(DATA)); check("string(<_/>) != ''", false, root(BOOLEAN)); check("string(<_/>) = ''", true, root(NOT), exists(DATA)); check("string(<_/>) <= ''", true, root(NOT), exists(DATA)); check("string(<_/>) >= ''", true, root(Bln.class)); check("string(<_/>) < ''", false, root(Bln.class)); check("('', 'a')[string() != '']", "a", root(IterFilter.class), empty(CmpG.class)); check("('', 'a')[string() = '']", "", root(IterFilter.class), exists(NOT)); } /** Comparisons with simple map operands. */ @Test public void gh1804() { // rewritings in comparisons check("<_>A</_> ! text() = 'A'", true, exists(IterPath.class), empty(IterMap.class)); check("<_>A</_> ! text() = 'A'", true, exists(IterPath.class), empty(IterMap.class)); check("let $a := <_>A</_> return $a ! text() = $a ! text()", true, count(IterPath.class, 2), empty(IterMap.class)); // EBV rewritings check("<a><b/></a>[b ! ..]", "<a>\n<b/>\n</a>", exists(CachedPath.class), empty(IterMap.class)); // do not rewrite absolute paths check("<a>a</a>/string() ! <x>{ . }</x>/text() = 'a'", true, exists(IterMap.class)); } /** Rewrite if to where. */ public void gh1806() { check("let $a := <_/> return if ($a = '') then $a else ()", "<_/>", empty(If.class), exists(Where.class)); check("for $a in (1, 2) return if ($a = 3) then $a else ()", "", empty(If.class), exists(Where.class), root(IterFilter.class)); check("for $t in ('a', 'b') return if($t) then $t else ()", "a\nb", root(IterFilter.class), exists(ContextValue.class)); check("for $t in ('a', 'b') return $t[$t]", "a\nb", root(IterFilter.class), exists(ContextValue.class)); } /** If expression with empty branches. */ @Test public void gh1809() { check("if(<_>1</_>[. = 1]) then () else ()", "", empty()); check("if(prof:void(1)) then () else ()", "", root(_PROF_VOID), count(_PROF_VOID, 1)); } /** EBV simplifications: if, switch, typeswitch. */ @Test public void gh1813() { // if expression check("(1, 2) ! boolean(if(.) then 'a' else <a/>)", "true\ntrue", root(SingletonSeq.class)); check("(1 to 2) ! boolean(if(.) then '' else ())", "false\nfalse", root(SingletonSeq.class)); check("boolean(if(random:double()) then '' else 0)", "false", root(List.class), exists(_PROF_VOID)); check("(1, 2)[if(.) then 0.0e0 else 0.0]", "", empty()); check("(1, 2)[if(.) then '' else xs:anyURI('')]", "", empty()); // no rewriting of numbers > 0 check("(1,2) ! boolean(if(.) then 'a' else 1)", "true\ntrue", exists(If.class)); // switch expression check("for $i in (1 to 3)\n" + "return if(switch($i)\n" + " case 1 return 0\n" + " case 2 return ''\n" + " default return ()\n" + ") then 'fail' else ''", "\n\n", root(SingletonSeq.class)); // typeswitch expression check("for $i in ('a', 1)\n" + "return if(typeswitch($i)\n" + " case xs:integer return 0\n" + " case xs:string return ''\n" + " default return ()\n" + ") then 'fail' else ''", "\n", root(SingletonSeq.class)); } /** Simple map, index rewritings. */ @Test public void gh1814() { execute(new CreateDB(NAME, "<x><y><z>A</z></y></x>")); check("exists(x[y/z = 'A'])", true, exists(ValueAccess.class)); check("exists(x[y ! z = 'A'])", true, exists(ValueAccess.class)); } /** Typing: data references. */ @Test public void gh1816() { execute(new CreateDB(NAME, "<x><y/></x>")); check("x/z", "", empty()); check("(x, y)/z", "", empty()); check("(x | y)/z", "", empty()); check("(if(random:double()) then x else y)/z", "", empty()); check("(let $_ := random:double() return x)/z", "", empty()); check("((# bla #) { x })/z", "", empty()); check("(switch (random:double())\n" + " case 1 return ()\n" + " default return x\n" + ")/z", "", empty()); check("(x, prof:void(()))/z", "", empty()); check("(x | prof:void(()))/z", "", empty()); check("(if(random:double()) then x)/z", "", empty()); } /** List to union in root of path expression. */ @Test public void gh1817() { check("<a/>[(b, c)/d]", "", empty(List.class), count(IterPath.class, 1)); // do not rewrite paths that yield no nodes check("(<a/>, <b/>)/name()", "a\nb", exists(List.class)); check("let $_ := <_/> return ($_, $_)/0", "0\n0", exists(SingletonSeq.class)); } /** List to union. */ @Test public void gh1818() { check("<a/>[b, text()]", "", exists(Union.class), count(SingleIterPath.class, 2)); // union expression will be further rewritten to single path check("<a/>[b, c]", "", empty(List.class), count(SingleIterPath.class, 1)); check("<a/>[(b, c) = '']", "", empty(List.class), count(SingleIterPath.class, 1)); check("<a/>[(b, c) = (b, c)]", "", empty(List.class), count(SingleIterPath.class, 2)); } /** FLWOR, no results, non-deterministic expressions. */ @Test public void gh1819() { check("for $_ in () return <x/>", "", empty()); check("for $_ in prof:void(1) return 1", "", root(_PROF_VOID)); check("let $_ := 1 return <x/>", "<x/>", root(CElem.class)); check("let $_ := prof:void(1) return 1", 1, root(List.class), exists(_PROF_VOID)); check("for $_ in 1 to 2 return 3", "3\n3", root(SingletonSeq.class)); check("for $_ in 1 to 2 return ()", "", empty()); // skip rewriting check("for $_ in 1 to 2 return <a/>", "<a/>\n<a/>", root(GFLWOR.class)); check("for $_ in 1 to 2 return prof:void(1)", "", root(GFLWOR.class)); } /** Merge and/or expressions. */ @Test public void gh1820() { // OR: merge check("(<_/>, <_/>) = 'a' or (<_/>, <_/>) = 'b'", false, empty(Or.class)); check("(<_/>, <_/>) = 'a' or (<_/>, <_/>) = ('b', 'c')", false, empty(Or.class)); check("<_>1</_>[. = 1 or . = (2, 3)]", "<_>1</_>", empty(Or.class), exists(CmpG.class)); check("<_>1</_>[not(. = 1) or . != (2, 3)]", "<_>1</_>", empty(Or.class)); check("exists(let $x := <a><b>c</b><b>d</b></a> return $x[b = 'c' or b = 'd'])", true, count(CmpHashG.class, 1)); // OR: no merge check("<_>1</_>[not(. = 1) or not(. = (2, 3))]", "<_>1</_>", exists(Or.class)); check("<_>1</_>[. = 1 or not(. != (2, 3))]", "<_>1</_>", exists(Or.class)); check("<_>1</_>[not(. = 1) or . = (2, 3)]", "", exists(Or.class)); check("<_>1</_>[. = 1 or not(. = (2, 3))]", "<_>1</_>", exists(Or.class)); check("<_>a</_>[. = 'a' or . != 'b']", "<_>a</_>", exists(Or.class)); check("<_>a</_>[. = 'a' or .. != 'b']", "<_>a</_>", exists(Or.class)); // AND: merge check("(<_/>, <_/>) = 'a' and (<_/>, <_/>) = 'b'", false, empty(And.class)); check("<_>1</_>[not(. = 1) and not(. = (2, 3))]", "", exists(CmpG.class), empty(CmpSimpleG.class)); check("not((<_/>, <_/>) != 'a') and not((<_/>, <_/>) != 'b')", false, exists(CmpG.class), empty(CmpSimpleG.class)); // AND: no merge check("(<_/>, <_/>) = 'a' and (<_/>, <_/>) = ('b', 'c')", false, exists(And.class)); check("exists(let $x := <a><b>c</b><b>d</b></a> return $x[b = 'c' and b = 'd'])", true, count(CmpG.class, 2)); check("<_>1</_>[. = 1 and . = (2, 3)]", "", exists(CmpG.class), exists(CmpSimpleG.class)); check("<_>1</_>[not(. = 1) and . = (2, 3)]", "", exists(CmpG.class), exists(CmpSimpleG.class)); check("<_>1</_>[. = 1 and not(. = (2, 3))]", "<_>1</_>", exists(CmpG.class), exists(CmpSimpleG.class)); check("(<_/>, <_/>) = '' and (<_/>, <_/>) = 'a'", false, exists(And.class)); } /** Map/array lookups: better typing. */ @Test public void gh1825() { check("[ 1 ](<_>1</_>) instance of xs:integer", true, root(Bln.class)); check("map { 'a': 2 }(<_>a</_>) instance of xs:integer?", true, root(Bln.class)); check("map { 1: 2 }(<_/>) instance of xs:integer?", true, root(Bln.class)); check("map { 1: (2, 'a') }(<_/>) instance of xs:anyAtomicType*", true, root(Bln.class)); } /** Rewriting of positional predicate. */ @Test public void gh1827() { check("declare function local:f($pos) { (1,2)[position() < $pos] };\n" + "local:f(1)", "", empty()); } /** Merge fn:empty and fn:exist functions. */ @Test public void gh1829() { check("exists(<a/>/a) or exists(<b/>/b)", false, root(BOOLEAN), empty(Or.class), empty(EXISTS), exists(Union.class)); check("for $i in 1 to 2 return exists($i[. = 1]) or exists($i[. = 2])", "true\ntrue", empty(Or.class), count(EXISTS, 1)); check("<a/>/a or <b/>/b", false, root(BOOLEAN), empty(Or.class), exists(Union.class)); check("<a/>[a or b]", "", empty(Or.class), count(SingleIterPath.class, 1)); check("<a/>[empty(b)][empty(c)]", "<a/>", count(EMPTY, 1), count(SingleIterPath.class, 1)); check("<a/>[empty((b, c))]", "<a/>", count(SingleIterPath.class, 1)); check("for $a in (<b/>, <c/>) return <a/>[empty(($a[. = 'a'], $a[. = 'b']))]", "<a/>\n<a/>", count(IterFilter.class, 2)); // no rewritings query("for $a in 1 to 2 return <a/>[empty(($a[. = 1], $a[. = 1]))]", "<a/>"); check("exists(<a/>/a) and exists(<b/>/b)", false, exists(And.class)); check("for $i in 1 to 2 return exists($i[. = 1]) and exists($i[. = 2])", "false\nfalse", exists(And.class)); check("<a/>/a and <b/>/b", false, exists(And.class)); check("<a/>[a and b]", "", count(SingleIterPath.class, 2)); check("<a/>[empty(b) or empty(c)]", "<a/>", exists(Or.class)); } /** Documents with different default namespaces. */ @Test public void gh1831() { execute(new CreateDB(NAME)); execute(new Add("a.xml", "<x xmlns='x'/>")); execute(new Add("b.xml", "<x/>")); query("x", "<x/>"); } /** Equality tests on QNames. */ @Test public void gh1823() { query("declare namespace p = 'U';\n" + "prefix-from-QName(QName('U', 'a')[. = xs:QName(<_>p:a</_>)]) or\n" + "prefix-from-QName(QName('U', 'p:a')[. = xs:QName(<_>p:a</_>)])", true); query("let $f := function($a) { string($a) }\n" + "return distinct-values(($f(QName('U', 'l')), $f(QName('U', 'p:l'))))", "l\np:l"); } /** Static typing, maps. */ @Test public void gh1834() { query("declare function local:f() as map(xs:string, xs:string) {" + " map:entry(<e/> ! string(), '')" + "}; local:f()?*", ""); query("declare function local:f() as map(xs:string, xs:string) {" + " map:put(map {}, <e/> ! string(), '')" + "}; local:f()?*", ""); } /** Set Expressions: Merge operands. */ @Test public void gh1838() { check("<_><a/></_>/(* union *[b])", "<a/>", empty(Union.class), empty(SingleIterPath.class), count(IterStep.class, 1)); check("<_><a/></_>/(* intersect *[b])", "", empty(Intersect.class), count(SingleIterPath.class, 1), count(IterStep.class, 2)); check("<_><a/></_>/(* except *[b])", "<a/>", empty(Except.class), exists(EMPTY), count(SingleIterPath.class, 1)); check("<_><a/></_>/*/(.[self::a] union .[self::b])", "<a/>", empty(Union.class)); check("<_><a/></_>/*/(.[self::a] intersect .[self::b])", "", empty(Intersect.class)); check("<_><a/></_>/*/(.[self::a] except .[self::b])", "<a/>", empty(Except.class), exists(EMPTY)); check("<_><a/></_>/(.[b][c] union .[d])", "", empty(Union.class), exists(And.class), exists(Or.class)); check("<_><a/></_>/(.[b][c] intersect .[d])", "", empty(Intersect.class), empty(And.class)); check("<_><a/></_>/(.[b][c] except .[d])", "", empty(Except.class), exists(EMPTY), empty(And.class)); // no optimization check("<_><a/></_>/(a union a/*[b])", "<a/>", exists(Union.class)); check("<_><a/></_>/(a union a/<b/>)", "<a/>\n<b/>", exists(Union.class)); check("<_><a/></_>/(a union self::a)", "<a/>", exists(Union.class)); check("<_><a/></_>/(a[1] union a[2])", "<a/>", exists(Union.class)); check("<_/>/(<b/>[*] union <c/>[*])", "", exists(Union.class)); } /** XQuery: distinct integer sequences. */ @Test public void gh1841() { check("<_/>[position() = (1, 1)]", "<_/>", root(CElem.class)); check("<_/>[position() = (1, 2, 1)]", "<_/>", count(Int.class, 2)); } }
[MIN] Cleanups
basex-core/src/test/java/org/basex/query/ast/RewritingsTest.java
[MIN] Cleanups
Java
mit
0dc97d295519a24a48b23b8261fa4bd38fc4fe03
0
pslgoh/rhodes,tauplatform/tau,pslgoh/rhodes,rhomobile/rhodes,pslgoh/rhodes,watusi/rhodes,rhomobile/rhodes,rhomobile/rhodes,watusi/rhodes,tauplatform/tau,watusi/rhodes,rhomobile/rhodes,pslgoh/rhodes,watusi/rhodes,rhomobile/rhodes,watusi/rhodes,rhomobile/rhodes,tauplatform/tau,watusi/rhodes,tauplatform/tau,rhomobile/rhodes,rhomobile/rhodes,pslgoh/rhodes,watusi/rhodes,pslgoh/rhodes,tauplatform/tau,pslgoh/rhodes,rhomobile/rhodes,tauplatform/tau,watusi/rhodes,tauplatform/tau,watusi/rhodes,watusi/rhodes,tauplatform/tau,pslgoh/rhodes,rhomobile/rhodes,pslgoh/rhodes,tauplatform/tau,tauplatform/tau,pslgoh/rhodes
package rhomobile.mapview; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import com.rho.RhoClassFactory; import com.rho.RhoConf; import com.rho.RhoEmptyLogger; import com.rho.RhoLogger; import com.rho.net.IHttpConnection; import net.rim.device.api.math.Fixed32; import net.rim.device.api.system.Bitmap; import net.rim.device.api.system.EncodedImage; import net.rim.device.api.ui.Field; import net.rim.device.api.ui.Graphics; import net.rim.device.api.util.Comparator; import net.rim.device.api.util.SimpleSortingVector; public class ESRIMapField extends Field implements RhoMapField { private static final RhoLogger LOG = RhoLogger.RHO_STRIP_LOG ? new RhoEmptyLogger() : new RhoLogger("ESRIMapField"); private static final int TILE_SIZE = 256; private static final int MIN_ZOOM = 0; private static final int MAX_ZOOM = 19; private static final int CACHE_UPDATE_INTERVAL = 500; // Maximum size of image cache (number of images stored locally) private static final int MAX_IMAGE_CACHE_SIZE = 32; // Mode of decoding EncodedImage to bitmap private static final int DECODE_MODE = EncodedImage.DECODE_NATIVE | EncodedImage.DECODE_NO_DITHER | EncodedImage.DECODE_READONLY | EncodedImage.DECODE_ALPHA; // Constants required to coordinates calculations private static final long MIN_LATITUDE = degreesToPixelsY(90, MAX_ZOOM); private static final long MAX_LATITUDE = degreesToPixelsY(-90, MAX_ZOOM); private static final long MAX_LONGITUDE = degreesToPixelsX(180, MAX_ZOOM); // DON'T CHANGE THIS CONSTANT!!! // This is maximum absolute value of sine ( == sin(85*PI/180) ) allowed by Merkator projection private static final double MAX_SIN = 0.99627207622; private static final double PI = Math.PI; private Hashtable mMapUrls = new Hashtable(); private String mMapType; //=============================================================================== // Coordinates of center in pixels of maximum zoom level private long mLatitude = degreesToPixelsY(0, MAX_ZOOM); private long mLongitude = degreesToPixelsX(0, MAX_ZOOM); private int mZoom = 0; private int mWidth; private int mHeight; private static class ByCoordinatesComparator implements Comparator { public int compare (Object o1, Object o2) { CachedImage img1 = (CachedImage)o1; CachedImage img2 = (CachedImage)o2; if (img1.latitude < img2.latitude) return -1; if (img1.latitude > img2.latitude) return 1; if (img1.longitude < img2.longitude) return 1; if (img1.longitude > img2.longitude) return -1; if (img1.zoom < img2.zoom) return -1; if (img1.zoom > img2.zoom) return 1; return 0; } } private static class ByAccessTimeComparator implements Comparator { public int compare (Object o1, Object o2) { long l1 = ((CachedImage)o1).lastUsed; long l2 = ((CachedImage)o2).lastUsed; return l1 < l2 ? 1 : l1 > l2 ? -1 : 0; } }; private class CachedImage { public EncodedImage image; public Bitmap bitmap; public long latitude; public long longitude; public int zoom; public String key; public long lastUsed; public CachedImage(EncodedImage img, long lat, long lon, int z) { image = img; bitmap = null; latitude = lat; longitude = lon; zoom = z; key = makeCacheKey(latitude, longitude, zoom); lastUsed = System.currentTimeMillis(); } }; private class ImageCache { private Hashtable hash; private SimpleSortingVector cvec; private SimpleSortingVector tvec; public ImageCache() { reinit(); } private void reinit() { hash = new Hashtable(); cvec = new SimpleSortingVector(); cvec.setSortComparator(new ByCoordinatesComparator()); cvec.setSort(true); tvec = new SimpleSortingVector(); tvec.setSortComparator(new ByAccessTimeComparator()); tvec.setSort(true); } public ImageCache clone() { ImageCache cloned = new ImageCache(); for (Enumeration e = hash.elements(); e.hasMoreElements();) cloned.put((CachedImage)e.nextElement()); return cloned; } public Enumeration sortedByCoordinates() { return cvec.elements(); } public CachedImage get(String key) { return (CachedImage)hash.get(key); } public void put(CachedImage img) { put(img, true); } private void put(CachedImage img, boolean doCheck) { hash.put(img.key, img); cvec.addElement(img); tvec.addElement(img); if (doCheck) check(); } private void check() { if (hash.size() < MAX_IMAGE_CACHE_SIZE) return; SimpleSortingVector vec = tvec; reinit(); Enumeration e = vec.elements(); while (e.hasMoreElements()) { CachedImage img = (CachedImage)e.nextElement(); put(img, false); } } }; private ImageCache mImgCache = new ImageCache(); private static abstract class MapCommand { public abstract String type(); public abstract String description(); } private static class MapFetchCommand extends MapCommand { public String baseUrl; public int zoom; public long latitude; public long longitude; public MapFetchCommand(String baseUrl, int zoom, long latitude, long longitude) { this.baseUrl = baseUrl; this.zoom = zoom; this.latitude = latitude; this.longitude = longitude; } private String makeDescription() { return "" + zoom + "/" + latitude + "/" + longitude; } public String type() { return "fetch"; } public String description() { return "fetch:" + makeDescription(); } }; private class MapThread extends Thread { private static final int BLOCK_SIZE = 1024; private Vector commands = new Vector(); private boolean active = true; public void process(MapCommand cmd) { synchronized (commands) { commands.addElement(cmd); commands.notify(); } } public void stop() { active = false; interrupt(); } public void run() { try { while (active) { MapCommand cmd = null; synchronized (commands) { if (commands.isEmpty()) { try { commands.wait(); } catch (InterruptedException e) { // Nothing } continue; } int last = commands.size() - 1; cmd = (MapCommand)commands.elementAt(last); commands.removeElementAt(last); if (cmd == null) continue; } try { if (cmd instanceof MapFetchCommand) processCommand((MapFetchCommand)cmd); else LOG.INFO("Received unknown command: " + cmd.type() + ", ignore it"); } catch (Exception e) { LOG.ERROR("Processing of map command failed", e); } } } catch (Exception e) { LOG.ERROR("Fatal error in map thread", e); } finally { LOG.INFO("Map thread exit"); } } private byte[] fetchData(String url) throws IOException { IHttpConnection conn = RhoClassFactory.getNetworkAccess().connect(url,false); conn.setRequestMethod("GET"); //conn.setRequestProperty("User-Agent", "Blackberry"); //conn.setRequestProperty("Accept", "*/*"); InputStream is = conn.openInputStream(); int code = conn.getResponseCode(); if (code/100 != 2) throw new IOException("ESRI map server respond with " + code + " " + conn.getResponseMessage()); int size = conn.getHeaderFieldInt("Content-Length", 0); byte[] data = new byte[size]; if (size == 0) size = 1073741824; // 1Gb :) byte[] buf = new byte[BLOCK_SIZE]; for (int offset = 0; offset < size;) { int n = is.read(buf, 0, BLOCK_SIZE); if (n <= 0) break; if (offset + n > data.length) { byte[] newData = new byte[offset + n]; System.arraycopy(data, 0, newData, 0, data.length); data = newData; } System.arraycopy(buf, 0, data, offset, n); offset += n; } return data; } private void processCommand(MapFetchCommand cmd) throws IOException { LOG.TRACE("Processing map fetch command (thread #" + hashCode() + "): " + cmd.description()); long ts = toMaxZoom(TILE_SIZE, cmd.zoom); int row = (int)(cmd.latitude/ts); int column = (int)(cmd.longitude/ts); StringBuffer url = new StringBuffer(); url.append(cmd.baseUrl); url.append("/MapServer/tile/"); url.append(cmd.zoom); url.append('/'); url.append(row); url.append('/'); url.append(column); String finalUrl = url.toString(); byte[] data = fetchData(finalUrl); EncodedImage img = EncodedImage.createEncodedImage(data, 0, data.length); img.setDecodeMode(DECODE_MODE); long lat = row*ts + ts/2; long lon = column*ts + ts/2; LOG.TRACE("Map request done, draw just received image: zoom=" + cmd.zoom + ", lat=" + lat + ", lon=" + lon); CachedImage cachedImage = new CachedImage(img, lat, lon, cmd.zoom); // Put image to the cache and trigger redraw synchronized (ESRIMapField.this) { mImgCache.put(cachedImage); } redraw(); } }; private MapThread mMapThread = new MapThread(); private class CacheUpdate extends Thread { private boolean active = true; public void stop() throws InterruptedException { active = false; join(); } public void run() { LOG.TRACE("Cache update thread started"); while (active) { try { Thread.sleep(CACHE_UPDATE_INTERVAL); } catch (InterruptedException e) { // Ignore } //LOG.TRACE("Cache update: next loop; mLatitude=" + mLatitude + // ", mLongitude=" + mLongitude + ", mZoom=" + mZoom); long ts = toMaxZoom(TILE_SIZE, mZoom); //LOG.TRACE("Tile size on the maximum zoom level: " + ts); long h = toMaxZoom(mHeight, mZoom); //LOG.TRACE("Height of the screen on the maximum zoom level: " + h); long w = toMaxZoom(mWidth, mZoom); //LOG.TRACE("Width of the screen on the maximum zoom level: " + w); long totalTiles = MapTools.math_pow2(mZoom); //LOG.TRACE("Total tiles count on zoom level " + mZoom + ": " + totalTiles); long tlLat = mLatitude - h/2; if (tlLat < 0) tlLat = 0; long tlLon = mLongitude - w/2; if (tlLon < 0) tlLon = 0; //LOG.TRACE("tlLat=" + tlLat + ", tlLon=" + tlLon); for (long lat = (tlLat/ts)*ts, latLim = Math.min(tlLat + h + ts, ts*totalTiles); lat < latLim; lat += ts) { for (long lon = (tlLon/ts)*ts, lonLim = Math.min(tlLon + w + ts, ts*totalTiles); lon < lonLim; lon += ts) { String key = makeCacheKey(lat, lon, mZoom); MapFetchCommand cmd = null; synchronized (ESRIMapField.this) { CachedImage img = mImgCache.get(key); if (img == null) { //LOG.TRACE("lat=" + lat + ", lon=" + lon + "; key=" + key); String baseUrl = (String)mMapUrls.get(mMapType); cmd = new MapFetchCommand(baseUrl, mZoom, lat, lon); CachedImage dummy = new CachedImage(null, lat, lon, mZoom); mImgCache.put(dummy); } } if (cmd != null) mMapThread.process(cmd); } } } LOG.TRACE("Cache update thread stopped"); } }; private CacheUpdate mCacheUpdate = new CacheUpdate(); public ESRIMapField() { String url = RhoConf.getInstance().getString("esri_map_url_roadmap"); if (url == null || url.length() == 0) url = "http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/"; mMapUrls.put("roadmap", url); url = RhoConf.getInstance().getString("esri_map_url_satellite"); if (url == null || url.length() == 0) url = "http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/"; mMapUrls.put("satellite", url); mMapType = "roadmap"; LOG.TRACE("ESRIMapField ctor: mLatitude=" + mLatitude + ", mLongitude=" + mLongitude); mMapThread.start(); mCacheUpdate.start(); } public void close() { mMapThread.stop(); try { mCacheUpdate.stop(); } catch (InterruptedException e) { LOG.ERROR("Stopping of cache update thread was interrupted", e); } } public void redraw() { invalidate(); } protected void paint(Graphics graphics) { // Draw background for (int i = 1, lim = 2*Math.max(mWidth, mHeight); i < lim; i += 5) { graphics.drawLine(0, i, i, 0); } ImageCache imgCache; synchronized (this) { imgCache = mImgCache.clone(); } // Draw map tiles Enumeration e = imgCache.sortedByCoordinates(); while (e.hasMoreElements()) { // Draw map CachedImage img = (CachedImage)e.nextElement(); if (img.image == null) continue; paintImage(graphics, img); } } private void paintImage(Graphics graphics, CachedImage img) { // Skip images with zoom level which differ from the current zoom level if (img.zoom != mZoom) return; long left = -toCurrentZoom(mLongitude - img.longitude, mZoom); long top = -toCurrentZoom(mLatitude - img.latitude, mZoom); if (img.zoom != mZoom) { double x = MapTools.math_pow2d(img.zoom - mZoom); int factor = Fixed32.tenThouToFP((int)(x*10000)); img.image = img.image.scaleImage32(factor, factor); img.bitmap = null; } int imgWidth = img.image.getScaledWidth(); int imgHeight = img.image.getScaledHeight(); left += (mWidth - imgWidth)/2; top += (mHeight - imgHeight)/2; int w = mWidth - (int)left; int h = mHeight - (int)top; int maxW = mWidth + TILE_SIZE; int maxH = mHeight + TILE_SIZE; if (w < 0 || h < 0 || w > maxW || h > maxH) { // Image will not be displayed, free its bitmap and skip it img.bitmap = null; return; } if (img.bitmap == null) img.bitmap = img.image.getBitmap(); graphics.drawBitmap((int)left, (int)top, w, h, img.bitmap, 0, 0); } protected void layout(int w, int h) { mWidth = Math.min(mWidth, w); mHeight = Math.min(mHeight, h); setExtent(mWidth, mHeight); } public int calculateZoom(double latDelta, double lonDelta) { int zoom1 = calcZoom(latDelta, mWidth); int zoom2 = calcZoom(lonDelta, mHeight); return zoom1 < zoom2 ? zoom1 : zoom2; } public Field getBBField() { return this; } public double getCenterLatitude() { return pixelsToDegreesY(mLatitude, MAX_ZOOM); } public double getCenterLongitude() { return pixelsToDegreesX(mLongitude, MAX_ZOOM); } private void validateCoordinates() { if (mLatitude < MIN_LATITUDE) mLatitude = MIN_LATITUDE; if (mLatitude > MAX_LATITUDE) mLatitude = MAX_LATITUDE; } public void moveTo(double lat, double lon) { mLatitude = degreesToPixelsY(lat, MAX_ZOOM); mLongitude = degreesToPixelsX(lon, MAX_ZOOM); validateCoordinates(); //LOG.TRACE("moveTo(" + lat + ", " + lon + "): mLatitude=" + mLatitude + ", mLongitude=" + mLongitude); } public void move(int dx, int dy) { mLatitude += toMaxZoom(dy, mZoom); mLongitude += toMaxZoom(dx, mZoom); validateCoordinates(); //LOG.TRACE("move(" + dx + ", " + dy + "): mLatitude=" + mLatitude + ", mLongitude=" + mLongitude); } public void setMapType(String type) { mMapType = type; //LOG.TRACE("setMapType: " + mMapType); } public void setPreferredSize(int width, int height) { mWidth = width; mHeight = height; } public int getPreferredWidth() { return mWidth; } public int getPreferredHeight() { return mHeight; } public void setZoom(int zoom) { mZoom = zoom; if (mZoom < MIN_ZOOM) mZoom = MIN_ZOOM; if (mZoom > MAX_ZOOM) mZoom = MAX_ZOOM; LOG.TRACE("setZoom: " + mZoom); } public int getMaxZoom() { return MAX_ZOOM; } public int getMinZoom() { return MIN_ZOOM; } public int getZoom() { return mZoom; } private static int calcZoom(double degrees, int pixels) { double angleRatio = degrees*TILE_SIZE/pixels; double twoInZoomExp = 360/angleRatio; int zoom = (int)MapTools.math_log2(twoInZoomExp); return zoom; } private static long toMaxZoom(long n, int zoom) { if (n == 0) return 0; long pow = MapTools.math_pow2(MAX_ZOOM - zoom); return n*pow; } private static long toCurrentZoom(long coord, int zoom) { if (coord == 0) return 0; long pow = MapTools.math_pow2(MAX_ZOOM - zoom); return coord/pow; } private static long degreesToPixelsX(double n, int z) { while (n < -180.0) n += 360.0; while (n > 180.0) n -= 360.0; double angleRatio = 360d/MapTools.math_pow2(z); double val = (n + 180)*TILE_SIZE/angleRatio; return (long)val; } private static long degreesToPixelsY(double n, int z) { // Merkator projection double sin_phi = MapTools.math_sin(n*PI/180); // MAX_SIN - maximum value of sine allowed by Merkator projection // (~85.0 degrees of north latitude) if (sin_phi < -MAX_SIN) sin_phi = -MAX_SIN; if (sin_phi > MAX_SIN) sin_phi = MAX_SIN; double ath = MapTools.math_atanh(sin_phi); double val = TILE_SIZE * MapTools.math_pow2(z) * (1 - ath/PI)/2; return (long)val; } private static double pixelsToDegreesX(long n, int z) { while (n < 0) n += MAX_LONGITUDE; while (n > MAX_LONGITUDE) n -= MAX_LONGITUDE; double angleRatio = 360d/MapTools.math_pow2(z); double val = n*angleRatio/TILE_SIZE - 180.0; return val; } private static double pixelsToDegreesY(long n, int z) { // Revert calculation of Merkator projection double ath = PI - 2*PI*n/(TILE_SIZE*MapTools.math_pow2(z)); double th = MapTools.math_tanh(ath); double val = 180*MapTools.math_asin(th)/PI; return val; } private String makeCacheKey(long lat, long lon, int z) { while (lon < 0) lon += MAX_LONGITUDE; while (lon > MAX_LONGITUDE) lon -= MAX_LONGITUDE; long ts = toMaxZoom(TILE_SIZE, z); long x = lon/ts; long y = lat/ts; StringBuffer buf = new StringBuffer(); buf.append(z); buf.append(';'); buf.append(x); buf.append(';'); buf.append(y); String key = buf.toString(); return key; } public long toScreenCoordinateX(double n) { long v = degreesToPixelsX(n, mZoom); long center = toCurrentZoom(mLongitude, mZoom); long begin = center - mWidth/2; return v - begin; } public long toScreenCoordinateY(double n) { long v = degreesToPixelsY(n, mZoom); long center = toCurrentZoom(mLatitude, mZoom); long begin = center - mHeight/2; return v - begin; } }
platform/bb/rhodes/src/rhomobile/mapview/ESRIMapField.java
package rhomobile.mapview; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import com.rho.RhoClassFactory; import com.rho.RhoConf; import com.rho.RhoEmptyLogger; import com.rho.RhoLogger; import com.rho.net.IHttpConnection; import net.rim.device.api.math.Fixed32; import net.rim.device.api.system.Bitmap; import net.rim.device.api.system.EncodedImage; import net.rim.device.api.ui.Field; import net.rim.device.api.ui.Graphics; import net.rim.device.api.util.Comparator; import net.rim.device.api.util.SimpleSortingVector; public class ESRIMapField extends Field implements RhoMapField { private static final RhoLogger LOG = RhoLogger.RHO_STRIP_LOG ? new RhoEmptyLogger() : new RhoLogger("ESRIMapField"); private static final int TILE_SIZE = 256; private static final int MIN_ZOOM = 0; private static final int MAX_ZOOM = 19; private static final int CACHE_UPDATE_INTERVAL = 500; // Maximum size of image cache (number of images stored locally) private static final int MAX_IMAGE_CACHE_SIZE = 32; // Mode of decoding EncodedImage to bitmap private static final int DECODE_MODE = EncodedImage.DECODE_NATIVE | EncodedImage.DECODE_NO_DITHER | EncodedImage.DECODE_READONLY | EncodedImage.DECODE_ALPHA; // Constants required to coordinates calculations private static final long MIN_LATITUDE = degreesToPixelsY(90, MAX_ZOOM); private static final long MAX_LATITUDE = degreesToPixelsY(-90, MAX_ZOOM); private static final long MAX_LONGITUDE = degreesToPixelsX(180, MAX_ZOOM); // DON'T CHANGE THIS CONSTANT!!! // This is maximum absolute value of sine ( == sin(85*PI/180) ) allowed by Merkator projection private static final double MAX_SIN = 0.99627207622; private static final double PI = Math.PI; private Hashtable mMapUrls = new Hashtable(); private String mMapType; //=============================================================================== // Coordinates of center in pixels of maximum zoom level private long mLatitude = degreesToPixelsY(0, MAX_ZOOM); private long mLongitude = degreesToPixelsX(0, MAX_ZOOM); private int mZoom = 0; private int mWidth; private int mHeight; private static class ByCoordinatesComparator implements Comparator { public int compare (Object o1, Object o2) { CachedImage img1 = (CachedImage)o1; CachedImage img2 = (CachedImage)o2; if (img1.latitude < img2.latitude) return -1; if (img1.latitude > img2.latitude) return 1; if (img1.longitude < img2.longitude) return 1; if (img1.longitude > img2.longitude) return -1; if (img1.zoom < img2.zoom) return -1; if (img1.zoom > img2.zoom) return 1; return 0; } } private static class ByAccessTimeComparator implements Comparator { public int compare (Object o1, Object o2) { long l1 = ((CachedImage)o1).lastUsed; long l2 = ((CachedImage)o2).lastUsed; return l1 < l2 ? 1 : l1 > l2 ? -1 : 0; } }; private class CachedImage { public EncodedImage image; public Bitmap bitmap; public long latitude; public long longitude; public int zoom; public String key; public long lastUsed; public CachedImage(EncodedImage img, long lat, long lon, int z) { image = img; bitmap = null; latitude = lat; longitude = lon; zoom = z; key = makeCacheKey(latitude, longitude, zoom); lastUsed = System.currentTimeMillis(); } }; private class ImageCache { private Hashtable hash; private SimpleSortingVector cvec; private SimpleSortingVector tvec; public ImageCache() { reinit(); } private void reinit() { hash = new Hashtable(); cvec = new SimpleSortingVector(); cvec.setSortComparator(new ByCoordinatesComparator()); cvec.setSort(true); tvec = new SimpleSortingVector(); tvec.setSortComparator(new ByAccessTimeComparator()); tvec.setSort(true); } public ImageCache clone() { ImageCache cloned = new ImageCache(); for (Enumeration e = hash.elements(); e.hasMoreElements();) cloned.put((CachedImage)e.nextElement()); return cloned; } public Enumeration sortedByCoordinates() { return cvec.elements(); } public CachedImage get(String key) { return (CachedImage)hash.get(key); } public void put(CachedImage img) { put(img, true); } private void put(CachedImage img, boolean doCheck) { hash.put(img.key, img); cvec.addElement(img); tvec.addElement(img); if (doCheck) check(); } private void check() { if (hash.size() < MAX_IMAGE_CACHE_SIZE) return; SimpleSortingVector vec = tvec; reinit(); Enumeration e = vec.elements(); while (e.hasMoreElements()) { CachedImage img = (CachedImage)e.nextElement(); put(img, false); } } }; private ImageCache mImgCache = new ImageCache(); private static abstract class MapCommand { public abstract String type(); public abstract String description(); } private static class MapFetchCommand extends MapCommand { public String baseUrl; public int zoom; public long latitude; public long longitude; public MapFetchCommand(String baseUrl, int zoom, long latitude, long longitude) { this.baseUrl = baseUrl; this.zoom = zoom; this.latitude = latitude; this.longitude = longitude; } private String makeDescription() { return "" + zoom + "/" + latitude + "/" + longitude; } public String type() { return "fetch"; } public String description() { return "fetch:" + makeDescription(); } }; private class MapThread extends Thread { private static final int BLOCK_SIZE = 1024; private Vector commands = new Vector(); private boolean active = true; public void process(MapCommand cmd) { synchronized (commands) { commands.addElement(cmd); commands.notify(); } } public void stop() { active = false; interrupt(); } public void run() { try { while (active) { MapCommand cmd = null; synchronized (commands) { if (commands.isEmpty()) { try { commands.wait(); } catch (InterruptedException e) { // Nothing } continue; } cmd = (MapCommand)commands.elementAt(0); commands.removeElementAt(0); if (cmd == null) continue; } try { if (cmd instanceof MapFetchCommand) processCommand((MapFetchCommand)cmd); else LOG.INFO("Received unknown command: " + cmd.type() + ", ignore it"); } catch (Exception e) { LOG.ERROR("Processing of map command failed", e); } } } catch (Exception e) { LOG.ERROR("Fatal error in map thread", e); } finally { LOG.INFO("Map thread exit"); } } private byte[] fetchData(String url) throws IOException { IHttpConnection conn = RhoClassFactory.getNetworkAccess().connect(url,false); conn.setRequestMethod("GET"); //conn.setRequestProperty("User-Agent", "Blackberry"); //conn.setRequestProperty("Accept", "*/*"); InputStream is = conn.openInputStream(); int code = conn.getResponseCode(); if (code/100 != 2) throw new IOException("ESRI map server respond with " + code + " " + conn.getResponseMessage()); int size = conn.getHeaderFieldInt("Content-Length", 0); byte[] data = new byte[size]; if (size == 0) size = 1073741824; // 1Gb :) byte[] buf = new byte[BLOCK_SIZE]; for (int offset = 0; offset < size;) { int n = is.read(buf, 0, BLOCK_SIZE); if (n <= 0) break; if (offset + n > data.length) { byte[] newData = new byte[offset + n]; System.arraycopy(data, 0, newData, 0, data.length); data = newData; } System.arraycopy(buf, 0, data, offset, n); offset += n; } return data; } private void processCommand(MapFetchCommand cmd) throws IOException { LOG.TRACE("Processing map fetch command (thread #" + hashCode() + "): " + cmd.description()); long ts = toMaxZoom(TILE_SIZE, cmd.zoom); int row = (int)(cmd.latitude/ts); int column = (int)(cmd.longitude/ts); StringBuffer url = new StringBuffer(); url.append(cmd.baseUrl); url.append("/MapServer/tile/"); url.append(cmd.zoom); url.append('/'); url.append(row); url.append('/'); url.append(column); String finalUrl = url.toString(); byte[] data = fetchData(finalUrl); EncodedImage img = EncodedImage.createEncodedImage(data, 0, data.length); img.setDecodeMode(DECODE_MODE); long lat = row*ts + ts/2; long lon = column*ts + ts/2; LOG.TRACE("Map request done, draw just received image: zoom=" + cmd.zoom + ", lat=" + lat + ", lon=" + lon); CachedImage cachedImage = new CachedImage(img, lat, lon, cmd.zoom); // Put image to the cache and trigger redraw synchronized (ESRIMapField.this) { mImgCache.put(cachedImage); } redraw(); } }; private MapThread mMapThread = new MapThread(); private class CacheUpdate extends Thread { private boolean active = true; public void stop() throws InterruptedException { active = false; join(); } public void run() { LOG.TRACE("Cache update thread started"); while (active) { try { Thread.sleep(CACHE_UPDATE_INTERVAL); } catch (InterruptedException e) { // Ignore } //LOG.TRACE("Cache update: next loop; mLatitude=" + mLatitude + // ", mLongitude=" + mLongitude + ", mZoom=" + mZoom); long ts = toMaxZoom(TILE_SIZE, mZoom); //LOG.TRACE("Tile size on the maximum zoom level: " + ts); long h = toMaxZoom(mHeight, mZoom); //LOG.TRACE("Height of the screen on the maximum zoom level: " + h); long w = toMaxZoom(mWidth, mZoom); //LOG.TRACE("Width of the screen on the maximum zoom level: " + w); long totalTiles = MapTools.math_pow2(mZoom); //LOG.TRACE("Total tiles count on zoom level " + mZoom + ": " + totalTiles); long tlLat = mLatitude - h/2; if (tlLat < 0) tlLat = 0; long tlLon = mLongitude - w/2; if (tlLon < 0) tlLon = 0; //LOG.TRACE("tlLat=" + tlLat + ", tlLon=" + tlLon); for (long lat = (tlLat/ts)*ts, latLim = Math.min(tlLat + h + ts, ts*totalTiles); lat < latLim; lat += ts) { for (long lon = (tlLon/ts)*ts, lonLim = Math.min(tlLon + w + ts, ts*totalTiles); lon < lonLim; lon += ts) { String key = makeCacheKey(lat, lon, mZoom); MapFetchCommand cmd = null; synchronized (ESRIMapField.this) { CachedImage img = mImgCache.get(key); if (img == null) { //LOG.TRACE("lat=" + lat + ", lon=" + lon + "; key=" + key); String baseUrl = (String)mMapUrls.get(mMapType); cmd = new MapFetchCommand(baseUrl, mZoom, lat, lon); CachedImage dummy = new CachedImage(null, lat, lon, mZoom); mImgCache.put(dummy); } } if (cmd != null) mMapThread.process(cmd); } } } LOG.TRACE("Cache update thread stopped"); } }; private CacheUpdate mCacheUpdate = new CacheUpdate(); public ESRIMapField() { String url = RhoConf.getInstance().getString("esri_map_url_roadmap"); if (url == null || url.length() == 0) url = "http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/"; mMapUrls.put("roadmap", url); url = RhoConf.getInstance().getString("esri_map_url_satellite"); if (url == null || url.length() == 0) url = "http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/"; mMapUrls.put("satellite", url); mMapType = "roadmap"; LOG.TRACE("ESRIMapField ctor: mLatitude=" + mLatitude + ", mLongitude=" + mLongitude); mMapThread.start(); mCacheUpdate.start(); } public void close() { mMapThread.stop(); try { mCacheUpdate.stop(); } catch (InterruptedException e) { LOG.ERROR("Stopping of cache update thread was interrupted", e); } } public void redraw() { invalidate(); } protected void paint(Graphics graphics) { // Draw background for (int i = 1, lim = 2*Math.max(mWidth, mHeight); i < lim; i += 5) { graphics.drawLine(0, i, i, 0); } ImageCache imgCache; synchronized (this) { imgCache = mImgCache.clone(); } // Draw map tiles Enumeration e = imgCache.sortedByCoordinates(); while (e.hasMoreElements()) { // Draw map CachedImage img = (CachedImage)e.nextElement(); if (img.image == null) continue; paintImage(graphics, img); } } private void paintImage(Graphics graphics, CachedImage img) { // Skip images with zoom level which differ from the current zoom level if (img.zoom != mZoom) return; long left = -toCurrentZoom(mLongitude - img.longitude, mZoom); long top = -toCurrentZoom(mLatitude - img.latitude, mZoom); if (img.zoom != mZoom) { double x = MapTools.math_pow2d(img.zoom - mZoom); int factor = Fixed32.tenThouToFP((int)(x*10000)); img.image = img.image.scaleImage32(factor, factor); img.bitmap = null; } int imgWidth = img.image.getScaledWidth(); int imgHeight = img.image.getScaledHeight(); left += (mWidth - imgWidth)/2; top += (mHeight - imgHeight)/2; int w = mWidth - (int)left; int h = mHeight - (int)top; int maxW = mWidth + TILE_SIZE; int maxH = mHeight + TILE_SIZE; if (w < 0 || h < 0 || w > maxW || h > maxH) { // Image will not be displayed, free its bitmap and skip it img.bitmap = null; return; } if (img.bitmap == null) img.bitmap = img.image.getBitmap(); graphics.drawBitmap((int)left, (int)top, w, h, img.bitmap, 0, 0); } protected void layout(int w, int h) { mWidth = Math.min(mWidth, w); mHeight = Math.min(mHeight, h); setExtent(mWidth, mHeight); } public int calculateZoom(double latDelta, double lonDelta) { int zoom1 = calcZoom(latDelta, mWidth); int zoom2 = calcZoom(lonDelta, mHeight); return zoom1 < zoom2 ? zoom1 : zoom2; } public Field getBBField() { return this; } public double getCenterLatitude() { return pixelsToDegreesY(mLatitude, MAX_ZOOM); } public double getCenterLongitude() { return pixelsToDegreesX(mLongitude, MAX_ZOOM); } private void validateCoordinates() { if (mLatitude < MIN_LATITUDE) mLatitude = MIN_LATITUDE; if (mLatitude > MAX_LATITUDE) mLatitude = MAX_LATITUDE; } public void moveTo(double lat, double lon) { mLatitude = degreesToPixelsY(lat, MAX_ZOOM); mLongitude = degreesToPixelsX(lon, MAX_ZOOM); validateCoordinates(); //LOG.TRACE("moveTo(" + lat + ", " + lon + "): mLatitude=" + mLatitude + ", mLongitude=" + mLongitude); } public void move(int dx, int dy) { mLatitude += toMaxZoom(dy, mZoom); mLongitude += toMaxZoom(dx, mZoom); validateCoordinates(); //LOG.TRACE("move(" + dx + ", " + dy + "): mLatitude=" + mLatitude + ", mLongitude=" + mLongitude); } public void setMapType(String type) { mMapType = type; //LOG.TRACE("setMapType: " + mMapType); } public void setPreferredSize(int width, int height) { mWidth = width; mHeight = height; } public int getPreferredWidth() { return mWidth; } public int getPreferredHeight() { return mHeight; } public void setZoom(int zoom) { mZoom = zoom; if (mZoom < MIN_ZOOM) mZoom = MIN_ZOOM; if (mZoom > MAX_ZOOM) mZoom = MAX_ZOOM; LOG.TRACE("setZoom: " + mZoom); } public int getMaxZoom() { return MAX_ZOOM; } public int getMinZoom() { return MIN_ZOOM; } public int getZoom() { return mZoom; } private static int calcZoom(double degrees, int pixels) { double angleRatio = degrees*TILE_SIZE/pixels; double twoInZoomExp = 360/angleRatio; int zoom = (int)MapTools.math_log2(twoInZoomExp); return zoom; } private static long toMaxZoom(long n, int zoom) { if (n == 0) return 0; long pow = MapTools.math_pow2(MAX_ZOOM - zoom); return n*pow; } private static long toCurrentZoom(long coord, int zoom) { if (coord == 0) return 0; long pow = MapTools.math_pow2(MAX_ZOOM - zoom); return coord/pow; } private static long degreesToPixelsX(double n, int z) { while (n < -180.0) n += 360.0; while (n > 180.0) n -= 360.0; double angleRatio = 360d/MapTools.math_pow2(z); double val = (n + 180)*TILE_SIZE/angleRatio; return (long)val; } private static long degreesToPixelsY(double n, int z) { // Merkator projection double sin_phi = MapTools.math_sin(n*PI/180); // MAX_SIN - maximum value of sine allowed by Merkator projection // (~85.0 degrees of north latitude) if (sin_phi < -MAX_SIN) sin_phi = -MAX_SIN; if (sin_phi > MAX_SIN) sin_phi = MAX_SIN; double ath = MapTools.math_atanh(sin_phi); double val = TILE_SIZE * MapTools.math_pow2(z) * (1 - ath/PI)/2; return (long)val; } private static double pixelsToDegreesX(long n, int z) { while (n < 0) n += MAX_LONGITUDE; while (n > MAX_LONGITUDE) n -= MAX_LONGITUDE; double angleRatio = 360d/MapTools.math_pow2(z); double val = n*angleRatio/TILE_SIZE - 180.0; return val; } private static double pixelsToDegreesY(long n, int z) { // Revert calculation of Merkator projection double ath = PI - 2*PI*n/(TILE_SIZE*MapTools.math_pow2(z)); double th = MapTools.math_tanh(ath); double val = 180*MapTools.math_asin(th)/PI; return val; } private String makeCacheKey(long lat, long lon, int z) { while (lon < 0) lon += MAX_LONGITUDE; while (lon > MAX_LONGITUDE) lon -= MAX_LONGITUDE; long ts = toMaxZoom(TILE_SIZE, z); long x = lon/ts; long y = lat/ts; StringBuffer buf = new StringBuffer(); buf.append(z); buf.append(';'); buf.append(x); buf.append(';'); buf.append(y); String key = buf.toString(); return key; } public long toScreenCoordinateX(double n) { long v = degreesToPixelsX(n, mZoom); long center = toCurrentZoom(mLongitude, mZoom); long begin = center - mWidth/2; return v - begin; } public long toScreenCoordinateY(double n) { long v = degreesToPixelsY(n, mZoom); long center = toCurrentZoom(mLatitude, mZoom); long begin = center - mHeight/2; return v - begin; } }
[BB MapView] change tiles fetch order from FIFO to LIFO
platform/bb/rhodes/src/rhomobile/mapview/ESRIMapField.java
[BB MapView] change tiles fetch order from FIFO to LIFO
Java
mit
5e541fa4c200723a3d389b6c42efa8edded211dd
0
alecgorge/jsonapi,alecgorge/jsonapi,alecgorge/jsonapi,alecgorge/jsonapi,alecgorge/jsonapi,alecgorge/jsonapi,alecgorge/jsonapi
package com.alecgorge.minecraft.jsonapi.stringifier; import java.io.File; import java.text.DateFormat; import java.text.SimpleDateFormat; 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.List; import java.util.Map; import java.util.TimeZone; import net.milkbowl.vault.economy.EconomyResponse; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.OfflinePlayer; import org.bukkit.Server; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import org.json.simpleForBukkit.JSONArray; import org.json.simpleForBukkit.JSONObject; import com.alecgorge.minecraft.jsonapi.JSONAPI; import com.alecgorge.minecraft.jsonapi.adminium.Adminium3; import com.alecgorge.minecraft.jsonapi.adminium.PushNotificationDaemon.AdminiumPushNotification; import com.alecgorge.minecraft.jsonapi.config.JSONAPIPermissionNode; import com.alecgorge.minecraft.jsonapi.permissions.JSONAPIGroup; import com.alecgorge.minecraft.jsonapi.permissions.JSONAPIUser; import com.alecgorge.minecraft.jsonapi.dynamic.Argument; import com.alecgorge.minecraft.jsonapi.dynamic.Method; public class BukkitStringifier { public static HashMap<String, Class<?>> handle = new HashMap<String, Class<?>>(); static TimeZone tz = TimeZone.getTimeZone("UTC"); static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); static { dateFormat.setTimeZone(tz); handle.put("Player", org.bukkit.entity.Player.class); handle.put("Player[]", org.bukkit.entity.Player[].class); handle.put("OfflinePlayer", org.bukkit.OfflinePlayer.class); handle.put("OfflinePlayer[]", org.bukkit.OfflinePlayer[].class); handle.put("Server", org.bukkit.Server.class); handle.put("World", org.bukkit.World.class); handle.put("World[]", org.bukkit.World[].class); handle.put("Plugin", org.bukkit.plugin.Plugin.class); handle.put("Plugin[]", org.bukkit.plugin.Plugin[].class); handle.put("ItemStack", org.bukkit.inventory.ItemStack.class); handle.put("File", java.io.File.class); handle.put("ItemStack[]", org.bukkit.inventory.ItemStack[].class); handle.put("PlayerInventory", org.bukkit.inventory.PlayerInventory.class); handle.put("Inventory", org.bukkit.inventory.Inventory.class); handle.put("Location", org.bukkit.Location.class); handle.put("World.Environment", org.bukkit.World.Environment.class); handle.put("GameMode", org.bukkit.GameMode.class); handle.put("Enchantment", org.bukkit.enchantments.Enchantment.class); handle.put("Block", org.bukkit.block.Block.class); handle.put("JSONAPIUser", JSONAPIUser.class); handle.put("JSONAPIGroup", JSONAPIGroup.class); handle.put("JSONAPIPermissionNode", JSONAPIPermissionNode.class); handle.put("Object[]", java.lang.Object[].class); handle.put("AdminiumPushNotification", AdminiumPushNotification.class); handle.put("Adminium3.AdminiumPushNotification", Adminium3.AdminiumPushNotification.class); handle.put("Date", Date.class); handle.put("Method", Method.class); if (JSONAPI.instance.getServer().getPluginManager().getPlugin("Vault") != null) { handle.put("EconomyResponse", net.milkbowl.vault.economy.EconomyResponse.class); } } public static boolean canHandle(Class<?> c) { for (Class<?> cc : handle.values()) { if (cc.isAssignableFrom(c)) { return true; } } return false; } public static Object handle(Object obj) { if (obj instanceof World.Environment) { World.Environment e = (World.Environment) obj; return e.name().toLowerCase(); } else if (obj instanceof File) { return ((File) obj).toString(); } else if (obj instanceof Block) { Block b = (Block) obj; JSONObject o = new JSONObject(); o.put("type", b.getTypeId()); o.put("data", b.getData()); return o; } else if (obj instanceof Player) { Player p = (Player) obj; JSONObject o = new JSONObject(); o.put("name", p.getName()); o.put("uuid", p.getUniqueId().toString()); o.put("op", p.isOp()); o.put("health", p.getHealth()); o.put("foodLevel", p.getFoodLevel()); o.put("exhaustion", p.getExhaustion()); o.put("ip", p.getAddress() != null ? p.getAddress().toString() : "offline"); o.put("itemInHand", p.getItemInHand()); o.put("location", p.getLocation()); o.put("inventory", p.getInventory()); // o.put("enderchest", p.getEnderChest()); o.put("sneaking", p.isSneaking()); o.put("sprinting", p.isSprinting()); o.put("inVehicle", p.isInsideVehicle()); o.put("sleeping", p.isSleeping()); o.put("world", p.getServer().getWorlds().indexOf(p.getWorld())); o.put("worldInfo", p.getWorld()); o.put("gameMode", p.getGameMode()); o.put("banned", p.isBanned()); o.put("whitelisted", p.isWhitelisted()); o.put("level", p.getLevel()); o.put("experience", p.getTotalExperience()); o.put("firstPlayed", Math.round(p.getFirstPlayed() / 1000.0)); o.put("lastPlayed", Math.round(p.getLastPlayed() / 1000.0)); o.put("enderchest", p.getEnderChest()); return o; } else if (obj instanceof OfflinePlayer) { OfflinePlayer op = (OfflinePlayer) obj; JSONObject o = new JSONObject(); Player target = JSONAPI.loadOfflinePlayer(op.getName()); if (target != null) return target; o.put("firstPlayed", Math.round(op.getFirstPlayed() / 1000.0)); o.put("lastPlayed", Math.round(op.getLastPlayed() / 1000.0)); o.put("banned", op.isBanned()); o.put("whitelisted", op.isWhitelisted()); o.put("name", op.getName()); o.put("uuid", op.getUniqueId().toString()); return o; } else if (obj instanceof Server) { Server s = (Server) obj; JSONObject o = new JSONObject(); o.put("maxPlayers", s.getMaxPlayers()); o.put("players", s.getOnlinePlayers()); o.put("port", s.getPort()); o.put("name", s.getName()); o.put("serverName", s.getServerName()); o.put("version", s.getVersion()); o.put("worlds", s.getWorlds()); return o; } else if (obj instanceof World) { World w = (World) obj; JSONObject o = new JSONObject(); o.put("environment", w.getEnvironment()); o.put("fullTime", w.getFullTime()); o.put("time", w.getTime()); o.put("name", w.getName()); o.put("isThundering", w.isThundering()); o.put("hasStorm", w.hasStorm()); o.put("remainingWeatherTicks", w.getWeatherDuration()); o.put("isPVP", w.getPVP()); o.put("difficulty", w.getDifficulty().getValue()); o.put("seed", String.valueOf(w.getSeed())); List<String> playerNames = new ArrayList<String>(); for(Player p : w.getPlayers()) { if(!p.getName().equals("�fHerobrine")) { playerNames.add(p.getName()); } } o.put("players", playerNames); return o; } else if (obj instanceof Plugin) { Plugin p = (Plugin) obj; PluginDescriptionFile d = p.getDescription(); JSONObject o = new JSONObject(); o.put("name", d.getName()); o.put("description", d.getDescription() == null ? "" : d.getDescription()); o.put("authors", d.getAuthors()); o.put("version", d.getVersion()); o.put("website", d.getWebsite() == null ? "" : d.getWebsite()); o.put("enabled", JSONAPI.instance.getServer().getPluginManager().isPluginEnabled(p)); o.put("commands", d.getCommands()); return o; } else if (obj instanceof ItemStack) { ItemStack i = (ItemStack) obj; JSONObject o = new JSONObject(); o.put("type", i.getTypeId()); o.put("durability", i.getDurability()); o.put("dataValue", (int) i.getData().getData()); o.put("amount", i.getAmount()); JSONObject enchantments = new JSONObject(); for (Map.Entry<Enchantment, Integer> enchantment : i.getEnchantments().entrySet()) { enchantments.put(enchantment.getKey().getId(), enchantment.getValue()); } o.put("enchantments", enchantments); if (((ItemStack) obj).getType().equals(Material.BOOK_AND_QUILL) || ((ItemStack) obj).getType().equals(Material.WRITTEN_BOOK)) { JSONObject book = new JSONObject(); BookMeta bookObj = (BookMeta)((ItemStack)obj).getItemMeta(); book.put("pages", bookObj.getPages()); book.put("title", bookObj.getTitle()); book.put("author", bookObj.getAuthor()); o.put("book", book); } return o; } else if (obj instanceof PlayerInventory) { PlayerInventory p = (PlayerInventory) obj; JSONObject o = new JSONObject(); JSONObject armor = new JSONObject(); armor.put("boots", p.getBoots()); armor.put("chestplate", p.getChestplate()); armor.put("helmet", p.getHelmet()); armor.put("leggings", p.getLeggings()); o.put("armor", armor); o.put("hand", p.getItemInHand()); o.put("inventory", Arrays.asList(p.getContents())); return o; } else if (obj instanceof Inventory) { Inventory p = (Inventory) obj; return Arrays.asList(p.getContents()); } else if (obj instanceof Location) { Location l = (Location) obj; JSONObject o = new JSONObject(); o.put("x", l.getX()); o.put("y", l.getY()); o.put("z", l.getZ()); o.put("pitch", l.getPitch()); o.put("yaw", l.getYaw()); return o; } else if (obj instanceof Plugin[]) { List<Plugin> l = Arrays.asList((Plugin[]) obj); Collections.sort(l, new PluginSorter()); return l; } else if(obj instanceof JSONAPIUser) { JSONObject o = new JSONObject(); JSONAPIUser u = (JSONAPIUser)obj; o.put("username", u.getUsername()); o.put("password", u.getPassword()); o.put("groups", u.getGroups()); return o; } else if (obj instanceof JSONAPIGroup) { JSONObject o = new JSONObject(); JSONAPIGroup g = (JSONAPIGroup)obj; o.put("name", g.getName()); o.put("streams", g.getStreams()); o.put("methods", g.getMethods()); o.put("permissions", g.getPermissions()); return o; } else if(obj instanceof JSONAPIPermissionNode) { // JSONObject o = new JSONObject(); JSONAPIPermissionNode n = (JSONAPIPermissionNode)obj; // o.put("name", n.getName()); // o.put("methods", n.getName()); // o.put("streams", n.getStreams()); return n.getName(); } else if (obj instanceof GameMode) { return ((GameMode) obj).getValue(); } else if (obj instanceof Enchantment) { return ((Enchantment) obj).getId(); } else if (JSONAPI.instance.getServer().getPluginManager().getPlugin("Vault") != null && obj instanceof EconomyResponse) { JSONObject o = new JSONObject(); EconomyResponse r = (EconomyResponse) obj; o.put("amount", r.amount); o.put("balance", r.balance); o.put("errorMessage", r.errorMessage); o.put("type", r.type.toString()); return o; } else if (obj instanceof Adminium3.AdminiumPushNotification) { JSONObject o = new JSONObject(); Adminium3.AdminiumPushNotification not = (Adminium3.AdminiumPushNotification)obj; o.put("date", not.getDateSent()); o.put("message", not.getMessage()); return o; } else if(obj instanceof AdminiumPushNotification) { JSONObject o = new JSONObject(); AdminiumPushNotification not = (AdminiumPushNotification)obj; o.put("date", not.getDateSent()); o.put("message", not.getMessage()); return o; } else if (obj instanceof Date) { return dateFormat.format((Date)obj); } else if (obj instanceof Method) { JSONObject o = new JSONObject(); Method m = (Method)obj; o.put("name", m.getName()); o.put("description", m.getDesc()); JSONObject ret = new JSONObject(); ret.put("type", m.getReturnValue().getCanonicalName()); ret.put("description", m.getReturnDesc()); JSONArray args = new JSONArray(); for(Argument a : m.getArgs()) { JSONObject arg = new JSONObject(); arg.put("description", a.getDesc()); arg.put("type", a.getType().getCanonicalName()); args.add(arg); } o.put("arguments", args); o.put("return", ret); return o; } else if (obj instanceof Object[]) { int l = ((Object[]) obj).length; JSONArray a = new JSONArray(); for (int i = 0; i < l; i++) { a.add(((Object[]) obj)[i]); } return a; } JSONAPI.instance.outLog.warning("Uncaugh object! Value:"); JSONAPI.instance.outLog.warning(obj.toString()); JSONAPI.instance.outLog.warning("Type:"); JSONAPI.instance.outLog.warning(obj.getClass().getName()); return new Object(); } static class PluginSorter implements Comparator<Plugin> { @Override public int compare(Plugin o1, Plugin o2) { return o1.getDescription().getName().compareTo(o2.getDescription().getName()); } } }
src/main/java/com/alecgorge/minecraft/jsonapi/stringifier/BukkitStringifier.java
package com.alecgorge.minecraft.jsonapi.stringifier; import java.io.File; import java.text.DateFormat; import java.text.SimpleDateFormat; 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.List; import java.util.Map; import java.util.TimeZone; import net.milkbowl.vault.economy.EconomyResponse; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.OfflinePlayer; import org.bukkit.Server; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import org.json.simpleForBukkit.JSONArray; import org.json.simpleForBukkit.JSONObject; import com.alecgorge.minecraft.jsonapi.JSONAPI; import com.alecgorge.minecraft.jsonapi.adminium.Adminium3; import com.alecgorge.minecraft.jsonapi.adminium.PushNotificationDaemon.AdminiumPushNotification; import com.alecgorge.minecraft.jsonapi.config.JSONAPIPermissionNode; import com.alecgorge.minecraft.jsonapi.permissions.JSONAPIGroup; import com.alecgorge.minecraft.jsonapi.permissions.JSONAPIUser; import com.alecgorge.minecraft.jsonapi.dynamic.Argument; import com.alecgorge.minecraft.jsonapi.dynamic.Method; public class BukkitStringifier { public static HashMap<String, Class<?>> handle = new HashMap<String, Class<?>>(); static TimeZone tz = TimeZone.getTimeZone("UTC"); static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); static { dateFormat.setTimeZone(tz); handle.put("Player", org.bukkit.entity.Player.class); handle.put("Player[]", org.bukkit.entity.Player[].class); handle.put("OfflinePlayer", org.bukkit.OfflinePlayer.class); handle.put("OfflinePlayer[]", org.bukkit.OfflinePlayer[].class); handle.put("Server", org.bukkit.Server.class); handle.put("World", org.bukkit.World.class); handle.put("World[]", org.bukkit.World[].class); handle.put("Plugin", org.bukkit.plugin.Plugin.class); handle.put("Plugin[]", org.bukkit.plugin.Plugin[].class); handle.put("ItemStack", org.bukkit.inventory.ItemStack.class); handle.put("File", java.io.File.class); handle.put("ItemStack[]", org.bukkit.inventory.ItemStack[].class); handle.put("PlayerInventory", org.bukkit.inventory.PlayerInventory.class); handle.put("Inventory", org.bukkit.inventory.Inventory.class); handle.put("Location", org.bukkit.Location.class); handle.put("World.Environment", org.bukkit.World.Environment.class); handle.put("GameMode", org.bukkit.GameMode.class); handle.put("Enchantment", org.bukkit.enchantments.Enchantment.class); handle.put("Block", org.bukkit.block.Block.class); handle.put("JSONAPIUser", JSONAPIUser.class); handle.put("JSONAPIGroup", JSONAPIGroup.class); handle.put("JSONAPIPermissionNode", JSONAPIPermissionNode.class); handle.put("Object[]", java.lang.Object[].class); handle.put("AdminiumPushNotification", AdminiumPushNotification.class); handle.put("Adminium3.AdminiumPushNotification", Adminium3.AdminiumPushNotification.class); handle.put("Date", Date.class); handle.put("Method", Method.class); if (JSONAPI.instance.getServer().getPluginManager().getPlugin("Vault") != null) { handle.put("EconomyResponse", net.milkbowl.vault.economy.EconomyResponse.class); } } public static boolean canHandle(Class<?> c) { for (Class<?> cc : handle.values()) { if (cc.isAssignableFrom(c)) { return true; } } return false; } public static Object handle(Object obj) { if (obj instanceof World.Environment) { World.Environment e = (World.Environment) obj; return e.name().toLowerCase(); } else if (obj instanceof File) { return ((File) obj).toString(); } else if (obj instanceof Block) { Block b = (Block) obj; JSONObject o = new JSONObject(); o.put("type", b.getTypeId()); o.put("data", b.getData()); return o; } else if (obj instanceof Player) { Player p = (Player) obj; JSONObject o = new JSONObject(); o.put("name", p.getName()); o.put("uuid", p.getUniqueId()); o.put("op", p.isOp()); o.put("health", p.getHealth()); o.put("foodLevel", p.getFoodLevel()); o.put("exhaustion", p.getExhaustion()); o.put("ip", p.getAddress() != null ? p.getAddress().toString() : "offline"); o.put("itemInHand", p.getItemInHand()); o.put("location", p.getLocation()); o.put("inventory", p.getInventory()); // o.put("enderchest", p.getEnderChest()); o.put("sneaking", p.isSneaking()); o.put("sprinting", p.isSprinting()); o.put("inVehicle", p.isInsideVehicle()); o.put("sleeping", p.isSleeping()); o.put("world", p.getServer().getWorlds().indexOf(p.getWorld())); o.put("worldInfo", p.getWorld()); o.put("gameMode", p.getGameMode()); o.put("banned", p.isBanned()); o.put("whitelisted", p.isWhitelisted()); o.put("level", p.getLevel()); o.put("experience", p.getTotalExperience()); o.put("firstPlayed", Math.round(p.getFirstPlayed() / 1000.0)); o.put("lastPlayed", Math.round(p.getLastPlayed() / 1000.0)); o.put("enderchest", p.getEnderChest()); return o; } else if (obj instanceof OfflinePlayer) { OfflinePlayer op = (OfflinePlayer) obj; JSONObject o = new JSONObject(); Player target = JSONAPI.loadOfflinePlayer(op.getName()); if (target != null) return target; o.put("firstPlayed", Math.round(op.getFirstPlayed() / 1000.0)); o.put("lastPlayed", Math.round(op.getLastPlayed() / 1000.0)); o.put("banned", op.isBanned()); o.put("whitelisted", op.isWhitelisted()); o.put("name", op.getName()); o.put("uuid", op.getUniqueId()); return o; } else if (obj instanceof Server) { Server s = (Server) obj; JSONObject o = new JSONObject(); o.put("maxPlayers", s.getMaxPlayers()); o.put("players", s.getOnlinePlayers()); o.put("port", s.getPort()); o.put("name", s.getName()); o.put("serverName", s.getServerName()); o.put("version", s.getVersion()); o.put("worlds", s.getWorlds()); return o; } else if (obj instanceof World) { World w = (World) obj; JSONObject o = new JSONObject(); o.put("environment", w.getEnvironment()); o.put("fullTime", w.getFullTime()); o.put("time", w.getTime()); o.put("name", w.getName()); o.put("isThundering", w.isThundering()); o.put("hasStorm", w.hasStorm()); o.put("remainingWeatherTicks", w.getWeatherDuration()); o.put("isPVP", w.getPVP()); o.put("difficulty", w.getDifficulty().getValue()); o.put("seed", String.valueOf(w.getSeed())); List<String> playerNames = new ArrayList<String>(); for(Player p : w.getPlayers()) { if(!p.getName().equals("�fHerobrine")) { playerNames.add(p.getName()); } } o.put("players", playerNames); return o; } else if (obj instanceof Plugin) { Plugin p = (Plugin) obj; PluginDescriptionFile d = p.getDescription(); JSONObject o = new JSONObject(); o.put("name", d.getName()); o.put("description", d.getDescription() == null ? "" : d.getDescription()); o.put("authors", d.getAuthors()); o.put("version", d.getVersion()); o.put("website", d.getWebsite() == null ? "" : d.getWebsite()); o.put("enabled", JSONAPI.instance.getServer().getPluginManager().isPluginEnabled(p)); o.put("commands", d.getCommands()); return o; } else if (obj instanceof ItemStack) { ItemStack i = (ItemStack) obj; JSONObject o = new JSONObject(); o.put("type", i.getTypeId()); o.put("durability", i.getDurability()); o.put("dataValue", (int) i.getData().getData()); o.put("amount", i.getAmount()); JSONObject enchantments = new JSONObject(); for (Map.Entry<Enchantment, Integer> enchantment : i.getEnchantments().entrySet()) { enchantments.put(enchantment.getKey().getId(), enchantment.getValue()); } o.put("enchantments", enchantments); if (((ItemStack) obj).getType().equals(Material.BOOK_AND_QUILL) || ((ItemStack) obj).getType().equals(Material.WRITTEN_BOOK)) { JSONObject book = new JSONObject(); BookMeta bookObj = (BookMeta)((ItemStack)obj).getItemMeta(); book.put("pages", bookObj.getPages()); book.put("title", bookObj.getTitle()); book.put("author", bookObj.getAuthor()); o.put("book", book); } return o; } else if (obj instanceof PlayerInventory) { PlayerInventory p = (PlayerInventory) obj; JSONObject o = new JSONObject(); JSONObject armor = new JSONObject(); armor.put("boots", p.getBoots()); armor.put("chestplate", p.getChestplate()); armor.put("helmet", p.getHelmet()); armor.put("leggings", p.getLeggings()); o.put("armor", armor); o.put("hand", p.getItemInHand()); o.put("inventory", Arrays.asList(p.getContents())); return o; } else if (obj instanceof Inventory) { Inventory p = (Inventory) obj; return Arrays.asList(p.getContents()); } else if (obj instanceof Location) { Location l = (Location) obj; JSONObject o = new JSONObject(); o.put("x", l.getX()); o.put("y", l.getY()); o.put("z", l.getZ()); o.put("pitch", l.getPitch()); o.put("yaw", l.getYaw()); return o; } else if (obj instanceof Plugin[]) { List<Plugin> l = Arrays.asList((Plugin[]) obj); Collections.sort(l, new PluginSorter()); return l; } else if(obj instanceof JSONAPIUser) { JSONObject o = new JSONObject(); JSONAPIUser u = (JSONAPIUser)obj; o.put("username", u.getUsername()); o.put("password", u.getPassword()); o.put("groups", u.getGroups()); return o; } else if (obj instanceof JSONAPIGroup) { JSONObject o = new JSONObject(); JSONAPIGroup g = (JSONAPIGroup)obj; o.put("name", g.getName()); o.put("streams", g.getStreams()); o.put("methods", g.getMethods()); o.put("permissions", g.getPermissions()); return o; } else if(obj instanceof JSONAPIPermissionNode) { // JSONObject o = new JSONObject(); JSONAPIPermissionNode n = (JSONAPIPermissionNode)obj; // o.put("name", n.getName()); // o.put("methods", n.getName()); // o.put("streams", n.getStreams()); return n.getName(); } else if (obj instanceof GameMode) { return ((GameMode) obj).getValue(); } else if (obj instanceof Enchantment) { return ((Enchantment) obj).getId(); } else if (JSONAPI.instance.getServer().getPluginManager().getPlugin("Vault") != null && obj instanceof EconomyResponse) { JSONObject o = new JSONObject(); EconomyResponse r = (EconomyResponse) obj; o.put("amount", r.amount); o.put("balance", r.balance); o.put("errorMessage", r.errorMessage); o.put("type", r.type.toString()); return o; } else if (obj instanceof Adminium3.AdminiumPushNotification) { JSONObject o = new JSONObject(); Adminium3.AdminiumPushNotification not = (Adminium3.AdminiumPushNotification)obj; o.put("date", not.getDateSent()); o.put("message", not.getMessage()); return o; } else if(obj instanceof AdminiumPushNotification) { JSONObject o = new JSONObject(); AdminiumPushNotification not = (AdminiumPushNotification)obj; o.put("date", not.getDateSent()); o.put("message", not.getMessage()); return o; } else if (obj instanceof Date) { return dateFormat.format((Date)obj); } else if (obj instanceof Method) { JSONObject o = new JSONObject(); Method m = (Method)obj; o.put("name", m.getName()); o.put("description", m.getDesc()); JSONObject ret = new JSONObject(); ret.put("type", m.getReturnValue().getCanonicalName()); ret.put("description", m.getReturnDesc()); JSONArray args = new JSONArray(); for(Argument a : m.getArgs()) { JSONObject arg = new JSONObject(); arg.put("description", a.getDesc()); arg.put("type", a.getType().getCanonicalName()); args.add(arg); } o.put("arguments", args); o.put("return", ret); return o; } else if (obj instanceof Object[]) { int l = ((Object[]) obj).length; JSONArray a = new JSONArray(); for (int i = 0; i < l; i++) { a.add(((Object[]) obj)[i]); } return a; } JSONAPI.instance.outLog.warning("Uncaugh object! Value:"); JSONAPI.instance.outLog.warning(obj.toString()); JSONAPI.instance.outLog.warning("Type:"); JSONAPI.instance.outLog.warning(obj.getClass().getName()); return new Object(); } static class PluginSorter implements Comparator<Plugin> { @Override public int compare(Plugin o1, Plugin o2) { return o1.getDescription().getName().compareTo(o2.getDescription().getName()); } } }
Convert UUID to string.
src/main/java/com/alecgorge/minecraft/jsonapi/stringifier/BukkitStringifier.java
Convert UUID to string.
Java
mit
bcea69070b544558f539d80ae5bbbbc05905adc1
0
eaglesakura/android-command-service
package com.eaglesakura.android.service; import com.eaglesakura.android.service.aidl.ICommandClientCallback; import com.eaglesakura.android.service.aidl.ICommandServerService; import com.eaglesakura.android.service.data.Payload; import com.eaglesakura.android.thread.ui.UIHandler; import com.eaglesakura.android.util.AndroidThreadUtil; import com.eaglesakura.util.LogUtil; import com.eaglesakura.util.StringUtil; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.os.RemoteException; /** * 別プロセスServiceと通信するためのインターフェース */ public abstract class CommandClient { protected final Context mContext; private ICommandServerService server; private final String id; public CommandClient(Context context) { this.mContext = context.getApplicationContext(); this.id = context.getPackageName() + "@" + getClass().getName(); } public String getId() { return id; } /** * クライアントを一意に識別するためのIDを任意に指定して生成する */ public CommandClient(Context context, String uid) { if (!StringUtil.isEmpty(uid)) { if (uid.indexOf('@') >= 0) { throw new IllegalArgumentException(); } } else { uid = getClass().getName(); } this.mContext = context.getApplicationContext(); this.id = context.getPackageName() + "@" + uid; } /** * Serviceに接続済みであればtrue */ public boolean isConnected() { return server != null; } protected ICommandServerService getServer() { return server; } protected void connectToSever(Intent intent) { AndroidThreadUtil.assertUIThread(); if (server != null) { return; } mContext.bindService(intent, connection, Context.BIND_AUTO_CREATE); } /** * 切断リクエストを送る */ public void disconnect() { AndroidThreadUtil.assertUIThread(); if (server == null) { // not connected return; } try { server.unregisterCallback(callback); } catch (Exception e) { LogUtil.log(e); } mContext.unbindService(connection); server = null; onDisconnected(); } private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, final IBinder service) { UIHandler.postUIorRun(new Runnable() { @Override public void run() { ICommandServerService newServer = ICommandServerService.Stub.asInterface(service); try { newServer.registerCallback(id, callback); } catch (RemoteException e) { throw new IllegalStateException(e); } server = newServer; onConnected(); } }); } @Override public void onServiceDisconnected(ComponentName name) { UIHandler.postUIorRun(new Runnable() { @Override public void run() { if (server != null) { server = null; onDisconnected(); } } }); } }; private ICommandClientCallback callback = new ICommandClientCallback.Stub() { @Override public Payload postToClient(String cmd, Payload payload) throws RemoteException { return onReceivedData(cmd, payload); } }; /** * サーバーにデータを送信する */ public Payload requestPostToServer(String cmd, Payload payload) throws RemoteException { if (server == null) { throw new IllegalStateException("Server not connected"); } return server.postToServer(cmd, id, payload); } /** * サーバーからのデータ取得時のハンドリングを行う * * @param cmd  処理するコマンド * @param payload 受け取ったデータペイロード */ protected Payload onReceivedData(String cmd, Payload payload) throws RemoteException { return null; } /** * サーバーに接続完了した */ protected void onConnected() { } /** * サーバーからデータ切断された */ protected void onDisconnected() { } }
src/main/java/com/eaglesakura/android/service/CommandClient.java
package com.eaglesakura.android.service; import com.eaglesakura.android.service.aidl.ICommandClientCallback; import com.eaglesakura.android.service.aidl.ICommandServerService; import com.eaglesakura.android.service.data.Payload; import com.eaglesakura.android.thread.ui.UIHandler; import com.eaglesakura.android.util.AndroidThreadUtil; import com.eaglesakura.util.LogUtil; import com.eaglesakura.util.StringUtil; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.os.RemoteException; /** * 別プロセスServiceと通信するためのインターフェース */ public abstract class CommandClient { protected final Context mContext; private ICommandServerService server; private final String id; public CommandClient(Context context) { this.mContext = context.getApplicationContext(); this.id = context.getPackageName() + "@" + getClass().getName(); } public String getId() { return id; } /** * クライアントを一意に識別するためのIDを任意に指定して生成する */ public CommandClient(Context context, String uid) { if (!StringUtil.isEmpty(uid)) { if (uid.indexOf('@') >= 0) { throw new IllegalArgumentException(); } } else { uid = getClass().getName(); } this.mContext = context.getApplicationContext(); this.id = context.getPackageName() + "@" + uid; } /** * Serviceに接続済みであればtrue */ public boolean isConnected() { return server != null; } protected ICommandServerService getServer() { return server; } protected void connectToSever(Intent intent) { AndroidThreadUtil.assertUIThread(); if (server != null) { return; } mContext.bindService(intent, connection, Context.BIND_AUTO_CREATE); } /** * 切断リクエストを送る */ public void disconnect() { AndroidThreadUtil.assertUIThread(); if (server == null) { // not connected return; } try { server.unregisterCallback(callback); } catch (Exception e) { LogUtil.log(e); } mContext.unbindService(connection); server = null; onDisconnected(); } private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, final IBinder service) { UIHandler.postUIorRun(new Runnable() { @Override public void run() { ICommandServerService newServer = ICommandServerService.Stub.asInterface(service); try { newServer.registerCallback(id, callback); } catch (RemoteException e) { throw new IllegalStateException(); } server = newServer; onConnected(); } }); } @Override public void onServiceDisconnected(ComponentName name) { UIHandler.postUIorRun(new Runnable() { @Override public void run() { if (server != null) { server = null; onDisconnected(); } } }); } }; private ICommandClientCallback callback = new ICommandClientCallback.Stub() { @Override public Payload postToClient(String cmd, Payload payload) throws RemoteException { return onReceivedData(cmd, payload); } }; /** * サーバーにデータを送信する */ public Payload requestPostToServer(String cmd, Payload payload) throws RemoteException { if (server == null) { throw new IllegalStateException("Server not connected"); } return server.postToServer(cmd, id, payload); } /** * サーバーからのデータ取得時のハンドリングを行う * * @param cmd  処理するコマンド * @param payload 受け取ったデータペイロード */ protected Payload onReceivedData(String cmd, Payload payload) throws RemoteException { return null; } /** * サーバーに接続完了した */ protected void onConnected() { } /** * サーバーからデータ切断された */ protected void onDisconnected() { } }
例外送出時の引数を追加
src/main/java/com/eaglesakura/android/service/CommandClient.java
例外送出時の引数を追加
Java
mit
fb3f2f87c73843756c2bfbb2364e55c8032d8c2f
0
elBukkit/MagicPlugin,elBukkit/MagicPlugin,elBukkit/MagicPlugin
package com.elmakers.mine.bukkit.wand; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.UUID; import java.util.logging.Level; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.elmakers.mine.bukkit.api.block.BrushMode; import com.elmakers.mine.bukkit.api.event.AddSpellEvent; import com.elmakers.mine.bukkit.api.event.SpellUpgradeEvent; import com.elmakers.mine.bukkit.api.event.WandPreActivateEvent; import com.elmakers.mine.bukkit.api.magic.MageController; import com.elmakers.mine.bukkit.api.magic.Messages; import com.elmakers.mine.bukkit.api.spell.CostReducer; import com.elmakers.mine.bukkit.api.spell.Spell; import com.elmakers.mine.bukkit.api.spell.SpellKey; import com.elmakers.mine.bukkit.api.spell.SpellTemplate; import com.elmakers.mine.bukkit.api.wand.WandTemplate; import com.elmakers.mine.bukkit.block.MaterialAndData; import com.elmakers.mine.bukkit.block.MaterialBrush; import com.elmakers.mine.bukkit.effect.builtin.EffectRing; import com.elmakers.mine.bukkit.heroes.HeroesManager; import com.elmakers.mine.bukkit.magic.BaseMagicProperties; import com.elmakers.mine.bukkit.magic.Mage; import com.elmakers.mine.bukkit.magic.MagicController; import com.elmakers.mine.bukkit.utility.ColorHD; import com.elmakers.mine.bukkit.utility.CompatibilityUtils; import com.elmakers.mine.bukkit.utility.ConfigurationUtils; import com.elmakers.mine.bukkit.utility.DeprecatedUtils; import com.elmakers.mine.bukkit.utility.InventoryUtils; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.elmakers.mine.bukkit.effect.SoundEffect; import de.slikey.effectlib.util.ParticleEffect; import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.BlockFace; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.MemoryConfiguration; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryView; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.plugin.Plugin; import org.bukkit.potion.PotionEffectType; import org.bukkit.util.Vector; public class Wand extends BaseMagicProperties implements CostReducer, com.elmakers.mine.bukkit.api.wand.Wand { public final static int INVENTORY_SIZE = 27; public final static int PLAYER_INVENTORY_SIZE = 36; public final static int HOTBAR_SIZE = 9; public final static int HOTBAR_INVENTORY_SIZE = HOTBAR_SIZE - 1; public final static float DEFAULT_SPELL_COLOR_MIX_WEIGHT = 0.0001f; public static int MAX_LORE_LENGTH = 24; public static String DEFAULT_WAND_TEMPLATE = "default"; private static int WAND_VERSION = 1; public final static String[] EMPTY_PARAMETERS = new String[0]; public final static Set<String> PROPERTY_KEYS = ImmutableSet.of( "active_spell", "active_material", "path", "template", "passive", "mana", "mana_regeneration", "mana_max", "mana_max_boost", "mana_regeneration_boost", "mana_per_damage", "bound", "soul", "has_uses", "uses", "upgrade", "indestructible", "undroppable", "consume_reduction", "cost_reduction", "cooldown_reduction", "effect_bubbles", "effect_color", "effect_particle", "effect_particle_count", "effect_particle_data", "effect_particle_interval", "effect_particle_min_velocity", "effect_particle_radius", "effect_particle_offset", "effect_sound", "effect_sound_interval", "effect_sound_pitch", "effect_sound_volume", "cast_spell", "cast_parameters", "cast_interval", "cast_min_velocity", "cast_velocity_direction", "hotbar_count", "hotbar", "icon", "icon_inactive", "icon_inactive_delay", "mode", "active_effects", "brush_mode", "keep", "locked", "quiet", "force", "randomize", "rename", "rename_description", "power", "overrides", "protection", "protection_physical", "protection_projectiles", "protection_falling", "protection_fire", "protection_explosions", "potion_effects", "materials", "spells", "powered", "protected", "heroes", "enchant_count", "max_enchant_count", "quick_cast", "left_click", "right_click", "drop", "swap", "block_fov", "block_chance", "block_reflect_chance", "block_mage_cooldown", "block_cooldown" ); private final static Set<String> HIDDEN_PROPERTY_KEYS = ImmutableSet.of( "id", "owner", "owner_id", "name", "description", "organize", "alphabetize", "fill", "stored", "upgrade_icon", "mana_timestamp", "upgrade_template", "custom_properties", // For legacy wands "haste", "health_regeneration", "hunger_regeneration", "xp", "xp_regeneration", "xp_max", "xp_max_boost", "xp_regeneration_boost", "mode_cast", "mode_drop", "version" ); /** * Set of properties that are used internally. * * Neither this list nor HIDDEN_PROPERTY_KEYS are really used anymore, but I'm keeping them * here in case we have some use for them in the future. * * Wands now load and retain any wand.* tags on their items. */ private final static Set<String> ALL_PROPERTY_KEYS_SET = Sets.union( PROPERTY_KEYS, HIDDEN_PROPERTY_KEYS); protected @Nonnull ItemStack item; /** * The currently active mage. * * Is only set when the wand is active of when the wand is * used for off-hand casting. */ protected @Nullable Mage mage; // Cached state private String id = ""; private List<Inventory> hotbars; private List<Inventory> inventories; private Map<String, Integer> spells = new HashMap<>(); private Map<String, Integer> spellLevels = new HashMap<>(); private Map<String, Integer> brushes = new HashMap<>(); private String activeSpell = ""; private String activeMaterial = ""; protected String wandName = ""; protected String description = ""; private String owner = ""; private String ownerId = ""; private String template = ""; private String path = ""; private boolean superProtected = false; private boolean superPowered = false; private boolean glow = false; private boolean soul = false; private boolean bound = false; private boolean indestructible = false; private boolean undroppable = false; private boolean keep = false; private boolean passive = false; private boolean autoOrganize = false; private boolean autoAlphabetize = false; private boolean autoFill = false; private boolean isUpgrade = false; private boolean randomize = false; private boolean rename = false; private boolean renameDescription = false; private boolean quickCast = false; private boolean quickCastDisabled = false; private boolean manualQuickCastDisabled = false; private boolean isInOffhand = false; private WandAction leftClickAction = WandAction.CAST; private WandAction rightClickAction = WandAction.TOGGLE; private WandAction dropAction = WandAction.CYCLE_HOTBAR; private WandAction swapAction = WandAction.NONE; private MaterialAndData icon = null; private MaterialAndData upgradeIcon = null; private MaterialAndData inactiveIcon = null; private int inactiveIconDelay = 0; private String upgradeTemplate = null; protected float costReduction = 0; protected float consumeReduction = 0; protected float cooldownReduction = 0; protected float damageReduction = 0; protected float damageReductionPhysical = 0; protected float damageReductionProjectiles = 0; protected float damageReductionFalling = 0; protected float damageReductionFire = 0; protected float damageReductionExplosions = 0; private float power = 0; private float blockFOV = 0; private float blockChance = 0; private float blockReflectChance = 0; private int blockMageCooldown = 0; private int blockCooldown = 0; private int maxEnchantCount = 0; private int enchantCount = 0; private boolean hasInventory = false; private boolean locked = false; private boolean forceUpgrade = false; private boolean isHeroes = false; private int uses = 0; private boolean hasUses = false; private boolean isSingleUse = false; private float mana = 0; private float manaMaxBoost = 0; private float manaRegenerationBoost = 0; private int manaRegeneration = 0; private int manaMax = 0; private long lastManaRegeneration = 0; private float manaPerDamage = 0; private int effectiveManaMax = 0; private int effectiveManaRegeneration = 0; private ColorHD effectColor = null; private float effectColorSpellMixWeight = DEFAULT_SPELL_COLOR_MIX_WEIGHT; private ParticleEffect effectParticle = null; private float effectParticleData = 0; private int effectParticleCount = 0; private int effectParticleInterval = 0; private double effectParticleMinVelocity = 0; private double effectParticleRadius = 0.2; private double effectParticleOffset = 0.3; private boolean effectBubbles = false; private boolean activeEffectsOnly = false; private EffectRing effectPlayer = null; private int castInterval = 0; private double castMinVelocity = 0; private Vector castVelocityDirection = null; private String castSpell = null; private ConfigurationSection castParameters = null; private Map<PotionEffectType, Integer> potionEffects = new HashMap<>(); private SoundEffect effectSound = null; private int effectSoundInterval = 0; private int quietLevel = 0; private Map<String, String> castOverrides = null; // Transient state private boolean effectBubblesApplied = false; private boolean hasSpellProgression = false; private long lastLocationTime; private Vector lastLocation; private long lastSoundEffect; private long lastParticleEffect; private long lastSpellCast; // Inventory functionality private WandMode mode = null; private WandMode brushMode = null; private int openInventoryPage = 0; private boolean inventoryIsOpen = false; private Inventory displayInventory = null; private int currentHotbar = 0; public static WandManaMode manaMode = WandManaMode.BAR; public static WandManaMode spMode = WandManaMode.NUMBER; public static boolean regenWhileInactive = true; public static Material DefaultUpgradeMaterial = Material.NETHER_STAR; public static Material DefaultWandMaterial = Material.BLAZE_ROD; public static Material EnchantableWandMaterial = null; public static boolean SpellGlow = false; public static boolean BrushGlow = false; public static boolean BrushItemGlow = true; public static boolean LiveHotbar = true; public static boolean LiveHotbarSkills = false; public static boolean LiveHotbarCooldown = true; public static boolean Unbreakable = false; public static boolean Undroppable = true; public static SoundEffect inventoryOpenSound = null; public static SoundEffect inventoryCloseSound = null; public static SoundEffect inventoryCycleSound = null; public static SoundEffect noActionSound = null; public static String WAND_KEY = "wand"; public static String UPGRADE_KEY = "wand_upgrade"; public static String WAND_SELF_DESTRUCT_KEY = null; public static byte HIDE_FLAGS = 60; public static String brushSelectSpell = ""; private Inventory storedInventory = null; private int storedSlot; public Wand(MagicController controller) { super(controller); hotbars = new ArrayList<>(); setHotbarCount(1); inventories = new ArrayList<>(); } /** * @deprecated Use {@link MagicController#getWand(ItemStack)}. */ @Deprecated public Wand(MagicController controller, ItemStack itemStack) { this(controller); Preconditions.checkNotNull(itemStack); if (itemStack.getType() == Material.AIR) { itemStack.setType(DefaultWandMaterial); } this.icon = new MaterialAndData(itemStack); item = itemStack; boolean needsSave = false; boolean isWand = isWand(item); boolean isUpgradeItem = isUpgrade(item); if (isWand || isUpgradeItem) { ConfigurationSection wandConfig = itemToConfig(item, new MemoryConfiguration()); int version = wandConfig.getInt("version", 0); if (version < WAND_VERSION) { migrate(version, wandConfig); needsSave = true; } load(wandConfig); } loadProperties(); // Migrate old upgrade items if ((isUpgrade || isUpgradeItem) && isWand) { needsSave = true; InventoryUtils.removeMeta(item, WAND_KEY); } if (needsSave) { saveState(); } updateName(); updateLore(); } public Wand(MagicController controller, ConfigurationSection config) { this(controller, DefaultWandMaterial, (short)0); load(config); loadProperties(); updateName(); updateLore(); saveState(); } protected Wand(MagicController controller, String templateName) throws UnknownWandException { this(controller); // Default to "default" wand if (templateName == null || templateName.length() == 0) { templateName = DEFAULT_WAND_TEMPLATE; } // Check for randomized/pre-enchanted wands int level = 0; if (templateName.contains("(")) { String levelString = templateName.substring(templateName.indexOf('(') + 1, templateName.length() - 1); try { level = Integer.parseInt(levelString); } catch (Exception ex) { throw new IllegalArgumentException(ex); } templateName = templateName.substring(0, templateName.indexOf('(')); } WandTemplate template = controller.getWandTemplate(templateName); if (template == null) { throw new UnknownWandException(templateName); } WandTemplate migrateTemplate = template.getMigrateTemplate(); if (migrateTemplate != null) { template = migrateTemplate; templateName = migrateTemplate.getKey(); } setTemplate(templateName); setProperty("version", WAND_VERSION); ConfigurationSection templateConfig = template.getConfiguration(); if (templateConfig == null) { throw new UnknownWandException(templateName); } // Load all properties loadProperties(); // Add vanilla enchantments InventoryUtils.applyEnchantments(item, templateConfig.getConfigurationSection("enchantments")); // Enchant, if an enchanting level was provided if (level > 0) { // Account for randomized locked wands boolean wasLocked = locked; locked = false; randomize(level, false, null, true); locked = wasLocked; } // Don't randomize now if set to randomize later // Otherwise, do this here so the description updates if (!randomize) { randomize(); } updateName(); updateLore(); saveState(); } public Wand(MagicController controller, Material icon, short iconData) { // This will make the Bukkit ItemStack into a real ItemStack with NBT data. this(controller, InventoryUtils.makeReal(new ItemStack(icon, 1, iconData))); saveState(); updateName(); } protected void migrate(int version, ConfigurationSection wandConfig) { // First migration, clean out wand data that matches template if (version == 0) { ConfigurationSection templateConfig = controller.getWandTemplateConfiguration(wandConfig.getString("template")); if (templateConfig != null) { Set<String> keys = templateConfig.getKeys(false); for (String key : keys) { Object templateData = templateConfig.get(key); Object wandData = wandConfig.get(key); if (wandData == null) continue; String templateString = templateData.toString(); String wandString = wandData.toString(); if (templateData instanceof List) { templateString = templateString.substring(1, templateString.length() - 1); templateString = templateString.replace(", ", ","); templateData = templateString; } if (wandString.equalsIgnoreCase(templateString)) { wandConfig.set(key, null); continue; } try { double numericValue = Double.parseDouble(wandString); double numericTemplate = Double.parseDouble(templateString); if (numericValue == numericTemplate) { wandConfig.set(key, null); continue; } } catch (NumberFormatException ex) { } if (wandData.equals(templateData)) { wandConfig.set(key, null); } } } } wandConfig.set("version", WAND_VERSION); } @Override public void load(ConfigurationSection configuration) { if (configuration != null) { setTemplate(configuration.getString("template")); } super.load(configuration); } protected void setHotbarCount(int count) { hotbars.clear(); while (hotbars.size() < count) { hotbars.add(CompatibilityUtils.createInventory(null, HOTBAR_INVENTORY_SIZE, "Wand")); } while (hotbars.size() > count) { hotbars.remove(0); } } @Override public void unenchant() { item = new ItemStack(item.getType(), 1, item.getDurability()); clear(); } public void setIcon(Material material, byte data) { setIcon(material == null ? null : new MaterialAndData(material, data)); updateIcon(); } public void updateItemIcon() { setIcon(icon); } protected void updateIcon() { if (icon != null && icon.getMaterial() != null && icon.getMaterial() != Material.AIR) { String iconKey = icon.getKey(); if (iconKey != null && iconKey.isEmpty()) { iconKey = null; } setProperty("icon", iconKey); } } @Override public void setInactiveIcon(com.elmakers.mine.bukkit.api.block.MaterialAndData materialData) { if (materialData == null) { inactiveIcon = null; } else if (materialData instanceof MaterialAndData) { inactiveIcon = ((MaterialAndData)materialData); } else { inactiveIcon = new MaterialAndData(materialData); } String inactiveIconKey = null; if (inactiveIcon != null && inactiveIcon.getMaterial() != null && inactiveIcon.getMaterial() != Material.AIR) { inactiveIconKey = inactiveIcon.getKey(); if (inactiveIconKey != null && inactiveIconKey.isEmpty()) { inactiveIconKey = null; } } setProperty("inactive_icon", inactiveIconKey); updateItemIcon(); } @Override public void setIcon(com.elmakers.mine.bukkit.api.block.MaterialAndData materialData) { if (materialData instanceof MaterialAndData) { setIcon((MaterialAndData)materialData); } else { setIcon(new MaterialAndData(materialData)); } updateIcon(); } public void setIcon(MaterialAndData materialData) { if (materialData == null || !materialData.isValid()) return; if (materialData.getMaterial() == Material.AIR || materialData.getMaterial() == null) { materialData.setMaterial(DefaultWandMaterial); } icon = materialData; if (item == null) { item = InventoryUtils.makeReal(this.icon.getItemStack(1)); } Short durability = null; if (!indestructible && !isUpgrade && icon.getMaterial().getMaxDurability() > 0) { durability = item.getDurability(); } try { if (inactiveIcon == null || (mage != null && getMode() == WandMode.INVENTORY && isInventoryOpen())) { icon.applyToItem(item); } else { inactiveIcon.applyToItem(item); } } catch (Exception ex) { controller.getLogger().log(Level.WARNING, "Unable to apply wand icon", ex); item.setType(DefaultWandMaterial); } if (durability != null) { item.setDurability(durability); } // Make indestructible // The isUpgrade checks here and above are for using custom icons in 1.9, this is a bit hacky. if ((indestructible || Unbreakable || isUpgrade) && !manaMode.useDurability()) { CompatibilityUtils.makeUnbreakable(item); } else { CompatibilityUtils.removeUnbreakable(item); } CompatibilityUtils.hideFlags(item, HIDE_FLAGS); } @Override public void makeUpgrade() { if (!isUpgrade) { isUpgrade = true; String oldName = wandName; String newName = controller.getMessages().get("wand.upgrade_name"); newName = newName.replace("$name", oldName); String newDescription = controller.getMessages().get("wand.upgrade_default_description"); if (template != null && template.length() > 0) { newDescription = controller.getMessages().get("wands." + template + ".upgrade_description", description); } setIcon(DefaultUpgradeMaterial, (byte) 0); setName(newName); setDescription(newDescription); InventoryUtils.removeMeta(item, WAND_KEY); saveState(); updateName(true); updateLore(); } } public void newId() { if (!this.isUpgrade && !this.isSingleUse) { id = UUID.randomUUID().toString(); } else { id = null; } setProperty("id", id); } public void checkId() { if ((id == null || id.length() == 0) && !this.isUpgrade) { newId(); } } @Override public String getId() { return isSingleUse ? template : id; } public float getManaRegenerationBoost() { return manaRegenerationBoost; } public float getManaMaxBoost() { return manaMaxBoost; } @Override public int getManaRegeneration() { return manaRegeneration; } @Override public int getManaMax() { return manaMax; } @Override public void setMana(float mana) { this.mana = Math.max(0, mana); setProperty("mana", this.mana); } @Override public void setManaMax(int manaMax) { this.manaMax = Math.max(0, manaMax); setProperty("mana_max", this.manaMax); } @Override public float getMana() { return mana; } @Override public void removeMana(float amount) { if (isHeroes && mage != null) { HeroesManager heroes = controller.getHeroes(); if (heroes != null) { heroes.removeMana(mage.getPlayer(), (int)Math.ceil(amount)); } } mana = Math.max(0, mana - amount); setProperty("mana", this.mana); updateMana(); } public boolean isModifiable() { return !locked; } @Override public boolean isIndestructible() { return indestructible; } @Override public boolean isUndroppable() { // Don't allow dropping wands while the inventory is open. return undroppable || isInventoryOpen(); } public boolean isUpgrade() { return isUpgrade; } public boolean usesMana() { if (isCostFree()) return false; return manaMax > 0 || isHeroes; } @Override public float getCooldownReduction() { return controller.getCooldownReduction() + cooldownReduction * controller.getMaxCooldownReduction(); } @Override public float getCostReduction() { if (isCostFree()) return 1.0f; return controller.getCostReduction() + costReduction * controller.getMaxCostReduction(); } @Override public float getConsumeReduction() { return consumeReduction; } @Override public float getCostScale() { return 1; } public void setCooldownReduction(float reduction) { cooldownReduction = reduction; setProperty("cooldown_reduction", cooldownReduction); } public boolean getHasInventory() { return hasInventory; } @Override public float getPower() { return power; } @Override public boolean isSuperProtected() { return superProtected; } @Override public boolean isSuperPowered() { return superPowered; } @Override public boolean isCostFree() { return costReduction > 1; } @Override public boolean isConsumeFree() { return consumeReduction >= 1; } @Override public boolean isCooldownFree() { return cooldownReduction > 1; } public float getDamageReduction() { return damageReduction; } public float getDamageReductionPhysical() { return damageReductionPhysical; } public float getDamageReductionProjectiles() { return damageReductionProjectiles; } public float getDamageReductionFalling() { return damageReductionFalling; } public float getDamageReductionFire() { return damageReductionFire; } public float getDamageReductionExplosions() { return damageReductionExplosions; } @Override public String getName() { return wandName; } public String getDescription() { return description; } public String getOwner() { return owner; } public String getOwnerId() { return ownerId; } @Override public long getWorth() { long worth = 0; // TODO: Item properties, brushes, etc Set<String> spells = getSpells(); for (String spellKey : spells) { SpellTemplate spell = controller.getSpellTemplate(spellKey); if (spell != null) { worth += spell.getWorth(); } } return worth; } @Override public void setName(String name) { wandName = ChatColor.stripColor(name); setProperty("name", wandName); updateName(); } public void setTemplate(String templateName) { this.template = templateName; setParent(controller.getWandTemplate(templateName)); setProperty("template", template); } @Override public String getTemplateKey() { return this.template; } @Override public boolean hasTag(String tag) { WandTemplate template = getTemplate(); return template != null && template.hasTag(tag); } @Override public com.elmakers.mine.bukkit.api.wand.WandUpgradePath getPath() { String pathKey = path; if (pathKey == null || pathKey.length() == 0) { pathKey = controller.getDefaultWandPath(); } return WandUpgradePath.getPath(pathKey); } public boolean hasPath() { return path != null && path.length() > 0; } @Override public void setDescription(String description) { this.description = description; setProperty("description", description); updateLore(); } public boolean tryToOwn(Player player) { if (ownerId == null || ownerId.length() == 0) { takeOwnership(player); return true; } return false; } public void takeOwnership(Player player) { if (mage != null && (ownerId == null || ownerId.length() == 0) && quietLevel < 2) { mage.sendMessage(getMessage("bound_instructions", "").replace("$wand", getName())); Spell spell = getActiveSpell(); if (spell != null) { String message = getMessage("spell_instructions", "").replace("$wand", getName()); mage.sendMessage(message.replace("$spell", spell.getName())); } if (spells.size() > 1) { mage.sendMessage(getMessage("inventory_instructions", "").replace("$wand", getName())); } com.elmakers.mine.bukkit.api.wand.WandUpgradePath path = getPath(); if (path != null) { String message = getMessage("enchant_instructions", "").replace("$wand", getName()); mage.sendMessage(message); } } owner = ChatColor.stripColor(player.getDisplayName()); ownerId = player.getUniqueId().toString(); setProperty("owner", owner); setProperty("owner_id", ownerId); updateLore(); } @Override public ItemStack getItem() { return item; } @Override public com.elmakers.mine.bukkit.api.block.MaterialAndData getIcon() { return icon; } @Override public com.elmakers.mine.bukkit.api.block.MaterialAndData getInactiveIcon() { return inactiveIcon; } protected List<Inventory> getAllInventories() { List<Inventory> allInventories = new ArrayList<>(inventories.size() + hotbars.size()); allInventories.addAll(hotbars); allInventories.addAll(inventories); return allInventories; } @Override public Set<String> getSpells() { return spells.keySet(); } protected String getSpellString() { Set<String> spellNames = new TreeSet<>(); for (Map.Entry<String, Integer> spellSlot : spells.entrySet()) { Integer slot = spellSlot.getValue(); String spellKey = spellSlot.getKey(); if (slot != null) { spellKey += "@" + slot; } spellNames.add(spellKey); } return StringUtils.join(spellNames, ","); } @Override public Set<String> getBrushes() { return brushes.keySet(); } protected String getMaterialString() { Set<String> materialNames = new TreeSet<>(); for (Map.Entry<String, Integer> brushSlot : brushes.entrySet()) { Integer slot = brushSlot.getValue(); String materialKey = brushSlot.getKey(); if (slot != null) { materialKey += "@" + slot; } materialNames.add(materialKey); } return StringUtils.join(materialNames, ","); } protected Integer parseSlot(String[] pieces) { Integer slot = null; if (pieces.length > 1) { try { slot = Integer.parseInt(pieces[1]); } catch (Exception ex) { slot = null; } if (slot != null && slot < 0) { slot = null; } } return slot; } protected void addToInventory(ItemStack itemStack) { if (itemStack == null || itemStack.getType() == Material.AIR) { return; } if (getBrushMode() != WandMode.INVENTORY && isBrush(itemStack)) { String brushKey = getBrush(itemStack); if (!MaterialBrush.isSpecialMaterialKey(brushKey) || MaterialBrush.isSchematic(brushKey)) { return; } } List<Inventory> checkInventories = getAllInventories(); boolean added = false; for (Inventory inventory : checkInventories) { HashMap<Integer, ItemStack> returned = inventory.addItem(itemStack); if (returned.size() == 0) { added = true; break; } } if (!added) { Inventory newInventory = CompatibilityUtils.createInventory(null, INVENTORY_SIZE, "Wand"); newInventory.addItem(itemStack); inventories.add(newInventory); } } protected Inventory getDisplayInventory() { if (displayInventory == null) { int inventorySize = INVENTORY_SIZE + HOTBAR_SIZE; displayInventory = CompatibilityUtils.createInventory(null, inventorySize, "Wand"); } return displayInventory; } protected @Nonnull Inventory getInventoryByIndex(int inventoryIndex) { // Auto create while (inventoryIndex >= inventories.size()) { inventories.add(CompatibilityUtils.createInventory(null, INVENTORY_SIZE, "Wand")); } return inventories.get(inventoryIndex); } protected int getHotbarSize() { return hotbars.size() * HOTBAR_INVENTORY_SIZE; } protected @Nonnull Inventory getInventory(int slot) { int hotbarSize = getHotbarSize(); if (slot < hotbarSize) { return hotbars.get(slot / HOTBAR_INVENTORY_SIZE); } int inventoryIndex = (slot - hotbarSize) / INVENTORY_SIZE; return getInventoryByIndex(inventoryIndex); } protected int getInventorySlot(int slot) { int hotbarSize = getHotbarSize(); if (slot < hotbarSize) { return slot % HOTBAR_INVENTORY_SIZE; } return ((slot - hotbarSize) % INVENTORY_SIZE); } protected void addToInventory(ItemStack itemStack, Integer slot) { if (slot == null) { addToInventory(itemStack); return; } Inventory inventory = getInventory(slot); slot = getInventorySlot(slot); ItemStack existing = inventory.getItem(slot); inventory.setItem(slot, itemStack); if (existing != null && existing.getType() != Material.AIR) { addToInventory(existing); } } protected void parseInventoryStrings(String spellString, String materialString) { // Force an update of the display inventory since chest mode is a different size displayInventory = null; for (Inventory hotbar : hotbars) { hotbar.clear(); } inventories.clear(); spells.clear(); spellLevels.clear(); brushes.clear(); // Support YML-List-As-String format spellString = spellString.replaceAll("[\\]\\[]", ""); String[] spellNames = StringUtils.split(spellString, ","); for (String spellName : spellNames) { String[] pieces = spellName.split("@"); Integer slot = parseSlot(pieces); // Handle aliases and upgrades smoothly String loadedKey = pieces[0].trim(); SpellKey spellKey = new SpellKey(loadedKey); SpellTemplate spell = controller.getSpellTemplate(loadedKey); // Downgrade spells if higher levels have gone missing while (spell == null && spellKey.getLevel() > 0) { spellKey = new SpellKey(spellKey.getBaseKey(), spellKey.getLevel() - 1); spell = controller.getSpellTemplate(spellKey.getKey()); } if (spell != null) { spellKey = spell.getSpellKey(); Integer currentLevel = spellLevels.get(spellKey.getBaseKey()); if (currentLevel == null || currentLevel < spellKey.getLevel()) { spellLevels.put(spellKey.getBaseKey(), spellKey.getLevel()); spells.put(spellKey.getKey(), slot); if (currentLevel != null) { SpellKey oldKey = new SpellKey(spellKey.getBaseKey(), currentLevel); spells.remove(oldKey.getKey()); } } if (activeSpell == null || activeSpell.length() == 0) { activeSpell = spellKey.getKey(); } } ItemStack itemStack = createSpellItem(spell, "", controller, getActiveMage(), this, false); if (itemStack != null) { addToInventory(itemStack, slot); } } materialString = materialString.replaceAll("[\\]\\[]", ""); String[] materialNames = StringUtils.split(materialString, ","); WandMode brushMode = getBrushMode(); for (String materialName : materialNames) { String[] pieces = materialName.split("@"); Integer slot = parseSlot(pieces); String materialKey = pieces[0].trim(); brushes.put(materialKey, slot); boolean addToInventory = brushMode == WandMode.INVENTORY || (MaterialBrush.isSpecialMaterialKey(materialKey) && !MaterialBrush.isSchematic(materialKey)); if (addToInventory) { ItemStack itemStack = createBrushIcon(materialKey); if (itemStack == null) { controller.getPlugin().getLogger().warning("Unable to create material icon for key " + materialKey); continue; } if (activeMaterial == null || activeMaterial.length() == 0) activeMaterial = materialKey; addToInventory(itemStack, slot); } } updateHasInventory(); if (openInventoryPage >= inventories.size()) { openInventoryPage = 0; } } protected ItemStack createSpellIcon(SpellTemplate spell) { return createSpellItem(spell, "", controller, getActiveMage(), this, false); } public static ItemStack createSpellItem(String spellKey, MagicController controller, Wand wand, boolean isItem) { String[] split = spellKey.split(" ", 2); return createSpellItem(controller.getSpellTemplate(split[0]), split.length > 1 ? split[1] : "", controller, wand == null ? null : wand.getActiveMage(), wand, isItem); } public static ItemStack createSpellItem(String spellKey, MagicController controller, com.elmakers.mine.bukkit.api.magic.Mage mage, Wand wand, boolean isItem) { String[] split = spellKey.split(" ", 2); return createSpellItem(controller.getSpellTemplate(split[0]), split.length > 1 ? split[1] : "", controller, mage, wand, isItem); } public static ItemStack createSpellItem(SpellTemplate spell, String args, MagicController controller, com.elmakers.mine.bukkit.api.magic.Mage mage, Wand wand, boolean isItem) { if (spell == null) return null; String iconURL = spell.getIconURL(); ItemStack itemStack = null; if (iconURL != null && controller.isUrlIconsEnabled()) { itemStack = InventoryUtils.getURLSkull(iconURL); } if (itemStack == null) { ItemStack originalItemStack = null; com.elmakers.mine.bukkit.api.block.MaterialAndData icon = spell.getIcon(); if (icon == null) { controller.getPlugin().getLogger().warning("Unable to create spell icon for " + spell.getName() + ", missing material"); return null; } try { originalItemStack = new ItemStack(icon.getMaterial(), 1, icon.getData()); itemStack = InventoryUtils.makeReal(originalItemStack); } catch (Exception ex) { itemStack = null; } if (itemStack == null) { if (icon.getMaterial() != Material.AIR) { String iconName = icon.getName(); controller.getPlugin().getLogger().warning("Unable to create spell icon for " + spell.getKey() + " with material " + iconName); } return originalItemStack; } } InventoryUtils.makeUnbreakable(itemStack); InventoryUtils.hideFlags(itemStack, (byte)63); updateSpellItem(controller.getMessages(), itemStack, spell, args, mage, wand, wand == null ? null : wand.activeMaterial, isItem); return itemStack; } protected ItemStack createBrushIcon(String materialKey) { return createBrushItem(materialKey, controller, this, false); } public static ItemStack createBrushItem(String materialKey, com.elmakers.mine.bukkit.api.magic.MageController controller, Wand wand, boolean isItem) { MaterialBrush brushData = MaterialBrush.parseMaterialKey(materialKey); if (brushData == null) return null; ItemStack itemStack = brushData.getItem(controller, isItem); if (BrushGlow || (isItem && BrushItemGlow)) { CompatibilityUtils.addGlow(itemStack); } InventoryUtils.makeUnbreakable(itemStack); InventoryUtils.hideFlags(itemStack, (byte)63); updateBrushItem(controller.getMessages(), itemStack, brushData, wand); return itemStack; } public void checkItem(ItemStack newItem) { if (newItem.getAmount() > item.getAmount()) { item.setAmount(newItem.getAmount()); } } protected boolean findItem() { if (mage != null) { Player player = mage.getPlayer(); if (player != null) { ItemStack itemInHand = player.getInventory().getItemInMainHand(); String itemId = getWandId(itemInHand); if (itemId != null && itemId.equals(id) && itemInHand != item) { item = itemInHand; return true; } itemInHand = player.getInventory().getItemInOffHand(); itemId = getWandId(itemInHand); if (itemId != null && itemId.equals(id) && itemInHand != item) { item = itemInHand; return true; } } } return false; } @Override public void saveState() { // Make sure we're on the current item instance if (findItem()) { updateItemIcon(); updateName(); updateLore(); } if (item == null || item.getType() == Material.AIR) return; // Check for upgrades that still have wand data if (isUpgrade && isWand(item)) { InventoryUtils.removeMeta(item, WAND_KEY); } Object wandNode = InventoryUtils.createNode(item, isUpgrade ? UPGRADE_KEY : WAND_KEY); if (wandNode == null) { controller.getLogger().warning("Failed to save wand state for wand to : " + item); Thread.dumpStack(); } else { InventoryUtils.saveTagsToNBT(getConfiguration(), wandNode); } if (mage != null) { Player player = mage.getPlayer(); if (player != null) { // Update the stored item, too- in case we save while the // inventory is open. if (storedInventory != null) { int currentSlot = player.getInventory().getHeldItemSlot(); ItemStack storedItem = storedInventory.getItem(currentSlot); String storedId = getWandId(storedItem); if (storedId != null && storedId.equals(id)) { storedInventory.setItem(currentSlot, item); } } } } } public static ConfigurationSection itemToConfig(ItemStack item, ConfigurationSection stateNode) { Object wandNode = InventoryUtils.getNode(item, WAND_KEY); if (wandNode == null) { wandNode = InventoryUtils.getNode(item, UPGRADE_KEY); if (wandNode == null) { return null; } } InventoryUtils.loadAllTagsFromNBT(stateNode, wandNode); return stateNode; } public static void configToItem(ConfigurationSection itemSection, ItemStack item) { ConfigurationSection stateNode = itemSection.getConfigurationSection("wand"); Object wandNode = InventoryUtils.createNode(item, Wand.WAND_KEY); if (wandNode != null) { InventoryUtils.saveTagsToNBT(stateNode, wandNode); } } protected String getPotionEffectString() { return getPotionEffectString(potionEffects); } @Override public void save(ConfigurationSection node, boolean filtered) { ConfigurationUtils.addConfigurations(node, getConfiguration()); // Filter out some fields if (filtered) { node.set("id", null); node.set("owner_id", null); node.set("owner", null); node.set("template", null); node.set("mana_timestamp", null); // Inherit from template if present if (template != null && !template.isEmpty()) { node.set("inherit", template); } } if (isUpgrade) { node.set("upgrade", true); } // Change some CSV to lists if (node.contains("spells") && node.isString("spells")) { node.set("spells", Arrays.asList(StringUtils.split(node.getString("spells"), ","))); } if (node.contains("materials") && node.isString("materials")) { node.set("materials", Arrays.asList(StringUtils.split(node.getString("materials"), ","))); } if (node.contains("overrides") && node.isString("overrides")) { node.set("overrides", Arrays.asList(StringUtils.split(node.getString("overrides"), ","))); } if (node.contains("potion_effects") && node.isString("potion_effects")) { node.set("potion_effects", Arrays.asList(StringUtils.split(node.getString("potion_effects"), ","))); } } public void updateBrushes() { setProperty("materials", getMaterialString()); } public void updateSpells() { setProperty("spells", getSpellString()); } public void setEffectColor(String hexColor) { // Annoying config conversion issue :\ if (hexColor.contains(".")) { hexColor = hexColor.substring(0, hexColor.indexOf('.')); } if (hexColor == null || hexColor.length() == 0 || hexColor.equals("none")) { effectColor = null; return; } effectColor = new ColorHD(hexColor); if (hexColor.equals("random")) { setProperty("effect_color", effectColor.toString()); } } public void loadProperties() { loadProperties(getEffectiveConfiguration()); } public void loadProperties(ConfigurationSection wandConfig) { locked = wandConfig.getBoolean("locked", locked); consumeReduction = (float)wandConfig.getDouble("consume_reduction"); costReduction = (float)wandConfig.getDouble("cost_reduction"); cooldownReduction = (float)wandConfig.getDouble("cooldown_reduction"); power = (float)wandConfig.getDouble("power"); damageReduction = (float)wandConfig.getDouble("protection"); damageReductionPhysical = (float)wandConfig.getDouble("protection_physical"); damageReductionProjectiles = (float)wandConfig.getDouble("protection_projectiles"); damageReductionFalling = (float)wandConfig.getDouble("protection_falling"); damageReductionFire = (float)wandConfig.getDouble("protection_fire"); damageReductionExplosions = (float)wandConfig.getDouble("protection_explosions"); blockChance = (float)wandConfig.getDouble("block_chance"); blockReflectChance = (float)wandConfig.getDouble("block_reflect_chance"); blockFOV = (float)wandConfig.getDouble("block_fov"); blockMageCooldown = wandConfig.getInt("block_mage_cooldown"); blockCooldown = wandConfig.getInt("block_cooldown"); manaRegeneration = wandConfig.getInt("mana_regeneration", wandConfig.getInt("xp_regeneration")); manaMax = wandConfig.getInt("mana_max", wandConfig.getInt("xp_max")); mana = wandConfig.getInt("mana", wandConfig.getInt("xp")); manaMaxBoost = (float)wandConfig.getDouble("mana_max_boost", wandConfig.getDouble("xp_max_boost")); manaRegenerationBoost = (float)wandConfig.getDouble("mana_regeneration_boost", wandConfig.getDouble("xp_regeneration_boost")); manaPerDamage = (float)wandConfig.getDouble("mana_per_damage"); // Check for single-use wands uses = wandConfig.getInt("uses"); String tempId = wandConfig.getString("id", id); isSingleUse = (tempId == null || tempId.isEmpty()) && uses == 1; hasUses = wandConfig.getBoolean("has_uses", hasUses) || uses > 0; // Convert some legacy properties to potion effects float healthRegeneration = (float)wandConfig.getDouble("health_regeneration", 0); float hungerRegeneration = (float)wandConfig.getDouble("hunger_regeneration", 0); float speedIncrease = (float)wandConfig.getDouble("haste", 0); if (speedIncrease > 0) { potionEffects.put(PotionEffectType.SPEED, 1); } if (healthRegeneration > 0) { potionEffects.put(PotionEffectType.REGENERATION, 1); } if (hungerRegeneration > 0) { potionEffects.put(PotionEffectType.SATURATION, 1); } if (regenWhileInactive) { lastManaRegeneration = wandConfig.getLong("mana_timestamp"); } else { lastManaRegeneration = System.currentTimeMillis(); } if (wandConfig.contains("effect_color")) { setEffectColor(wandConfig.getString("effect_color")); } id = wandConfig.getString("id", id); isUpgrade = wandConfig.getBoolean("upgrade", isUpgrade); quietLevel = wandConfig.getInt("quiet", quietLevel); effectBubbles = wandConfig.getBoolean("effect_bubbles", effectBubbles); keep = wandConfig.getBoolean("keep", keep); passive = wandConfig.getBoolean("passive", passive); indestructible = wandConfig.getBoolean("indestructible", indestructible); superPowered = wandConfig.getBoolean("powered", superPowered); superProtected = wandConfig.getBoolean("protected", superProtected); glow = wandConfig.getBoolean("glow", glow); undroppable = wandConfig.getBoolean("undroppable", undroppable); isHeroes = wandConfig.getBoolean("heroes", isHeroes); bound = wandConfig.getBoolean("bound", bound); soul = wandConfig.getBoolean("soul", soul); forceUpgrade = wandConfig.getBoolean("force", forceUpgrade); autoOrganize = wandConfig.getBoolean("organize", autoOrganize); autoAlphabetize = wandConfig.getBoolean("alphabetize", autoAlphabetize); autoFill = wandConfig.getBoolean("fill", autoFill); randomize = wandConfig.getBoolean("randomize", randomize); rename = wandConfig.getBoolean("rename", rename); renameDescription = wandConfig.getBoolean("rename_description", renameDescription); enchantCount = wandConfig.getInt("enchant_count", enchantCount); maxEnchantCount = wandConfig.getInt("max_enchant_count", maxEnchantCount); if (wandConfig.contains("effect_particle")) { effectParticle = ConfigurationUtils.toParticleEffect(wandConfig.getString("effect_particle")); effectParticleData = 0; } if (wandConfig.contains("effect_sound")) { effectSound = ConfigurationUtils.toSoundEffect(wandConfig.getString("effect_sound")); } activeEffectsOnly = wandConfig.getBoolean("active_effects", activeEffectsOnly); effectParticleData = (float)wandConfig.getDouble("effect_particle_data", effectParticleData); effectParticleCount = wandConfig.getInt("effect_particle_count", effectParticleCount); effectParticleRadius = wandConfig.getDouble("effect_particle_radius", effectParticleRadius); effectParticleOffset = wandConfig.getDouble("effect_particle_offset", effectParticleOffset); effectParticleInterval = wandConfig.getInt("effect_particle_interval", effectParticleInterval); effectParticleMinVelocity = wandConfig.getDouble("effect_particle_min_velocity", effectParticleMinVelocity); effectSoundInterval = wandConfig.getInt("effect_sound_interval", effectSoundInterval); castInterval = wandConfig.getInt("cast_interval", castInterval); castMinVelocity = wandConfig.getDouble("cast_min_velocity", castMinVelocity); castVelocityDirection = ConfigurationUtils.getVector(wandConfig, "cast_velocity_direction", castVelocityDirection); castSpell = wandConfig.getString("cast_spell", castSpell); String castParameterString = wandConfig.getString("cast_parameters", null); if (castParameterString != null && !castParameterString.isEmpty()) { castParameters = new MemoryConfiguration(); ConfigurationUtils.addParameters(StringUtils.split(castParameterString, " "), castParameters); } boolean needsInventoryUpdate = false; if (wandConfig.contains("mode")) { WandMode newMode = parseWandMode(wandConfig.getString("mode"), mode); if (newMode != mode) { setMode(newMode); needsInventoryUpdate = true; } } if (wandConfig.contains("brush_mode")) { setBrushMode(parseWandMode(wandConfig.getString("brush_mode"), brushMode)); } String quickCastType = wandConfig.getString("quick_cast", wandConfig.getString("mode_cast")); if (quickCastType != null) { if (quickCastType.equalsIgnoreCase("true")) { quickCast = true; // This is to turn the redundant spell lore off quickCastDisabled = true; manualQuickCastDisabled = false; } else if (quickCastType.equalsIgnoreCase("manual")) { quickCast = false; quickCastDisabled = true; manualQuickCastDisabled = false; } else if (quickCastType.equalsIgnoreCase("disable")) { quickCast = false; quickCastDisabled = true; manualQuickCastDisabled = true; } else { quickCast = false; quickCastDisabled = false; manualQuickCastDisabled = false; } } // Backwards compatibility if (wandConfig.getBoolean("mode_drop", false)) { dropAction = WandAction.TOGGLE; swapAction = WandAction.CYCLE_HOTBAR; rightClickAction = WandAction.NONE; } else if (mode == WandMode.CAST) { leftClickAction = WandAction.CAST; rightClickAction = WandAction.CAST; swapAction = WandAction.NONE; dropAction = WandAction.NONE; } leftClickAction = parseWandAction(wandConfig.getString("left_click"), leftClickAction); rightClickAction = parseWandAction(wandConfig.getString("right_click"), rightClickAction); dropAction = parseWandAction(wandConfig.getString("drop"), dropAction); swapAction = parseWandAction(wandConfig.getString("swap"), swapAction); owner = wandConfig.getString("owner", owner); ownerId = wandConfig.getString("owner_id", ownerId); template = wandConfig.getString("template", template); upgradeTemplate = wandConfig.getString("upgrade_template", upgradeTemplate); path = wandConfig.getString("path", path); activeSpell = wandConfig.getString("active_spell", activeSpell); activeMaterial = wandConfig.getString("active_material", activeMaterial); String wandMaterials = ""; String wandSpells = ""; if (wandConfig.contains("hotbar_count")) { int newCount = Math.max(1, wandConfig.getInt("hotbar_count")); if (newCount != hotbars.size() || newCount > hotbars.size()) { if (isInventoryOpen()) { closeInventory(); } needsInventoryUpdate = true; setHotbarCount(newCount); } } if (wandConfig.contains("hotbar")) { int hotbar = wandConfig.getInt("hotbar"); currentHotbar = hotbar < 0 || hotbar >= hotbars.size() ? 0 : hotbar; } // Default to template names, override with localizations and finally with wand data wandName = controller.getMessages().get("wand.default_name"); description = ""; // Check for migration information in the template config ConfigurationSection templateConfig = null; if (template != null && !template.isEmpty()) { templateConfig = controller.getWandTemplateConfiguration(template); if (templateConfig != null) { wandName = templateConfig.getString("name", wandName); description = templateConfig.getString("description", description); } wandName = controller.getMessages().get("wands." + template + ".name", wandName); description = controller.getMessages().get("wands." + template + ".description", description); } wandName = wandConfig.getString("name", wandName); description = wandConfig.getString("description", description); WandTemplate wandTemplate = getTemplate(); WandTemplate migrateTemplate = wandTemplate == null ? null : wandTemplate.getMigrateTemplate(); if (migrateTemplate != null) { template = migrateTemplate.getKey(); templateConfig = migrateTemplate.getConfiguration(); wandTemplate = migrateTemplate; } if (wandTemplate != null) { // Add vanilla attributes InventoryUtils.applyAttributes(item, wandTemplate.getAttributes(), wandTemplate.getAttributeSlot()); } if (wandConfig.contains("icon_inactive")) { String iconKey = wandConfig.getString("icon_inactive"); if (wandTemplate != null) { iconKey = wandTemplate.migrateIcon(iconKey); } if (iconKey != null) { inactiveIcon = new MaterialAndData(iconKey); } } if (inactiveIcon != null && (inactiveIcon.getMaterial() == null || inactiveIcon.getMaterial() == Material.AIR)) { inactiveIcon = null; } inactiveIconDelay = wandConfig.getInt("icon_inactive_delay", inactiveIconDelay); if (wandConfig.contains("randomize_icon")) { setIcon(new MaterialAndData(wandConfig.getString("randomize_icon"))); randomize = true; } else if (!randomize && wandConfig.contains("icon")) { String iconKey = wandConfig.getString("icon"); if (wandTemplate != null) { iconKey = wandTemplate.migrateIcon(iconKey); } if (iconKey.contains(",")) { Random r = new Random(); String[] keys = StringUtils.split(iconKey, ','); iconKey = keys[r.nextInt(keys.length)]; } // Port old custom wand icons if (templateConfig != null && iconKey.contains("i.imgur.com")) { iconKey = templateConfig.getString("icon"); } setIcon(new MaterialAndData(iconKey)); } else if (isUpgrade) { setIcon(new MaterialAndData(DefaultUpgradeMaterial)); } if (wandConfig.contains("upgrade_icon")) { upgradeIcon = new MaterialAndData(wandConfig.getString("upgrade_icon")); } // Check for path-based migration, may update icons com.elmakers.mine.bukkit.api.wand.WandUpgradePath upgradePath = getPath(); if (upgradePath != null) { hasSpellProgression = upgradePath.getSpells().size() > 0 || upgradePath.getExtraSpells().size() > 0 || upgradePath.getRequiredSpells().size() > 0; upgradePath.checkMigration(this); } else { hasSpellProgression = false; } // Load spells if (needsInventoryUpdate) { // Force a re-parse of materials and spells wandSpells = getSpellString(); wandMaterials = getMaterialString(); } wandMaterials = wandConfig.getString("materials", wandMaterials); wandSpells = wandConfig.getString("spells", wandSpells); if (wandMaterials.length() > 0 || wandSpells.length() > 0) { wandMaterials = wandMaterials.length() == 0 ? getMaterialString() : wandMaterials; wandSpells = wandSpells.length() == 0 ? getSpellString() : wandSpells; parseInventoryStrings(wandSpells, wandMaterials); } if (wandConfig.contains("overrides")) { castOverrides = null; String overrides = wandConfig.getString("overrides", null); if (overrides != null && !overrides.isEmpty()) { // Support YML-List-As-String format overrides = overrides.replaceAll("[\\]\\[]", ""); castOverrides = new HashMap<>(); String[] pairs = StringUtils.split(overrides, ','); for (String pair : pairs) { // Unescape commas pair = pair.replace("\\|", ","); String[] keyValue = StringUtils.split(pair, " "); if (keyValue.length > 0) { String value = keyValue.length > 1 ? keyValue[1] : ""; castOverrides.put(keyValue[0], value); } } } } if (wandConfig.contains("potion_effects")) { potionEffects.clear(); addPotionEffects(potionEffects, wandConfig.getString("potion_effects", null)); } // Some cleanup and sanity checks. In theory we don't need to store any non-zero value (as it is with the traders) // so try to keep defaults as 0/0.0/false. if (effectSound == null) { effectSoundInterval = 0; } else { effectSoundInterval = (effectSoundInterval == 0) ? 5 : effectSoundInterval; } if (effectParticle == null) { effectParticleInterval = 0; } updateMaxMana(false); checkActiveMaterial(); } @Override public void describe(CommandSender sender) { Object wandNode = InventoryUtils.getNode(item, WAND_KEY); boolean isUpgrade = false; if (wandNode == null) { isUpgrade = true; wandNode = InventoryUtils.getNode(item, UPGRADE_KEY); } if (wandNode == null) { sender.sendMessage("Found a wand with missing NBT data. This may be an old wand, or something may have wiped its data"); return; } ChatColor wandColor = isModifiable() ? ChatColor.AQUA : ChatColor.RED; sender.sendMessage(wandColor + wandName); if (isUpgrade) { sender.sendMessage(ChatColor.YELLOW + "(Upgrade)"); } if (description.length() > 0) { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.GREEN + description); } else { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.GREEN + "(No Description)"); } if (owner.length() > 0 || ownerId.length() > 0) { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.WHITE + owner + " (" + ChatColor.GRAY + ownerId + ChatColor.WHITE + ")"); } else { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.WHITE + "(No Owner)"); } for (String key : PROPERTY_KEYS) { String value = InventoryUtils.getMetaString(wandNode, key); if (value != null && value.length() > 0) { sender.sendMessage(key + ": " + value); } } ConfigurationSection templateConfig = controller.getWandTemplateConfiguration(template); if (templateConfig != null) { sender.sendMessage("" + ChatColor.BOLD + ChatColor.GREEN + "Template Configuration:"); for (String key : PROPERTY_KEYS) { String value = templateConfig.getString(key); if (value != null && value.length() > 0) { sender.sendMessage(key + ": " + value); } } } } private static String getBrushDisplayName(Messages messages, MaterialBrush brush) { String materialName = brush == null ? null : brush.getName(messages); if (materialName == null) { materialName = "none"; } return ChatColor.GRAY + materialName; } private static String getSpellDisplayName(Messages messages, SpellTemplate spell, MaterialBrush brush) { String name = ""; if (spell != null) { if (brush != null && spell.usesBrush()) { name = ChatColor.GOLD + spell.getName() + " " + getBrushDisplayName(messages, brush) + ChatColor.WHITE; } else { name = ChatColor.GOLD + spell.getName() + ChatColor.WHITE; } } return name; } private String getActiveWandName(SpellTemplate spell, MaterialBrush brush) { // Build wand name int remaining = getRemainingUses(); ChatColor wandColor = (hasUses && remaining <= 1) ? ChatColor.DARK_RED : isModifiable() ? (bound ? ChatColor.DARK_AQUA : ChatColor.AQUA) : (path != null && path.length() > 0 ? ChatColor.LIGHT_PURPLE : ChatColor.GOLD); String name = wandColor + getDisplayName(); if (randomize) return name; Set<String> spells = getSpells(); // Add active spell to description Messages messages = controller.getMessages(); boolean showSpell = isModifiable() && hasSpellProgression(); showSpell = !quickCast && (spells.size() > 1 || showSpell); if (spell != null && showSpell) { name = getSpellDisplayName(messages, spell, brush) + " (" + name + ChatColor.WHITE + ")"; } if (remaining > 1) { String message = getMessage("uses_remaining_brief"); name = name + ChatColor.DARK_RED + " (" + ChatColor.RED + message.replace("$count", ((Integer)remaining).toString()) + ChatColor.DARK_RED + ")"; } return name; } private String getActiveWandName(SpellTemplate spell) { return getActiveWandName(spell, MaterialBrush.parseMaterialKey(activeMaterial)); } private String getActiveWandName(MaterialBrush brush) { SpellTemplate spell = null; if (activeSpell != null && activeSpell.length() > 0) { spell = controller.getSpellTemplate(activeSpell); } return getActiveWandName(spell, brush); } private String getActiveWandName() { SpellTemplate spell = null; if (activeSpell != null && activeSpell.length() > 0) { spell = controller.getSpellTemplate(activeSpell); } return getActiveWandName(spell); } protected String getDisplayName() { return ChatColor.translateAlternateColorCodes('&', randomize ? getMessage("randomized_name") : wandName); } public void updateName(boolean isActive) { if (isActive) { CompatibilityUtils.setDisplayName(item, !isUpgrade ? getActiveWandName() : ChatColor.GOLD + getDisplayName()); } else { CompatibilityUtils.setDisplayName(item, ChatColor.stripColor(getDisplayName())); } // Reset Enchantment glow if (glow) { CompatibilityUtils.addGlow(item); } } private void updateName() { updateName(true); } protected static String convertToHTML(String line) { int tagCount = 1; line = "<span style=\"color:white\">" + line; for (ChatColor c : ChatColor.values()) { tagCount += StringUtils.countMatches(line, c.toString()); String replaceStyle = ""; if (c == ChatColor.ITALIC) { replaceStyle = "font-style: italic"; } else if (c == ChatColor.BOLD) { replaceStyle = "font-weight: bold"; } else if (c == ChatColor.UNDERLINE) { replaceStyle = "text-decoration: underline"; } else { String color = c.name().toLowerCase().replace("_", ""); if (c == ChatColor.LIGHT_PURPLE) { color = "mediumpurple"; } replaceStyle = "color:" + color; } line = line.replace(c.toString(), "<span style=\"" + replaceStyle + "\">"); } for (int i = 0; i < tagCount; i++) { line += "</span>"; } return line; } public String getHTMLDescription() { Collection<String> rawLore = getLore(); Collection<String> lore = new ArrayList<>(); lore.add("<h2>" + convertToHTML(getActiveWandName()) + "</h2>"); for (String line : rawLore) { lore.add(convertToHTML(line)); } return "<div style=\"background-color: black; margin: 8px; padding: 8px\">" + StringUtils.join(lore, "<br/>") + "</div>"; } protected List<String> getLore() { return getLore(getSpells().size(), getBrushes().size()); } protected void addPropertyLore(List<String> lore) { if (usesMana()) { if (effectiveManaMax != manaMax) { String fullMessage = getLevelString(controller.getMessages(), "wand.mana_amount_boosted", manaMax, controller.getMaxMana()); lore.add(ChatColor.LIGHT_PURPLE + "" + ChatColor.ITALIC + fullMessage.replace("$mana", Integer.toString(effectiveManaMax))); } else { lore.add(ChatColor.LIGHT_PURPLE + "" + ChatColor.ITALIC + getLevelString(controller.getMessages(), "wand.mana_amount", manaMax, controller.getMaxMana())); } if (manaRegeneration > 0) { if (effectiveManaRegeneration != manaRegeneration) { String fullMessage = getLevelString(controller.getMessages(), "wand.mana_regeneration_boosted", manaRegeneration, controller.getMaxManaRegeneration()); lore.add(ChatColor.LIGHT_PURPLE + "" + ChatColor.ITALIC + fullMessage.replace("$mana", Integer.toString(effectiveManaRegeneration))); } else { lore.add(ChatColor.RESET + "" + ChatColor.LIGHT_PURPLE + getLevelString(controller.getMessages(), "wand.mana_regeneration", manaRegeneration, controller.getMaxManaRegeneration())); } } if (manaPerDamage > 0) { lore.add(ChatColor.DARK_RED + "" + ChatColor.ITALIC + getLevelString(controller.getMessages(), "wand.mana_per_damage", manaPerDamage, controller.getMaxManaRegeneration())); } } if (superPowered) { lore.add(ChatColor.DARK_AQUA + getMessage("super_powered")); } if (blockReflectChance > 0) { lore.add(ChatColor.AQUA + getLevelString(controller.getMessages(), "wand.reflect_chance", blockReflectChance)); } else if (blockChance != 0) { lore.add(ChatColor.AQUA + getLevelString(controller.getMessages(), "wand.block_chance", blockChance)); } if (manaMaxBoost != 0) { lore.add(ChatColor.LIGHT_PURPLE + "" + ChatColor.ITALIC + getPercentageString(controller.getMessages(), "wand.mana_boost", manaMaxBoost)); } if (manaRegenerationBoost != 0) { lore.add(ChatColor.LIGHT_PURPLE + "" + ChatColor.ITALIC + getPercentageString(controller.getMessages(), "wand.mana_regeneration_boost", manaRegenerationBoost)); } if (castSpell != null) { SpellTemplate spell = controller.getSpellTemplate(castSpell); if (spell != null) { lore.add(ChatColor.AQUA + getMessage("spell_aura").replace("$spell", spell.getName())); } } for (Map.Entry<PotionEffectType, Integer> effect : potionEffects.entrySet()) { lore.add(ChatColor.AQUA + describePotionEffect(effect.getKey(), effect.getValue())); } if (consumeReduction > 0) lore.add(ChatColor.AQUA + getLevelString(controller.getMessages(), "wand.consume_reduction", consumeReduction)); if (costReduction > 0) lore.add(ChatColor.AQUA + getLevelString(controller.getMessages(), "wand.cost_reduction", costReduction)); if (cooldownReduction > 0) lore.add(ChatColor.AQUA + getLevelString(controller.getMessages(), "wand.cooldown_reduction", cooldownReduction)); if (power > 0) lore.add(ChatColor.AQUA + getLevelString(controller.getMessages(), "wand.power", power)); if (superProtected) { lore.add(ChatColor.DARK_AQUA + getMessage("super_protected")); } else { if (damageReduction > 0) lore.add(ChatColor.AQUA + getLevelString(controller.getMessages(), "wand.protection", damageReduction)); if (damageReductionPhysical > 0) lore.add(ChatColor.AQUA + getLevelString(controller.getMessages(), "wand.protection_physical", damageReductionPhysical)); if (damageReductionProjectiles > 0) lore.add(ChatColor.AQUA + getLevelString(controller.getMessages(), "wand.protection_projectile", damageReductionProjectiles)); if (damageReductionFalling > 0) lore.add(ChatColor.AQUA + getLevelString(controller.getMessages(), "wand.protection_fall", damageReductionFalling)); if (damageReductionFire > 0) lore.add(ChatColor.AQUA + getLevelString(controller.getMessages(), "wand.protection_fire", damageReductionFire)); if (damageReductionExplosions > 0) lore.add(ChatColor.AQUA + getLevelString(controller.getMessages(), "wand.protection_blast", damageReductionExplosions)); } } public static String getLevelString(Messages messages, String templateName, float amount) { return messages.getLevelString(templateName, amount); } public static String getLevelString(Messages messages, String templateName, float amount, float max) { return messages.getLevelString(templateName, amount, max); } public static String getPercentageString(Messages messages, String templateName, float amount) { return messages.getPercentageString(templateName, amount); } protected List<String> getLore(int spellCount, int materialCount) { List<String> lore = new ArrayList<>(); if (description.length() > 0) { if (description.contains("$path")) { String pathName = "Unknown"; com.elmakers.mine.bukkit.api.wand.WandUpgradePath path = getPath(); if (path != null) { pathName = path.getName(); } String description = this.description; description = description.replace("$path", pathName); InventoryUtils.wrapText(ChatColor.ITALIC + "" + ChatColor.GREEN, description, MAX_LORE_LENGTH, lore); } else if (description.contains("$")) { String randomDescription = getMessage("randomized_lore"); if (randomDescription.length() > 0) { InventoryUtils.wrapText(ChatColor.ITALIC + "" + ChatColor.DARK_GREEN, randomDescription, MAX_LORE_LENGTH, lore); } } else { InventoryUtils.wrapText(ChatColor.ITALIC + "" + ChatColor.GREEN, description, MAX_LORE_LENGTH, lore); } } if (randomize) { return lore; } if (!isUpgrade) { if (owner.length() > 0) { if (bound) { if (soul) { String ownerDescription = getMessage("soulbound_description", "$name").replace("$name", owner); lore.add(ChatColor.ITALIC + "" + ChatColor.DARK_AQUA + ownerDescription); } else { String ownerDescription = getMessage("bound_description", "$name").replace("$name", owner); lore.add(ChatColor.ITALIC + "" + ChatColor.DARK_AQUA + ownerDescription); } } else { String ownerDescription = getMessage("owner_description", "$name").replace("$name", owner); lore.add(ChatColor.ITALIC + "" + ChatColor.DARK_GREEN + ownerDescription); } } } SpellTemplate spell = controller.getSpellTemplate(activeSpell); Messages messages = controller.getMessages(); // This is here specifically for a wand that only has // one spell now, but may get more later. Since you // can't open the inventory in this state, you can not // otherwise see the spell lore. if (spell != null && spellCount == 1 && !hasInventory && !isUpgrade) { addSpellLore(messages, spell, lore, getActiveMage(), this); } if (materialCount == 1 && activeMaterial != null && activeMaterial.length() > 0) { lore.add(getBrushDisplayName(messages, MaterialBrush.parseMaterialKey(activeMaterial))); } if (spellCount > 0) { if (isUpgrade) { lore.add(getMessage("upgrade_spell_count").replace("$count", ((Integer)spellCount).toString())); } else if (spellCount > 1) { lore.add(getMessage("spell_count").replace("$count", ((Integer)spellCount).toString())); } } if (materialCount > 0) { if (isUpgrade) { lore.add(getMessage("upgrade_material_count").replace("$count", ((Integer)materialCount).toString())); } else if (materialCount > 1) { lore.add(getMessage("material_count").replace("$count", ((Integer)materialCount).toString())); } } int remaining = getRemainingUses(); if (remaining > 0) { if (isUpgrade) { String message = (remaining == 1) ? getMessage("upgrade_uses_singular") : getMessage("upgrade_uses"); lore.add(ChatColor.RED + message.replace("$count", ((Integer)remaining).toString())); } else { String message = (remaining == 1) ? getMessage("uses_remaining_singular") : getMessage("uses_remaining_brief"); lore.add(ChatColor.RED + message.replace("$count", ((Integer)remaining).toString())); } } addPropertyLore(lore); if (isUpgrade) { lore.add(ChatColor.YELLOW + getMessage("upgrade_item_description")); } return lore; } protected void updateLore() { CompatibilityUtils.setLore(item, getLore()); if (glow) { CompatibilityUtils.addGlow(item); } } public void save() { saveState(); updateName(); updateLore(); } public int getRemainingUses() { return uses; } public void makeEnchantable(boolean enchantable) { if (EnchantableWandMaterial == null) return; if (!enchantable) { item.setType(icon.getMaterial()); item.setDurability(icon.getData()); } else { Set<Material> enchantableMaterials = controller.getMaterialSet("enchantable"); if (!enchantableMaterials.contains(item.getType())) { item.setType(EnchantableWandMaterial); item.setDurability((short)0); } } updateName(); } public static boolean hasActiveWand(Player player) { if (player == null) return false; ItemStack activeItem = player.getInventory().getItemInMainHand(); return isWand(activeItem); } public static Wand getActiveWand(MagicController controller, Player player) { ItemStack activeItem = player.getInventory().getItemInMainHand(); if (isWand(activeItem)) { return controller.getWand(activeItem); } return null; } public static boolean isWand(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, WAND_KEY); } public static boolean isWandOrUpgrade(ItemStack item) { return isWand(item) || isUpgrade(item); } public static boolean isSpecial(ItemStack item) { return isWand(item) || isUpgrade(item) || isSpell(item) || isBrush(item) || isSP(item); } public static boolean isBound(ItemStack item) { Object wandSection = InventoryUtils.getNode(item, WAND_KEY); if (wandSection == null) return false; String boundValue = InventoryUtils.getMetaString(wandSection, "bound"); return boundValue != null && boundValue.equalsIgnoreCase("true"); } public static boolean isSelfDestructWand(ItemStack item) { return item != null && WAND_SELF_DESTRUCT_KEY != null && InventoryUtils.hasMeta(item, WAND_SELF_DESTRUCT_KEY); } public static boolean isSP(ItemStack item) { return InventoryUtils.hasMeta(item, "sp"); } public static Integer getSP(ItemStack item) { if (InventoryUtils.isEmpty(item)) return null; String spNode = InventoryUtils.getMetaString(item, "sp"); if (spNode == null) return null; Integer sp = null; try { sp = Integer.parseInt(spNode); } catch (Exception ex) { sp = null; } return sp; } public static boolean isSingleUse(ItemStack item) { if (InventoryUtils.isEmpty(item)) return false; Object wandNode = InventoryUtils.getNode(item, WAND_KEY); if (wandNode == null) return false; String useCount = InventoryUtils.getMetaString(wandNode, "uses"); String wandId = InventoryUtils.getMetaString(wandNode, "id"); return useCount != null && useCount.equals("1") && (wandId == null || wandId.isEmpty()); } public static boolean isUpgrade(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, UPGRADE_KEY); } public static boolean isSpell(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, "spell"); } public static boolean isSkill(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, "skill"); } public static boolean isBrush(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, "brush"); } protected static Object getWandOrUpgradeNode(ItemStack item) { if (InventoryUtils.isEmpty(item)) return null; Object wandNode = InventoryUtils.getNode(item, WAND_KEY); if (wandNode == null) { wandNode = InventoryUtils.getNode(item, UPGRADE_KEY); } return wandNode; } public static String getWandTemplate(ItemStack item) { Object wandNode = getWandOrUpgradeNode(item); if (wandNode == null) return null; return InventoryUtils.getMetaString(wandNode, "template"); } public static String getWandId(ItemStack item) { if (InventoryUtils.isEmpty(item)) return null; Object wandNode = InventoryUtils.getNode(item, WAND_KEY); if (wandNode == null || isUpgrade(item)) return null; if (isSingleUse(item)) return getWandTemplate(item); return InventoryUtils.getMetaString(wandNode, "id"); } public static String getSpell(ItemStack item) { if (InventoryUtils.isEmpty(item)) return null; Object spellNode = InventoryUtils.getNode(item, "spell"); if (spellNode == null) return null; return InventoryUtils.getMetaString(spellNode, "key"); } public static String getSpellArgs(ItemStack item) { if (InventoryUtils.isEmpty(item)) return null; Object spellNode = InventoryUtils.getNode(item, "spell"); if (spellNode == null) return null; return InventoryUtils.getMetaString(spellNode, "args"); } public static String getBrush(ItemStack item) { if (InventoryUtils.isEmpty(item)) return null; Object brushNode = InventoryUtils.getNode(item, "brush"); if (brushNode == null) return null; return InventoryUtils.getMetaString(brushNode, "key"); } protected void updateInventoryName(ItemStack item, boolean activeName) { if (isSpell(item)) { Spell spell = mage.getSpell(getSpell(item)); if (spell != null) { updateSpellItem(controller.getMessages(), item, spell, "", getActiveMage(), activeName ? this : null, activeMaterial, false); } } else if (isBrush(item)) { updateBrushItem(controller.getMessages(), item, getBrush(item), activeName ? this : null); } } public static void updateSpellItem(Messages messages, ItemStack itemStack, SpellTemplate spell, String args, Wand wand, String activeMaterial, boolean isItem) { updateSpellItem(messages, itemStack, spell, args, wand == null ? null : wand.getActiveMage(), wand, activeMaterial, isItem); } public static void updateSpellItem(Messages messages, ItemStack itemStack, SpellTemplate spell, String args, com.elmakers.mine.bukkit.api.magic.Mage mage, Wand wand, String activeMaterial, boolean isItem) { String displayName; if (wand != null && !wand.isQuickCast()) { displayName = wand.getActiveWandName(spell); } else { displayName = getSpellDisplayName(messages, spell, MaterialBrush.parseMaterialKey(activeMaterial)); } CompatibilityUtils.setDisplayName(itemStack, displayName); List<String> lore = new ArrayList<>(); addSpellLore(messages, spell, lore, mage, wand); if (isItem) { lore.add(ChatColor.YELLOW + messages.get("wand.spell_item_description")); } CompatibilityUtils.setLore(itemStack, lore); Object spellNode = CompatibilityUtils.createNode(itemStack, "spell"); CompatibilityUtils.setMeta(spellNode, "key", spell.getKey()); CompatibilityUtils.setMeta(spellNode, "args", args); if (SpellGlow) { CompatibilityUtils.addGlow(itemStack); } } public static void updateBrushItem(Messages messages, ItemStack itemStack, String materialKey, Wand wand) { updateBrushItem(messages, itemStack, MaterialBrush.parseMaterialKey(materialKey), wand); } public static void updateBrushItem(Messages messages, ItemStack itemStack, MaterialBrush brush, Wand wand) { String displayName; if (wand != null) { Spell activeSpell = wand.getActiveSpell(); if (activeSpell != null && activeSpell.usesBrush()) { displayName = wand.getActiveWandName(brush); } else { displayName = ChatColor.RED + brush.getName(messages); } } else { displayName = brush.getName(messages); } CompatibilityUtils.setDisplayName(itemStack, displayName); Object brushNode = CompatibilityUtils.createNode(itemStack, "brush"); CompatibilityUtils.setMeta(brushNode, "key", brush.getKey()); } public void updateHotbar() { if (mage == null) return; if (!isInventoryOpen()) return; Player player = mage.getPlayer(); if (player == null) return; if (!hasStoredInventory()) return; WandMode wandMode = getMode(); if (wandMode == WandMode.INVENTORY) { PlayerInventory inventory = player.getInventory(); updateHotbar(inventory); DeprecatedUtils.updateInventory(player); } } @SuppressWarnings("deprecation") private void updateInventory() { if (mage == null) return; if (!isInventoryOpen()) return; Player player = mage.getPlayer(); if (player == null) return; WandMode wandMode = getMode(); if (wandMode == WandMode.INVENTORY) { if (!hasStoredInventory()) return; PlayerInventory inventory = player.getInventory(); for (int i = 0; i < PLAYER_INVENTORY_SIZE; i++) { inventory.setItem(i, null); } updateHotbar(inventory); updateInventory(inventory, false); updateName(); player.updateInventory(); } else if (wandMode == WandMode.CHEST) { Inventory inventory = getDisplayInventory(); inventory.clear(); updateInventory(inventory, true); player.updateInventory(); } } private void updateHotbar(PlayerInventory playerInventory) { if (getMode() != WandMode.INVENTORY) return; Inventory hotbar = getHotbar(); if (hotbar == null) return; // Check for an item already in the player's held slot, which // we are about to replace with the wand. int currentSlot = playerInventory.getHeldItemSlot(); ItemStack currentItem = playerInventory.getItem(currentSlot); String currentId = getWandId(currentItem); if (currentId != null && !currentId.equals(id)) { return; } // Reset the held item, just in case Bukkit made a copy or something. playerInventory.setItemInMainHand(this.item); // Set hotbar items from remaining list int targetOffset = 0; for (int hotbarSlot = 0; hotbarSlot < HOTBAR_INVENTORY_SIZE; hotbarSlot++) { if (hotbarSlot == currentSlot) { targetOffset = 1; } ItemStack hotbarItem = hotbar.getItem(hotbarSlot); updateInventoryName(hotbarItem, true); playerInventory.setItem(hotbarSlot + targetOffset, hotbarItem); } } private void updateInventory(Inventory targetInventory, boolean addHotbars) { // Set inventory from current page int currentOffset = addHotbars ? 0 : HOTBAR_SIZE; List<Inventory> inventories = this.inventories; if (openInventoryPage < inventories.size()) { Inventory inventory = inventories.get(openInventoryPage); ItemStack[] contents = inventory.getContents(); for (int i = 0; i < contents.length; i++) { ItemStack inventoryItem = contents[i]; updateInventoryName(inventoryItem, false); targetInventory.setItem(currentOffset, inventoryItem); currentOffset++; } } if (addHotbars && openInventoryPage < hotbars.size()) { Inventory inventory = hotbars.get(openInventoryPage); ItemStack[] contents = inventory.getContents(); for (int i = 0; i < contents.length; i++) { ItemStack inventoryItem = contents[i]; updateInventoryName(inventoryItem, false); targetInventory.setItem(currentOffset, inventoryItem); currentOffset++; } } } protected static void addSpellLore(Messages messages, SpellTemplate spell, List<String> lore, com.elmakers.mine.bukkit.api.magic.Mage mage, Wand wand) { spell.addLore(messages, mage, wand, lore); } protected Inventory getOpenInventory() { while (openInventoryPage >= inventories.size()) { inventories.add(CompatibilityUtils.createInventory(null, INVENTORY_SIZE, "Wand")); } return inventories.get(openInventoryPage); } public void saveInventory() { if (mage == null) return; if (!isInventoryOpen()) return; if (mage.getPlayer() == null) return; if (getMode() != WandMode.INVENTORY) return; if (!hasStoredInventory()) return; // Work-around glitches that happen if you're dragging an item on death if (mage.isDead()) return; // Fill in the hotbar Player player = mage.getPlayer(); PlayerInventory playerInventory = player.getInventory(); Inventory hotbar = getHotbar(); if (hotbar != null) { int saveOffset = 0; for (int i = 0; i < HOTBAR_SIZE; i++) { ItemStack playerItem = playerInventory.getItem(i); if (isWand(playerItem)) { saveOffset = -1; continue; } int hotbarOffset = i + saveOffset; if (hotbarOffset >= hotbar.getSize()) { // This can happen if there is somehow no wand in the wand inventory. break; } if (!updateSlot(i + saveOffset + currentHotbar * HOTBAR_INVENTORY_SIZE, playerItem)) { playerItem = new ItemStack(Material.AIR); playerInventory.setItem(i, playerItem); } hotbar.setItem(i + saveOffset, playerItem); } } // Fill in the active inventory page int hotbarOffset = getHotbarSize(); Inventory openInventory = getOpenInventory(); for (int i = 0; i < openInventory.getSize(); i++) { ItemStack playerItem = playerInventory.getItem(i + HOTBAR_SIZE); if (!updateSlot(i + hotbarOffset + openInventoryPage * INVENTORY_SIZE, playerItem)) { playerItem = new ItemStack(Material.AIR); playerInventory.setItem(i + HOTBAR_SIZE, playerItem); } openInventory.setItem(i, playerItem); } } protected boolean updateSlot(int slot, ItemStack item) { String spellKey = getSpell(item); if (spellKey != null) { spells.put(spellKey, slot); } else { String brushKey = getBrush(item); if (brushKey != null) { brushes.put(brushKey, slot); } else if (mage != null && item != null && item.getType() != Material.AIR) { // Must have been an item inserted directly into player's inventory? mage.giveItem(item); return false; } } return true; } @Override public int enchant(int totalLevels, com.elmakers.mine.bukkit.api.magic.Mage mage, boolean addSpells) { return randomize(totalLevels, true, mage, addSpells); } @Override public int enchant(int totalLevels, com.elmakers.mine.bukkit.api.magic.Mage mage) { return randomize(totalLevels, true, mage, true); } @Override public int enchant(int totalLevels) { return randomize(totalLevels, true, null, true); } protected int randomize(int totalLevels, boolean additive, com.elmakers.mine.bukkit.api.magic.Mage enchanter, boolean addSpells) { if (enchanter == null && mage != null) { enchanter = mage; } if (maxEnchantCount > 0 && enchantCount >= maxEnchantCount) { if (enchanter != null) { enchanter.sendMessage(getMessage("max_enchanted").replace("$wand", getName())); } return 0; } WandUpgradePath path = (WandUpgradePath)getPath(); if (path == null) { if (enchanter != null) { enchanter.sendMessage(getMessage("no_path").replace("$wand", getName())); } return 0; } int minLevel = path.getMinLevel(); if (totalLevels < minLevel) { if (enchanter != null) { String levelMessage = getMessage("need_more_levels"); levelMessage = levelMessage.replace("$levels", Integer.toString(minLevel)); enchanter.sendMessage(levelMessage); } return 0; } // Just a hard-coded sanity check int maxLevel = path.getMaxLevel(); totalLevels = Math.min(totalLevels, maxLevel * 50); int addLevels = Math.min(totalLevels, maxLevel); int levels = 0; boolean modified = true; while (addLevels >= minLevel && modified) { boolean hasUpgrade = path.hasUpgrade(); WandLevel level = path.getLevel(addLevels); if (!path.canEnchant(this) && (path.hasSpells() || path.hasMaterials())) { // Check for level up WandUpgradePath nextPath = path.getUpgrade(); if (nextPath != null) { if (path.checkUpgradeRequirements(this, enchanter)) { path.upgrade(this, enchanter); } break; } else { enchanter.sendMessage(getMessage("fully_enchanted").replace("$wand", getName())); break; } } modified = level.randomizeWand(enchanter, this, additive, hasUpgrade, addSpells); totalLevels -= maxLevel; if (modified) { if (enchanter != null) { path.enchanted(enchanter); } levels += addLevels; // Check for level up WandUpgradePath nextPath = path.getUpgrade(); if (nextPath != null && path.checkUpgradeRequirements(this, null) && !path.canEnchant(this)) { path.upgrade(this, enchanter); path = nextPath; } } else if (path.canEnchant(this)) { if (enchanter != null && levels == 0 && addSpells) { String message = getMessage("require_more_levels"); enchanter.sendMessage(message); } } else if (hasUpgrade) { if (path.checkUpgradeRequirements(this, enchanter)) { path.upgrade(this, enchanter); levels += addLevels; } } else if (enchanter != null) { enchanter.sendMessage(getMessage("fully_enchanted").replace("$wand", getName())); } addLevels = Math.min(totalLevels, maxLevel); additive = true; } if (levels > 0) { enchantCount++; setProperty("enchant_count", enchantCount); } saveState(); updateName(); updateLore(); return levels; } public static ItemStack createItem(MagicController controller, String templateName) { ItemStack item = createSpellItem(templateName, controller, null, true); if (item == null) { item = createBrushItem(templateName, controller, null, true); if (item == null) { Wand wand = createWand(controller, templateName); if (wand != null) { item = wand.getItem(); } } } return item; } public static Wand createWand(MagicController controller, String templateName) { if (controller == null) return null; Wand wand = null; try { wand = new Wand(controller, templateName); } catch (UnknownWandException ignore) { // the Wand constructor throws an exception on an unknown template } catch (Exception ex) { ex.printStackTrace(); } return wand; } public static Wand createWand(MagicController controller, ItemStack itemStack) { if (controller == null) return null; Wand wand = null; try { wand = controller.getWand(InventoryUtils.makeReal(itemStack)); wand.saveState(); wand.updateName(); } catch (Exception ex) { ex.printStackTrace(); } return wand; } public boolean add(Wand other) { return add(other, this.mage); } @Override public boolean add(com.elmakers.mine.bukkit.api.wand.Wand other, com.elmakers.mine.bukkit.api.magic.Mage mage) { if (other instanceof Wand) { return add((Wand)other, mage); } return false; } public boolean add(Wand other, com.elmakers.mine.bukkit.api.magic.Mage mage) { if (!isModifiable()) { // Only allow upgrading a modifiable wand via an upgrade item // and only if the paths match. if (!other.isUpgrade() || other.path == null || path == null || other.path.isEmpty() || path.isEmpty() || !other.path.equals(path)) { return false; } } // Can't combine limited-use wands if (hasUses || other.hasUses) { return false; } if (isHeroes || other.isHeroes) { return false; } ConfigurationSection templateConfig = controller.getWandTemplateConfiguration(other.getTemplateKey()); // Check for forced upgrades if (other.isForcedUpgrade()) { if (templateConfig == null) { return false; } templateConfig = ConfigurationUtils.cloneConfiguration(templateConfig); templateConfig.set("name", templateConfig.getString("upgrade_name")); templateConfig.set("description", templateConfig.getString("upgrade_description")); templateConfig.set("force", null); templateConfig.set("upgrade", null); templateConfig.set("icon", templateConfig.getString("upgrade_icon")); templateConfig.set("indestructible", null); configure(templateConfig); loadProperties(); saveState(); return true; } // Don't allow upgrades from an item on a different path if (other.isUpgrade() && other.path != null && !other.path.isEmpty() && (this.path == null || !this.path.equals(other.path))) { return false; } ConfigurationSection upgradeConfig = other.getEffectiveConfiguration(); upgradeConfig.set("id", null); upgradeConfig.set("indestructible", null); upgradeConfig.set("upgrade", null); upgradeConfig.set("icon", upgradeIcon == null ? null : upgradeIcon.getKey()); upgradeConfig.set("template", upgradeTemplate); Messages messages = controller.getMessages(); if (other.rename && templateConfig != null) { String newName = messages.get("wands." + other.template + ".name"); newName = templateConfig.getString("name", newName); upgradeConfig.set("name", newName); } else { upgradeConfig.set("name", null); } if (other.renameDescription && templateConfig != null) { String newDescription = messages.get("wands." + other.template + ".description"); newDescription = templateConfig.getString("description", newDescription); upgradeConfig.set("description", newDescription); } else { upgradeConfig.set("description", null); } boolean modified = upgrade(upgradeConfig); if (modified) { loadProperties(); saveState(); } return modified; } public boolean isForcedUpgrade() { return isUpgrade && forceUpgrade; } public boolean keepOnDeath() { return keep; } public static WandMode parseWandMode(String modeString, WandMode defaultValue) { if (modeString != null && !modeString.isEmpty()) { try { defaultValue = WandMode.valueOf(modeString.toUpperCase()); } catch(Exception ex) { } } return defaultValue; } public static WandAction parseWandAction(String actionString, WandAction defaultValue) { if (actionString != null && !actionString.isEmpty()) { try { defaultValue = WandAction.valueOf(actionString.toUpperCase()); } catch(Exception ex) { } } return defaultValue; } private void updateActiveMaterial() { if (mage == null) return; if (activeMaterial == null) { mage.clearBuildingMaterial(); } else { com.elmakers.mine.bukkit.api.block.MaterialBrush brush = mage.getBrush(); brush.update(activeMaterial); } } public void cycleActive(int direction) { Player player = mage != null ? mage.getPlayer() : null; if (player != null && player.isSneaking()) { com.elmakers.mine.bukkit.api.spell.Spell activeSpell = getActiveSpell(); boolean cycleMaterials = false; if (activeSpell != null) { cycleMaterials = activeSpell.usesBrushSelection(); } if (cycleMaterials) { cycleMaterials(direction); } else { cycleSpells(direction); } } else { cycleSpells(direction); } } public void toggleInventory() { if (mage != null && mage.cancel()) { mage.playSoundEffect(noActionSound); return; } Player player = mage == null ? null : mage.getPlayer(); boolean isSneaking = player != null && player.isSneaking(); Spell currentSpell = getActiveSpell(); if (getBrushMode() == WandMode.CHEST && brushSelectSpell != null && !brushSelectSpell.isEmpty() && isSneaking && currentSpell != null && currentSpell.usesBrushSelection()) { Spell brushSelect = mage.getSpell(brushSelectSpell); if (brushSelect != null) { brushSelect.cast(); return; } } if (!hasInventory) { if (activeSpell == null || activeSpell.length() == 0) { Set<String> spells = getSpells(); // Sanity check, so it'll switch to inventory next time updateHasInventory(); if (spells.size() > 0) { setActiveSpell(spells.iterator().next()); } } updateName(); return; } if (!isInventoryOpen()) { openInventory(); } else { closeInventory(); } } public void updateHasInventory() { int inventorySize = getSpells().size() + getBrushes().size(); hasInventory = inventorySize > 1 || (inventorySize == 1 && hasSpellProgression); } @SuppressWarnings("deprecation") public void cycleInventory(int direction) { if (!hasInventory) { return; } if (isInventoryOpen()) { saveInventory(); int inventoryCount = inventories.size(); openInventoryPage = inventoryCount == 0 ? 0 : (openInventoryPage + inventoryCount + direction) % inventoryCount; updateInventory(); if (mage != null && inventories.size() > 1) { if (!playPassiveEffects("cycle") && inventoryCycleSound != null) { mage.playSoundEffect(inventoryCycleSound); } mage.getPlayer().updateInventory(); } } } @Override public void cycleHotbar() { cycleHotbar(1); } public void cycleHotbar(int direction) { if (!hasInventory || getMode() != WandMode.INVENTORY) { return; } if (isInventoryOpen() && mage != null && hotbars.size() > 1) { saveInventory(); int hotbarCount = hotbars.size(); currentHotbar = hotbarCount == 0 ? 0 : (currentHotbar + hotbarCount + direction) % hotbarCount; updateHotbar(); if (!playPassiveEffects("cycle") && inventoryCycleSound != null) { mage.playSoundEffect(inventoryCycleSound); } updateHotbarStatus(); DeprecatedUtils.updateInventory(mage.getPlayer()); } } public void cycleInventory() { cycleInventory(1); } @SuppressWarnings("deprecation") public void openInventory() { if (mage == null) return; WandMode wandMode = getMode(); if (wandMode == WandMode.CHEST) { inventoryIsOpen = true; if (!playPassiveEffects("open") && inventoryOpenSound != null) { mage.playSoundEffect(inventoryOpenSound); } updateInventory(); mage.getPlayer().openInventory(getDisplayInventory()); } else if (wandMode == WandMode.INVENTORY) { if (hasStoredInventory()) return; if (storeInventory()) { inventoryIsOpen = true; showActiveIcon(true); if (!playPassiveEffects("open") && inventoryOpenSound != null) { mage.playSoundEffect(inventoryOpenSound); } updateInventory(); updateHotbarStatus(); mage.getPlayer().updateInventory(); } } } @Override public void closeInventory() { if (!isInventoryOpen()) return; controller.disableItemSpawn(); WandMode mode = getMode(); try { saveInventory(); updateSpells(); inventoryIsOpen = false; if (mage != null) { if (!playPassiveEffects("close") && inventoryCloseSound != null) { mage.playSoundEffect(inventoryCloseSound); } if (mode == WandMode.INVENTORY) { restoreInventory(); showActiveIcon(false); } else { mage.getPlayer().closeInventory(); } // Check for items the player might've glitched onto their body... PlayerInventory inventory = mage.getPlayer().getInventory(); ItemStack testItem = inventory.getHelmet(); if (isSpell(testItem) || isBrush(testItem)) { inventory.setHelmet(new ItemStack(Material.AIR)); DeprecatedUtils.updateInventory(mage.getPlayer()); } testItem = inventory.getBoots(); if (isSpell(testItem) || isBrush(testItem)) { inventory.setBoots(new ItemStack(Material.AIR)); DeprecatedUtils.updateInventory(mage.getPlayer()); } testItem = inventory.getLeggings(); if (isSpell(testItem) || isBrush(testItem)) { inventory.setLeggings(new ItemStack(Material.AIR)); DeprecatedUtils.updateInventory(mage.getPlayer()); } testItem = inventory.getChestplate(); if (isSpell(testItem) || isBrush(testItem)) { inventory.setChestplate(new ItemStack(Material.AIR)); DeprecatedUtils.updateInventory(mage.getPlayer()); } // This is kind of a hack :( testItem = inventory.getItemInOffHand(); if (isSpell(testItem) || isBrush(testItem)) { inventory.setItemInOffHand(new ItemStack(Material.AIR)); DeprecatedUtils.updateInventory(mage.getPlayer()); } } } catch (Throwable ex) { restoreInventory(); } if (mode == WandMode.INVENTORY && mage != null) { try { mage.getPlayer().closeInventory(); } catch (Throwable ex) { ex.printStackTrace(); } } controller.enableItemSpawn(); } @Override public boolean fill(Player player) { return fill(player, 0); } @Override public boolean fill(Player player, int maxLevel) { Collection<String> currentSpells = new ArrayList<>(getSpells()); for (String spellKey : currentSpells) { SpellTemplate spell = controller.getSpellTemplate(spellKey); if (!spell.hasCastPermission(player)) { removeSpell(spellKey); } } Collection<SpellTemplate> allSpells = controller.getPlugin().getSpellTemplates(); // Hack to prevent messaging Mage mage = this.mage; this.mage = null; for (SpellTemplate spell : allSpells) { String key = spell.getKey(); if (maxLevel > 0 && spell.getSpellKey().getLevel() > maxLevel) { continue; } if (key.startsWith("heroes*")) { continue; } if (spell.hasCastPermission(player) && spell.hasIcon() && !spell.isHidden()) { addSpell(key); } } this.mage = mage; setProperty("fill", null); autoFill = false; saveState(); return true; } protected void randomize() { if (description.contains("$")) { String newDescription = controller.getMessages().escape(description); if (!newDescription.equals(description)) { setDescription(newDescription); updateLore(); updateName(); setProperty("randomize", false); } } if (template != null && template.length() > 0) { ConfigurationSection wandConfig = controller.getWandTemplateConfiguration(template); if (wandConfig != null && wandConfig.contains("icon")) { String iconKey = wandConfig.getString("icon"); if (iconKey.contains(",")) { Random r = new Random(); String[] keys = StringUtils.split(iconKey, ','); iconKey = keys[r.nextInt(keys.length)]; setIcon(ConfigurationUtils.toMaterialAndData(iconKey)); updateIcon(); setProperty("randomize", false); } } } } protected void checkActiveMaterial() { if (activeMaterial == null || activeMaterial.length() == 0) { Set<String> materials = getBrushes(); if (materials.size() > 0) { activeMaterial = materials.iterator().next(); } } } @Override public boolean addItem(ItemStack item) { if (isUpgrade) return false; if (isModifiable() && isSpell(item) && !isSkill(item)) { String spellKey = getSpell(item); Set<String> spells = getSpells(); if (!spells.contains(spellKey) && addSpell(spellKey)) { return true; } } else if (isModifiable() && isBrush(item)) { String materialKey = getBrush(item); Set<String> materials = getBrushes(); if (!materials.contains(materialKey) && addBrush(materialKey)) { return true; } } else if (isUpgrade(item)) { Wand wand = controller.getWand(item); return this.add(wand); } if (mage != null && !mage.isAtMaxSkillPoints()) { Integer sp = getSP(item); if (sp != null) { mage.addSkillPoints(sp * item.getAmount()); return true; } } return false; } protected void updateEffects() { updateEffects(mage); } public void updateEffects(Mage mage) { if (mage == null) return; Player player = mage.getPlayer(); if (player == null) return; // Update Bubble effects effects if (effectBubbles && effectColor != null) { CompatibilityUtils.addPotionEffect(player, effectColor.getColor()); effectBubblesApplied = true; } else if (effectBubblesApplied) { effectBubblesApplied = false; CompatibilityUtils.removePotionEffect(player); } Location location = mage.getLocation(); long now = System.currentTimeMillis(); Vector mageLocation = location.toVector(); boolean playEffects = !activeEffectsOnly || inventoryIsOpen; if (playEffects && effectParticle != null && effectParticleInterval > 0 && effectParticleCount > 0) { boolean velocityCheck = true; if (effectParticleMinVelocity > 0) { if (lastLocation != null && lastLocationTime != 0) { double velocitySquared = effectParticleMinVelocity * effectParticleMinVelocity; Vector velocity = lastLocation.subtract(mageLocation); velocity.setY(0); double speedSquared = velocity.lengthSquared() * 1000 / (now - lastLocationTime); velocityCheck = (speedSquared > velocitySquared); } else { velocityCheck = false; } } if (velocityCheck && (lastParticleEffect == 0 || now > lastParticleEffect + effectParticleInterval)) { lastParticleEffect = now; Location effectLocation = player.getLocation(); Location eyeLocation = player.getEyeLocation(); effectLocation.setY(eyeLocation.getY() + effectParticleOffset); if (effectPlayer == null) { effectPlayer = new EffectRing(controller.getPlugin()); effectPlayer.setParticleCount(1); effectPlayer.setIterations(1); effectPlayer.setParticleOffset(0, 0, 0); } effectPlayer.setMaterial(location.getBlock().getRelative(BlockFace.DOWN)); if (effectParticleData == 0) { effectPlayer.setColor(getEffectColor()); } else { effectPlayer.setColor(null); } effectPlayer.setParticleType(effectParticle); effectPlayer.setParticleData(effectParticleData); effectPlayer.setSize(effectParticleCount); effectPlayer.setRadius((float)effectParticleRadius); effectPlayer.start(effectLocation, null); } } if (castSpell != null && castInterval > 0) { boolean velocityCheck = true; if (castMinVelocity > 0) { if (lastLocation != null && lastLocationTime != 0) { double velocitySquared = castMinVelocity * castMinVelocity; Vector velocity = lastLocation.subtract(mageLocation).multiply(-1); if (castVelocityDirection != null) { velocity = velocity.multiply(castVelocityDirection); // This is kind of a hack to make jump-detection work. if (castVelocityDirection.getY() < 0) { velocityCheck = velocity.getY() < 0; } else { velocityCheck = velocity.getY() > 0; } } if (velocityCheck) { double speedSquared = velocity.lengthSquared() * 1000 / (now - lastLocationTime); velocityCheck = (speedSquared > velocitySquared); } } else { velocityCheck = false; } } if (velocityCheck && (lastSpellCast == 0 || now > lastSpellCast + castInterval)) { lastSpellCast = now; Spell spell = mage.getSpell(castSpell); if (spell != null) { if (castParameters == null) { castParameters = new MemoryConfiguration(); } castParameters.set("track_casts", false); mage.setCostReduction(100); mage.setQuiet(true); try { spell.cast(castParameters); } catch (Exception ex) { controller.getLogger().log(Level.WARNING, "Error casting aura spell " + spell.getKey(), ex); } mage.setQuiet(false); mage.setCostReduction(0); } } } if (playEffects && effectSound != null && controller.soundsEnabled() && effectSoundInterval > 0) { if (lastSoundEffect == 0 || now > lastSoundEffect + effectSoundInterval) { lastSoundEffect = now; effectSound.play(controller.getPlugin(), mage.getPlayer()); } } lastLocation = mageLocation; lastLocationTime = now; } protected void updateDurability() { int maxDurability = item.getType().getMaxDurability(); if (maxDurability > 0 && effectiveManaMax > 0) { int durability = (short)(mana * maxDurability / effectiveManaMax); durability = maxDurability - durability; if (durability >= maxDurability) { durability = maxDurability - 1; } else if (durability < 0) { durability = 0; } item.setDurability((short)durability); } } public boolean usesXPBar() { return (hasSpellProgression && spMode.useXP()) || (usesMana() && manaMode.useXP()); } public boolean usesXPNumber() { return (hasSpellProgression && spMode.useXPNumber() && controller.isSPEnabled()) || (usesMana() && manaMode.useXP()); } public boolean hasSpellProgression() { return hasSpellProgression; } public boolean usesXPDisplay() { return usesXPBar() || usesXPNumber(); } @Override public void updateMana() { Player player = mage == null ? null : mage.getPlayer(); if (player == null) return; if (usesMana()) { if (manaMode.useGlow()) { if (mana == effectiveManaMax) { CompatibilityUtils.addGlow(item); } else { CompatibilityUtils.removeGlow(item); } } if (manaMode.useDurability()) { updateDurability(); } } if (usesXPDisplay()) { int playerLevel = player.getLevel(); float playerProgress = player.getExp(); if (usesMana() && manaMode.useXPNumber()) { playerLevel = (int) mana; } if (usesMana() && manaMode.useXPBar()) { playerProgress = Math.max(0, mana / effectiveManaMax); } if (controller.isSPEnabled() && spMode.useXPNumber() && hasSpellProgression) { playerLevel = mage.getSkillPoints(); } mage.sendExperience(playerProgress, playerLevel); } } @Override public boolean isInventoryOpen() { return mage != null && inventoryIsOpen; } @Override public void unbind() { if (!bound) return; com.elmakers.mine.bukkit.api.magic.Mage owningMage = this.mage; deactivate(); if (ownerId != null) { if (owningMage == null || !owningMage.getId().equals(ownerId)) { owningMage = controller.getRegisteredMage(ownerId); } if (owningMage != null) { owningMage.unbind(this); } ownerId = null; } bound = false; owner = null; setProperty("bound", false); setProperty("owner", null); setProperty("owner_id", null); saveState(); } @Override public void bind() { if (bound) return; Mage holdingMage = mage; deactivate(); bound = true; setProperty("bound", true); saveState(); if (holdingMage != null) { holdingMage.checkWand(); } } @Override public void deactivate() { if (mage == null) return; // Play deactivate FX playPassiveEffects("deactivate"); Mage mage = this.mage; Player player = mage.getPlayer(); if (effectBubblesApplied && player != null) { CompatibilityUtils.removePotionEffect(player); effectBubblesApplied = false; } if (isInventoryOpen()) { closeInventory(); } showActiveIcon(false); storedInventory = null; if (usesXPNumber() || usesXPBar()) { mage.resetSentExperience(); } saveState(); mage.deactivateWand(this); this.mage = null; updateMaxMana(true); } @Override public Spell getActiveSpell() { if (mage == null || activeSpell == null || activeSpell.length() == 0) return null; return mage.getSpell(activeSpell); } @Override public SpellTemplate getBaseSpell(String spellName) { return getBaseSpell(new SpellKey(spellName)); } public SpellTemplate getBaseSpell(SpellKey key) { Integer spellLevel = spellLevels.get(key.getBaseKey()); if (spellLevel == null) return null; String spellKey = key.getBaseKey(); if (key.isVariant()) { spellKey += "|" + key.getLevel(); } return controller.getSpellTemplate(spellKey); } @Override public String getActiveSpellKey() { return activeSpell; } @Override public String getActiveBrushKey() { return activeMaterial; } @Override public void damageDealt(double damage, Entity target) { if (effectiveManaMax == 0 && manaMax > 0) { effectiveManaMax = manaMax; } if (manaPerDamage > 0 && effectiveManaMax > 0 && mana < effectiveManaMax) { mana = Math.min(effectiveManaMax, mana + (float)damage * manaPerDamage); updateMana(); } } @Override public boolean cast() { return cast(getActiveSpell()); } public boolean cast(Spell spell) { if (spell != null) { Collection<String> castParameters = null; if (castOverrides != null && castOverrides.size() > 0) { castParameters = new ArrayList<>(); for (Map.Entry<String, String> entry : castOverrides.entrySet()) { String[] key = StringUtils.split(entry.getKey(), "."); if (key.length == 0) continue; if (key.length == 2 && !key[0].equals("default") && !key[0].equals(spell.getSpellKey().getBaseKey()) && !key[0].equals(spell.getSpellKey().getKey())) { continue; } castParameters.add(key.length == 2 ? key[1] : key[0]); castParameters.add(entry.getValue()); } } if (spell.cast(castParameters == null ? null : castParameters.toArray(EMPTY_PARAMETERS))) { Color spellColor = spell.getColor(); use(); if (spellColor != null && this.effectColor != null) { this.effectColor = this.effectColor.mixColor(spellColor, effectColorSpellMixWeight); setProperty("effect_color", effectColor.toString()); // Note that we don't save this change. // The hope is that the wand will get saved at some point later // And we don't want to trigger NBT writes every spell cast. // And the effect color morphing isn't all that important if a few // casts get lost. } updateHotbarStatus(); return true; } } return false; } @SuppressWarnings("deprecation") protected void use() { if (mage == null) return; if (hasUses) { ItemStack item = getItem(); if (item.getAmount() > 1) { item.setAmount(item.getAmount() - 1); } else { if (uses > 0) { uses--; } if (uses <= 0) { Player player = mage.getPlayer(); deactivate(); PlayerInventory playerInventory = player.getInventory(); item = player.getItemInHand(); if (item.getAmount() > 1) { item.setAmount(item.getAmount() - 1); } else { playerInventory.setItemInHand(new ItemStack(Material.AIR, 1)); } player.updateInventory(); } else { saveState(); updateName(); updateLore(); } } } } // Taken from NMS HumanEntity public static int getExpToLevel(int expLevel) { return expLevel >= 30 ? 112 + (expLevel - 30) * 9 : (expLevel >= 15 ? 37 + (expLevel - 15) * 5 : 7 + expLevel * 2); } public static int getExperience(int expLevel, float expProgress) { int xp = 0; for (int level = 0; level < expLevel; level++) { xp += Wand.getExpToLevel(level); } return xp + (int) (expProgress * Wand.getExpToLevel(expLevel)); } protected void updateHotbarStatus() { Player player = mage == null ? null : mage.getPlayer(); if (player != null && LiveHotbar && getMode() == WandMode.INVENTORY && isInventoryOpen()) { mage.updateHotbarStatus(); } } public boolean tickMana(Player player) { boolean updated = false; if (usesMana()) { long now = System.currentTimeMillis(); if (isHeroes) { HeroesManager heroes = controller.getHeroes(); if (heroes != null) { effectiveManaMax = heroes.getMaxMana(player); effectiveManaRegeneration = heroes.getManaRegen(player); manaMax = effectiveManaMax; manaRegeneration = effectiveManaRegeneration; setMana(heroes.getMana(player)); updated = true; } } else if (manaRegeneration > 0 && lastManaRegeneration > 0 && effectiveManaRegeneration > 0) { long delta = now - lastManaRegeneration; if (effectiveManaMax == 0 && manaMax > 0) { effectiveManaMax = manaMax; } setMana(Math.min(effectiveManaMax, mana + (float) effectiveManaRegeneration * (float)delta / 1000)); updated = true; } lastManaRegeneration = now; setProperty("mana_timestamp", lastManaRegeneration); } return updated; } public void tick() { if (mage == null) return; Player player = mage.getPlayer(); if (player == null) return; if (tickMana(player)) { updateMana(); } if (player.isBlocking() && blockMageCooldown > 0) { mage.setRemainingCooldown(blockMageCooldown); } // Update hotbar glow updateHotbarStatus(); if (!passive) { if (damageReductionFire > 0 && player.getFireTicks() > 0) { player.setFireTicks(0); } updateEffects(); } } public void armorUpdated() { updateMaxMana(true); } protected void updateMaxMana(boolean updateLore) { if (isHeroes) return; int currentMana = effectiveManaMax; int currentManaRegen = effectiveManaRegeneration; float effectiveBoost = manaMaxBoost; float effectiveRegenBoost = manaRegenerationBoost; if (mage != null) { Collection<Wand> activeArmor = mage.getActiveArmor(); for (Wand armorWand : activeArmor) { effectiveBoost += armorWand.getManaMaxBoost(); effectiveRegenBoost += armorWand.getManaRegenerationBoost(); } Wand offhandWand = mage.getOffhandWand(); if (offhandWand != null && !offhandWand.isPassive()) { effectiveBoost += offhandWand.getManaMaxBoost(); effectiveRegenBoost += offhandWand.getManaRegenerationBoost(); } } effectiveManaMax = manaMax; if (effectiveBoost != 0) { effectiveManaMax = (int)Math.ceil(effectiveManaMax + effectiveBoost * effectiveManaMax); } effectiveManaRegeneration = manaRegeneration; if (effectiveRegenBoost != 0) { effectiveManaRegeneration = (int)Math.ceil(effectiveManaRegeneration + effectiveRegenBoost * effectiveManaRegeneration); } if (updateLore && (currentMana != effectiveManaMax || effectiveManaRegeneration != currentManaRegen)) { updateLore(); } } public static Float getWandFloat(ItemStack item, String key) { try { Object wandNode = InventoryUtils.getNode(item, WAND_KEY); if (wandNode != null) { String value = InventoryUtils.getMetaString(wandNode, key); if (value != null && !value.isEmpty()) { return Float.parseFloat(value); } } } catch (Exception ex) { } return null; } public static String getWandString(ItemStack item, String key) { try { Object wandNode = InventoryUtils.getNode(item, WAND_KEY); if (wandNode != null) { return InventoryUtils.getMetaString(wandNode, key); } } catch (Exception ex) { } return null; } public MagicController getMaster() { return controller; } public void cycleSpells(int direction) { Set<String> spellsSet = getSpells(); ArrayList<String> spells = new ArrayList<>(spellsSet); if (spells.size() == 0) return; if (activeSpell == null) { setActiveSpell(spells.get(0).split("@")[0]); return; } int spellIndex = 0; for (int i = 0; i < spells.size(); i++) { if (spells.get(i).split("@")[0].equals(activeSpell)) { spellIndex = i; break; } } spellIndex = (spellIndex + direction) % spells.size(); setActiveSpell(spells.get(spellIndex).split("@")[0]); } public void cycleMaterials(int direction) { Set<String> materialsSet = getBrushes(); ArrayList<String> materials = new ArrayList<>(materialsSet); if (materials.size() == 0) return; if (activeMaterial == null) { setActiveBrush(materials.get(0).split("@")[0]); return; } int materialIndex = 0; for (int i = 0; i < materials.size(); i++) { if (materials.get(i).split("@")[0].equals(activeMaterial)) { materialIndex = i; break; } } materialIndex = (materialIndex + direction) % materials.size(); setActiveBrush(materials.get(materialIndex).split("@")[0]); } public Mage getActiveMage() { return mage; } public void setActiveMage(com.elmakers.mine.bukkit.api.magic.Mage mage) { if (mage instanceof Mage) { this.mage = (Mage)mage; } } public Color getEffectColor() { return effectColor == null ? null : effectColor.getColor(); } public ParticleEffect getEffectParticle() { return effectParticle; } public Inventory getHotbar() { if (this.hotbars.size() == 0) return null; if (currentHotbar < 0 || currentHotbar >= this.hotbars.size()) { currentHotbar = 0; } return this.hotbars.get(currentHotbar); } public int getHotbarCount() { if (getMode() != WandMode.INVENTORY) return 0; return hotbars.size(); } public List<Inventory> getHotbars() { return hotbars; } @Override public boolean isQuickCastDisabled() { return quickCastDisabled; } public boolean isManualQuickCastDisabled() { return manualQuickCastDisabled; } @Override public boolean isQuickCast() { return quickCast; } public WandMode getMode() { WandMode wandMode = mode != null ? mode : controller.getDefaultWandMode(); Player player = mage == null ? null : mage.getPlayer(); if (wandMode == WandMode.INVENTORY && player != null && player.getGameMode() == GameMode.CREATIVE) { wandMode = WandMode.CHEST; } return wandMode; } public WandMode getBrushMode() { return brushMode != null ? brushMode : controller.getDefaultBrushMode(); } public void setMode(WandMode mode) { this.mode = mode; } public void setBrushMode(WandMode mode) { this.brushMode = mode; } @Override public boolean showCastMessages() { return quietLevel == 0; } @Override public boolean showMessages() { return quietLevel < 2; } public boolean isStealth() { return quietLevel > 2; } @Override public void setPath(String path) { this.path = path; setProperty("path", path); } /* * Public API Implementation */ @Override public boolean isLost(com.elmakers.mine.bukkit.api.wand.LostWand lostWand) { return this.id != null && this.id.equals(lostWand.getId()); } @Override public LostWand makeLost(Location location) { return new LostWand(this, location); } @Override @Deprecated public void activate(com.elmakers.mine.bukkit.api.magic.Mage mage) { if (mage instanceof Mage) { activate((Mage)mage); } } protected void showActiveIcon(boolean show) { if (this.icon == null || this.inactiveIcon == null || this.inactiveIcon.getMaterial() == Material.AIR || this.inactiveIcon.getMaterial() == null) return; if (this.icon.getMaterial() == Material.AIR || this.icon.getMaterial() == null) { this.icon.setMaterial(DefaultWandMaterial); } if (show) { if (inactiveIconDelay > 0) { Plugin plugin = controller.getPlugin(); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { findItem(); icon.applyToItem(item); } }, inactiveIconDelay * 20 / 1000); } else { findItem(); icon.applyToItem(item); } } else { findItem(); inactiveIcon.applyToItem(this.item); } } public boolean activate(Mage mage) { return activate(mage, false); } public boolean activateOffhand(Mage mage) { return activate(mage, true); } public boolean activate(Mage mage, boolean offhand) { if (mage == null) return false; Player player = mage.getPlayer(); if (player != null) { if (!controller.hasWandPermission(player, this)) return false; InventoryView openInventory = player.getOpenInventory(); InventoryType inventoryType = openInventory.getType(); if (inventoryType == InventoryType.ENCHANTING || inventoryType == InventoryType.ANVIL) return false; } if (!canUse(player)) { mage.sendMessage(getMessage("bound").replace("$name", getOwner())); return false; } this.checkId(); if (this.isUpgrade) { controller.getLogger().warning("Activated an upgrade item- this shouldn't happen"); return false; } WandPreActivateEvent preActivateEvent = new WandPreActivateEvent(mage, this); Bukkit.getPluginManager().callEvent(preActivateEvent); if (preActivateEvent.isCancelled()) { return false; } this.mage = mage; this.isInOffhand = offhand; // Since these wands can't be opened we will just show them as open when held // We have to delay this 1 tick so it happens after the Mage has accepted the Wand if (getMode() != WandMode.INVENTORY || offhand) { Plugin plugin = controller.getPlugin(); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { showActiveIcon(true); playPassiveEffects("open"); } }, 1); } boolean forceUpdate = false; // Check for an empty wand and auto-fill if (!isUpgrade && (controller.fillWands() || autoFill)) { fill(mage.getPlayer(), controller.getMaxWandFillLevel()); } if (isHeroes && player != null) { HeroesManager heroes = controller.getHeroes(); if (heroes != null) { Set<String> skills = heroes.getSkills(player); Collection<String> currentSpells = new ArrayList<>(getSpells()); for (String spellKey : currentSpells) { if (spellKey.startsWith("heroes*") && !skills.contains(spellKey.substring(7))) { removeSpell(spellKey); } } // Hack to prevent messaging this.mage = null; for (String skillKey : skills) { String heroesKey = "heroes*" + skillKey; if (!spells.containsKey(heroesKey)) { addSpell(heroesKey); } } this.mage = mage; } } // Check for auto-organize if (autoOrganize && !isUpgrade) { organizeInventory(mage); } // Check for auto-alphabetize if (autoAlphabetize && !isUpgrade) { alphabetizeInventory(); } // Check for spell or other special icons in the player's inventory Inventory inventory = player.getInventory(); ItemStack[] items = inventory.getContents(); for (int i = 0; i < items.length; i++) { ItemStack item = items[i]; if (addItem(item)) { inventory.setItem(i, null); forceUpdate = true; } } // Check for auto-bind if (bound) { String mageName = ChatColor.stripColor(mage.getPlayer().getDisplayName()); String mageId = mage.getPlayer().getUniqueId().toString(); boolean ownerRenamed = owner != null && ownerId != null && ownerId.equals(mageId) && !owner.equals(mageName); if (ownerId == null || ownerId.length() == 0 || owner == null || ownerRenamed) { takeOwnership(mage.getPlayer()); } } // Check for randomized wands if (randomize) { randomize(); forceUpdate = true; } checkActiveMaterial(); tick(); saveState(); updateMaxMana(false); updateActiveMaterial(); updateName(); updateLore(); // Play activate FX playPassiveEffects("activate"); lastSoundEffect = 0; lastParticleEffect = 0; lastSpellCast = 0; lastLocationTime = 0; lastLocation = null; if (forceUpdate) { DeprecatedUtils.updateInventory(player); } return true; } @Override public boolean organizeInventory() { if (mage != null) { return organizeInventory(mage); } return false; } @Override public boolean organizeInventory(com.elmakers.mine.bukkit.api.magic.Mage mage) { WandOrganizer organizer = new WandOrganizer(this, mage); organizer.organize(); openInventoryPage = 0; currentHotbar = 0; autoOrganize = false; autoAlphabetize = false; return true; } @Override public boolean alphabetizeInventory() { WandOrganizer organizer = new WandOrganizer(this); organizer.alphabetize(); openInventoryPage = 0; currentHotbar = 0; autoOrganize = false; autoAlphabetize = false; return true; } @Override public com.elmakers.mine.bukkit.api.wand.Wand duplicate() { ItemStack newItem = InventoryUtils.getCopy(item); Wand newWand = controller.getWand(newItem); newWand.saveState(); return newWand; } @Override public boolean configure(Map<String, Object> properties) { Map<Object, Object> convertedProperties = new HashMap<Object, Object>(properties); configure(ConfigurationUtils.toConfigurationSection(convertedProperties)); loadProperties(); saveState(); updateName(); updateLore(); return true; } @Override public boolean upgrade(Map<String, Object> properties) { Map<Object, Object> convertedProperties = new HashMap<Object, Object>(properties); upgrade(ConfigurationUtils.toConfigurationSection(convertedProperties)); loadProperties(); saveState(); updateName(); updateLore(); return true; } @Override public boolean isLocked() { return this.locked; } @Override public void unlock() { locked = false; setProperty("locked", false); } public boolean isPassive() { return passive; } @Override public boolean canUse(Player player) { if (!bound || ownerId == null || ownerId.length() == 0) return true; if (controller.hasPermission(player, "Magic.wand.override_bind", false)) return true; return ownerId.equalsIgnoreCase(player.getUniqueId().toString()); } @Override public boolean addSpell(String spellName) { if (!isModifiable()) return false; SpellKey spellKey = new SpellKey(spellName); if (hasSpell(spellKey)) { return false; } saveInventory(); SpellTemplate template = controller.getSpellTemplate(spellName); if (template == null) { controller.getLogger().warning("Tried to add unknown spell to wand: " + spellName); return false; } // This handles adding via an alias if (hasSpell(template.getKey())) return false; ItemStack spellItem = createSpellIcon(template); if (spellItem == null) { return false; } spellKey = template.getSpellKey(); int level = spellKey.getLevel(); int inventoryCount = inventories.size(); int spellCount = spells.size(); // Special handling for spell upgrades and spells to remove Integer inventorySlot = null; Integer currentLevel = spellLevels.get(spellKey.getBaseKey()); SpellTemplate currentSpell = getBaseSpell(spellKey); List<SpellKey> spellsToRemove = new ArrayList<>(template.getSpellsToRemove().size()); for (SpellKey key : template.getSpellsToRemove()) { if (spellLevels.get(key.getBaseKey()) != null) { spellsToRemove.add(key); } } if (currentLevel != null || !spellsToRemove.isEmpty()) { List<Inventory> allInventories = getAllInventories(); int currentSlot = 0; for (Inventory inventory : allInventories) { ItemStack[] items = inventory.getContents(); for (int index = 0; index < items.length; index++) { ItemStack itemStack = items[index]; if (isSpell(itemStack)) { SpellKey checkKey = new SpellKey(getSpell(itemStack)); if (checkKey.getBaseKey().equals(spellKey.getBaseKey())) { inventorySlot = currentSlot; inventory.setItem(index, null); spells.remove(checkKey.getKey()); } else { for (SpellKey key : spellsToRemove) { if (checkKey.getBaseKey().equals(key.getBaseKey())) { inventory.setItem(index, null); spells.remove(key.getKey()); spellLevels.remove(key.getBaseKey()); } } } } currentSlot++; } } } spellLevels.put(spellKey.getBaseKey(), level); spells.put(template.getKey(), inventorySlot); if (currentLevel != null) { if (activeSpell != null && !activeSpell.isEmpty()) { SpellKey currentKey = new SpellKey(activeSpell); if (currentKey.getBaseKey().equals(spellKey.getBaseKey())) { setActiveSpell(spellKey.getKey()); } } } if (activeSpell == null || activeSpell.isEmpty()) { setActiveSpell(spellKey.getKey()); } addToInventory(spellItem, inventorySlot); updateInventory(); updateHasInventory(); updateSpells(); saveState(); updateLore(); if (mage != null) { if (currentSpell != null) { String levelDescription = template.getLevelDescription(); if (levelDescription == null || levelDescription.isEmpty()) { levelDescription = template.getName(); } sendLevelMessage("spell_upgraded", currentSpell.getName(), levelDescription); mage.sendMessage(template.getUpgradeDescription().replace("$name", currentSpell.getName())); SpellUpgradeEvent upgradeEvent = new SpellUpgradeEvent(mage, this, currentSpell, template); Bukkit.getPluginManager().callEvent(upgradeEvent); } else { sendAddMessage("spell_added", template.getName()); AddSpellEvent addEvent = new AddSpellEvent(mage, this, template); Bukkit.getPluginManager().callEvent(addEvent); } if (spells.size() != spellCount) { if (spellCount == 0) { String message = getMessage("spell_instructions", "").replace("$wand", getName()); mage.sendMessage(message.replace("$spell", template.getName())); } else if (spellCount == 1) { mage.sendMessage(getMessage("inventory_instructions", "").replace("$wand", getName())); } if (inventoryCount == 1 && inventories.size() > 1) { mage.sendMessage(getMessage("page_instructions", "").replace("$wand", getName())); } } } return true; } @Override protected void sendAddMessage(String messageKey, String nameParam) { if (mage == null || nameParam == null || nameParam.isEmpty()) return; String message = getMessage(messageKey).replace("$name", nameParam).replace("$wand", getName()); mage.sendMessage(message); } protected void sendLevelMessage(String messageKey, String nameParam, String level) { if (mage == null || nameParam == null || nameParam.isEmpty()) return; String message = getMessage(messageKey).replace("$name", nameParam).replace("$wand", getName()).replace("$level", level); mage.sendMessage(message); } @Override protected void sendMessage(String messageKey) { if (mage == null || messageKey == null || messageKey.isEmpty()) return; String message = getMessage(messageKey).replace("$wand", getName()); mage.sendMessage(message); } @Override public String getMessage(String key, String defaultValue) { String message = controller.getMessages().get("wand." + key, defaultValue); if (template != null && !template.isEmpty()) { message = controller.getMessages().get("wands." + template + "." + key, message); } return message; } @Override protected void sendDebug(String debugMessage) { if (mage != null) { mage.sendDebugMessage(debugMessage); } } @Override public boolean add(com.elmakers.mine.bukkit.api.wand.Wand other) { if (other instanceof Wand) { return add((Wand)other); } return false; } @Override public boolean hasBrush(String materialKey) { return getBrushes().contains(materialKey); } @Override public boolean hasSpell(String spellName) { return hasSpell(new SpellKey(spellName)); } public boolean hasSpell(SpellKey spellKey) { Integer level = spellLevels.get(spellKey.getBaseKey()); return (level != null && level >= spellKey.getLevel()); } @Override public boolean addBrush(String materialKey) { if (!isModifiable()) return false; if (hasBrush(materialKey)) return false; saveInventory(); ItemStack itemStack = createBrushIcon(materialKey); if (itemStack == null) return false; int inventoryCount = inventories.size(); int brushCount = brushes.size(); brushes.put(materialKey, null); addToInventory(itemStack); if (activeMaterial == null || activeMaterial.length() == 0) { activateBrush(materialKey); } else { updateInventory(); } updateHasInventory(); updateBrushes(); saveState(); updateLore(); if (mage != null) { Messages messages = controller.getMessages(); String materialName = MaterialBrush.getMaterialName(messages, materialKey); if (materialName == null) { mage.getController().getLogger().warning("Invalid material: " + materialKey); materialName = materialKey; } sendAddMessage("brush_added", materialName); if (brushCount == 0) { mage.sendMessage(getMessage("brush_instructions").replace("$wand", getName())); } if (inventoryCount == 1 && inventories.size() > 1) { mage.sendMessage(getMessage("page_instructions").replace("$wand", getName())); } } return true; } @Override public void setActiveBrush(String materialKey) { activateBrush(materialKey); if (materialKey == null || mage == null) { return; } com.elmakers.mine.bukkit.api.block.MaterialBrush brush = mage.getBrush(); if (brush == null) { return; } boolean eraseWasActive = brush.isEraseModifierActive(); brush.activate(mage.getLocation(), materialKey); if (mage != null) { BrushMode mode = brush.getMode(); if (mode == BrushMode.CLONE) { mage.sendMessage(getMessage("clone_material_activated")); } else if (mode == BrushMode.REPLICATE) { mage.sendMessage(getMessage("replicate_material_activated")); } if (!eraseWasActive && brush.isEraseModifierActive()) { mage.sendMessage(getMessage("erase_modifier_activated")); } } } public void setActiveBrush(ItemStack itemStack) { if (!isBrush(itemStack)) return; setActiveBrush(getBrush(itemStack)); } public void activateBrush(String materialKey) { this.activeMaterial = materialKey; setProperty("active_material", this.activeMaterial); saveState(); updateName(); updateActiveMaterial(); updateHotbar(); } @Override public void setActiveSpell(String activeSpell) { SpellKey spellKey = new SpellKey(activeSpell); activeSpell = spellKey.getBaseKey(); if (!spellLevels.containsKey(activeSpell)) { return; } spellKey = new SpellKey(spellKey.getBaseKey(), spellLevels.get(activeSpell)); this.activeSpell = spellKey.getKey(); setProperty("active_spell", this.activeSpell); saveState(); updateName(); } @Override public boolean removeBrush(String materialKey) { if (!isModifiable() || materialKey == null) return false; saveInventory(); if (materialKey.equals(activeMaterial)) { activeMaterial = null; } brushes.remove(materialKey); List<Inventory> allInventories = getAllInventories(); boolean found = false; for (Inventory inventory : allInventories) { ItemStack[] items = inventory.getContents(); for (int index = 0; index < items.length; index++) { ItemStack itemStack = items[index]; if (itemStack != null && isBrush(itemStack)) { String itemKey = getBrush(itemStack); if (itemKey.equals(materialKey)) { found = true; inventory.setItem(index, null); } else if (activeMaterial == null) { activeMaterial = materialKey; } if (found && activeMaterial != null) { break; } } } } updateActiveMaterial(); updateInventory(); updateBrushes(); saveState(); updateName(); updateLore(); return found; } @Override public boolean removeSpell(String spellName) { if (!isModifiable()) return false; saveInventory(); if (spellName.equals(activeSpell)) { setActiveSpell(null); } spells.remove(spellName); SpellKey spellKey = new SpellKey(spellName); spellLevels.remove(spellKey.getBaseKey()); List<Inventory> allInventories = getAllInventories(); boolean found = false; for (Inventory inventory : allInventories) { ItemStack[] items = inventory.getContents(); for (int index = 0; index < items.length; index++) { ItemStack itemStack = items[index]; if (itemStack != null && itemStack.getType() != Material.AIR && isSpell(itemStack)) { if (getSpell(itemStack).equals(spellName)) { found = true; inventory.setItem(index, null); } else if (activeSpell == null) { setActiveSpell(getSpell(itemStack)); } if (found && activeSpell != null) { break; } } } } updateInventory(); updateHasInventory(); updateSpells(); saveState(); updateName(); updateLore(); return found; } @Override public Map<String, String> getOverrides() { return castOverrides == null ? new HashMap<String, String>() : new HashMap<>(castOverrides); } @Override public void setOverrides(Map<String, String> overrides) { if (overrides == null) { this.castOverrides = null; } else { this.castOverrides = new HashMap<>(overrides); } updateOverrides(); } @Override public void removeOverride(String key) { if (castOverrides != null) { castOverrides.remove(key); updateOverrides(); } } @Override public void setOverride(String key, String value) { if (castOverrides == null) { castOverrides = new HashMap<>(); } if (value == null || value.length() == 0) { castOverrides.remove(key); } else { castOverrides.put(key, value); } updateOverrides(); } @Override public boolean addOverride(String key, String value) { if (castOverrides == null) { castOverrides = new HashMap<>(); } boolean modified = false; if (value == null || value.length() == 0) { modified = castOverrides.containsKey(key); castOverrides.remove(key); } else { String current = castOverrides.get(key); modified = current == null || !current.equals(value); castOverrides.put(key, value); } if (modified) { updateOverrides(); } return modified; } protected void updateOverrides() { if (castOverrides != null && castOverrides.size() > 0) { Collection<String> parameters = new ArrayList<>(); for (Map.Entry<String, String> entry : castOverrides.entrySet()) { String value = entry.getValue(); parameters.add(entry.getKey() + " " + value.replace(",", "\\|")); } setProperty("overrides", StringUtils.join(parameters, ",")); } else { setProperty("overrides", null); } } public boolean hasStoredInventory() { return storedInventory != null; } public Inventory getStoredInventory() { return storedInventory; } public boolean addToStoredInventory(ItemStack item) { if (storedInventory == null) { return false; } HashMap<Integer, ItemStack> remainder = storedInventory.addItem(item); return remainder.size() == 0; } public void setStoredSlot(int slot) { this.storedSlot = slot; } public boolean storeInventory() { if (storedInventory != null) { if (mage != null) { mage.sendMessage("Your wand contains a previously stored inventory and will not activate, let go of it to clear."); } controller.getLogger().warning("Tried to store an inventory with one already present: " + (mage == null ? "?" : mage.getName())); return false; } Player player = mage.getPlayer(); if (player == null) { return false; } PlayerInventory inventory = player.getInventory(); storedInventory = CompatibilityUtils.createInventory(null, PLAYER_INVENTORY_SIZE, "Stored Inventory"); for (int i = 0; i < PLAYER_INVENTORY_SIZE; i++) { // Make sure we don't store any spells or magical materials, just in case ItemStack item = inventory.getItem(i); if (!Wand.isSpell(item) || Wand.isSkill(item)) { storedInventory.setItem(i, item); } inventory.setItem(i, null); } storedSlot = inventory.getHeldItemSlot(); inventory.setItem(storedSlot, item); return true; } @SuppressWarnings("deprecation") public boolean restoreInventory() { if (storedInventory == null) { return false; } Player player = mage.getPlayer(); if (player == null) { return false; } PlayerInventory inventory = player.getInventory(); // Check for the wand having been removed somehow, we don't want to put it back // if that happened. // This fixes dupe issues with armor stands, among other things // We do need to account for the wand not being the active slot anymore ItemStack storedItem = storedInventory.getItem(storedSlot); ItemStack currentItem = inventory.getItem(storedSlot); String currentId = getWandId(currentItem); String storedId = getWandId(storedItem); if (storedId != null && storedId.equals(id) && !Objects.equal(currentId, id)) { // Hacky special-case to avoid glitching spells out of the inventory // via the offhand slot. if (isSpell(currentItem)) { currentItem = null; } storedInventory.setItem(storedSlot, currentItem); controller.info("Cleared wand on inv close for player " + player.getName()); } for (int i = 0; i < storedInventory.getSize(); i++) { inventory.setItem(i, storedInventory.getItem(i)); } storedInventory = null; saveState(); inventory.setHeldItemSlot(storedSlot); player.updateInventory(); return true; } @Override public boolean isSoul() { return soul; } @Override public boolean isBound() { return bound; } @Override public Spell getSpell(String spellKey, com.elmakers.mine.bukkit.api.magic.Mage mage) { if (mage == null) { return null; } SpellKey key = new SpellKey(spellKey); String baseKey = key.getBaseKey(); Integer level = spellLevels.get(baseKey); if (level == null) { return null; } SpellKey levelKey = new SpellKey(baseKey, level); return mage.getSpell(levelKey.getKey()); } @Override public SpellTemplate getSpellTemplate(String spellKey) { SpellKey key = new SpellKey(spellKey); String baseKey = key.getBaseKey(); Integer level = spellLevels.get(baseKey); if (level == null) { return null; } SpellKey levelKey = new SpellKey(baseKey, level); return controller.getSpellTemplate(levelKey.getKey()); } @Override public Spell getSpell(String spellKey) { return getSpell(spellKey, mage); } @Override public int getSpellLevel(String spellKey) { SpellKey key = new SpellKey(spellKey); Integer level = spellLevels.get(key.getBaseKey()); return level == null ? 0 : level; } @Override public MageController getController() { return controller; } protected Map<String, Integer> getSpellInventory() { return new HashMap<>(spells); } protected Map<String, Integer> getBrushInventory() { return new HashMap<>(brushes); } protected void updateSpellInventory(Map<String, Integer> updateSpells) { for (Map.Entry<String, Integer> spellEntry : spells.entrySet()) { String spellKey = spellEntry.getKey(); Integer slot = updateSpells.get(spellKey); if (slot != null) { spellEntry.setValue(slot); } } } protected void updateBrushInventory(Map<String, Integer> updateBrushes) { for (Map.Entry<String, Integer> brushEntry : brushes.entrySet()) { String brushKey = brushEntry.getKey(); Integer slot = updateBrushes.get(brushKey); if (slot != null) { brushEntry.setValue(slot); } } } public Map<PotionEffectType, Integer> getPotionEffects() { return potionEffects; } @Override public float getHealthRegeneration() { Integer level = potionEffects.get(PotionEffectType.REGENERATION); return level != null && level > 0 ? (float)level : 0; } @Override public float getHungerRegeneration() { Integer level = potionEffects.get(PotionEffectType.SATURATION); return level != null && level > 0 ? (float)level : 0; } @Override public WandTemplate getTemplate() { if (template == null || template.isEmpty()) return null; return controller.getWandTemplate(template); } public boolean playPassiveEffects(String effects) { WandTemplate wandTemplate = getTemplate(); if (wandTemplate != null && mage != null) { boolean offhandActive = mage.setOffhandActive(isInOffhand); boolean result = false; try { result = wandTemplate.playEffects(mage, effects); } catch (Exception ex) { result = false; controller.getLogger().log(Level.WARNING, "Error playing effects " + effects + " from wand " + template, ex); } mage.setOffhandActive(offhandActive); return result; } return false; } @Override public boolean playEffects(String effects) { if (activeEffectsOnly && !inventoryIsOpen) { return false; } return playPassiveEffects(effects); } public WandAction getDropAction() { return dropAction; } public WandAction getRightClickAction() { return rightClickAction; } public WandAction getLeftClickAction() { return leftClickAction; } public WandAction getSwapAction() { return swapAction; } public boolean performAction(WandAction action) { WandMode mode = getMode(); switch (action) { case CAST: cast(); break; case TOGGLE: if (mode != WandMode.CHEST && mode != WandMode.INVENTORY) return false; toggleInventory(); break; case CYCLE: cycleActive(1); break; case CYCLE_REVERSE: cycleActive(-1); break; case CYCLE_HOTBAR: if (mode != WandMode.INVENTORY || !isInventoryOpen()) return false; if (getHotbarCount() > 1) { cycleHotbar(1); } else { closeInventory(); } break; case CYCLE_HOTBAR_REVERSE: if (mode != WandMode.INVENTORY) return false; if (getHotbarCount() > 1) { cycleHotbar(-1); } else if (isInventoryOpen()) { closeInventory(); } else { return false; } break; default: return false; } return true; } @Override public boolean checkAndUpgrade(boolean quiet) { com.elmakers.mine.bukkit.api.wand.WandUpgradePath path = getPath(); com.elmakers.mine.bukkit.api.wand.WandUpgradePath nextPath = path != null ? path.getUpgrade(): null; if (nextPath == null || path.canEnchant(this)) { return true; } if (!path.checkUpgradeRequirements(this, quiet ? null : mage)) { return false; } path.upgrade(this, mage); return true; } public int getEffectiveManaMax() { return effectiveManaMax; } public int getEffectiveManaRegeneration() { return effectiveManaRegeneration; } @Override public boolean isBlocked(double angle) { if (mage == null) return false; if (blockChance == 0) return false; if (blockFOV > 0 && angle > blockFOV) return false; long lastBlock = mage.getLastBlockTime(); if (blockCooldown > 0 && lastBlock > 0 && lastBlock + blockCooldown > System.currentTimeMillis()) return false; boolean isBlocked = Math.random() <= blockChance; if (isBlocked) { playEffects("spell_blocked"); mage.setLastBlockTime(System.currentTimeMillis()); } return isBlocked; } @Override public boolean isReflected(double angle) { if (mage == null) return false; if (blockReflectChance == 0) return false; if (blockFOV > 0 && angle > blockFOV) return false; long lastBlock = mage.getLastBlockTime(); if (blockCooldown > 0 && lastBlock > 0 && lastBlock + blockCooldown > System.currentTimeMillis()) return false; boolean isReflected = Math.random() <= blockReflectChance; if (isReflected) { playEffects("spell_reflected"); if (mage != null) mage.setLastBlockTime(System.currentTimeMillis()); } return isReflected; } }
Magic/src/main/java/com/elmakers/mine/bukkit/wand/Wand.java
package com.elmakers.mine.bukkit.wand; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.UUID; import java.util.logging.Level; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.elmakers.mine.bukkit.api.block.BrushMode; import com.elmakers.mine.bukkit.api.event.AddSpellEvent; import com.elmakers.mine.bukkit.api.event.SpellUpgradeEvent; import com.elmakers.mine.bukkit.api.event.WandPreActivateEvent; import com.elmakers.mine.bukkit.api.magic.MageController; import com.elmakers.mine.bukkit.api.magic.Messages; import com.elmakers.mine.bukkit.api.spell.CostReducer; import com.elmakers.mine.bukkit.api.spell.Spell; import com.elmakers.mine.bukkit.api.spell.SpellKey; import com.elmakers.mine.bukkit.api.spell.SpellTemplate; import com.elmakers.mine.bukkit.api.wand.WandTemplate; import com.elmakers.mine.bukkit.block.MaterialAndData; import com.elmakers.mine.bukkit.block.MaterialBrush; import com.elmakers.mine.bukkit.effect.builtin.EffectRing; import com.elmakers.mine.bukkit.heroes.HeroesManager; import com.elmakers.mine.bukkit.magic.BaseMagicProperties; import com.elmakers.mine.bukkit.magic.Mage; import com.elmakers.mine.bukkit.magic.MagicController; import com.elmakers.mine.bukkit.utility.ColorHD; import com.elmakers.mine.bukkit.utility.CompatibilityUtils; import com.elmakers.mine.bukkit.utility.ConfigurationUtils; import com.elmakers.mine.bukkit.utility.DeprecatedUtils; import com.elmakers.mine.bukkit.utility.InventoryUtils; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.elmakers.mine.bukkit.effect.SoundEffect; import de.slikey.effectlib.util.ParticleEffect; import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.BlockFace; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.MemoryConfiguration; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryView; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.plugin.Plugin; import org.bukkit.potion.PotionEffectType; import org.bukkit.util.Vector; public class Wand extends BaseMagicProperties implements CostReducer, com.elmakers.mine.bukkit.api.wand.Wand { public final static int INVENTORY_SIZE = 27; public final static int PLAYER_INVENTORY_SIZE = 36; public final static int HOTBAR_SIZE = 9; public final static int HOTBAR_INVENTORY_SIZE = HOTBAR_SIZE - 1; public final static float DEFAULT_SPELL_COLOR_MIX_WEIGHT = 0.0001f; public static int MAX_LORE_LENGTH = 24; public static String DEFAULT_WAND_TEMPLATE = "default"; private static int WAND_VERSION = 1; public final static String[] EMPTY_PARAMETERS = new String[0]; public final static Set<String> PROPERTY_KEYS = ImmutableSet.of( "active_spell", "active_material", "path", "template", "passive", "mana", "mana_regeneration", "mana_max", "mana_max_boost", "mana_regeneration_boost", "mana_per_damage", "bound", "soul", "has_uses", "uses", "upgrade", "indestructible", "undroppable", "consume_reduction", "cost_reduction", "cooldown_reduction", "effect_bubbles", "effect_color", "effect_particle", "effect_particle_count", "effect_particle_data", "effect_particle_interval", "effect_particle_min_velocity", "effect_particle_radius", "effect_particle_offset", "effect_sound", "effect_sound_interval", "effect_sound_pitch", "effect_sound_volume", "cast_spell", "cast_parameters", "cast_interval", "cast_min_velocity", "cast_velocity_direction", "hotbar_count", "hotbar", "icon", "icon_inactive", "icon_inactive_delay", "mode", "active_effects", "brush_mode", "keep", "locked", "quiet", "force", "randomize", "rename", "rename_description", "power", "overrides", "protection", "protection_physical", "protection_projectiles", "protection_falling", "protection_fire", "protection_explosions", "potion_effects", "materials", "spells", "powered", "protected", "heroes", "enchant_count", "max_enchant_count", "quick_cast", "left_click", "right_click", "drop", "swap", "block_fov", "block_chance", "block_reflect_chance", "block_mage_cooldown", "block_cooldown" ); private final static Set<String> HIDDEN_PROPERTY_KEYS = ImmutableSet.of( "id", "owner", "owner_id", "name", "description", "organize", "alphabetize", "fill", "stored", "upgrade_icon", "mana_timestamp", "upgrade_template", "custom_properties", // For legacy wands "haste", "health_regeneration", "hunger_regeneration", "xp", "xp_regeneration", "xp_max", "xp_max_boost", "xp_regeneration_boost", "mode_cast", "mode_drop", "version" ); /** * Set of properties that are used internally. * * Neither this list nor HIDDEN_PROPERTY_KEYS are really used anymore, but I'm keeping them * here in case we have some use for them in the future. * * Wands now load and retain any wand.* tags on their items. */ private final static Set<String> ALL_PROPERTY_KEYS_SET = Sets.union( PROPERTY_KEYS, HIDDEN_PROPERTY_KEYS); protected @Nonnull ItemStack item; /** * The currently active mage. * * Is only set when the wand is active of when the wand is * used for off-hand casting. */ protected @Nullable Mage mage; // Cached state private String id = ""; private List<Inventory> hotbars; private List<Inventory> inventories; private Map<String, Integer> spells = new HashMap<>(); private Map<String, Integer> spellLevels = new HashMap<>(); private Map<String, Integer> brushes = new HashMap<>(); private String activeSpell = ""; private String activeMaterial = ""; protected String wandName = ""; protected String description = ""; private String owner = ""; private String ownerId = ""; private String template = ""; private String path = ""; private boolean superProtected = false; private boolean superPowered = false; private boolean glow = false; private boolean soul = false; private boolean bound = false; private boolean indestructible = false; private boolean undroppable = false; private boolean keep = false; private boolean passive = false; private boolean autoOrganize = false; private boolean autoAlphabetize = false; private boolean autoFill = false; private boolean isUpgrade = false; private boolean randomize = false; private boolean rename = false; private boolean renameDescription = false; private boolean quickCast = false; private boolean quickCastDisabled = false; private boolean manualQuickCastDisabled = false; private WandAction leftClickAction = WandAction.CAST; private WandAction rightClickAction = WandAction.TOGGLE; private WandAction dropAction = WandAction.CYCLE_HOTBAR; private WandAction swapAction = WandAction.NONE; private MaterialAndData icon = null; private MaterialAndData upgradeIcon = null; private MaterialAndData inactiveIcon = null; private int inactiveIconDelay = 0; private String upgradeTemplate = null; protected float costReduction = 0; protected float consumeReduction = 0; protected float cooldownReduction = 0; protected float damageReduction = 0; protected float damageReductionPhysical = 0; protected float damageReductionProjectiles = 0; protected float damageReductionFalling = 0; protected float damageReductionFire = 0; protected float damageReductionExplosions = 0; private float power = 0; private float blockFOV = 0; private float blockChance = 0; private float blockReflectChance = 0; private int blockMageCooldown = 0; private int blockCooldown = 0; private int maxEnchantCount = 0; private int enchantCount = 0; private boolean hasInventory = false; private boolean locked = false; private boolean forceUpgrade = false; private boolean isHeroes = false; private int uses = 0; private boolean hasUses = false; private boolean isSingleUse = false; private float mana = 0; private float manaMaxBoost = 0; private float manaRegenerationBoost = 0; private int manaRegeneration = 0; private int manaMax = 0; private long lastManaRegeneration = 0; private float manaPerDamage = 0; private int effectiveManaMax = 0; private int effectiveManaRegeneration = 0; private ColorHD effectColor = null; private float effectColorSpellMixWeight = DEFAULT_SPELL_COLOR_MIX_WEIGHT; private ParticleEffect effectParticle = null; private float effectParticleData = 0; private int effectParticleCount = 0; private int effectParticleInterval = 0; private double effectParticleMinVelocity = 0; private double effectParticleRadius = 0.2; private double effectParticleOffset = 0.3; private boolean effectBubbles = false; private boolean activeEffectsOnly = false; private EffectRing effectPlayer = null; private int castInterval = 0; private double castMinVelocity = 0; private Vector castVelocityDirection = null; private String castSpell = null; private ConfigurationSection castParameters = null; private Map<PotionEffectType, Integer> potionEffects = new HashMap<>(); private SoundEffect effectSound = null; private int effectSoundInterval = 0; private int quietLevel = 0; private Map<String, String> castOverrides = null; // Transient state private boolean effectBubblesApplied = false; private boolean hasSpellProgression = false; private long lastLocationTime; private Vector lastLocation; private long lastSoundEffect; private long lastParticleEffect; private long lastSpellCast; // Inventory functionality private WandMode mode = null; private WandMode brushMode = null; private int openInventoryPage = 0; private boolean inventoryIsOpen = false; private Inventory displayInventory = null; private int currentHotbar = 0; public static WandManaMode manaMode = WandManaMode.BAR; public static WandManaMode spMode = WandManaMode.NUMBER; public static boolean regenWhileInactive = true; public static Material DefaultUpgradeMaterial = Material.NETHER_STAR; public static Material DefaultWandMaterial = Material.BLAZE_ROD; public static Material EnchantableWandMaterial = null; public static boolean SpellGlow = false; public static boolean BrushGlow = false; public static boolean BrushItemGlow = true; public static boolean LiveHotbar = true; public static boolean LiveHotbarSkills = false; public static boolean LiveHotbarCooldown = true; public static boolean Unbreakable = false; public static boolean Undroppable = true; public static SoundEffect inventoryOpenSound = null; public static SoundEffect inventoryCloseSound = null; public static SoundEffect inventoryCycleSound = null; public static SoundEffect noActionSound = null; public static String WAND_KEY = "wand"; public static String UPGRADE_KEY = "wand_upgrade"; public static String WAND_SELF_DESTRUCT_KEY = null; public static byte HIDE_FLAGS = 60; public static String brushSelectSpell = ""; private Inventory storedInventory = null; private int storedSlot; public Wand(MagicController controller) { super(controller); hotbars = new ArrayList<>(); setHotbarCount(1); inventories = new ArrayList<>(); } /** * @deprecated Use {@link MagicController#getWand(ItemStack)}. */ @Deprecated public Wand(MagicController controller, ItemStack itemStack) { this(controller); Preconditions.checkNotNull(itemStack); if (itemStack.getType() == Material.AIR) { itemStack.setType(DefaultWandMaterial); } this.icon = new MaterialAndData(itemStack); item = itemStack; boolean needsSave = false; boolean isWand = isWand(item); boolean isUpgradeItem = isUpgrade(item); if (isWand || isUpgradeItem) { ConfigurationSection wandConfig = itemToConfig(item, new MemoryConfiguration()); int version = wandConfig.getInt("version", 0); if (version < WAND_VERSION) { migrate(version, wandConfig); needsSave = true; } load(wandConfig); } loadProperties(); // Migrate old upgrade items if ((isUpgrade || isUpgradeItem) && isWand) { needsSave = true; InventoryUtils.removeMeta(item, WAND_KEY); } if (needsSave) { saveState(); } updateName(); updateLore(); } public Wand(MagicController controller, ConfigurationSection config) { this(controller, DefaultWandMaterial, (short)0); load(config); loadProperties(); updateName(); updateLore(); saveState(); } protected Wand(MagicController controller, String templateName) throws UnknownWandException { this(controller); // Default to "default" wand if (templateName == null || templateName.length() == 0) { templateName = DEFAULT_WAND_TEMPLATE; } // Check for randomized/pre-enchanted wands int level = 0; if (templateName.contains("(")) { String levelString = templateName.substring(templateName.indexOf('(') + 1, templateName.length() - 1); try { level = Integer.parseInt(levelString); } catch (Exception ex) { throw new IllegalArgumentException(ex); } templateName = templateName.substring(0, templateName.indexOf('(')); } WandTemplate template = controller.getWandTemplate(templateName); if (template == null) { throw new UnknownWandException(templateName); } WandTemplate migrateTemplate = template.getMigrateTemplate(); if (migrateTemplate != null) { template = migrateTemplate; templateName = migrateTemplate.getKey(); } setTemplate(templateName); setProperty("version", WAND_VERSION); ConfigurationSection templateConfig = template.getConfiguration(); if (templateConfig == null) { throw new UnknownWandException(templateName); } // Load all properties loadProperties(); // Add vanilla enchantments InventoryUtils.applyEnchantments(item, templateConfig.getConfigurationSection("enchantments")); // Enchant, if an enchanting level was provided if (level > 0) { // Account for randomized locked wands boolean wasLocked = locked; locked = false; randomize(level, false, null, true); locked = wasLocked; } // Don't randomize now if set to randomize later // Otherwise, do this here so the description updates if (!randomize) { randomize(); } updateName(); updateLore(); saveState(); } public Wand(MagicController controller, Material icon, short iconData) { // This will make the Bukkit ItemStack into a real ItemStack with NBT data. this(controller, InventoryUtils.makeReal(new ItemStack(icon, 1, iconData))); saveState(); updateName(); } protected void migrate(int version, ConfigurationSection wandConfig) { // First migration, clean out wand data that matches template if (version == 0) { ConfigurationSection templateConfig = controller.getWandTemplateConfiguration(wandConfig.getString("template")); if (templateConfig != null) { Set<String> keys = templateConfig.getKeys(false); for (String key : keys) { Object templateData = templateConfig.get(key); Object wandData = wandConfig.get(key); if (wandData == null) continue; String templateString = templateData.toString(); String wandString = wandData.toString(); if (templateData instanceof List) { templateString = templateString.substring(1, templateString.length() - 1); templateString = templateString.replace(", ", ","); templateData = templateString; } if (wandString.equalsIgnoreCase(templateString)) { wandConfig.set(key, null); continue; } try { double numericValue = Double.parseDouble(wandString); double numericTemplate = Double.parseDouble(templateString); if (numericValue == numericTemplate) { wandConfig.set(key, null); continue; } } catch (NumberFormatException ex) { } if (wandData.equals(templateData)) { wandConfig.set(key, null); } } } } wandConfig.set("version", WAND_VERSION); } @Override public void load(ConfigurationSection configuration) { if (configuration != null) { setTemplate(configuration.getString("template")); } super.load(configuration); } protected void setHotbarCount(int count) { hotbars.clear(); while (hotbars.size() < count) { hotbars.add(CompatibilityUtils.createInventory(null, HOTBAR_INVENTORY_SIZE, "Wand")); } while (hotbars.size() > count) { hotbars.remove(0); } } @Override public void unenchant() { item = new ItemStack(item.getType(), 1, item.getDurability()); clear(); } public void setIcon(Material material, byte data) { setIcon(material == null ? null : new MaterialAndData(material, data)); updateIcon(); } public void updateItemIcon() { setIcon(icon); } protected void updateIcon() { if (icon != null && icon.getMaterial() != null && icon.getMaterial() != Material.AIR) { String iconKey = icon.getKey(); if (iconKey != null && iconKey.isEmpty()) { iconKey = null; } setProperty("icon", iconKey); } } @Override public void setInactiveIcon(com.elmakers.mine.bukkit.api.block.MaterialAndData materialData) { if (materialData == null) { inactiveIcon = null; } else if (materialData instanceof MaterialAndData) { inactiveIcon = ((MaterialAndData)materialData); } else { inactiveIcon = new MaterialAndData(materialData); } String inactiveIconKey = null; if (inactiveIcon != null && inactiveIcon.getMaterial() != null && inactiveIcon.getMaterial() != Material.AIR) { inactiveIconKey = inactiveIcon.getKey(); if (inactiveIconKey != null && inactiveIconKey.isEmpty()) { inactiveIconKey = null; } } setProperty("inactive_icon", inactiveIconKey); updateItemIcon(); } @Override public void setIcon(com.elmakers.mine.bukkit.api.block.MaterialAndData materialData) { if (materialData instanceof MaterialAndData) { setIcon((MaterialAndData)materialData); } else { setIcon(new MaterialAndData(materialData)); } updateIcon(); } public void setIcon(MaterialAndData materialData) { if (materialData == null || !materialData.isValid()) return; if (materialData.getMaterial() == Material.AIR || materialData.getMaterial() == null) { materialData.setMaterial(DefaultWandMaterial); } icon = materialData; if (item == null) { item = InventoryUtils.makeReal(this.icon.getItemStack(1)); } Short durability = null; if (!indestructible && !isUpgrade && icon.getMaterial().getMaxDurability() > 0) { durability = item.getDurability(); } try { if (inactiveIcon == null || (mage != null && getMode() == WandMode.INVENTORY && isInventoryOpen())) { icon.applyToItem(item); } else { inactiveIcon.applyToItem(item); } } catch (Exception ex) { controller.getLogger().log(Level.WARNING, "Unable to apply wand icon", ex); item.setType(DefaultWandMaterial); } if (durability != null) { item.setDurability(durability); } // Make indestructible // The isUpgrade checks here and above are for using custom icons in 1.9, this is a bit hacky. if ((indestructible || Unbreakable || isUpgrade) && !manaMode.useDurability()) { CompatibilityUtils.makeUnbreakable(item); } else { CompatibilityUtils.removeUnbreakable(item); } CompatibilityUtils.hideFlags(item, HIDE_FLAGS); } @Override public void makeUpgrade() { if (!isUpgrade) { isUpgrade = true; String oldName = wandName; String newName = controller.getMessages().get("wand.upgrade_name"); newName = newName.replace("$name", oldName); String newDescription = controller.getMessages().get("wand.upgrade_default_description"); if (template != null && template.length() > 0) { newDescription = controller.getMessages().get("wands." + template + ".upgrade_description", description); } setIcon(DefaultUpgradeMaterial, (byte) 0); setName(newName); setDescription(newDescription); InventoryUtils.removeMeta(item, WAND_KEY); saveState(); updateName(true); updateLore(); } } public void newId() { if (!this.isUpgrade && !this.isSingleUse) { id = UUID.randomUUID().toString(); } else { id = null; } setProperty("id", id); } public void checkId() { if ((id == null || id.length() == 0) && !this.isUpgrade) { newId(); } } @Override public String getId() { return isSingleUse ? template : id; } public float getManaRegenerationBoost() { return manaRegenerationBoost; } public float getManaMaxBoost() { return manaMaxBoost; } @Override public int getManaRegeneration() { return manaRegeneration; } @Override public int getManaMax() { return manaMax; } @Override public void setMana(float mana) { this.mana = Math.max(0, mana); setProperty("mana", this.mana); } @Override public void setManaMax(int manaMax) { this.manaMax = Math.max(0, manaMax); setProperty("mana_max", this.manaMax); } @Override public float getMana() { return mana; } @Override public void removeMana(float amount) { if (isHeroes && mage != null) { HeroesManager heroes = controller.getHeroes(); if (heroes != null) { heroes.removeMana(mage.getPlayer(), (int)Math.ceil(amount)); } } mana = Math.max(0, mana - amount); setProperty("mana", this.mana); updateMana(); } public boolean isModifiable() { return !locked; } @Override public boolean isIndestructible() { return indestructible; } @Override public boolean isUndroppable() { // Don't allow dropping wands while the inventory is open. return undroppable || isInventoryOpen(); } public boolean isUpgrade() { return isUpgrade; } public boolean usesMana() { if (isCostFree()) return false; return manaMax > 0 || isHeroes; } @Override public float getCooldownReduction() { return controller.getCooldownReduction() + cooldownReduction * controller.getMaxCooldownReduction(); } @Override public float getCostReduction() { if (isCostFree()) return 1.0f; return controller.getCostReduction() + costReduction * controller.getMaxCostReduction(); } @Override public float getConsumeReduction() { return consumeReduction; } @Override public float getCostScale() { return 1; } public void setCooldownReduction(float reduction) { cooldownReduction = reduction; setProperty("cooldown_reduction", cooldownReduction); } public boolean getHasInventory() { return hasInventory; } @Override public float getPower() { return power; } @Override public boolean isSuperProtected() { return superProtected; } @Override public boolean isSuperPowered() { return superPowered; } @Override public boolean isCostFree() { return costReduction > 1; } @Override public boolean isConsumeFree() { return consumeReduction >= 1; } @Override public boolean isCooldownFree() { return cooldownReduction > 1; } public float getDamageReduction() { return damageReduction; } public float getDamageReductionPhysical() { return damageReductionPhysical; } public float getDamageReductionProjectiles() { return damageReductionProjectiles; } public float getDamageReductionFalling() { return damageReductionFalling; } public float getDamageReductionFire() { return damageReductionFire; } public float getDamageReductionExplosions() { return damageReductionExplosions; } @Override public String getName() { return wandName; } public String getDescription() { return description; } public String getOwner() { return owner; } public String getOwnerId() { return ownerId; } @Override public long getWorth() { long worth = 0; // TODO: Item properties, brushes, etc Set<String> spells = getSpells(); for (String spellKey : spells) { SpellTemplate spell = controller.getSpellTemplate(spellKey); if (spell != null) { worth += spell.getWorth(); } } return worth; } @Override public void setName(String name) { wandName = ChatColor.stripColor(name); setProperty("name", wandName); updateName(); } public void setTemplate(String templateName) { this.template = templateName; setParent(controller.getWandTemplate(templateName)); setProperty("template", template); } @Override public String getTemplateKey() { return this.template; } @Override public boolean hasTag(String tag) { WandTemplate template = getTemplate(); return template != null && template.hasTag(tag); } @Override public com.elmakers.mine.bukkit.api.wand.WandUpgradePath getPath() { String pathKey = path; if (pathKey == null || pathKey.length() == 0) { pathKey = controller.getDefaultWandPath(); } return WandUpgradePath.getPath(pathKey); } public boolean hasPath() { return path != null && path.length() > 0; } @Override public void setDescription(String description) { this.description = description; setProperty("description", description); updateLore(); } public boolean tryToOwn(Player player) { if (ownerId == null || ownerId.length() == 0) { takeOwnership(player); return true; } return false; } public void takeOwnership(Player player) { if (mage != null && (ownerId == null || ownerId.length() == 0) && quietLevel < 2) { mage.sendMessage(getMessage("bound_instructions", "").replace("$wand", getName())); Spell spell = getActiveSpell(); if (spell != null) { String message = getMessage("spell_instructions", "").replace("$wand", getName()); mage.sendMessage(message.replace("$spell", spell.getName())); } if (spells.size() > 1) { mage.sendMessage(getMessage("inventory_instructions", "").replace("$wand", getName())); } com.elmakers.mine.bukkit.api.wand.WandUpgradePath path = getPath(); if (path != null) { String message = getMessage("enchant_instructions", "").replace("$wand", getName()); mage.sendMessage(message); } } owner = ChatColor.stripColor(player.getDisplayName()); ownerId = player.getUniqueId().toString(); setProperty("owner", owner); setProperty("owner_id", ownerId); updateLore(); } @Override public ItemStack getItem() { return item; } @Override public com.elmakers.mine.bukkit.api.block.MaterialAndData getIcon() { return icon; } @Override public com.elmakers.mine.bukkit.api.block.MaterialAndData getInactiveIcon() { return inactiveIcon; } protected List<Inventory> getAllInventories() { List<Inventory> allInventories = new ArrayList<>(inventories.size() + hotbars.size()); allInventories.addAll(hotbars); allInventories.addAll(inventories); return allInventories; } @Override public Set<String> getSpells() { return spells.keySet(); } protected String getSpellString() { Set<String> spellNames = new TreeSet<>(); for (Map.Entry<String, Integer> spellSlot : spells.entrySet()) { Integer slot = spellSlot.getValue(); String spellKey = spellSlot.getKey(); if (slot != null) { spellKey += "@" + slot; } spellNames.add(spellKey); } return StringUtils.join(spellNames, ","); } @Override public Set<String> getBrushes() { return brushes.keySet(); } protected String getMaterialString() { Set<String> materialNames = new TreeSet<>(); for (Map.Entry<String, Integer> brushSlot : brushes.entrySet()) { Integer slot = brushSlot.getValue(); String materialKey = brushSlot.getKey(); if (slot != null) { materialKey += "@" + slot; } materialNames.add(materialKey); } return StringUtils.join(materialNames, ","); } protected Integer parseSlot(String[] pieces) { Integer slot = null; if (pieces.length > 1) { try { slot = Integer.parseInt(pieces[1]); } catch (Exception ex) { slot = null; } if (slot != null && slot < 0) { slot = null; } } return slot; } protected void addToInventory(ItemStack itemStack) { if (itemStack == null || itemStack.getType() == Material.AIR) { return; } if (getBrushMode() != WandMode.INVENTORY && isBrush(itemStack)) { String brushKey = getBrush(itemStack); if (!MaterialBrush.isSpecialMaterialKey(brushKey) || MaterialBrush.isSchematic(brushKey)) { return; } } List<Inventory> checkInventories = getAllInventories(); boolean added = false; for (Inventory inventory : checkInventories) { HashMap<Integer, ItemStack> returned = inventory.addItem(itemStack); if (returned.size() == 0) { added = true; break; } } if (!added) { Inventory newInventory = CompatibilityUtils.createInventory(null, INVENTORY_SIZE, "Wand"); newInventory.addItem(itemStack); inventories.add(newInventory); } } protected Inventory getDisplayInventory() { if (displayInventory == null) { int inventorySize = INVENTORY_SIZE + HOTBAR_SIZE; displayInventory = CompatibilityUtils.createInventory(null, inventorySize, "Wand"); } return displayInventory; } protected @Nonnull Inventory getInventoryByIndex(int inventoryIndex) { // Auto create while (inventoryIndex >= inventories.size()) { inventories.add(CompatibilityUtils.createInventory(null, INVENTORY_SIZE, "Wand")); } return inventories.get(inventoryIndex); } protected int getHotbarSize() { return hotbars.size() * HOTBAR_INVENTORY_SIZE; } protected @Nonnull Inventory getInventory(int slot) { int hotbarSize = getHotbarSize(); if (slot < hotbarSize) { return hotbars.get(slot / HOTBAR_INVENTORY_SIZE); } int inventoryIndex = (slot - hotbarSize) / INVENTORY_SIZE; return getInventoryByIndex(inventoryIndex); } protected int getInventorySlot(int slot) { int hotbarSize = getHotbarSize(); if (slot < hotbarSize) { return slot % HOTBAR_INVENTORY_SIZE; } return ((slot - hotbarSize) % INVENTORY_SIZE); } protected void addToInventory(ItemStack itemStack, Integer slot) { if (slot == null) { addToInventory(itemStack); return; } Inventory inventory = getInventory(slot); slot = getInventorySlot(slot); ItemStack existing = inventory.getItem(slot); inventory.setItem(slot, itemStack); if (existing != null && existing.getType() != Material.AIR) { addToInventory(existing); } } protected void parseInventoryStrings(String spellString, String materialString) { // Force an update of the display inventory since chest mode is a different size displayInventory = null; for (Inventory hotbar : hotbars) { hotbar.clear(); } inventories.clear(); spells.clear(); spellLevels.clear(); brushes.clear(); // Support YML-List-As-String format spellString = spellString.replaceAll("[\\]\\[]", ""); String[] spellNames = StringUtils.split(spellString, ","); for (String spellName : spellNames) { String[] pieces = spellName.split("@"); Integer slot = parseSlot(pieces); // Handle aliases and upgrades smoothly String loadedKey = pieces[0].trim(); SpellKey spellKey = new SpellKey(loadedKey); SpellTemplate spell = controller.getSpellTemplate(loadedKey); // Downgrade spells if higher levels have gone missing while (spell == null && spellKey.getLevel() > 0) { spellKey = new SpellKey(spellKey.getBaseKey(), spellKey.getLevel() - 1); spell = controller.getSpellTemplate(spellKey.getKey()); } if (spell != null) { spellKey = spell.getSpellKey(); Integer currentLevel = spellLevels.get(spellKey.getBaseKey()); if (currentLevel == null || currentLevel < spellKey.getLevel()) { spellLevels.put(spellKey.getBaseKey(), spellKey.getLevel()); spells.put(spellKey.getKey(), slot); if (currentLevel != null) { SpellKey oldKey = new SpellKey(spellKey.getBaseKey(), currentLevel); spells.remove(oldKey.getKey()); } } if (activeSpell == null || activeSpell.length() == 0) { activeSpell = spellKey.getKey(); } } ItemStack itemStack = createSpellItem(spell, "", controller, getActiveMage(), this, false); if (itemStack != null) { addToInventory(itemStack, slot); } } materialString = materialString.replaceAll("[\\]\\[]", ""); String[] materialNames = StringUtils.split(materialString, ","); WandMode brushMode = getBrushMode(); for (String materialName : materialNames) { String[] pieces = materialName.split("@"); Integer slot = parseSlot(pieces); String materialKey = pieces[0].trim(); brushes.put(materialKey, slot); boolean addToInventory = brushMode == WandMode.INVENTORY || (MaterialBrush.isSpecialMaterialKey(materialKey) && !MaterialBrush.isSchematic(materialKey)); if (addToInventory) { ItemStack itemStack = createBrushIcon(materialKey); if (itemStack == null) { controller.getPlugin().getLogger().warning("Unable to create material icon for key " + materialKey); continue; } if (activeMaterial == null || activeMaterial.length() == 0) activeMaterial = materialKey; addToInventory(itemStack, slot); } } updateHasInventory(); if (openInventoryPage >= inventories.size()) { openInventoryPage = 0; } } protected ItemStack createSpellIcon(SpellTemplate spell) { return createSpellItem(spell, "", controller, getActiveMage(), this, false); } public static ItemStack createSpellItem(String spellKey, MagicController controller, Wand wand, boolean isItem) { String[] split = spellKey.split(" ", 2); return createSpellItem(controller.getSpellTemplate(split[0]), split.length > 1 ? split[1] : "", controller, wand == null ? null : wand.getActiveMage(), wand, isItem); } public static ItemStack createSpellItem(String spellKey, MagicController controller, com.elmakers.mine.bukkit.api.magic.Mage mage, Wand wand, boolean isItem) { String[] split = spellKey.split(" ", 2); return createSpellItem(controller.getSpellTemplate(split[0]), split.length > 1 ? split[1] : "", controller, mage, wand, isItem); } public static ItemStack createSpellItem(SpellTemplate spell, String args, MagicController controller, com.elmakers.mine.bukkit.api.magic.Mage mage, Wand wand, boolean isItem) { if (spell == null) return null; String iconURL = spell.getIconURL(); ItemStack itemStack = null; if (iconURL != null && controller.isUrlIconsEnabled()) { itemStack = InventoryUtils.getURLSkull(iconURL); } if (itemStack == null) { ItemStack originalItemStack = null; com.elmakers.mine.bukkit.api.block.MaterialAndData icon = spell.getIcon(); if (icon == null) { controller.getPlugin().getLogger().warning("Unable to create spell icon for " + spell.getName() + ", missing material"); return null; } try { originalItemStack = new ItemStack(icon.getMaterial(), 1, icon.getData()); itemStack = InventoryUtils.makeReal(originalItemStack); } catch (Exception ex) { itemStack = null; } if (itemStack == null) { if (icon.getMaterial() != Material.AIR) { String iconName = icon.getName(); controller.getPlugin().getLogger().warning("Unable to create spell icon for " + spell.getKey() + " with material " + iconName); } return originalItemStack; } } InventoryUtils.makeUnbreakable(itemStack); InventoryUtils.hideFlags(itemStack, (byte)63); updateSpellItem(controller.getMessages(), itemStack, spell, args, mage, wand, wand == null ? null : wand.activeMaterial, isItem); return itemStack; } protected ItemStack createBrushIcon(String materialKey) { return createBrushItem(materialKey, controller, this, false); } public static ItemStack createBrushItem(String materialKey, com.elmakers.mine.bukkit.api.magic.MageController controller, Wand wand, boolean isItem) { MaterialBrush brushData = MaterialBrush.parseMaterialKey(materialKey); if (brushData == null) return null; ItemStack itemStack = brushData.getItem(controller, isItem); if (BrushGlow || (isItem && BrushItemGlow)) { CompatibilityUtils.addGlow(itemStack); } InventoryUtils.makeUnbreakable(itemStack); InventoryUtils.hideFlags(itemStack, (byte)63); updateBrushItem(controller.getMessages(), itemStack, brushData, wand); return itemStack; } public void checkItem(ItemStack newItem) { if (newItem.getAmount() > item.getAmount()) { item.setAmount(newItem.getAmount()); } } protected boolean findItem() { if (mage != null) { Player player = mage.getPlayer(); if (player != null) { ItemStack itemInHand = player.getInventory().getItemInMainHand(); String itemId = getWandId(itemInHand); if (itemId != null && itemId.equals(id) && itemInHand != item) { item = itemInHand; return true; } itemInHand = player.getInventory().getItemInOffHand(); itemId = getWandId(itemInHand); if (itemId != null && itemId.equals(id) && itemInHand != item) { item = itemInHand; return true; } } } return false; } @Override public void saveState() { // Make sure we're on the current item instance if (findItem()) { updateItemIcon(); updateName(); updateLore(); } if (item == null || item.getType() == Material.AIR) return; // Check for upgrades that still have wand data if (isUpgrade && isWand(item)) { InventoryUtils.removeMeta(item, WAND_KEY); } Object wandNode = InventoryUtils.createNode(item, isUpgrade ? UPGRADE_KEY : WAND_KEY); if (wandNode == null) { controller.getLogger().warning("Failed to save wand state for wand to : " + item); Thread.dumpStack(); } else { InventoryUtils.saveTagsToNBT(getConfiguration(), wandNode); } if (mage != null) { Player player = mage.getPlayer(); if (player != null) { // Update the stored item, too- in case we save while the // inventory is open. if (storedInventory != null) { int currentSlot = player.getInventory().getHeldItemSlot(); ItemStack storedItem = storedInventory.getItem(currentSlot); String storedId = getWandId(storedItem); if (storedId != null && storedId.equals(id)) { storedInventory.setItem(currentSlot, item); } } } } } public static ConfigurationSection itemToConfig(ItemStack item, ConfigurationSection stateNode) { Object wandNode = InventoryUtils.getNode(item, WAND_KEY); if (wandNode == null) { wandNode = InventoryUtils.getNode(item, UPGRADE_KEY); if (wandNode == null) { return null; } } InventoryUtils.loadAllTagsFromNBT(stateNode, wandNode); return stateNode; } public static void configToItem(ConfigurationSection itemSection, ItemStack item) { ConfigurationSection stateNode = itemSection.getConfigurationSection("wand"); Object wandNode = InventoryUtils.createNode(item, Wand.WAND_KEY); if (wandNode != null) { InventoryUtils.saveTagsToNBT(stateNode, wandNode); } } protected String getPotionEffectString() { return getPotionEffectString(potionEffects); } @Override public void save(ConfigurationSection node, boolean filtered) { ConfigurationUtils.addConfigurations(node, getConfiguration()); // Filter out some fields if (filtered) { node.set("id", null); node.set("owner_id", null); node.set("owner", null); node.set("template", null); node.set("mana_timestamp", null); // Inherit from template if present if (template != null && !template.isEmpty()) { node.set("inherit", template); } } if (isUpgrade) { node.set("upgrade", true); } // Change some CSV to lists if (node.contains("spells") && node.isString("spells")) { node.set("spells", Arrays.asList(StringUtils.split(node.getString("spells"), ","))); } if (node.contains("materials") && node.isString("materials")) { node.set("materials", Arrays.asList(StringUtils.split(node.getString("materials"), ","))); } if (node.contains("overrides") && node.isString("overrides")) { node.set("overrides", Arrays.asList(StringUtils.split(node.getString("overrides"), ","))); } if (node.contains("potion_effects") && node.isString("potion_effects")) { node.set("potion_effects", Arrays.asList(StringUtils.split(node.getString("potion_effects"), ","))); } } public void updateBrushes() { setProperty("materials", getMaterialString()); } public void updateSpells() { setProperty("spells", getSpellString()); } public void setEffectColor(String hexColor) { // Annoying config conversion issue :\ if (hexColor.contains(".")) { hexColor = hexColor.substring(0, hexColor.indexOf('.')); } if (hexColor == null || hexColor.length() == 0 || hexColor.equals("none")) { effectColor = null; return; } effectColor = new ColorHD(hexColor); if (hexColor.equals("random")) { setProperty("effect_color", effectColor.toString()); } } public void loadProperties() { loadProperties(getEffectiveConfiguration()); } public void loadProperties(ConfigurationSection wandConfig) { locked = wandConfig.getBoolean("locked", locked); consumeReduction = (float)wandConfig.getDouble("consume_reduction"); costReduction = (float)wandConfig.getDouble("cost_reduction"); cooldownReduction = (float)wandConfig.getDouble("cooldown_reduction"); power = (float)wandConfig.getDouble("power"); damageReduction = (float)wandConfig.getDouble("protection"); damageReductionPhysical = (float)wandConfig.getDouble("protection_physical"); damageReductionProjectiles = (float)wandConfig.getDouble("protection_projectiles"); damageReductionFalling = (float)wandConfig.getDouble("protection_falling"); damageReductionFire = (float)wandConfig.getDouble("protection_fire"); damageReductionExplosions = (float)wandConfig.getDouble("protection_explosions"); blockChance = (float)wandConfig.getDouble("block_chance"); blockReflectChance = (float)wandConfig.getDouble("block_reflect_chance"); blockFOV = (float)wandConfig.getDouble("block_fov"); blockMageCooldown = wandConfig.getInt("block_mage_cooldown"); blockCooldown = wandConfig.getInt("block_cooldown"); manaRegeneration = wandConfig.getInt("mana_regeneration", wandConfig.getInt("xp_regeneration")); manaMax = wandConfig.getInt("mana_max", wandConfig.getInt("xp_max")); mana = wandConfig.getInt("mana", wandConfig.getInt("xp")); manaMaxBoost = (float)wandConfig.getDouble("mana_max_boost", wandConfig.getDouble("xp_max_boost")); manaRegenerationBoost = (float)wandConfig.getDouble("mana_regeneration_boost", wandConfig.getDouble("xp_regeneration_boost")); manaPerDamage = (float)wandConfig.getDouble("mana_per_damage"); // Check for single-use wands uses = wandConfig.getInt("uses"); String tempId = wandConfig.getString("id", id); isSingleUse = (tempId == null || tempId.isEmpty()) && uses == 1; hasUses = wandConfig.getBoolean("has_uses", hasUses) || uses > 0; // Convert some legacy properties to potion effects float healthRegeneration = (float)wandConfig.getDouble("health_regeneration", 0); float hungerRegeneration = (float)wandConfig.getDouble("hunger_regeneration", 0); float speedIncrease = (float)wandConfig.getDouble("haste", 0); if (speedIncrease > 0) { potionEffects.put(PotionEffectType.SPEED, 1); } if (healthRegeneration > 0) { potionEffects.put(PotionEffectType.REGENERATION, 1); } if (hungerRegeneration > 0) { potionEffects.put(PotionEffectType.SATURATION, 1); } if (regenWhileInactive) { lastManaRegeneration = wandConfig.getLong("mana_timestamp"); } else { lastManaRegeneration = System.currentTimeMillis(); } if (wandConfig.contains("effect_color")) { setEffectColor(wandConfig.getString("effect_color")); } id = wandConfig.getString("id", id); isUpgrade = wandConfig.getBoolean("upgrade", isUpgrade); quietLevel = wandConfig.getInt("quiet", quietLevel); effectBubbles = wandConfig.getBoolean("effect_bubbles", effectBubbles); keep = wandConfig.getBoolean("keep", keep); passive = wandConfig.getBoolean("passive", passive); indestructible = wandConfig.getBoolean("indestructible", indestructible); superPowered = wandConfig.getBoolean("powered", superPowered); superProtected = wandConfig.getBoolean("protected", superProtected); glow = wandConfig.getBoolean("glow", glow); undroppable = wandConfig.getBoolean("undroppable", undroppable); isHeroes = wandConfig.getBoolean("heroes", isHeroes); bound = wandConfig.getBoolean("bound", bound); soul = wandConfig.getBoolean("soul", soul); forceUpgrade = wandConfig.getBoolean("force", forceUpgrade); autoOrganize = wandConfig.getBoolean("organize", autoOrganize); autoAlphabetize = wandConfig.getBoolean("alphabetize", autoAlphabetize); autoFill = wandConfig.getBoolean("fill", autoFill); randomize = wandConfig.getBoolean("randomize", randomize); rename = wandConfig.getBoolean("rename", rename); renameDescription = wandConfig.getBoolean("rename_description", renameDescription); enchantCount = wandConfig.getInt("enchant_count", enchantCount); maxEnchantCount = wandConfig.getInt("max_enchant_count", maxEnchantCount); if (wandConfig.contains("effect_particle")) { effectParticle = ConfigurationUtils.toParticleEffect(wandConfig.getString("effect_particle")); effectParticleData = 0; } if (wandConfig.contains("effect_sound")) { effectSound = ConfigurationUtils.toSoundEffect(wandConfig.getString("effect_sound")); } activeEffectsOnly = wandConfig.getBoolean("active_effects", activeEffectsOnly); effectParticleData = (float)wandConfig.getDouble("effect_particle_data", effectParticleData); effectParticleCount = wandConfig.getInt("effect_particle_count", effectParticleCount); effectParticleRadius = wandConfig.getDouble("effect_particle_radius", effectParticleRadius); effectParticleOffset = wandConfig.getDouble("effect_particle_offset", effectParticleOffset); effectParticleInterval = wandConfig.getInt("effect_particle_interval", effectParticleInterval); effectParticleMinVelocity = wandConfig.getDouble("effect_particle_min_velocity", effectParticleMinVelocity); effectSoundInterval = wandConfig.getInt("effect_sound_interval", effectSoundInterval); castInterval = wandConfig.getInt("cast_interval", castInterval); castMinVelocity = wandConfig.getDouble("cast_min_velocity", castMinVelocity); castVelocityDirection = ConfigurationUtils.getVector(wandConfig, "cast_velocity_direction", castVelocityDirection); castSpell = wandConfig.getString("cast_spell", castSpell); String castParameterString = wandConfig.getString("cast_parameters", null); if (castParameterString != null && !castParameterString.isEmpty()) { castParameters = new MemoryConfiguration(); ConfigurationUtils.addParameters(StringUtils.split(castParameterString, " "), castParameters); } boolean needsInventoryUpdate = false; if (wandConfig.contains("mode")) { WandMode newMode = parseWandMode(wandConfig.getString("mode"), mode); if (newMode != mode) { setMode(newMode); needsInventoryUpdate = true; } } if (wandConfig.contains("brush_mode")) { setBrushMode(parseWandMode(wandConfig.getString("brush_mode"), brushMode)); } String quickCastType = wandConfig.getString("quick_cast", wandConfig.getString("mode_cast")); if (quickCastType != null) { if (quickCastType.equalsIgnoreCase("true")) { quickCast = true; // This is to turn the redundant spell lore off quickCastDisabled = true; manualQuickCastDisabled = false; } else if (quickCastType.equalsIgnoreCase("manual")) { quickCast = false; quickCastDisabled = true; manualQuickCastDisabled = false; } else if (quickCastType.equalsIgnoreCase("disable")) { quickCast = false; quickCastDisabled = true; manualQuickCastDisabled = true; } else { quickCast = false; quickCastDisabled = false; manualQuickCastDisabled = false; } } // Backwards compatibility if (wandConfig.getBoolean("mode_drop", false)) { dropAction = WandAction.TOGGLE; swapAction = WandAction.CYCLE_HOTBAR; rightClickAction = WandAction.NONE; } else if (mode == WandMode.CAST) { leftClickAction = WandAction.CAST; rightClickAction = WandAction.CAST; swapAction = WandAction.NONE; dropAction = WandAction.NONE; } leftClickAction = parseWandAction(wandConfig.getString("left_click"), leftClickAction); rightClickAction = parseWandAction(wandConfig.getString("right_click"), rightClickAction); dropAction = parseWandAction(wandConfig.getString("drop"), dropAction); swapAction = parseWandAction(wandConfig.getString("swap"), swapAction); owner = wandConfig.getString("owner", owner); ownerId = wandConfig.getString("owner_id", ownerId); template = wandConfig.getString("template", template); upgradeTemplate = wandConfig.getString("upgrade_template", upgradeTemplate); path = wandConfig.getString("path", path); activeSpell = wandConfig.getString("active_spell", activeSpell); activeMaterial = wandConfig.getString("active_material", activeMaterial); String wandMaterials = ""; String wandSpells = ""; if (wandConfig.contains("hotbar_count")) { int newCount = Math.max(1, wandConfig.getInt("hotbar_count")); if (newCount != hotbars.size() || newCount > hotbars.size()) { if (isInventoryOpen()) { closeInventory(); } needsInventoryUpdate = true; setHotbarCount(newCount); } } if (wandConfig.contains("hotbar")) { int hotbar = wandConfig.getInt("hotbar"); currentHotbar = hotbar < 0 || hotbar >= hotbars.size() ? 0 : hotbar; } // Default to template names, override with localizations and finally with wand data wandName = controller.getMessages().get("wand.default_name"); description = ""; // Check for migration information in the template config ConfigurationSection templateConfig = null; if (template != null && !template.isEmpty()) { templateConfig = controller.getWandTemplateConfiguration(template); if (templateConfig != null) { wandName = templateConfig.getString("name", wandName); description = templateConfig.getString("description", description); } wandName = controller.getMessages().get("wands." + template + ".name", wandName); description = controller.getMessages().get("wands." + template + ".description", description); } wandName = wandConfig.getString("name", wandName); description = wandConfig.getString("description", description); WandTemplate wandTemplate = getTemplate(); WandTemplate migrateTemplate = wandTemplate == null ? null : wandTemplate.getMigrateTemplate(); if (migrateTemplate != null) { template = migrateTemplate.getKey(); templateConfig = migrateTemplate.getConfiguration(); wandTemplate = migrateTemplate; } if (wandTemplate != null) { // Add vanilla attributes InventoryUtils.applyAttributes(item, wandTemplate.getAttributes(), wandTemplate.getAttributeSlot()); } if (wandConfig.contains("icon_inactive")) { String iconKey = wandConfig.getString("icon_inactive"); if (wandTemplate != null) { iconKey = wandTemplate.migrateIcon(iconKey); } if (iconKey != null) { inactiveIcon = new MaterialAndData(iconKey); } } if (inactiveIcon != null && (inactiveIcon.getMaterial() == null || inactiveIcon.getMaterial() == Material.AIR)) { inactiveIcon = null; } inactiveIconDelay = wandConfig.getInt("icon_inactive_delay", inactiveIconDelay); if (wandConfig.contains("randomize_icon")) { setIcon(new MaterialAndData(wandConfig.getString("randomize_icon"))); randomize = true; } else if (!randomize && wandConfig.contains("icon")) { String iconKey = wandConfig.getString("icon"); if (wandTemplate != null) { iconKey = wandTemplate.migrateIcon(iconKey); } if (iconKey.contains(",")) { Random r = new Random(); String[] keys = StringUtils.split(iconKey, ','); iconKey = keys[r.nextInt(keys.length)]; } // Port old custom wand icons if (templateConfig != null && iconKey.contains("i.imgur.com")) { iconKey = templateConfig.getString("icon"); } setIcon(new MaterialAndData(iconKey)); } else if (isUpgrade) { setIcon(new MaterialAndData(DefaultUpgradeMaterial)); } if (wandConfig.contains("upgrade_icon")) { upgradeIcon = new MaterialAndData(wandConfig.getString("upgrade_icon")); } // Check for path-based migration, may update icons com.elmakers.mine.bukkit.api.wand.WandUpgradePath upgradePath = getPath(); if (upgradePath != null) { hasSpellProgression = upgradePath.getSpells().size() > 0 || upgradePath.getExtraSpells().size() > 0 || upgradePath.getRequiredSpells().size() > 0; upgradePath.checkMigration(this); } else { hasSpellProgression = false; } // Load spells if (needsInventoryUpdate) { // Force a re-parse of materials and spells wandSpells = getSpellString(); wandMaterials = getMaterialString(); } wandMaterials = wandConfig.getString("materials", wandMaterials); wandSpells = wandConfig.getString("spells", wandSpells); if (wandMaterials.length() > 0 || wandSpells.length() > 0) { wandMaterials = wandMaterials.length() == 0 ? getMaterialString() : wandMaterials; wandSpells = wandSpells.length() == 0 ? getSpellString() : wandSpells; parseInventoryStrings(wandSpells, wandMaterials); } if (wandConfig.contains("overrides")) { castOverrides = null; String overrides = wandConfig.getString("overrides", null); if (overrides != null && !overrides.isEmpty()) { // Support YML-List-As-String format overrides = overrides.replaceAll("[\\]\\[]", ""); castOverrides = new HashMap<>(); String[] pairs = StringUtils.split(overrides, ','); for (String pair : pairs) { // Unescape commas pair = pair.replace("\\|", ","); String[] keyValue = StringUtils.split(pair, " "); if (keyValue.length > 0) { String value = keyValue.length > 1 ? keyValue[1] : ""; castOverrides.put(keyValue[0], value); } } } } if (wandConfig.contains("potion_effects")) { potionEffects.clear(); addPotionEffects(potionEffects, wandConfig.getString("potion_effects", null)); } // Some cleanup and sanity checks. In theory we don't need to store any non-zero value (as it is with the traders) // so try to keep defaults as 0/0.0/false. if (effectSound == null) { effectSoundInterval = 0; } else { effectSoundInterval = (effectSoundInterval == 0) ? 5 : effectSoundInterval; } if (effectParticle == null) { effectParticleInterval = 0; } updateMaxMana(false); checkActiveMaterial(); } @Override public void describe(CommandSender sender) { Object wandNode = InventoryUtils.getNode(item, WAND_KEY); boolean isUpgrade = false; if (wandNode == null) { isUpgrade = true; wandNode = InventoryUtils.getNode(item, UPGRADE_KEY); } if (wandNode == null) { sender.sendMessage("Found a wand with missing NBT data. This may be an old wand, or something may have wiped its data"); return; } ChatColor wandColor = isModifiable() ? ChatColor.AQUA : ChatColor.RED; sender.sendMessage(wandColor + wandName); if (isUpgrade) { sender.sendMessage(ChatColor.YELLOW + "(Upgrade)"); } if (description.length() > 0) { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.GREEN + description); } else { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.GREEN + "(No Description)"); } if (owner.length() > 0 || ownerId.length() > 0) { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.WHITE + owner + " (" + ChatColor.GRAY + ownerId + ChatColor.WHITE + ")"); } else { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.WHITE + "(No Owner)"); } for (String key : PROPERTY_KEYS) { String value = InventoryUtils.getMetaString(wandNode, key); if (value != null && value.length() > 0) { sender.sendMessage(key + ": " + value); } } ConfigurationSection templateConfig = controller.getWandTemplateConfiguration(template); if (templateConfig != null) { sender.sendMessage("" + ChatColor.BOLD + ChatColor.GREEN + "Template Configuration:"); for (String key : PROPERTY_KEYS) { String value = templateConfig.getString(key); if (value != null && value.length() > 0) { sender.sendMessage(key + ": " + value); } } } } private static String getBrushDisplayName(Messages messages, MaterialBrush brush) { String materialName = brush == null ? null : brush.getName(messages); if (materialName == null) { materialName = "none"; } return ChatColor.GRAY + materialName; } private static String getSpellDisplayName(Messages messages, SpellTemplate spell, MaterialBrush brush) { String name = ""; if (spell != null) { if (brush != null && spell.usesBrush()) { name = ChatColor.GOLD + spell.getName() + " " + getBrushDisplayName(messages, brush) + ChatColor.WHITE; } else { name = ChatColor.GOLD + spell.getName() + ChatColor.WHITE; } } return name; } private String getActiveWandName(SpellTemplate spell, MaterialBrush brush) { // Build wand name int remaining = getRemainingUses(); ChatColor wandColor = (hasUses && remaining <= 1) ? ChatColor.DARK_RED : isModifiable() ? (bound ? ChatColor.DARK_AQUA : ChatColor.AQUA) : (path != null && path.length() > 0 ? ChatColor.LIGHT_PURPLE : ChatColor.GOLD); String name = wandColor + getDisplayName(); if (randomize) return name; Set<String> spells = getSpells(); // Add active spell to description Messages messages = controller.getMessages(); boolean showSpell = isModifiable() && hasSpellProgression(); showSpell = !quickCast && (spells.size() > 1 || showSpell); if (spell != null && showSpell) { name = getSpellDisplayName(messages, spell, brush) + " (" + name + ChatColor.WHITE + ")"; } if (remaining > 1) { String message = getMessage("uses_remaining_brief"); name = name + ChatColor.DARK_RED + " (" + ChatColor.RED + message.replace("$count", ((Integer)remaining).toString()) + ChatColor.DARK_RED + ")"; } return name; } private String getActiveWandName(SpellTemplate spell) { return getActiveWandName(spell, MaterialBrush.parseMaterialKey(activeMaterial)); } private String getActiveWandName(MaterialBrush brush) { SpellTemplate spell = null; if (activeSpell != null && activeSpell.length() > 0) { spell = controller.getSpellTemplate(activeSpell); } return getActiveWandName(spell, brush); } private String getActiveWandName() { SpellTemplate spell = null; if (activeSpell != null && activeSpell.length() > 0) { spell = controller.getSpellTemplate(activeSpell); } return getActiveWandName(spell); } protected String getDisplayName() { return ChatColor.translateAlternateColorCodes('&', randomize ? getMessage("randomized_name") : wandName); } public void updateName(boolean isActive) { if (isActive) { CompatibilityUtils.setDisplayName(item, !isUpgrade ? getActiveWandName() : ChatColor.GOLD + getDisplayName()); } else { CompatibilityUtils.setDisplayName(item, ChatColor.stripColor(getDisplayName())); } // Reset Enchantment glow if (glow) { CompatibilityUtils.addGlow(item); } } private void updateName() { updateName(true); } protected static String convertToHTML(String line) { int tagCount = 1; line = "<span style=\"color:white\">" + line; for (ChatColor c : ChatColor.values()) { tagCount += StringUtils.countMatches(line, c.toString()); String replaceStyle = ""; if (c == ChatColor.ITALIC) { replaceStyle = "font-style: italic"; } else if (c == ChatColor.BOLD) { replaceStyle = "font-weight: bold"; } else if (c == ChatColor.UNDERLINE) { replaceStyle = "text-decoration: underline"; } else { String color = c.name().toLowerCase().replace("_", ""); if (c == ChatColor.LIGHT_PURPLE) { color = "mediumpurple"; } replaceStyle = "color:" + color; } line = line.replace(c.toString(), "<span style=\"" + replaceStyle + "\">"); } for (int i = 0; i < tagCount; i++) { line += "</span>"; } return line; } public String getHTMLDescription() { Collection<String> rawLore = getLore(); Collection<String> lore = new ArrayList<>(); lore.add("<h2>" + convertToHTML(getActiveWandName()) + "</h2>"); for (String line : rawLore) { lore.add(convertToHTML(line)); } return "<div style=\"background-color: black; margin: 8px; padding: 8px\">" + StringUtils.join(lore, "<br/>") + "</div>"; } protected List<String> getLore() { return getLore(getSpells().size(), getBrushes().size()); } protected void addPropertyLore(List<String> lore) { if (usesMana()) { if (effectiveManaMax != manaMax) { String fullMessage = getLevelString(controller.getMessages(), "wand.mana_amount_boosted", manaMax, controller.getMaxMana()); lore.add(ChatColor.LIGHT_PURPLE + "" + ChatColor.ITALIC + fullMessage.replace("$mana", Integer.toString(effectiveManaMax))); } else { lore.add(ChatColor.LIGHT_PURPLE + "" + ChatColor.ITALIC + getLevelString(controller.getMessages(), "wand.mana_amount", manaMax, controller.getMaxMana())); } if (manaRegeneration > 0) { if (effectiveManaRegeneration != manaRegeneration) { String fullMessage = getLevelString(controller.getMessages(), "wand.mana_regeneration_boosted", manaRegeneration, controller.getMaxManaRegeneration()); lore.add(ChatColor.LIGHT_PURPLE + "" + ChatColor.ITALIC + fullMessage.replace("$mana", Integer.toString(effectiveManaRegeneration))); } else { lore.add(ChatColor.RESET + "" + ChatColor.LIGHT_PURPLE + getLevelString(controller.getMessages(), "wand.mana_regeneration", manaRegeneration, controller.getMaxManaRegeneration())); } } if (manaPerDamage > 0) { lore.add(ChatColor.DARK_RED + "" + ChatColor.ITALIC + getLevelString(controller.getMessages(), "wand.mana_per_damage", manaPerDamage, controller.getMaxManaRegeneration())); } } if (superPowered) { lore.add(ChatColor.DARK_AQUA + getMessage("super_powered")); } if (blockReflectChance > 0) { lore.add(ChatColor.AQUA + getLevelString(controller.getMessages(), "wand.reflect_chance", blockReflectChance)); } else if (blockChance != 0) { lore.add(ChatColor.AQUA + getLevelString(controller.getMessages(), "wand.block_chance", blockChance)); } if (manaMaxBoost != 0) { lore.add(ChatColor.LIGHT_PURPLE + "" + ChatColor.ITALIC + getPercentageString(controller.getMessages(), "wand.mana_boost", manaMaxBoost)); } if (manaRegenerationBoost != 0) { lore.add(ChatColor.LIGHT_PURPLE + "" + ChatColor.ITALIC + getPercentageString(controller.getMessages(), "wand.mana_regeneration_boost", manaRegenerationBoost)); } if (castSpell != null) { SpellTemplate spell = controller.getSpellTemplate(castSpell); if (spell != null) { lore.add(ChatColor.AQUA + getMessage("spell_aura").replace("$spell", spell.getName())); } } for (Map.Entry<PotionEffectType, Integer> effect : potionEffects.entrySet()) { lore.add(ChatColor.AQUA + describePotionEffect(effect.getKey(), effect.getValue())); } if (consumeReduction > 0) lore.add(ChatColor.AQUA + getLevelString(controller.getMessages(), "wand.consume_reduction", consumeReduction)); if (costReduction > 0) lore.add(ChatColor.AQUA + getLevelString(controller.getMessages(), "wand.cost_reduction", costReduction)); if (cooldownReduction > 0) lore.add(ChatColor.AQUA + getLevelString(controller.getMessages(), "wand.cooldown_reduction", cooldownReduction)); if (power > 0) lore.add(ChatColor.AQUA + getLevelString(controller.getMessages(), "wand.power", power)); if (superProtected) { lore.add(ChatColor.DARK_AQUA + getMessage("super_protected")); } else { if (damageReduction > 0) lore.add(ChatColor.AQUA + getLevelString(controller.getMessages(), "wand.protection", damageReduction)); if (damageReductionPhysical > 0) lore.add(ChatColor.AQUA + getLevelString(controller.getMessages(), "wand.protection_physical", damageReductionPhysical)); if (damageReductionProjectiles > 0) lore.add(ChatColor.AQUA + getLevelString(controller.getMessages(), "wand.protection_projectile", damageReductionProjectiles)); if (damageReductionFalling > 0) lore.add(ChatColor.AQUA + getLevelString(controller.getMessages(), "wand.protection_fall", damageReductionFalling)); if (damageReductionFire > 0) lore.add(ChatColor.AQUA + getLevelString(controller.getMessages(), "wand.protection_fire", damageReductionFire)); if (damageReductionExplosions > 0) lore.add(ChatColor.AQUA + getLevelString(controller.getMessages(), "wand.protection_blast", damageReductionExplosions)); } } public static String getLevelString(Messages messages, String templateName, float amount) { return messages.getLevelString(templateName, amount); } public static String getLevelString(Messages messages, String templateName, float amount, float max) { return messages.getLevelString(templateName, amount, max); } public static String getPercentageString(Messages messages, String templateName, float amount) { return messages.getPercentageString(templateName, amount); } protected List<String> getLore(int spellCount, int materialCount) { List<String> lore = new ArrayList<>(); if (description.length() > 0) { if (description.contains("$path")) { String pathName = "Unknown"; com.elmakers.mine.bukkit.api.wand.WandUpgradePath path = getPath(); if (path != null) { pathName = path.getName(); } String description = this.description; description = description.replace("$path", pathName); InventoryUtils.wrapText(ChatColor.ITALIC + "" + ChatColor.GREEN, description, MAX_LORE_LENGTH, lore); } else if (description.contains("$")) { String randomDescription = getMessage("randomized_lore"); if (randomDescription.length() > 0) { InventoryUtils.wrapText(ChatColor.ITALIC + "" + ChatColor.DARK_GREEN, randomDescription, MAX_LORE_LENGTH, lore); } } else { InventoryUtils.wrapText(ChatColor.ITALIC + "" + ChatColor.GREEN, description, MAX_LORE_LENGTH, lore); } } if (randomize) { return lore; } if (!isUpgrade) { if (owner.length() > 0) { if (bound) { if (soul) { String ownerDescription = getMessage("soulbound_description", "$name").replace("$name", owner); lore.add(ChatColor.ITALIC + "" + ChatColor.DARK_AQUA + ownerDescription); } else { String ownerDescription = getMessage("bound_description", "$name").replace("$name", owner); lore.add(ChatColor.ITALIC + "" + ChatColor.DARK_AQUA + ownerDescription); } } else { String ownerDescription = getMessage("owner_description", "$name").replace("$name", owner); lore.add(ChatColor.ITALIC + "" + ChatColor.DARK_GREEN + ownerDescription); } } } SpellTemplate spell = controller.getSpellTemplate(activeSpell); Messages messages = controller.getMessages(); // This is here specifically for a wand that only has // one spell now, but may get more later. Since you // can't open the inventory in this state, you can not // otherwise see the spell lore. if (spell != null && spellCount == 1 && !hasInventory && !isUpgrade) { addSpellLore(messages, spell, lore, getActiveMage(), this); } if (materialCount == 1 && activeMaterial != null && activeMaterial.length() > 0) { lore.add(getBrushDisplayName(messages, MaterialBrush.parseMaterialKey(activeMaterial))); } if (spellCount > 0) { if (isUpgrade) { lore.add(getMessage("upgrade_spell_count").replace("$count", ((Integer)spellCount).toString())); } else if (spellCount > 1) { lore.add(getMessage("spell_count").replace("$count", ((Integer)spellCount).toString())); } } if (materialCount > 0) { if (isUpgrade) { lore.add(getMessage("upgrade_material_count").replace("$count", ((Integer)materialCount).toString())); } else if (materialCount > 1) { lore.add(getMessage("material_count").replace("$count", ((Integer)materialCount).toString())); } } int remaining = getRemainingUses(); if (remaining > 0) { if (isUpgrade) { String message = (remaining == 1) ? getMessage("upgrade_uses_singular") : getMessage("upgrade_uses"); lore.add(ChatColor.RED + message.replace("$count", ((Integer)remaining).toString())); } else { String message = (remaining == 1) ? getMessage("uses_remaining_singular") : getMessage("uses_remaining_brief"); lore.add(ChatColor.RED + message.replace("$count", ((Integer)remaining).toString())); } } addPropertyLore(lore); if (isUpgrade) { lore.add(ChatColor.YELLOW + getMessage("upgrade_item_description")); } return lore; } protected void updateLore() { CompatibilityUtils.setLore(item, getLore()); if (glow) { CompatibilityUtils.addGlow(item); } } public void save() { saveState(); updateName(); updateLore(); } public int getRemainingUses() { return uses; } public void makeEnchantable(boolean enchantable) { if (EnchantableWandMaterial == null) return; if (!enchantable) { item.setType(icon.getMaterial()); item.setDurability(icon.getData()); } else { Set<Material> enchantableMaterials = controller.getMaterialSet("enchantable"); if (!enchantableMaterials.contains(item.getType())) { item.setType(EnchantableWandMaterial); item.setDurability((short)0); } } updateName(); } public static boolean hasActiveWand(Player player) { if (player == null) return false; ItemStack activeItem = player.getInventory().getItemInMainHand(); return isWand(activeItem); } public static Wand getActiveWand(MagicController controller, Player player) { ItemStack activeItem = player.getInventory().getItemInMainHand(); if (isWand(activeItem)) { return controller.getWand(activeItem); } return null; } public static boolean isWand(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, WAND_KEY); } public static boolean isWandOrUpgrade(ItemStack item) { return isWand(item) || isUpgrade(item); } public static boolean isSpecial(ItemStack item) { return isWand(item) || isUpgrade(item) || isSpell(item) || isBrush(item) || isSP(item); } public static boolean isBound(ItemStack item) { Object wandSection = InventoryUtils.getNode(item, WAND_KEY); if (wandSection == null) return false; String boundValue = InventoryUtils.getMetaString(wandSection, "bound"); return boundValue != null && boundValue.equalsIgnoreCase("true"); } public static boolean isSelfDestructWand(ItemStack item) { return item != null && WAND_SELF_DESTRUCT_KEY != null && InventoryUtils.hasMeta(item, WAND_SELF_DESTRUCT_KEY); } public static boolean isSP(ItemStack item) { return InventoryUtils.hasMeta(item, "sp"); } public static Integer getSP(ItemStack item) { if (InventoryUtils.isEmpty(item)) return null; String spNode = InventoryUtils.getMetaString(item, "sp"); if (spNode == null) return null; Integer sp = null; try { sp = Integer.parseInt(spNode); } catch (Exception ex) { sp = null; } return sp; } public static boolean isSingleUse(ItemStack item) { if (InventoryUtils.isEmpty(item)) return false; Object wandNode = InventoryUtils.getNode(item, WAND_KEY); if (wandNode == null) return false; String useCount = InventoryUtils.getMetaString(wandNode, "uses"); String wandId = InventoryUtils.getMetaString(wandNode, "id"); return useCount != null && useCount.equals("1") && (wandId == null || wandId.isEmpty()); } public static boolean isUpgrade(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, UPGRADE_KEY); } public static boolean isSpell(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, "spell"); } public static boolean isSkill(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, "skill"); } public static boolean isBrush(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, "brush"); } protected static Object getWandOrUpgradeNode(ItemStack item) { if (InventoryUtils.isEmpty(item)) return null; Object wandNode = InventoryUtils.getNode(item, WAND_KEY); if (wandNode == null) { wandNode = InventoryUtils.getNode(item, UPGRADE_KEY); } return wandNode; } public static String getWandTemplate(ItemStack item) { Object wandNode = getWandOrUpgradeNode(item); if (wandNode == null) return null; return InventoryUtils.getMetaString(wandNode, "template"); } public static String getWandId(ItemStack item) { if (InventoryUtils.isEmpty(item)) return null; Object wandNode = InventoryUtils.getNode(item, WAND_KEY); if (wandNode == null || isUpgrade(item)) return null; if (isSingleUse(item)) return getWandTemplate(item); return InventoryUtils.getMetaString(wandNode, "id"); } public static String getSpell(ItemStack item) { if (InventoryUtils.isEmpty(item)) return null; Object spellNode = InventoryUtils.getNode(item, "spell"); if (spellNode == null) return null; return InventoryUtils.getMetaString(spellNode, "key"); } public static String getSpellArgs(ItemStack item) { if (InventoryUtils.isEmpty(item)) return null; Object spellNode = InventoryUtils.getNode(item, "spell"); if (spellNode == null) return null; return InventoryUtils.getMetaString(spellNode, "args"); } public static String getBrush(ItemStack item) { if (InventoryUtils.isEmpty(item)) return null; Object brushNode = InventoryUtils.getNode(item, "brush"); if (brushNode == null) return null; return InventoryUtils.getMetaString(brushNode, "key"); } protected void updateInventoryName(ItemStack item, boolean activeName) { if (isSpell(item)) { Spell spell = mage.getSpell(getSpell(item)); if (spell != null) { updateSpellItem(controller.getMessages(), item, spell, "", getActiveMage(), activeName ? this : null, activeMaterial, false); } } else if (isBrush(item)) { updateBrushItem(controller.getMessages(), item, getBrush(item), activeName ? this : null); } } public static void updateSpellItem(Messages messages, ItemStack itemStack, SpellTemplate spell, String args, Wand wand, String activeMaterial, boolean isItem) { updateSpellItem(messages, itemStack, spell, args, wand == null ? null : wand.getActiveMage(), wand, activeMaterial, isItem); } public static void updateSpellItem(Messages messages, ItemStack itemStack, SpellTemplate spell, String args, com.elmakers.mine.bukkit.api.magic.Mage mage, Wand wand, String activeMaterial, boolean isItem) { String displayName; if (wand != null && !wand.isQuickCast()) { displayName = wand.getActiveWandName(spell); } else { displayName = getSpellDisplayName(messages, spell, MaterialBrush.parseMaterialKey(activeMaterial)); } CompatibilityUtils.setDisplayName(itemStack, displayName); List<String> lore = new ArrayList<>(); addSpellLore(messages, spell, lore, mage, wand); if (isItem) { lore.add(ChatColor.YELLOW + messages.get("wand.spell_item_description")); } CompatibilityUtils.setLore(itemStack, lore); Object spellNode = CompatibilityUtils.createNode(itemStack, "spell"); CompatibilityUtils.setMeta(spellNode, "key", spell.getKey()); CompatibilityUtils.setMeta(spellNode, "args", args); if (SpellGlow) { CompatibilityUtils.addGlow(itemStack); } } public static void updateBrushItem(Messages messages, ItemStack itemStack, String materialKey, Wand wand) { updateBrushItem(messages, itemStack, MaterialBrush.parseMaterialKey(materialKey), wand); } public static void updateBrushItem(Messages messages, ItemStack itemStack, MaterialBrush brush, Wand wand) { String displayName; if (wand != null) { Spell activeSpell = wand.getActiveSpell(); if (activeSpell != null && activeSpell.usesBrush()) { displayName = wand.getActiveWandName(brush); } else { displayName = ChatColor.RED + brush.getName(messages); } } else { displayName = brush.getName(messages); } CompatibilityUtils.setDisplayName(itemStack, displayName); Object brushNode = CompatibilityUtils.createNode(itemStack, "brush"); CompatibilityUtils.setMeta(brushNode, "key", brush.getKey()); } public void updateHotbar() { if (mage == null) return; if (!isInventoryOpen()) return; Player player = mage.getPlayer(); if (player == null) return; if (!hasStoredInventory()) return; WandMode wandMode = getMode(); if (wandMode == WandMode.INVENTORY) { PlayerInventory inventory = player.getInventory(); updateHotbar(inventory); DeprecatedUtils.updateInventory(player); } } @SuppressWarnings("deprecation") private void updateInventory() { if (mage == null) return; if (!isInventoryOpen()) return; Player player = mage.getPlayer(); if (player == null) return; WandMode wandMode = getMode(); if (wandMode == WandMode.INVENTORY) { if (!hasStoredInventory()) return; PlayerInventory inventory = player.getInventory(); for (int i = 0; i < PLAYER_INVENTORY_SIZE; i++) { inventory.setItem(i, null); } updateHotbar(inventory); updateInventory(inventory, false); updateName(); player.updateInventory(); } else if (wandMode == WandMode.CHEST) { Inventory inventory = getDisplayInventory(); inventory.clear(); updateInventory(inventory, true); player.updateInventory(); } } private void updateHotbar(PlayerInventory playerInventory) { if (getMode() != WandMode.INVENTORY) return; Inventory hotbar = getHotbar(); if (hotbar == null) return; // Check for an item already in the player's held slot, which // we are about to replace with the wand. int currentSlot = playerInventory.getHeldItemSlot(); ItemStack currentItem = playerInventory.getItem(currentSlot); String currentId = getWandId(currentItem); if (currentId != null && !currentId.equals(id)) { return; } // Reset the held item, just in case Bukkit made a copy or something. playerInventory.setItemInMainHand(this.item); // Set hotbar items from remaining list int targetOffset = 0; for (int hotbarSlot = 0; hotbarSlot < HOTBAR_INVENTORY_SIZE; hotbarSlot++) { if (hotbarSlot == currentSlot) { targetOffset = 1; } ItemStack hotbarItem = hotbar.getItem(hotbarSlot); updateInventoryName(hotbarItem, true); playerInventory.setItem(hotbarSlot + targetOffset, hotbarItem); } } private void updateInventory(Inventory targetInventory, boolean addHotbars) { // Set inventory from current page int currentOffset = addHotbars ? 0 : HOTBAR_SIZE; List<Inventory> inventories = this.inventories; if (openInventoryPage < inventories.size()) { Inventory inventory = inventories.get(openInventoryPage); ItemStack[] contents = inventory.getContents(); for (int i = 0; i < contents.length; i++) { ItemStack inventoryItem = contents[i]; updateInventoryName(inventoryItem, false); targetInventory.setItem(currentOffset, inventoryItem); currentOffset++; } } if (addHotbars && openInventoryPage < hotbars.size()) { Inventory inventory = hotbars.get(openInventoryPage); ItemStack[] contents = inventory.getContents(); for (int i = 0; i < contents.length; i++) { ItemStack inventoryItem = contents[i]; updateInventoryName(inventoryItem, false); targetInventory.setItem(currentOffset, inventoryItem); currentOffset++; } } } protected static void addSpellLore(Messages messages, SpellTemplate spell, List<String> lore, com.elmakers.mine.bukkit.api.magic.Mage mage, Wand wand) { spell.addLore(messages, mage, wand, lore); } protected Inventory getOpenInventory() { while (openInventoryPage >= inventories.size()) { inventories.add(CompatibilityUtils.createInventory(null, INVENTORY_SIZE, "Wand")); } return inventories.get(openInventoryPage); } public void saveInventory() { if (mage == null) return; if (!isInventoryOpen()) return; if (mage.getPlayer() == null) return; if (getMode() != WandMode.INVENTORY) return; if (!hasStoredInventory()) return; // Work-around glitches that happen if you're dragging an item on death if (mage.isDead()) return; // Fill in the hotbar Player player = mage.getPlayer(); PlayerInventory playerInventory = player.getInventory(); Inventory hotbar = getHotbar(); if (hotbar != null) { int saveOffset = 0; for (int i = 0; i < HOTBAR_SIZE; i++) { ItemStack playerItem = playerInventory.getItem(i); if (isWand(playerItem)) { saveOffset = -1; continue; } int hotbarOffset = i + saveOffset; if (hotbarOffset >= hotbar.getSize()) { // This can happen if there is somehow no wand in the wand inventory. break; } if (!updateSlot(i + saveOffset + currentHotbar * HOTBAR_INVENTORY_SIZE, playerItem)) { playerItem = new ItemStack(Material.AIR); playerInventory.setItem(i, playerItem); } hotbar.setItem(i + saveOffset, playerItem); } } // Fill in the active inventory page int hotbarOffset = getHotbarSize(); Inventory openInventory = getOpenInventory(); for (int i = 0; i < openInventory.getSize(); i++) { ItemStack playerItem = playerInventory.getItem(i + HOTBAR_SIZE); if (!updateSlot(i + hotbarOffset + openInventoryPage * INVENTORY_SIZE, playerItem)) { playerItem = new ItemStack(Material.AIR); playerInventory.setItem(i + HOTBAR_SIZE, playerItem); } openInventory.setItem(i, playerItem); } } protected boolean updateSlot(int slot, ItemStack item) { String spellKey = getSpell(item); if (spellKey != null) { spells.put(spellKey, slot); } else { String brushKey = getBrush(item); if (brushKey != null) { brushes.put(brushKey, slot); } else if (mage != null && item != null && item.getType() != Material.AIR) { // Must have been an item inserted directly into player's inventory? mage.giveItem(item); return false; } } return true; } @Override public int enchant(int totalLevels, com.elmakers.mine.bukkit.api.magic.Mage mage, boolean addSpells) { return randomize(totalLevels, true, mage, addSpells); } @Override public int enchant(int totalLevels, com.elmakers.mine.bukkit.api.magic.Mage mage) { return randomize(totalLevels, true, mage, true); } @Override public int enchant(int totalLevels) { return randomize(totalLevels, true, null, true); } protected int randomize(int totalLevels, boolean additive, com.elmakers.mine.bukkit.api.magic.Mage enchanter, boolean addSpells) { if (enchanter == null && mage != null) { enchanter = mage; } if (maxEnchantCount > 0 && enchantCount >= maxEnchantCount) { if (enchanter != null) { enchanter.sendMessage(getMessage("max_enchanted").replace("$wand", getName())); } return 0; } WandUpgradePath path = (WandUpgradePath)getPath(); if (path == null) { if (enchanter != null) { enchanter.sendMessage(getMessage("no_path").replace("$wand", getName())); } return 0; } int minLevel = path.getMinLevel(); if (totalLevels < minLevel) { if (enchanter != null) { String levelMessage = getMessage("need_more_levels"); levelMessage = levelMessage.replace("$levels", Integer.toString(minLevel)); enchanter.sendMessage(levelMessage); } return 0; } // Just a hard-coded sanity check int maxLevel = path.getMaxLevel(); totalLevels = Math.min(totalLevels, maxLevel * 50); int addLevels = Math.min(totalLevels, maxLevel); int levels = 0; boolean modified = true; while (addLevels >= minLevel && modified) { boolean hasUpgrade = path.hasUpgrade(); WandLevel level = path.getLevel(addLevels); if (!path.canEnchant(this) && (path.hasSpells() || path.hasMaterials())) { // Check for level up WandUpgradePath nextPath = path.getUpgrade(); if (nextPath != null) { if (path.checkUpgradeRequirements(this, enchanter)) { path.upgrade(this, enchanter); } break; } else { enchanter.sendMessage(getMessage("fully_enchanted").replace("$wand", getName())); break; } } modified = level.randomizeWand(enchanter, this, additive, hasUpgrade, addSpells); totalLevels -= maxLevel; if (modified) { if (enchanter != null) { path.enchanted(enchanter); } levels += addLevels; // Check for level up WandUpgradePath nextPath = path.getUpgrade(); if (nextPath != null && path.checkUpgradeRequirements(this, null) && !path.canEnchant(this)) { path.upgrade(this, enchanter); path = nextPath; } } else if (path.canEnchant(this)) { if (enchanter != null && levels == 0 && addSpells) { String message = getMessage("require_more_levels"); enchanter.sendMessage(message); } } else if (hasUpgrade) { if (path.checkUpgradeRequirements(this, enchanter)) { path.upgrade(this, enchanter); levels += addLevels; } } else if (enchanter != null) { enchanter.sendMessage(getMessage("fully_enchanted").replace("$wand", getName())); } addLevels = Math.min(totalLevels, maxLevel); additive = true; } if (levels > 0) { enchantCount++; setProperty("enchant_count", enchantCount); } saveState(); updateName(); updateLore(); return levels; } public static ItemStack createItem(MagicController controller, String templateName) { ItemStack item = createSpellItem(templateName, controller, null, true); if (item == null) { item = createBrushItem(templateName, controller, null, true); if (item == null) { Wand wand = createWand(controller, templateName); if (wand != null) { item = wand.getItem(); } } } return item; } public static Wand createWand(MagicController controller, String templateName) { if (controller == null) return null; Wand wand = null; try { wand = new Wand(controller, templateName); } catch (UnknownWandException ignore) { // the Wand constructor throws an exception on an unknown template } catch (Exception ex) { ex.printStackTrace(); } return wand; } public static Wand createWand(MagicController controller, ItemStack itemStack) { if (controller == null) return null; Wand wand = null; try { wand = controller.getWand(InventoryUtils.makeReal(itemStack)); wand.saveState(); wand.updateName(); } catch (Exception ex) { ex.printStackTrace(); } return wand; } public boolean add(Wand other) { return add(other, this.mage); } @Override public boolean add(com.elmakers.mine.bukkit.api.wand.Wand other, com.elmakers.mine.bukkit.api.magic.Mage mage) { if (other instanceof Wand) { return add((Wand)other, mage); } return false; } public boolean add(Wand other, com.elmakers.mine.bukkit.api.magic.Mage mage) { if (!isModifiable()) { // Only allow upgrading a modifiable wand via an upgrade item // and only if the paths match. if (!other.isUpgrade() || other.path == null || path == null || other.path.isEmpty() || path.isEmpty() || !other.path.equals(path)) { return false; } } // Can't combine limited-use wands if (hasUses || other.hasUses) { return false; } if (isHeroes || other.isHeroes) { return false; } ConfigurationSection templateConfig = controller.getWandTemplateConfiguration(other.getTemplateKey()); // Check for forced upgrades if (other.isForcedUpgrade()) { if (templateConfig == null) { return false; } templateConfig = ConfigurationUtils.cloneConfiguration(templateConfig); templateConfig.set("name", templateConfig.getString("upgrade_name")); templateConfig.set("description", templateConfig.getString("upgrade_description")); templateConfig.set("force", null); templateConfig.set("upgrade", null); templateConfig.set("icon", templateConfig.getString("upgrade_icon")); templateConfig.set("indestructible", null); configure(templateConfig); loadProperties(); saveState(); return true; } // Don't allow upgrades from an item on a different path if (other.isUpgrade() && other.path != null && !other.path.isEmpty() && (this.path == null || !this.path.equals(other.path))) { return false; } ConfigurationSection upgradeConfig = other.getEffectiveConfiguration(); upgradeConfig.set("id", null); upgradeConfig.set("indestructible", null); upgradeConfig.set("upgrade", null); upgradeConfig.set("icon", upgradeIcon == null ? null : upgradeIcon.getKey()); upgradeConfig.set("template", upgradeTemplate); Messages messages = controller.getMessages(); if (other.rename && templateConfig != null) { String newName = messages.get("wands." + other.template + ".name"); newName = templateConfig.getString("name", newName); upgradeConfig.set("name", newName); } else { upgradeConfig.set("name", null); } if (other.renameDescription && templateConfig != null) { String newDescription = messages.get("wands." + other.template + ".description"); newDescription = templateConfig.getString("description", newDescription); upgradeConfig.set("description", newDescription); } else { upgradeConfig.set("description", null); } boolean modified = upgrade(upgradeConfig); if (modified) { loadProperties(); saveState(); } return modified; } public boolean isForcedUpgrade() { return isUpgrade && forceUpgrade; } public boolean keepOnDeath() { return keep; } public static WandMode parseWandMode(String modeString, WandMode defaultValue) { if (modeString != null && !modeString.isEmpty()) { try { defaultValue = WandMode.valueOf(modeString.toUpperCase()); } catch(Exception ex) { } } return defaultValue; } public static WandAction parseWandAction(String actionString, WandAction defaultValue) { if (actionString != null && !actionString.isEmpty()) { try { defaultValue = WandAction.valueOf(actionString.toUpperCase()); } catch(Exception ex) { } } return defaultValue; } private void updateActiveMaterial() { if (mage == null) return; if (activeMaterial == null) { mage.clearBuildingMaterial(); } else { com.elmakers.mine.bukkit.api.block.MaterialBrush brush = mage.getBrush(); brush.update(activeMaterial); } } public void cycleActive(int direction) { Player player = mage != null ? mage.getPlayer() : null; if (player != null && player.isSneaking()) { com.elmakers.mine.bukkit.api.spell.Spell activeSpell = getActiveSpell(); boolean cycleMaterials = false; if (activeSpell != null) { cycleMaterials = activeSpell.usesBrushSelection(); } if (cycleMaterials) { cycleMaterials(direction); } else { cycleSpells(direction); } } else { cycleSpells(direction); } } public void toggleInventory() { if (mage != null && mage.cancel()) { mage.playSoundEffect(noActionSound); return; } Player player = mage == null ? null : mage.getPlayer(); boolean isSneaking = player != null && player.isSneaking(); Spell currentSpell = getActiveSpell(); if (getBrushMode() == WandMode.CHEST && brushSelectSpell != null && !brushSelectSpell.isEmpty() && isSneaking && currentSpell != null && currentSpell.usesBrushSelection()) { Spell brushSelect = mage.getSpell(brushSelectSpell); if (brushSelect != null) { brushSelect.cast(); return; } } if (!hasInventory) { if (activeSpell == null || activeSpell.length() == 0) { Set<String> spells = getSpells(); // Sanity check, so it'll switch to inventory next time updateHasInventory(); if (spells.size() > 0) { setActiveSpell(spells.iterator().next()); } } updateName(); return; } if (!isInventoryOpen()) { openInventory(); } else { closeInventory(); } } public void updateHasInventory() { int inventorySize = getSpells().size() + getBrushes().size(); hasInventory = inventorySize > 1 || (inventorySize == 1 && hasSpellProgression); } @SuppressWarnings("deprecation") public void cycleInventory(int direction) { if (!hasInventory) { return; } if (isInventoryOpen()) { saveInventory(); int inventoryCount = inventories.size(); openInventoryPage = inventoryCount == 0 ? 0 : (openInventoryPage + inventoryCount + direction) % inventoryCount; updateInventory(); if (mage != null && inventories.size() > 1) { if (!playPassiveEffects("cycle") && inventoryCycleSound != null) { mage.playSoundEffect(inventoryCycleSound); } mage.getPlayer().updateInventory(); } } } @Override public void cycleHotbar() { cycleHotbar(1); } public void cycleHotbar(int direction) { if (!hasInventory || getMode() != WandMode.INVENTORY) { return; } if (isInventoryOpen() && mage != null && hotbars.size() > 1) { saveInventory(); int hotbarCount = hotbars.size(); currentHotbar = hotbarCount == 0 ? 0 : (currentHotbar + hotbarCount + direction) % hotbarCount; updateHotbar(); if (!playPassiveEffects("cycle") && inventoryCycleSound != null) { mage.playSoundEffect(inventoryCycleSound); } updateHotbarStatus(); DeprecatedUtils.updateInventory(mage.getPlayer()); } } public void cycleInventory() { cycleInventory(1); } @SuppressWarnings("deprecation") public void openInventory() { if (mage == null) return; WandMode wandMode = getMode(); if (wandMode == WandMode.CHEST) { inventoryIsOpen = true; if (!playPassiveEffects("open") && inventoryOpenSound != null) { mage.playSoundEffect(inventoryOpenSound); } updateInventory(); mage.getPlayer().openInventory(getDisplayInventory()); } else if (wandMode == WandMode.INVENTORY) { if (hasStoredInventory()) return; if (storeInventory()) { inventoryIsOpen = true; showActiveIcon(true); if (!playPassiveEffects("open") && inventoryOpenSound != null) { mage.playSoundEffect(inventoryOpenSound); } updateInventory(); updateHotbarStatus(); mage.getPlayer().updateInventory(); } } } @Override public void closeInventory() { if (!isInventoryOpen()) return; controller.disableItemSpawn(); WandMode mode = getMode(); try { saveInventory(); updateSpells(); inventoryIsOpen = false; if (mage != null) { if (!playPassiveEffects("close") && inventoryCloseSound != null) { mage.playSoundEffect(inventoryCloseSound); } if (mode == WandMode.INVENTORY) { restoreInventory(); showActiveIcon(false); } else { mage.getPlayer().closeInventory(); } // Check for items the player might've glitched onto their body... PlayerInventory inventory = mage.getPlayer().getInventory(); ItemStack testItem = inventory.getHelmet(); if (isSpell(testItem) || isBrush(testItem)) { inventory.setHelmet(new ItemStack(Material.AIR)); DeprecatedUtils.updateInventory(mage.getPlayer()); } testItem = inventory.getBoots(); if (isSpell(testItem) || isBrush(testItem)) { inventory.setBoots(new ItemStack(Material.AIR)); DeprecatedUtils.updateInventory(mage.getPlayer()); } testItem = inventory.getLeggings(); if (isSpell(testItem) || isBrush(testItem)) { inventory.setLeggings(new ItemStack(Material.AIR)); DeprecatedUtils.updateInventory(mage.getPlayer()); } testItem = inventory.getChestplate(); if (isSpell(testItem) || isBrush(testItem)) { inventory.setChestplate(new ItemStack(Material.AIR)); DeprecatedUtils.updateInventory(mage.getPlayer()); } // This is kind of a hack :( testItem = inventory.getItemInOffHand(); if (isSpell(testItem) || isBrush(testItem)) { inventory.setItemInOffHand(new ItemStack(Material.AIR)); DeprecatedUtils.updateInventory(mage.getPlayer()); } } } catch (Throwable ex) { restoreInventory(); } if (mode == WandMode.INVENTORY && mage != null) { try { mage.getPlayer().closeInventory(); } catch (Throwable ex) { ex.printStackTrace(); } } controller.enableItemSpawn(); } @Override public boolean fill(Player player) { return fill(player, 0); } @Override public boolean fill(Player player, int maxLevel) { Collection<String> currentSpells = new ArrayList<>(getSpells()); for (String spellKey : currentSpells) { SpellTemplate spell = controller.getSpellTemplate(spellKey); if (!spell.hasCastPermission(player)) { removeSpell(spellKey); } } Collection<SpellTemplate> allSpells = controller.getPlugin().getSpellTemplates(); // Hack to prevent messaging Mage mage = this.mage; this.mage = null; for (SpellTemplate spell : allSpells) { String key = spell.getKey(); if (maxLevel > 0 && spell.getSpellKey().getLevel() > maxLevel) { continue; } if (key.startsWith("heroes*")) { continue; } if (spell.hasCastPermission(player) && spell.hasIcon() && !spell.isHidden()) { addSpell(key); } } this.mage = mage; setProperty("fill", null); autoFill = false; saveState(); return true; } protected void randomize() { if (description.contains("$")) { String newDescription = controller.getMessages().escape(description); if (!newDescription.equals(description)) { setDescription(newDescription); updateLore(); updateName(); setProperty("randomize", false); } } if (template != null && template.length() > 0) { ConfigurationSection wandConfig = controller.getWandTemplateConfiguration(template); if (wandConfig != null && wandConfig.contains("icon")) { String iconKey = wandConfig.getString("icon"); if (iconKey.contains(",")) { Random r = new Random(); String[] keys = StringUtils.split(iconKey, ','); iconKey = keys[r.nextInt(keys.length)]; setIcon(ConfigurationUtils.toMaterialAndData(iconKey)); updateIcon(); setProperty("randomize", false); } } } } protected void checkActiveMaterial() { if (activeMaterial == null || activeMaterial.length() == 0) { Set<String> materials = getBrushes(); if (materials.size() > 0) { activeMaterial = materials.iterator().next(); } } } @Override public boolean addItem(ItemStack item) { if (isUpgrade) return false; if (isModifiable() && isSpell(item) && !isSkill(item)) { String spellKey = getSpell(item); Set<String> spells = getSpells(); if (!spells.contains(spellKey) && addSpell(spellKey)) { return true; } } else if (isModifiable() && isBrush(item)) { String materialKey = getBrush(item); Set<String> materials = getBrushes(); if (!materials.contains(materialKey) && addBrush(materialKey)) { return true; } } else if (isUpgrade(item)) { Wand wand = controller.getWand(item); return this.add(wand); } if (mage != null && !mage.isAtMaxSkillPoints()) { Integer sp = getSP(item); if (sp != null) { mage.addSkillPoints(sp * item.getAmount()); return true; } } return false; } protected void updateEffects() { updateEffects(mage); } public void updateEffects(Mage mage) { if (mage == null) return; Player player = mage.getPlayer(); if (player == null) return; // Update Bubble effects effects if (effectBubbles && effectColor != null) { CompatibilityUtils.addPotionEffect(player, effectColor.getColor()); effectBubblesApplied = true; } else if (effectBubblesApplied) { effectBubblesApplied = false; CompatibilityUtils.removePotionEffect(player); } Location location = mage.getLocation(); long now = System.currentTimeMillis(); Vector mageLocation = location.toVector(); boolean playEffects = !activeEffectsOnly || inventoryIsOpen; if (playEffects && effectParticle != null && effectParticleInterval > 0 && effectParticleCount > 0) { boolean velocityCheck = true; if (effectParticleMinVelocity > 0) { if (lastLocation != null && lastLocationTime != 0) { double velocitySquared = effectParticleMinVelocity * effectParticleMinVelocity; Vector velocity = lastLocation.subtract(mageLocation); velocity.setY(0); double speedSquared = velocity.lengthSquared() * 1000 / (now - lastLocationTime); velocityCheck = (speedSquared > velocitySquared); } else { velocityCheck = false; } } if (velocityCheck && (lastParticleEffect == 0 || now > lastParticleEffect + effectParticleInterval)) { lastParticleEffect = now; Location effectLocation = player.getLocation(); Location eyeLocation = player.getEyeLocation(); effectLocation.setY(eyeLocation.getY() + effectParticleOffset); if (effectPlayer == null) { effectPlayer = new EffectRing(controller.getPlugin()); effectPlayer.setParticleCount(1); effectPlayer.setIterations(1); effectPlayer.setParticleOffset(0, 0, 0); } effectPlayer.setMaterial(location.getBlock().getRelative(BlockFace.DOWN)); if (effectParticleData == 0) { effectPlayer.setColor(getEffectColor()); } else { effectPlayer.setColor(null); } effectPlayer.setParticleType(effectParticle); effectPlayer.setParticleData(effectParticleData); effectPlayer.setSize(effectParticleCount); effectPlayer.setRadius((float)effectParticleRadius); effectPlayer.start(effectLocation, null); } } if (castSpell != null && castInterval > 0) { boolean velocityCheck = true; if (castMinVelocity > 0) { if (lastLocation != null && lastLocationTime != 0) { double velocitySquared = castMinVelocity * castMinVelocity; Vector velocity = lastLocation.subtract(mageLocation).multiply(-1); if (castVelocityDirection != null) { velocity = velocity.multiply(castVelocityDirection); // This is kind of a hack to make jump-detection work. if (castVelocityDirection.getY() < 0) { velocityCheck = velocity.getY() < 0; } else { velocityCheck = velocity.getY() > 0; } } if (velocityCheck) { double speedSquared = velocity.lengthSquared() * 1000 / (now - lastLocationTime); velocityCheck = (speedSquared > velocitySquared); } } else { velocityCheck = false; } } if (velocityCheck && (lastSpellCast == 0 || now > lastSpellCast + castInterval)) { lastSpellCast = now; Spell spell = mage.getSpell(castSpell); if (spell != null) { if (castParameters == null) { castParameters = new MemoryConfiguration(); } castParameters.set("track_casts", false); mage.setCostReduction(100); mage.setQuiet(true); try { spell.cast(castParameters); } catch (Exception ex) { controller.getLogger().log(Level.WARNING, "Error casting aura spell " + spell.getKey(), ex); } mage.setQuiet(false); mage.setCostReduction(0); } } } if (playEffects && effectSound != null && controller.soundsEnabled() && effectSoundInterval > 0) { if (lastSoundEffect == 0 || now > lastSoundEffect + effectSoundInterval) { lastSoundEffect = now; effectSound.play(controller.getPlugin(), mage.getPlayer()); } } lastLocation = mageLocation; lastLocationTime = now; } protected void updateDurability() { int maxDurability = item.getType().getMaxDurability(); if (maxDurability > 0 && effectiveManaMax > 0) { int durability = (short)(mana * maxDurability / effectiveManaMax); durability = maxDurability - durability; if (durability >= maxDurability) { durability = maxDurability - 1; } else if (durability < 0) { durability = 0; } item.setDurability((short)durability); } } public boolean usesXPBar() { return (hasSpellProgression && spMode.useXP()) || (usesMana() && manaMode.useXP()); } public boolean usesXPNumber() { return (hasSpellProgression && spMode.useXPNumber() && controller.isSPEnabled()) || (usesMana() && manaMode.useXP()); } public boolean hasSpellProgression() { return hasSpellProgression; } public boolean usesXPDisplay() { return usesXPBar() || usesXPNumber(); } @Override public void updateMana() { Player player = mage == null ? null : mage.getPlayer(); if (player == null) return; if (usesMana()) { if (manaMode.useGlow()) { if (mana == effectiveManaMax) { CompatibilityUtils.addGlow(item); } else { CompatibilityUtils.removeGlow(item); } } if (manaMode.useDurability()) { updateDurability(); } } if (usesXPDisplay()) { int playerLevel = player.getLevel(); float playerProgress = player.getExp(); if (usesMana() && manaMode.useXPNumber()) { playerLevel = (int) mana; } if (usesMana() && manaMode.useXPBar()) { playerProgress = Math.max(0, mana / effectiveManaMax); } if (controller.isSPEnabled() && spMode.useXPNumber() && hasSpellProgression) { playerLevel = mage.getSkillPoints(); } mage.sendExperience(playerProgress, playerLevel); } } @Override public boolean isInventoryOpen() { return mage != null && inventoryIsOpen; } @Override public void unbind() { if (!bound) return; com.elmakers.mine.bukkit.api.magic.Mage owningMage = this.mage; deactivate(); if (ownerId != null) { if (owningMage == null || !owningMage.getId().equals(ownerId)) { owningMage = controller.getRegisteredMage(ownerId); } if (owningMage != null) { owningMage.unbind(this); } ownerId = null; } bound = false; owner = null; setProperty("bound", false); setProperty("owner", null); setProperty("owner_id", null); saveState(); } @Override public void bind() { if (bound) return; Mage holdingMage = mage; deactivate(); bound = true; setProperty("bound", true); saveState(); if (holdingMage != null) { holdingMage.checkWand(); } } @Override public void deactivate() { if (mage == null) return; // Play deactivate FX playPassiveEffects("deactivate"); Mage mage = this.mage; Player player = mage.getPlayer(); if (effectBubblesApplied && player != null) { CompatibilityUtils.removePotionEffect(player); effectBubblesApplied = false; } if (isInventoryOpen()) { closeInventory(); } showActiveIcon(false); storedInventory = null; if (usesXPNumber() || usesXPBar()) { mage.resetSentExperience(); } saveState(); mage.deactivateWand(this); this.mage = null; updateMaxMana(true); } @Override public Spell getActiveSpell() { if (mage == null || activeSpell == null || activeSpell.length() == 0) return null; return mage.getSpell(activeSpell); } @Override public SpellTemplate getBaseSpell(String spellName) { return getBaseSpell(new SpellKey(spellName)); } public SpellTemplate getBaseSpell(SpellKey key) { Integer spellLevel = spellLevels.get(key.getBaseKey()); if (spellLevel == null) return null; String spellKey = key.getBaseKey(); if (key.isVariant()) { spellKey += "|" + key.getLevel(); } return controller.getSpellTemplate(spellKey); } @Override public String getActiveSpellKey() { return activeSpell; } @Override public String getActiveBrushKey() { return activeMaterial; } @Override public void damageDealt(double damage, Entity target) { if (effectiveManaMax == 0 && manaMax > 0) { effectiveManaMax = manaMax; } if (manaPerDamage > 0 && effectiveManaMax > 0 && mana < effectiveManaMax) { mana = Math.min(effectiveManaMax, mana + (float)damage * manaPerDamage); updateMana(); } } @Override public boolean cast() { return cast(getActiveSpell()); } public boolean cast(Spell spell) { if (spell != null) { Collection<String> castParameters = null; if (castOverrides != null && castOverrides.size() > 0) { castParameters = new ArrayList<>(); for (Map.Entry<String, String> entry : castOverrides.entrySet()) { String[] key = StringUtils.split(entry.getKey(), "."); if (key.length == 0) continue; if (key.length == 2 && !key[0].equals("default") && !key[0].equals(spell.getSpellKey().getBaseKey()) && !key[0].equals(spell.getSpellKey().getKey())) { continue; } castParameters.add(key.length == 2 ? key[1] : key[0]); castParameters.add(entry.getValue()); } } if (spell.cast(castParameters == null ? null : castParameters.toArray(EMPTY_PARAMETERS))) { Color spellColor = spell.getColor(); use(); if (spellColor != null && this.effectColor != null) { this.effectColor = this.effectColor.mixColor(spellColor, effectColorSpellMixWeight); setProperty("effect_color", effectColor.toString()); // Note that we don't save this change. // The hope is that the wand will get saved at some point later // And we don't want to trigger NBT writes every spell cast. // And the effect color morphing isn't all that important if a few // casts get lost. } updateHotbarStatus(); return true; } } return false; } @SuppressWarnings("deprecation") protected void use() { if (mage == null) return; if (hasUses) { ItemStack item = getItem(); if (item.getAmount() > 1) { item.setAmount(item.getAmount() - 1); } else { if (uses > 0) { uses--; } if (uses <= 0) { Player player = mage.getPlayer(); deactivate(); PlayerInventory playerInventory = player.getInventory(); item = player.getItemInHand(); if (item.getAmount() > 1) { item.setAmount(item.getAmount() - 1); } else { playerInventory.setItemInHand(new ItemStack(Material.AIR, 1)); } player.updateInventory(); } else { saveState(); updateName(); updateLore(); } } } } // Taken from NMS HumanEntity public static int getExpToLevel(int expLevel) { return expLevel >= 30 ? 112 + (expLevel - 30) * 9 : (expLevel >= 15 ? 37 + (expLevel - 15) * 5 : 7 + expLevel * 2); } public static int getExperience(int expLevel, float expProgress) { int xp = 0; for (int level = 0; level < expLevel; level++) { xp += Wand.getExpToLevel(level); } return xp + (int) (expProgress * Wand.getExpToLevel(expLevel)); } protected void updateHotbarStatus() { Player player = mage == null ? null : mage.getPlayer(); if (player != null && LiveHotbar && getMode() == WandMode.INVENTORY && isInventoryOpen()) { mage.updateHotbarStatus(); } } public boolean tickMana(Player player) { boolean updated = false; if (usesMana()) { long now = System.currentTimeMillis(); if (isHeroes) { HeroesManager heroes = controller.getHeroes(); if (heroes != null) { effectiveManaMax = heroes.getMaxMana(player); effectiveManaRegeneration = heroes.getManaRegen(player); manaMax = effectiveManaMax; manaRegeneration = effectiveManaRegeneration; setMana(heroes.getMana(player)); updated = true; } } else if (manaRegeneration > 0 && lastManaRegeneration > 0 && effectiveManaRegeneration > 0) { long delta = now - lastManaRegeneration; if (effectiveManaMax == 0 && manaMax > 0) { effectiveManaMax = manaMax; } setMana(Math.min(effectiveManaMax, mana + (float) effectiveManaRegeneration * (float)delta / 1000)); updated = true; } lastManaRegeneration = now; setProperty("mana_timestamp", lastManaRegeneration); } return updated; } public void tick() { if (mage == null) return; Player player = mage.getPlayer(); if (player == null) return; if (tickMana(player)) { updateMana(); } if (player.isBlocking() && blockMageCooldown > 0) { mage.setRemainingCooldown(blockMageCooldown); } // Update hotbar glow updateHotbarStatus(); if (!passive) { if (damageReductionFire > 0 && player.getFireTicks() > 0) { player.setFireTicks(0); } updateEffects(); } } public void armorUpdated() { updateMaxMana(true); } protected void updateMaxMana(boolean updateLore) { if (isHeroes) return; int currentMana = effectiveManaMax; int currentManaRegen = effectiveManaRegeneration; float effectiveBoost = manaMaxBoost; float effectiveRegenBoost = manaRegenerationBoost; if (mage != null) { Collection<Wand> activeArmor = mage.getActiveArmor(); for (Wand armorWand : activeArmor) { effectiveBoost += armorWand.getManaMaxBoost(); effectiveRegenBoost += armorWand.getManaRegenerationBoost(); } Wand offhandWand = mage.getOffhandWand(); if (offhandWand != null && !offhandWand.isPassive()) { effectiveBoost += offhandWand.getManaMaxBoost(); effectiveRegenBoost += offhandWand.getManaRegenerationBoost(); } } effectiveManaMax = manaMax; if (effectiveBoost != 0) { effectiveManaMax = (int)Math.ceil(effectiveManaMax + effectiveBoost * effectiveManaMax); } effectiveManaRegeneration = manaRegeneration; if (effectiveRegenBoost != 0) { effectiveManaRegeneration = (int)Math.ceil(effectiveManaRegeneration + effectiveRegenBoost * effectiveManaRegeneration); } if (updateLore && (currentMana != effectiveManaMax || effectiveManaRegeneration != currentManaRegen)) { updateLore(); } } public static Float getWandFloat(ItemStack item, String key) { try { Object wandNode = InventoryUtils.getNode(item, WAND_KEY); if (wandNode != null) { String value = InventoryUtils.getMetaString(wandNode, key); if (value != null && !value.isEmpty()) { return Float.parseFloat(value); } } } catch (Exception ex) { } return null; } public static String getWandString(ItemStack item, String key) { try { Object wandNode = InventoryUtils.getNode(item, WAND_KEY); if (wandNode != null) { return InventoryUtils.getMetaString(wandNode, key); } } catch (Exception ex) { } return null; } public MagicController getMaster() { return controller; } public void cycleSpells(int direction) { Set<String> spellsSet = getSpells(); ArrayList<String> spells = new ArrayList<>(spellsSet); if (spells.size() == 0) return; if (activeSpell == null) { setActiveSpell(spells.get(0).split("@")[0]); return; } int spellIndex = 0; for (int i = 0; i < spells.size(); i++) { if (spells.get(i).split("@")[0].equals(activeSpell)) { spellIndex = i; break; } } spellIndex = (spellIndex + direction) % spells.size(); setActiveSpell(spells.get(spellIndex).split("@")[0]); } public void cycleMaterials(int direction) { Set<String> materialsSet = getBrushes(); ArrayList<String> materials = new ArrayList<>(materialsSet); if (materials.size() == 0) return; if (activeMaterial == null) { setActiveBrush(materials.get(0).split("@")[0]); return; } int materialIndex = 0; for (int i = 0; i < materials.size(); i++) { if (materials.get(i).split("@")[0].equals(activeMaterial)) { materialIndex = i; break; } } materialIndex = (materialIndex + direction) % materials.size(); setActiveBrush(materials.get(materialIndex).split("@")[0]); } public Mage getActiveMage() { return mage; } public void setActiveMage(com.elmakers.mine.bukkit.api.magic.Mage mage) { if (mage instanceof Mage) { this.mage = (Mage)mage; } } public Color getEffectColor() { return effectColor == null ? null : effectColor.getColor(); } public ParticleEffect getEffectParticle() { return effectParticle; } public Inventory getHotbar() { if (this.hotbars.size() == 0) return null; if (currentHotbar < 0 || currentHotbar >= this.hotbars.size()) { currentHotbar = 0; } return this.hotbars.get(currentHotbar); } public int getHotbarCount() { if (getMode() != WandMode.INVENTORY) return 0; return hotbars.size(); } public List<Inventory> getHotbars() { return hotbars; } @Override public boolean isQuickCastDisabled() { return quickCastDisabled; } public boolean isManualQuickCastDisabled() { return manualQuickCastDisabled; } @Override public boolean isQuickCast() { return quickCast; } public WandMode getMode() { WandMode wandMode = mode != null ? mode : controller.getDefaultWandMode(); Player player = mage == null ? null : mage.getPlayer(); if (wandMode == WandMode.INVENTORY && player != null && player.getGameMode() == GameMode.CREATIVE) { wandMode = WandMode.CHEST; } return wandMode; } public WandMode getBrushMode() { return brushMode != null ? brushMode : controller.getDefaultBrushMode(); } public void setMode(WandMode mode) { this.mode = mode; } public void setBrushMode(WandMode mode) { this.brushMode = mode; } @Override public boolean showCastMessages() { return quietLevel == 0; } @Override public boolean showMessages() { return quietLevel < 2; } public boolean isStealth() { return quietLevel > 2; } @Override public void setPath(String path) { this.path = path; setProperty("path", path); } /* * Public API Implementation */ @Override public boolean isLost(com.elmakers.mine.bukkit.api.wand.LostWand lostWand) { return this.id != null && this.id.equals(lostWand.getId()); } @Override public LostWand makeLost(Location location) { return new LostWand(this, location); } @Override @Deprecated public void activate(com.elmakers.mine.bukkit.api.magic.Mage mage) { if (mage instanceof Mage) { activate((Mage)mage); } } protected void showActiveIcon(boolean show) { if (this.icon == null || this.inactiveIcon == null || this.inactiveIcon.getMaterial() == Material.AIR || this.inactiveIcon.getMaterial() == null) return; if (this.icon.getMaterial() == Material.AIR || this.icon.getMaterial() == null) { this.icon.setMaterial(DefaultWandMaterial); } if (show) { if (inactiveIconDelay > 0) { Plugin plugin = controller.getPlugin(); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { findItem(); icon.applyToItem(item); } }, inactiveIconDelay * 20 / 1000); } else { findItem(); icon.applyToItem(item); } } else { findItem(); inactiveIcon.applyToItem(this.item); } } public boolean activate(Mage mage) { return activate(mage, false); } public boolean activateOffhand(Mage mage) { return activate(mage, true); } public boolean activate(Mage mage, boolean offhand) { if (mage == null) return false; Player player = mage.getPlayer(); if (player != null) { if (!controller.hasWandPermission(player, this)) return false; InventoryView openInventory = player.getOpenInventory(); InventoryType inventoryType = openInventory.getType(); if (inventoryType == InventoryType.ENCHANTING || inventoryType == InventoryType.ANVIL) return false; } if (!canUse(player)) { mage.sendMessage(getMessage("bound").replace("$name", getOwner())); return false; } this.checkId(); if (this.isUpgrade) { controller.getLogger().warning("Activated an upgrade item- this shouldn't happen"); return false; } WandPreActivateEvent preActivateEvent = new WandPreActivateEvent(mage, this); Bukkit.getPluginManager().callEvent(preActivateEvent); if (preActivateEvent.isCancelled()) { return false; } this.mage = mage; // Since these wands can't be opened we will just show them as open when held if (getMode() != WandMode.INVENTORY || offhand) { showActiveIcon(true); playPassiveEffects("open"); } boolean forceUpdate = false; // Check for an empty wand and auto-fill if (!isUpgrade && (controller.fillWands() || autoFill)) { fill(mage.getPlayer(), controller.getMaxWandFillLevel()); } if (isHeroes && player != null) { HeroesManager heroes = controller.getHeroes(); if (heroes != null) { Set<String> skills = heroes.getSkills(player); Collection<String> currentSpells = new ArrayList<>(getSpells()); for (String spellKey : currentSpells) { if (spellKey.startsWith("heroes*") && !skills.contains(spellKey.substring(7))) { removeSpell(spellKey); } } // Hack to prevent messaging this.mage = null; for (String skillKey : skills) { String heroesKey = "heroes*" + skillKey; if (!spells.containsKey(heroesKey)) { addSpell(heroesKey); } } this.mage = mage; } } // Check for auto-organize if (autoOrganize && !isUpgrade) { organizeInventory(mage); } // Check for auto-alphabetize if (autoAlphabetize && !isUpgrade) { alphabetizeInventory(); } // Check for spell or other special icons in the player's inventory Inventory inventory = player.getInventory(); ItemStack[] items = inventory.getContents(); for (int i = 0; i < items.length; i++) { ItemStack item = items[i]; if (addItem(item)) { inventory.setItem(i, null); forceUpdate = true; } } // Check for auto-bind if (bound) { String mageName = ChatColor.stripColor(mage.getPlayer().getDisplayName()); String mageId = mage.getPlayer().getUniqueId().toString(); boolean ownerRenamed = owner != null && ownerId != null && ownerId.equals(mageId) && !owner.equals(mageName); if (ownerId == null || ownerId.length() == 0 || owner == null || ownerRenamed) { takeOwnership(mage.getPlayer()); } } // Check for randomized wands if (randomize) { randomize(); forceUpdate = true; } checkActiveMaterial(); tick(); saveState(); updateMaxMana(false); updateActiveMaterial(); updateName(); updateLore(); // Play activate FX playPassiveEffects("activate"); lastSoundEffect = 0; lastParticleEffect = 0; lastSpellCast = 0; lastLocationTime = 0; lastLocation = null; if (forceUpdate) { DeprecatedUtils.updateInventory(player); } return true; } @Override public boolean organizeInventory() { if (mage != null) { return organizeInventory(mage); } return false; } @Override public boolean organizeInventory(com.elmakers.mine.bukkit.api.magic.Mage mage) { WandOrganizer organizer = new WandOrganizer(this, mage); organizer.organize(); openInventoryPage = 0; currentHotbar = 0; autoOrganize = false; autoAlphabetize = false; return true; } @Override public boolean alphabetizeInventory() { WandOrganizer organizer = new WandOrganizer(this); organizer.alphabetize(); openInventoryPage = 0; currentHotbar = 0; autoOrganize = false; autoAlphabetize = false; return true; } @Override public com.elmakers.mine.bukkit.api.wand.Wand duplicate() { ItemStack newItem = InventoryUtils.getCopy(item); Wand newWand = controller.getWand(newItem); newWand.saveState(); return newWand; } @Override public boolean configure(Map<String, Object> properties) { Map<Object, Object> convertedProperties = new HashMap<Object, Object>(properties); configure(ConfigurationUtils.toConfigurationSection(convertedProperties)); loadProperties(); saveState(); updateName(); updateLore(); return true; } @Override public boolean upgrade(Map<String, Object> properties) { Map<Object, Object> convertedProperties = new HashMap<Object, Object>(properties); upgrade(ConfigurationUtils.toConfigurationSection(convertedProperties)); loadProperties(); saveState(); updateName(); updateLore(); return true; } @Override public boolean isLocked() { return this.locked; } @Override public void unlock() { locked = false; setProperty("locked", false); } public boolean isPassive() { return passive; } @Override public boolean canUse(Player player) { if (!bound || ownerId == null || ownerId.length() == 0) return true; if (controller.hasPermission(player, "Magic.wand.override_bind", false)) return true; return ownerId.equalsIgnoreCase(player.getUniqueId().toString()); } @Override public boolean addSpell(String spellName) { if (!isModifiable()) return false; SpellKey spellKey = new SpellKey(spellName); if (hasSpell(spellKey)) { return false; } saveInventory(); SpellTemplate template = controller.getSpellTemplate(spellName); if (template == null) { controller.getLogger().warning("Tried to add unknown spell to wand: " + spellName); return false; } // This handles adding via an alias if (hasSpell(template.getKey())) return false; ItemStack spellItem = createSpellIcon(template); if (spellItem == null) { return false; } spellKey = template.getSpellKey(); int level = spellKey.getLevel(); int inventoryCount = inventories.size(); int spellCount = spells.size(); // Special handling for spell upgrades and spells to remove Integer inventorySlot = null; Integer currentLevel = spellLevels.get(spellKey.getBaseKey()); SpellTemplate currentSpell = getBaseSpell(spellKey); List<SpellKey> spellsToRemove = new ArrayList<>(template.getSpellsToRemove().size()); for (SpellKey key : template.getSpellsToRemove()) { if (spellLevels.get(key.getBaseKey()) != null) { spellsToRemove.add(key); } } if (currentLevel != null || !spellsToRemove.isEmpty()) { List<Inventory> allInventories = getAllInventories(); int currentSlot = 0; for (Inventory inventory : allInventories) { ItemStack[] items = inventory.getContents(); for (int index = 0; index < items.length; index++) { ItemStack itemStack = items[index]; if (isSpell(itemStack)) { SpellKey checkKey = new SpellKey(getSpell(itemStack)); if (checkKey.getBaseKey().equals(spellKey.getBaseKey())) { inventorySlot = currentSlot; inventory.setItem(index, null); spells.remove(checkKey.getKey()); } else { for (SpellKey key : spellsToRemove) { if (checkKey.getBaseKey().equals(key.getBaseKey())) { inventory.setItem(index, null); spells.remove(key.getKey()); spellLevels.remove(key.getBaseKey()); } } } } currentSlot++; } } } spellLevels.put(spellKey.getBaseKey(), level); spells.put(template.getKey(), inventorySlot); if (currentLevel != null) { if (activeSpell != null && !activeSpell.isEmpty()) { SpellKey currentKey = new SpellKey(activeSpell); if (currentKey.getBaseKey().equals(spellKey.getBaseKey())) { setActiveSpell(spellKey.getKey()); } } } if (activeSpell == null || activeSpell.isEmpty()) { setActiveSpell(spellKey.getKey()); } addToInventory(spellItem, inventorySlot); updateInventory(); updateHasInventory(); updateSpells(); saveState(); updateLore(); if (mage != null) { if (currentSpell != null) { String levelDescription = template.getLevelDescription(); if (levelDescription == null || levelDescription.isEmpty()) { levelDescription = template.getName(); } sendLevelMessage("spell_upgraded", currentSpell.getName(), levelDescription); mage.sendMessage(template.getUpgradeDescription().replace("$name", currentSpell.getName())); SpellUpgradeEvent upgradeEvent = new SpellUpgradeEvent(mage, this, currentSpell, template); Bukkit.getPluginManager().callEvent(upgradeEvent); } else { sendAddMessage("spell_added", template.getName()); AddSpellEvent addEvent = new AddSpellEvent(mage, this, template); Bukkit.getPluginManager().callEvent(addEvent); } if (spells.size() != spellCount) { if (spellCount == 0) { String message = getMessage("spell_instructions", "").replace("$wand", getName()); mage.sendMessage(message.replace("$spell", template.getName())); } else if (spellCount == 1) { mage.sendMessage(getMessage("inventory_instructions", "").replace("$wand", getName())); } if (inventoryCount == 1 && inventories.size() > 1) { mage.sendMessage(getMessage("page_instructions", "").replace("$wand", getName())); } } } return true; } @Override protected void sendAddMessage(String messageKey, String nameParam) { if (mage == null || nameParam == null || nameParam.isEmpty()) return; String message = getMessage(messageKey).replace("$name", nameParam).replace("$wand", getName()); mage.sendMessage(message); } protected void sendLevelMessage(String messageKey, String nameParam, String level) { if (mage == null || nameParam == null || nameParam.isEmpty()) return; String message = getMessage(messageKey).replace("$name", nameParam).replace("$wand", getName()).replace("$level", level); mage.sendMessage(message); } @Override protected void sendMessage(String messageKey) { if (mage == null || messageKey == null || messageKey.isEmpty()) return; String message = getMessage(messageKey).replace("$wand", getName()); mage.sendMessage(message); } @Override public String getMessage(String key, String defaultValue) { String message = controller.getMessages().get("wand." + key, defaultValue); if (template != null && !template.isEmpty()) { message = controller.getMessages().get("wands." + template + "." + key, message); } return message; } @Override protected void sendDebug(String debugMessage) { if (mage != null) { mage.sendDebugMessage(debugMessage); } } @Override public boolean add(com.elmakers.mine.bukkit.api.wand.Wand other) { if (other instanceof Wand) { return add((Wand)other); } return false; } @Override public boolean hasBrush(String materialKey) { return getBrushes().contains(materialKey); } @Override public boolean hasSpell(String spellName) { return hasSpell(new SpellKey(spellName)); } public boolean hasSpell(SpellKey spellKey) { Integer level = spellLevels.get(spellKey.getBaseKey()); return (level != null && level >= spellKey.getLevel()); } @Override public boolean addBrush(String materialKey) { if (!isModifiable()) return false; if (hasBrush(materialKey)) return false; saveInventory(); ItemStack itemStack = createBrushIcon(materialKey); if (itemStack == null) return false; int inventoryCount = inventories.size(); int brushCount = brushes.size(); brushes.put(materialKey, null); addToInventory(itemStack); if (activeMaterial == null || activeMaterial.length() == 0) { activateBrush(materialKey); } else { updateInventory(); } updateHasInventory(); updateBrushes(); saveState(); updateLore(); if (mage != null) { Messages messages = controller.getMessages(); String materialName = MaterialBrush.getMaterialName(messages, materialKey); if (materialName == null) { mage.getController().getLogger().warning("Invalid material: " + materialKey); materialName = materialKey; } sendAddMessage("brush_added", materialName); if (brushCount == 0) { mage.sendMessage(getMessage("brush_instructions").replace("$wand", getName())); } if (inventoryCount == 1 && inventories.size() > 1) { mage.sendMessage(getMessage("page_instructions").replace("$wand", getName())); } } return true; } @Override public void setActiveBrush(String materialKey) { activateBrush(materialKey); if (materialKey == null || mage == null) { return; } com.elmakers.mine.bukkit.api.block.MaterialBrush brush = mage.getBrush(); if (brush == null) { return; } boolean eraseWasActive = brush.isEraseModifierActive(); brush.activate(mage.getLocation(), materialKey); if (mage != null) { BrushMode mode = brush.getMode(); if (mode == BrushMode.CLONE) { mage.sendMessage(getMessage("clone_material_activated")); } else if (mode == BrushMode.REPLICATE) { mage.sendMessage(getMessage("replicate_material_activated")); } if (!eraseWasActive && brush.isEraseModifierActive()) { mage.sendMessage(getMessage("erase_modifier_activated")); } } } public void setActiveBrush(ItemStack itemStack) { if (!isBrush(itemStack)) return; setActiveBrush(getBrush(itemStack)); } public void activateBrush(String materialKey) { this.activeMaterial = materialKey; setProperty("active_material", this.activeMaterial); saveState(); updateName(); updateActiveMaterial(); updateHotbar(); } @Override public void setActiveSpell(String activeSpell) { SpellKey spellKey = new SpellKey(activeSpell); activeSpell = spellKey.getBaseKey(); if (!spellLevels.containsKey(activeSpell)) { return; } spellKey = new SpellKey(spellKey.getBaseKey(), spellLevels.get(activeSpell)); this.activeSpell = spellKey.getKey(); setProperty("active_spell", this.activeSpell); saveState(); updateName(); } @Override public boolean removeBrush(String materialKey) { if (!isModifiable() || materialKey == null) return false; saveInventory(); if (materialKey.equals(activeMaterial)) { activeMaterial = null; } brushes.remove(materialKey); List<Inventory> allInventories = getAllInventories(); boolean found = false; for (Inventory inventory : allInventories) { ItemStack[] items = inventory.getContents(); for (int index = 0; index < items.length; index++) { ItemStack itemStack = items[index]; if (itemStack != null && isBrush(itemStack)) { String itemKey = getBrush(itemStack); if (itemKey.equals(materialKey)) { found = true; inventory.setItem(index, null); } else if (activeMaterial == null) { activeMaterial = materialKey; } if (found && activeMaterial != null) { break; } } } } updateActiveMaterial(); updateInventory(); updateBrushes(); saveState(); updateName(); updateLore(); return found; } @Override public boolean removeSpell(String spellName) { if (!isModifiable()) return false; saveInventory(); if (spellName.equals(activeSpell)) { setActiveSpell(null); } spells.remove(spellName); SpellKey spellKey = new SpellKey(spellName); spellLevels.remove(spellKey.getBaseKey()); List<Inventory> allInventories = getAllInventories(); boolean found = false; for (Inventory inventory : allInventories) { ItemStack[] items = inventory.getContents(); for (int index = 0; index < items.length; index++) { ItemStack itemStack = items[index]; if (itemStack != null && itemStack.getType() != Material.AIR && isSpell(itemStack)) { if (getSpell(itemStack).equals(spellName)) { found = true; inventory.setItem(index, null); } else if (activeSpell == null) { setActiveSpell(getSpell(itemStack)); } if (found && activeSpell != null) { break; } } } } updateInventory(); updateHasInventory(); updateSpells(); saveState(); updateName(); updateLore(); return found; } @Override public Map<String, String> getOverrides() { return castOverrides == null ? new HashMap<String, String>() : new HashMap<>(castOverrides); } @Override public void setOverrides(Map<String, String> overrides) { if (overrides == null) { this.castOverrides = null; } else { this.castOverrides = new HashMap<>(overrides); } updateOverrides(); } @Override public void removeOverride(String key) { if (castOverrides != null) { castOverrides.remove(key); updateOverrides(); } } @Override public void setOverride(String key, String value) { if (castOverrides == null) { castOverrides = new HashMap<>(); } if (value == null || value.length() == 0) { castOverrides.remove(key); } else { castOverrides.put(key, value); } updateOverrides(); } @Override public boolean addOverride(String key, String value) { if (castOverrides == null) { castOverrides = new HashMap<>(); } boolean modified = false; if (value == null || value.length() == 0) { modified = castOverrides.containsKey(key); castOverrides.remove(key); } else { String current = castOverrides.get(key); modified = current == null || !current.equals(value); castOverrides.put(key, value); } if (modified) { updateOverrides(); } return modified; } protected void updateOverrides() { if (castOverrides != null && castOverrides.size() > 0) { Collection<String> parameters = new ArrayList<>(); for (Map.Entry<String, String> entry : castOverrides.entrySet()) { String value = entry.getValue(); parameters.add(entry.getKey() + " " + value.replace(",", "\\|")); } setProperty("overrides", StringUtils.join(parameters, ",")); } else { setProperty("overrides", null); } } public boolean hasStoredInventory() { return storedInventory != null; } public Inventory getStoredInventory() { return storedInventory; } public boolean addToStoredInventory(ItemStack item) { if (storedInventory == null) { return false; } HashMap<Integer, ItemStack> remainder = storedInventory.addItem(item); return remainder.size() == 0; } public void setStoredSlot(int slot) { this.storedSlot = slot; } public boolean storeInventory() { if (storedInventory != null) { if (mage != null) { mage.sendMessage("Your wand contains a previously stored inventory and will not activate, let go of it to clear."); } controller.getLogger().warning("Tried to store an inventory with one already present: " + (mage == null ? "?" : mage.getName())); return false; } Player player = mage.getPlayer(); if (player == null) { return false; } PlayerInventory inventory = player.getInventory(); storedInventory = CompatibilityUtils.createInventory(null, PLAYER_INVENTORY_SIZE, "Stored Inventory"); for (int i = 0; i < PLAYER_INVENTORY_SIZE; i++) { // Make sure we don't store any spells or magical materials, just in case ItemStack item = inventory.getItem(i); if (!Wand.isSpell(item) || Wand.isSkill(item)) { storedInventory.setItem(i, item); } inventory.setItem(i, null); } storedSlot = inventory.getHeldItemSlot(); inventory.setItem(storedSlot, item); return true; } @SuppressWarnings("deprecation") public boolean restoreInventory() { if (storedInventory == null) { return false; } Player player = mage.getPlayer(); if (player == null) { return false; } PlayerInventory inventory = player.getInventory(); // Check for the wand having been removed somehow, we don't want to put it back // if that happened. // This fixes dupe issues with armor stands, among other things // We do need to account for the wand not being the active slot anymore ItemStack storedItem = storedInventory.getItem(storedSlot); ItemStack currentItem = inventory.getItem(storedSlot); String currentId = getWandId(currentItem); String storedId = getWandId(storedItem); if (storedId != null && storedId.equals(id) && !Objects.equal(currentId, id)) { // Hacky special-case to avoid glitching spells out of the inventory // via the offhand slot. if (isSpell(currentItem)) { currentItem = null; } storedInventory.setItem(storedSlot, currentItem); controller.info("Cleared wand on inv close for player " + player.getName()); } for (int i = 0; i < storedInventory.getSize(); i++) { inventory.setItem(i, storedInventory.getItem(i)); } storedInventory = null; saveState(); inventory.setHeldItemSlot(storedSlot); player.updateInventory(); return true; } @Override public boolean isSoul() { return soul; } @Override public boolean isBound() { return bound; } @Override public Spell getSpell(String spellKey, com.elmakers.mine.bukkit.api.magic.Mage mage) { if (mage == null) { return null; } SpellKey key = new SpellKey(spellKey); String baseKey = key.getBaseKey(); Integer level = spellLevels.get(baseKey); if (level == null) { return null; } SpellKey levelKey = new SpellKey(baseKey, level); return mage.getSpell(levelKey.getKey()); } @Override public SpellTemplate getSpellTemplate(String spellKey) { SpellKey key = new SpellKey(spellKey); String baseKey = key.getBaseKey(); Integer level = spellLevels.get(baseKey); if (level == null) { return null; } SpellKey levelKey = new SpellKey(baseKey, level); return controller.getSpellTemplate(levelKey.getKey()); } @Override public Spell getSpell(String spellKey) { return getSpell(spellKey, mage); } @Override public int getSpellLevel(String spellKey) { SpellKey key = new SpellKey(spellKey); Integer level = spellLevels.get(key.getBaseKey()); return level == null ? 0 : level; } @Override public MageController getController() { return controller; } protected Map<String, Integer> getSpellInventory() { return new HashMap<>(spells); } protected Map<String, Integer> getBrushInventory() { return new HashMap<>(brushes); } protected void updateSpellInventory(Map<String, Integer> updateSpells) { for (Map.Entry<String, Integer> spellEntry : spells.entrySet()) { String spellKey = spellEntry.getKey(); Integer slot = updateSpells.get(spellKey); if (slot != null) { spellEntry.setValue(slot); } } } protected void updateBrushInventory(Map<String, Integer> updateBrushes) { for (Map.Entry<String, Integer> brushEntry : brushes.entrySet()) { String brushKey = brushEntry.getKey(); Integer slot = updateBrushes.get(brushKey); if (slot != null) { brushEntry.setValue(slot); } } } public Map<PotionEffectType, Integer> getPotionEffects() { return potionEffects; } @Override public float getHealthRegeneration() { Integer level = potionEffects.get(PotionEffectType.REGENERATION); return level != null && level > 0 ? (float)level : 0; } @Override public float getHungerRegeneration() { Integer level = potionEffects.get(PotionEffectType.SATURATION); return level != null && level > 0 ? (float)level : 0; } @Override public WandTemplate getTemplate() { if (template == null || template.isEmpty()) return null; return controller.getWandTemplate(template); } public boolean playPassiveEffects(String effects) { WandTemplate wandTemplate = getTemplate(); if (wandTemplate != null && mage != null) { return wandTemplate.playEffects(mage, effects); } return false; } @Override public boolean playEffects(String effects) { if (activeEffectsOnly && !inventoryIsOpen) { return false; } return playPassiveEffects(effects); } public WandAction getDropAction() { return dropAction; } public WandAction getRightClickAction() { return rightClickAction; } public WandAction getLeftClickAction() { return leftClickAction; } public WandAction getSwapAction() { return swapAction; } public boolean performAction(WandAction action) { WandMode mode = getMode(); switch (action) { case CAST: cast(); break; case TOGGLE: if (mode != WandMode.CHEST && mode != WandMode.INVENTORY) return false; toggleInventory(); break; case CYCLE: cycleActive(1); break; case CYCLE_REVERSE: cycleActive(-1); break; case CYCLE_HOTBAR: if (mode != WandMode.INVENTORY || !isInventoryOpen()) return false; if (getHotbarCount() > 1) { cycleHotbar(1); } else { closeInventory(); } break; case CYCLE_HOTBAR_REVERSE: if (mode != WandMode.INVENTORY) return false; if (getHotbarCount() > 1) { cycleHotbar(-1); } else if (isInventoryOpen()) { closeInventory(); } else { return false; } break; default: return false; } return true; } @Override public boolean checkAndUpgrade(boolean quiet) { com.elmakers.mine.bukkit.api.wand.WandUpgradePath path = getPath(); com.elmakers.mine.bukkit.api.wand.WandUpgradePath nextPath = path != null ? path.getUpgrade(): null; if (nextPath == null || path.canEnchant(this)) { return true; } if (!path.checkUpgradeRequirements(this, quiet ? null : mage)) { return false; } path.upgrade(this, mage); return true; } public int getEffectiveManaMax() { return effectiveManaMax; } public int getEffectiveManaRegeneration() { return effectiveManaRegeneration; } @Override public boolean isBlocked(double angle) { if (mage == null) return false; if (blockChance == 0) return false; if (blockFOV > 0 && angle > blockFOV) return false; long lastBlock = mage.getLastBlockTime(); if (blockCooldown > 0 && lastBlock > 0 && lastBlock + blockCooldown > System.currentTimeMillis()) return false; boolean isBlocked = Math.random() <= blockChance; if (isBlocked) { playEffects("spell_blocked"); mage.setLastBlockTime(System.currentTimeMillis()); } return isBlocked; } @Override public boolean isReflected(double angle) { if (mage == null) return false; if (blockReflectChance == 0) return false; if (blockFOV > 0 && angle > blockFOV) return false; long lastBlock = mage.getLastBlockTime(); if (blockCooldown > 0 && lastBlock > 0 && lastBlock + blockCooldown > System.currentTimeMillis()) return false; boolean isReflected = Math.random() <= blockReflectChance; if (isReflected) { playEffects("spell_reflected"); if (mage != null) mage.setLastBlockTime(System.currentTimeMillis()); } return isReflected; } }
Play wand FX at the correct location when in offhand
Magic/src/main/java/com/elmakers/mine/bukkit/wand/Wand.java
Play wand FX at the correct location when in offhand
Java
mit
64ed0471bd23d7056817f055b8cde25c63e58ad5
0
brahalla/PhotoAlbum-api
package com.brahalla.PhotoAlbum.configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { authenticationManagerBuilder .inMemoryAuthentication() .withUser("user") .password("password") .roles("USER") .and().withUser("admin") .password("password") .roles("ADMIN","USER"); } @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity .authorizeRequests() .anyRequest().fullyAuthenticated() //.and().authorizeUrls() .and().formLogin() .loginPage("authenticate") .permitAll() .and().httpBasic() .and().csrf() .disable(); } }
src/main/java/com/brahalla/PhotoAlbum/configuration/WebSecurityConfiguration.java
package com.brahalla.PhotoAlbum.configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder authenticationManagerBuilder) { authenticationManagerBuilder .inMemoryAuthentication() .withUser("user") .password("password") .roles("USER") .and().withUser("admin") .password("password") .roles("ADMIN","USER"); } @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity .authorizeRequests() .anyRequest().fullyAuthenticated() //.and().authorizeUrls() .and().formLogin() .loginPage("authenticate") .permitAll() .and().httpBasic() .and().csrf() .disable(); } }
adding exception throw
src/main/java/com/brahalla/PhotoAlbum/configuration/WebSecurityConfiguration.java
adding exception throw
Java
agpl-3.0
40d7f3b19f6cd7df70d3fcfa609d5a7cf600e7d7
0
ivanovlev/Gadgetbridge,Freeyourgadget/Gadgetbridge,roidelapluie/Gadgetbridge,rosenpin/Gadgetbridge,ivanovlev/Gadgetbridge,rosenpin/Gadgetbridge,rosenpin/Gadgetbridge,Freeyourgadget/Gadgetbridge,roidelapluie/Gadgetbridge,ivanovlev/Gadgetbridge,roidelapluie/Gadgetbridge,Freeyourgadget/Gadgetbridge,Freeyourgadget/Gadgetbridge
package nodomain.freeyourgadget.gadgetbridge.service.btle.actions; import android.bluetooth.BluetoothGatt; import android.content.Context; import nodomain.freeyourgadget.gadgetbridge.util.GB; public class SetProgressAction extends PlainAction { private final String text; private final boolean ongoing; private final int percentage; private final Context context; /** * When run, will update the progress notification. * * @param text * @param ongoing * @param percentage * @param context */ public SetProgressAction(String text, boolean ongoing, int percentage, Context context) { this.text = text; this.ongoing = ongoing; this.percentage = percentage; this.context = context; } @Override public boolean run(BluetoothGatt gatt) { GB.updateInstallNotification(this.text, this.ongoing, this.percentage, this.context); return true; } @Override public String toString() { return getCreationTime() + ": " + getClass().getSimpleName() + ": " + text + "; " + percentage + "%"; } }
app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/btle/actions/SetProgressAction.java
package nodomain.freeyourgadget.gadgetbridge.service.btle.actions; import android.bluetooth.BluetoothGatt; import android.content.Context; import nodomain.freeyourgadget.gadgetbridge.util.GB; public class SetProgressAction extends PlainAction { private final String text; private final boolean ongoing; private final int percentage; private final Context context; /** * When run, will update the progress notification. * * @param text * @param ongoing * @param percentage * @param context */ public SetProgressAction(String text, boolean ongoing, int percentage, Context context) { this.text = text; this.ongoing = ongoing; this.percentage = percentage; this.context = context; } @Override public boolean run(BluetoothGatt gatt) { GB.updateInstallNotification(this.text, this.ongoing, this.percentage, this.context); return true; } }
Improved log output for progress actions
app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/btle/actions/SetProgressAction.java
Improved log output for progress actions
Java
agpl-3.0
8f4d90196942f2caefdbd983e4ee0282fb68b6d5
0
JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio
/* * DependencyManager.java * * Copyright (C) 2009-15 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.common.dependencies; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.rstudio.core.client.CommandWith2Args; import org.rstudio.core.client.CommandWithArg; import org.rstudio.core.client.Debug; import org.rstudio.core.client.StringUtil; import org.rstudio.core.client.widget.MessageDialog; import org.rstudio.core.client.widget.Operation; import org.rstudio.core.client.widget.ProgressIndicator; import org.rstudio.studio.client.application.events.EventBus; import org.rstudio.studio.client.common.GlobalDisplay; import org.rstudio.studio.client.common.GlobalProgressDelayer; import org.rstudio.studio.client.common.console.ConsoleProcess; import org.rstudio.studio.client.common.console.ProcessExitEvent; import org.rstudio.studio.client.common.dependencies.events.InstallShinyEvent; import org.rstudio.studio.client.common.dependencies.model.Dependency; import org.rstudio.studio.client.common.dependencies.model.DependencyServerOperations; import org.rstudio.studio.client.server.ServerError; import org.rstudio.studio.client.server.ServerRequestCallback; import org.rstudio.studio.client.workbench.views.packages.events.PackageStateChangedEvent; import org.rstudio.studio.client.workbench.views.packages.events.PackageStateChangedHandler; import org.rstudio.studio.client.workbench.views.vcs.common.ConsoleProgressDialog; import com.google.gwt.core.client.JsArray; import com.google.gwt.user.client.Command; import com.google.inject.Inject; import com.google.inject.Singleton; @Singleton public class DependencyManager implements InstallShinyEvent.Handler, PackageStateChangedHandler { class DependencyRequest { DependencyRequest( String progressCaptionIn, String userActionIn, CommandWith2Args<String,Command> userPromptIn, Dependency[] dependenciesIn, boolean silentEmbeddedUpdateIn, CommandWithArg<Boolean> onCompleteIn) { progressCaption = progressCaptionIn; userAction = userActionIn; userPrompt = userPromptIn; dependencies = dependenciesIn; silentEmbeddedUpdate = silentEmbeddedUpdateIn; onComplete = onCompleteIn; } String progressCaption; String userAction; CommandWith2Args<String,Command> userPrompt; Dependency[] dependencies; boolean silentEmbeddedUpdate; CommandWithArg<Boolean> onComplete; } @Inject public DependencyManager(GlobalDisplay globalDisplay, DependencyServerOperations server, EventBus eventBus) { globalDisplay_ = globalDisplay; server_ = server; satisfied_ = new ArrayList<Dependency>(); requestQueue_ = new LinkedList<DependencyRequest>(); eventBus.addHandler(InstallShinyEvent.TYPE, this); eventBus.addHandler(PackageStateChangedEvent.TYPE, this); } public void withDependencies(String progressCaption, CommandWith2Args<String,Command> userPrompt, Dependency[] dependencies, boolean silentEmbeddedUpdate, CommandWithArg<Boolean> onComplete) { withDependencies(progressCaption, null, userPrompt, dependencies, silentEmbeddedUpdate, onComplete); } public void withDependencies(String progressCaption, String userAction, Dependency[] dependencies, boolean silentEmbeddedUpdate, final CommandWithArg<Boolean> onComplete) { withDependencies(progressCaption, userAction, null, dependencies, silentEmbeddedUpdate, onComplete); } public void withPackrat(String userAction, final Command command) { withDependencies( "Packrat", userAction, new Dependency[] { Dependency.cranPackage("packrat", "0.4.8-1", true) }, false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } }); } public void withRSConnect(String userAction, boolean requiresRmarkdown, CommandWith2Args<String, Command> userPrompt, final CommandWithArg<Boolean> onCompleted) { // build dependency array ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("digest", "0.6")); deps.add(Dependency.cranPackage("RCurl", "1.95")); deps.add(Dependency.cranPackage("RJSONIO", "1.0")); deps.add(Dependency.cranPackage("PKI", "0.1")); deps.add(Dependency.cranPackage("rstudioapi", "0.5")); deps.add(Dependency.cranPackage("yaml", "2.1.5")); if (requiresRmarkdown) deps.addAll(rmarkdownDependencies()); deps.add(Dependency.cranPackage("packrat", "0.4.8-1", true)); deps.add(Dependency.embeddedPackage("rsconnect")); withDependencies( "Publishing", userAction, userPrompt, deps.toArray(new Dependency[deps.size()]), true, // we want the embedded rsconnect package to be updated if needed onCompleted ); } public void withRMarkdown(String userAction, final Command command) { withRMarkdown("R Markdown", userAction, command); } public void withRMarkdown(String progressCaption, String userAction, final Command command) { withDependencies( progressCaption, userAction, rmarkdownDependenciesArray(), true, // we want to update to the embedded version if needed new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } public void withRMarkdown(String progressCaption, String userAction, final CommandWithArg<Boolean> command) { withDependencies( progressCaption, userAction, rmarkdownDependenciesArray(), true, command); } public static List<Dependency> rmarkdownDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("evaluate", "0.8")); deps.add(Dependency.cranPackage("digest", "0.6")); deps.add(Dependency.cranPackage("highr", "0.3")); deps.add(Dependency.cranPackage("markdown", "0.7")); deps.add(Dependency.cranPackage("stringr", "0.6")); deps.add(Dependency.cranPackage("yaml", "2.1.5")); deps.add(Dependency.cranPackage("Rcpp", "0.11.5")); deps.add(Dependency.cranPackage("htmltools", "0.3.5")); deps.add(Dependency.cranPackage("caTools", "1.14")); deps.add(Dependency.cranPackage("bitops", "1.0-6")); deps.add(Dependency.cranPackage("knitr", "1.14", true)); deps.add(Dependency.cranPackage("jsonlite", "0.9.19")); deps.add(Dependency.cranPackage("base64enc", "0.1-3")); deps.add(Dependency.cranPackage("rprojroot", "1.0")); deps.add(Dependency.embeddedPackage("rmarkdown")); return deps; } public static Dependency[] rmarkdownDependenciesArray() { List<Dependency> deps = rmarkdownDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withShiny(final String userAction, final Command command) { // create user prompt command CommandWith2Args<String, Command> userPrompt = new CommandWith2Args<String, Command>() { @Override public void execute(final String unmetDeps, final Command yesCommand) { globalDisplay_.showYesNoMessage( MessageDialog.QUESTION, "Install Shiny Package", userAction + " requires installation of an updated version " + "of the shiny package.\n\nDo you want to install shiny now?", new Operation() { @Override public void execute() { yesCommand.execute(); } }, true); } }; // perform dependency resolution withDependencies( "Checking installed packages", userPrompt, shinyDependenciesArray(), true, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } public void withShinyAddins(final Command command) { // define dependencies ArrayList<Dependency> deps = shinyDependencies(); // htmltools version deps.add(Dependency.cranPackage("miniUI", "0.1.1", true)); deps.add(Dependency.cranPackage("rstudioapi", "0.5", true)); withDependencies( "Checking installed packages", "Executing addins", deps.toArray(new Dependency[deps.size()]), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private Dependency[] shinyDependenciesArray() { ArrayList<Dependency> deps = shinyDependencies(); return deps.toArray(new Dependency[deps.size()]); } private ArrayList<Dependency> shinyDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("Rcpp", "0.11.5")); deps.add(Dependency.cranPackage("httpuv", "1.3.3")); deps.add(Dependency.cranPackage("mime", "0.3")); deps.add(Dependency.cranPackage("jsonlite", "0.9.19")); deps.add(Dependency.cranPackage("xtable", "1.7")); deps.add(Dependency.cranPackage("digest", "0.6")); deps.add(Dependency.cranPackage("R6", "2.0")); deps.add(Dependency.cranPackage("sourcetools", "0.1.5")); deps.add(Dependency.cranPackage("htmltools", "0.3.5")); deps.add(Dependency.cranPackage("shiny", "0.13", true)); return deps; } @Override public void onInstallShiny(InstallShinyEvent event) { withShiny(event.getUserAction(), new Command() { public void execute() {}}); } @Override public void onPackageStateChanged(PackageStateChangedEvent event) { // when the package state changes, clear the dependency cache -- this // is extremely conservative as it's unlikely most (or any) of the // packages have been invalidated, but it's safe to do so since it'll // just cause us to hit the server once more to verify satisfied_.clear(); } public void withDataImportCSV(String userAction, final Command command) { withDependencies( "Preparing Import from CSV", userAction, dataImportCsvDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportCsvDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("readr", "0.2.2")); deps.add(Dependency.cranPackage("Rcpp", "0.11.5")); return deps; } private Dependency[] dataImportCsvDependenciesArray() { ArrayList<Dependency> deps = dataImportCsvDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportSAV(String userAction, final Command command) { withDependencies( "Preparing Import from SPSS, SAS and Stata", userAction, dataImportSavDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportSavDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("haven", "0.2.0")); deps.add(Dependency.cranPackage("Rcpp", "0.11.5")); return deps; } private Dependency[] dataImportSavDependenciesArray() { ArrayList<Dependency> deps = dataImportSavDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportXLS(String userAction, final Command command) { withDependencies( "Preparing Import from Excel", userAction, dataImportXlsDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportXlsDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("readxl", "0.1.0")); deps.add(Dependency.cranPackage("Rcpp", "0.11.5")); return deps; } private Dependency[] dataImportXlsDependenciesArray() { ArrayList<Dependency> deps = dataImportXlsDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportXML(String userAction, final Command command) { withDependencies( "Preparing Import from XML", userAction, dataImportXmlDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportXmlDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("xml2", "0.1.2")); return deps; } private Dependency[] dataImportXmlDependenciesArray() { ArrayList<Dependency> deps = dataImportXmlDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportJSON(String userAction, final Command command) { withDependencies( "Preparing Import from JSON", userAction, dataImportJsonDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportJsonDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("jsonlite", "0.9.19")); return deps; } private Dependency[] dataImportJsonDependenciesArray() { ArrayList<Dependency> deps = dataImportJsonDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportJDBC(String userAction, final Command command) { withDependencies( "Preparing Import from JDBC", userAction, dataImportJdbcDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportJdbcDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("RJDBC", "0.2-5")); deps.add(Dependency.cranPackage("rJava", "0.4-15")); return deps; } private Dependency[] dataImportJdbcDependenciesArray() { ArrayList<Dependency> deps = dataImportJdbcDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportODBC(String userAction, final Command command) { withDependencies( "Preparing Import from ODBC", userAction, dataImportOdbcDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportOdbcDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("RODBC", "1.3-12")); return deps; } private Dependency[] dataImportOdbcDependenciesArray() { ArrayList<Dependency> deps = dataImportOdbcDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportMongo(String userAction, final Command command) { withDependencies( "Preparing Import from Mongo DB", userAction, dataImportMongoDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportMongoDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("mongolite", "0.8")); deps.add(Dependency.cranPackage("jsonlite", "0.9.19")); return deps; } private Dependency[] dataImportMongoDependenciesArray() { ArrayList<Dependency> deps = dataImportMongoDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withProfvis(String userAction, final Command command) { withDependencies( "Preparing Profiler", userAction, new Dependency[] { Dependency.cranPackage("stringr", "0.6"), Dependency.cranPackage("jsonlite", "0.9.19"), Dependency.cranPackage("htmltools", "0.3"), Dependency.cranPackage("yaml", "2.1.5"), Dependency.cranPackage("htmlwidgets", "0.6", true), Dependency.cranPackage("profvis", "0.3.2", true) }, true, // update profvis if needed new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private void withDependencies(String progressCaption, final String userAction, final CommandWith2Args<String,Command> userPrompt, Dependency[] dependencies, final boolean silentEmbeddedUpdate, final CommandWithArg<Boolean> onComplete) { // add the request to the queue rather than processing it right away; // this frees us of the burden of trying to de-dupe requests for the // same packages which may occur simultaneously (since we also cache // results, all such duplicate requests will return simultaneously, fed // by a single RPC) requestQueue_.add(new DependencyRequest(progressCaption, userAction, userPrompt, dependencies, silentEmbeddedUpdate, new CommandWithArg<Boolean>() { @Override public void execute(Boolean arg) { // complete the user action, if any onComplete.execute(arg); // process the next request in the queue processingQueue_ = false; processRequestQueue(); } })); processRequestQueue(); } private void processRequestQueue() { if (processingQueue_ == true || requestQueue_.isEmpty()) return; processingQueue_ = true; processDependencyRequest(requestQueue_.pop()); } private void processDependencyRequest(final DependencyRequest req) { // convert dependencies to JsArray, excluding satisfied dependencies final JsArray<Dependency> deps = JsArray.createArray().cast(); for (int i = 0; i < req.dependencies.length; i++) { boolean satisfied = false; for (Dependency d: satisfied_) { if (req.dependencies[i].isEqualTo(d)) { satisfied = true; break; } } if (!satisfied) deps.push(req.dependencies[i]); } // if no unsatisfied dependencies were found, we're done already if (deps.length() == 0) { req.onComplete.execute(true); return; } // create progress indicator final ProgressIndicator progress = new GlobalProgressDelayer( globalDisplay_, 250, req.progressCaption + "...").getIndicator(); // query for unsatisfied dependencies server_.unsatisfiedDependencies( deps, req.silentEmbeddedUpdate, new ServerRequestCallback<JsArray<Dependency>>() { @Override public void onResponseReceived( final JsArray<Dependency> unsatisfiedDeps) { progress.onCompleted(); updateSatisfied(deps, unsatisfiedDeps); // if we've satisfied all dependencies then execute the command if (unsatisfiedDeps.length() == 0) { req.onComplete.execute(true); return; } // check to see if we can satisfy the version requirement for all // dependencies String unsatisfiedVersions = ""; for (int i = 0; i < unsatisfiedDeps.length(); i++) { if (!unsatisfiedDeps.get(i).getVersionSatisfied()) { unsatisfiedVersions += unsatisfiedDeps.get(i).getName() + " " + unsatisfiedDeps.get(i).getVersion(); String version = unsatisfiedDeps.get(i).getAvailableVersion(); if (version.isEmpty()) unsatisfiedVersions += " is not available\n"; else unsatisfiedVersions += " is required but " + version + " is available\n"; } } if (!unsatisfiedVersions.isEmpty()) { // error if we can't satisfy requirements globalDisplay_.showErrorMessage( StringUtil.isNullOrEmpty(req.userAction) ? "Packages Not Found" : req.userAction, "Required package versions could not be found:\n\n" + unsatisfiedVersions + "\n" + "Check that getOption(\"repos\") refers to a CRAN " + "repository that contains the needed package versions."); req.onComplete.execute(false); } else { // otherwise ask the user if they want to install the // unsatisifed dependencies final CommandWithArg<Boolean> installCommand = new CommandWithArg<Boolean>() { @Override public void execute(Boolean confirmed) { // bail if user didn't confirm if (!confirmed) { req.onComplete.execute(false); return; } // the incoming JsArray from the server may not serialize // as expected when this code is executed from a satellite // (see RemoteServer.sendRequestViaMainWorkbench), so we // clone it before passing to the dependency installer JsArray<Dependency> newArray = JsArray.createArray().cast(); newArray.setLength(unsatisfiedDeps.length()); for (int i = 0; i < unsatisfiedDeps.length(); i++) { newArray.set(i, unsatisfiedDeps.get(i)); } installDependencies( newArray, req.silentEmbeddedUpdate, req.onComplete); } }; if (req.userPrompt != null) { req.userPrompt.execute(describeDepPkgs(unsatisfiedDeps), new Command() { @Override public void execute() { installCommand.execute(true); } }); } else { confirmPackageInstallation(req.userAction, unsatisfiedDeps, installCommand); } } } @Override public void onError(ServerError error) { progress.onError(error.getUserMessage()); req.onComplete.execute(false); } }); } private void installDependencies(final JsArray<Dependency> dependencies, final boolean silentEmbeddedUpdate, final CommandWithArg<Boolean> onComplete) { server_.installDependencies( dependencies, new ServerRequestCallback<ConsoleProcess>() { @Override public void onResponseReceived(ConsoleProcess proc) { final ConsoleProgressDialog dialog = new ConsoleProgressDialog(proc, server_); dialog.showModal(); proc.addProcessExitHandler( new ProcessExitEvent.Handler() { @Override public void onProcessExit(ProcessExitEvent event) { ifDependenciesSatisifed(dependencies, silentEmbeddedUpdate, new CommandWithArg<Boolean>(){ @Override public void execute(Boolean succeeded) { dialog.hide(); onComplete.execute(succeeded); } }); } }); } @Override public void onError(ServerError error) { Debug.logError(error); globalDisplay_.showErrorMessage( "Dependency installation failed", error.getUserMessage()); onComplete.execute(false); } }); } private void ifDependenciesSatisifed(JsArray<Dependency> dependencies, boolean silentEmbeddedUpdate, final CommandWithArg<Boolean> onComplete) { server_.unsatisfiedDependencies( dependencies, silentEmbeddedUpdate, new ServerRequestCallback<JsArray<Dependency>>() { @Override public void onResponseReceived(JsArray<Dependency> dependencies) { onComplete.execute(dependencies.length() == 0); } @Override public void onError(ServerError error) { Debug.logError(error); globalDisplay_.showErrorMessage( "Could not determine available packages", error.getUserMessage()); onComplete.execute(false); } }); } private void confirmPackageInstallation( String userAction, final JsArray<Dependency> dependencies, final CommandWithArg<Boolean> onComplete) { String msg = null; if (dependencies.length() == 1) { msg = "requires an updated version of the " + dependencies.get(0).getName() + " package. " + "\n\nDo you want to install this package now?"; } else { msg = "requires updated versions of the following packages: " + describeDepPkgs(dependencies) + ". " + "\n\nDo you want to install these packages now?"; } if (userAction != null) { globalDisplay_.showYesNoMessage( MessageDialog.QUESTION, "Install Required Packages", userAction + " " + msg, false, new Operation() { @Override public void execute() { onComplete.execute(true); } }, new Operation() { @Override public void execute() { onComplete.execute(false); } }, true); } else { onComplete.execute(false); } } private String describeDepPkgs(JsArray<Dependency> dependencies) { ArrayList<String> deps = new ArrayList<String>(); for (int i = 0; i < dependencies.length(); i++) deps.add(dependencies.get(i).getName()); return StringUtil.join(deps, ", "); } public void withUnsatisfiedDependencies(final Dependency dependency, final ServerRequestCallback<JsArray<Dependency>> requestCallback) { // determine if already satisfied for (Dependency d: satisfied_) { if (d.isEqualTo(dependency)) { JsArray<Dependency> empty = JsArray.createArray().cast(); requestCallback.onResponseReceived(empty); return; } } List<Dependency> dependencies = new ArrayList<Dependency>(); dependencies.add(dependency); withUnsatisfiedDependencies(dependencies, requestCallback); } private void withUnsatisfiedDependencies(final List<Dependency> dependencies, final ServerRequestCallback<JsArray<Dependency>> requestCallback) { final JsArray<Dependency> jsDependencies = JsArray.createArray(dependencies.size()).cast(); for (int i = 0; i < dependencies.size(); i++) jsDependencies.set(i, dependencies.get(i)); server_.unsatisfiedDependencies( jsDependencies, false, new ServerRequestCallback<JsArray<Dependency>>() { @Override public void onResponseReceived(JsArray<Dependency> unsatisfied) { updateSatisfied(jsDependencies, unsatisfied); requestCallback.onResponseReceived(unsatisfied); } @Override public void onError(ServerError error) { requestCallback.onError(error); } }); } /** * Updates the cache of satisfied dependencies. * * @param all The dependencies that were requested * @param unsatisfied The dependencies that were not satisfied */ private void updateSatisfied(JsArray<Dependency> all, JsArray<Dependency> unsatisfied) { for (int i = 0; i < all.length(); i++) { boolean satisfied = true; for (int j = 0; j < unsatisfied.length(); j++) { if (unsatisfied.get(j).isEqualTo(all.get(i))) { satisfied = false; break; } } if (satisfied) { satisfied_.add(all.get(i)); } } } private boolean processingQueue_ = false; private final LinkedList<DependencyRequest> requestQueue_; private final GlobalDisplay globalDisplay_; private final DependencyServerOperations server_; private final ArrayList<Dependency> satisfied_; }
src/gwt/src/org/rstudio/studio/client/common/dependencies/DependencyManager.java
/* * DependencyManager.java * * Copyright (C) 2009-15 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.common.dependencies; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.rstudio.core.client.CommandWith2Args; import org.rstudio.core.client.CommandWithArg; import org.rstudio.core.client.Debug; import org.rstudio.core.client.StringUtil; import org.rstudio.core.client.widget.MessageDialog; import org.rstudio.core.client.widget.Operation; import org.rstudio.core.client.widget.ProgressIndicator; import org.rstudio.studio.client.application.events.EventBus; import org.rstudio.studio.client.common.GlobalDisplay; import org.rstudio.studio.client.common.GlobalProgressDelayer; import org.rstudio.studio.client.common.console.ConsoleProcess; import org.rstudio.studio.client.common.console.ProcessExitEvent; import org.rstudio.studio.client.common.dependencies.events.InstallShinyEvent; import org.rstudio.studio.client.common.dependencies.model.Dependency; import org.rstudio.studio.client.common.dependencies.model.DependencyServerOperations; import org.rstudio.studio.client.server.ServerError; import org.rstudio.studio.client.server.ServerRequestCallback; import org.rstudio.studio.client.workbench.views.packages.events.PackageStateChangedEvent; import org.rstudio.studio.client.workbench.views.packages.events.PackageStateChangedHandler; import org.rstudio.studio.client.workbench.views.vcs.common.ConsoleProgressDialog; import com.google.gwt.core.client.JsArray; import com.google.gwt.user.client.Command; import com.google.inject.Inject; import com.google.inject.Singleton; @Singleton public class DependencyManager implements InstallShinyEvent.Handler, PackageStateChangedHandler { class DependencyRequest { DependencyRequest( String progressCaptionIn, String userActionIn, CommandWith2Args<String,Command> userPromptIn, Dependency[] dependenciesIn, boolean silentEmbeddedUpdateIn, CommandWithArg<Boolean> onCompleteIn) { progressCaption = progressCaptionIn; userAction = userActionIn; userPrompt = userPromptIn; dependencies = dependenciesIn; silentEmbeddedUpdate = silentEmbeddedUpdateIn; onComplete = onCompleteIn; } String progressCaption; String userAction; CommandWith2Args<String,Command> userPrompt; Dependency[] dependencies; boolean silentEmbeddedUpdate; CommandWithArg<Boolean> onComplete; } @Inject public DependencyManager(GlobalDisplay globalDisplay, DependencyServerOperations server, EventBus eventBus) { globalDisplay_ = globalDisplay; server_ = server; satisfied_ = new ArrayList<Dependency>(); requestQueue_ = new LinkedList<DependencyRequest>(); eventBus.addHandler(InstallShinyEvent.TYPE, this); eventBus.addHandler(PackageStateChangedEvent.TYPE, this); } public void withDependencies(String progressCaption, CommandWith2Args<String,Command> userPrompt, Dependency[] dependencies, boolean silentEmbeddedUpdate, CommandWithArg<Boolean> onComplete) { withDependencies(progressCaption, null, userPrompt, dependencies, silentEmbeddedUpdate, onComplete); } public void withDependencies(String progressCaption, String userAction, Dependency[] dependencies, boolean silentEmbeddedUpdate, final CommandWithArg<Boolean> onComplete) { withDependencies(progressCaption, userAction, null, dependencies, silentEmbeddedUpdate, onComplete); } public void withPackrat(String userAction, final Command command) { withDependencies( "Packrat", userAction, new Dependency[] { Dependency.cranPackage("packrat", "0.4.8-1", true) }, false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } }); } public void withRSConnect(String userAction, boolean requiresRmarkdown, CommandWith2Args<String, Command> userPrompt, final CommandWithArg<Boolean> onCompleted) { // build dependency array ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("digest", "0.6")); deps.add(Dependency.cranPackage("RCurl", "1.95")); deps.add(Dependency.cranPackage("RJSONIO", "1.0")); deps.add(Dependency.cranPackage("PKI", "0.1")); deps.add(Dependency.cranPackage("rstudioapi", "0.5")); deps.add(Dependency.cranPackage("yaml", "2.1.5")); if (requiresRmarkdown) deps.addAll(rmarkdownDependencies()); deps.add(Dependency.cranPackage("packrat", "0.4.8-1", true)); deps.add(Dependency.embeddedPackage("rsconnect")); withDependencies( "Publishing", userAction, userPrompt, deps.toArray(new Dependency[deps.size()]), true, // we want the embedded rsconnect package to be updated if needed onCompleted ); } public void withRMarkdown(String userAction, final Command command) { withRMarkdown("R Markdown", userAction, command); } public void withRMarkdown(String progressCaption, String userAction, final Command command) { withDependencies( progressCaption, userAction, rmarkdownDependenciesArray(), true, // we want to update to the embedded version if needed new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } public void withRMarkdown(String progressCaption, String userAction, final CommandWithArg<Boolean> command) { withDependencies( progressCaption, userAction, rmarkdownDependenciesArray(), true, command); } public static List<Dependency> rmarkdownDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("evaluate", "0.8")); deps.add(Dependency.cranPackage("digest", "0.6")); deps.add(Dependency.cranPackage("formatR", "1.1")); deps.add(Dependency.cranPackage("highr", "0.3")); deps.add(Dependency.cranPackage("markdown", "0.7")); deps.add(Dependency.cranPackage("stringr", "0.6")); deps.add(Dependency.cranPackage("yaml", "2.1.5")); deps.add(Dependency.cranPackage("Rcpp", "0.11.5")); deps.add(Dependency.cranPackage("htmltools", "0.3.5")); deps.add(Dependency.cranPackage("caTools", "1.14")); deps.add(Dependency.cranPackage("bitops", "1.0-6")); deps.add(Dependency.cranPackage("knitr", "1.14", true)); deps.add(Dependency.cranPackage("jsonlite", "0.9.19")); deps.add(Dependency.cranPackage("base64enc", "0.1-3")); deps.add(Dependency.cranPackage("rprojroot", "1.0")); deps.add(Dependency.embeddedPackage("rmarkdown")); return deps; } public static Dependency[] rmarkdownDependenciesArray() { List<Dependency> deps = rmarkdownDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withShiny(final String userAction, final Command command) { // create user prompt command CommandWith2Args<String, Command> userPrompt = new CommandWith2Args<String, Command>() { @Override public void execute(final String unmetDeps, final Command yesCommand) { globalDisplay_.showYesNoMessage( MessageDialog.QUESTION, "Install Shiny Package", userAction + " requires installation of an updated version " + "of the shiny package.\n\nDo you want to install shiny now?", new Operation() { @Override public void execute() { yesCommand.execute(); } }, true); } }; // perform dependency resolution withDependencies( "Checking installed packages", userPrompt, shinyDependenciesArray(), true, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } public void withShinyAddins(final Command command) { // define dependencies ArrayList<Dependency> deps = shinyDependencies(); // htmltools version deps.add(Dependency.cranPackage("miniUI", "0.1.1", true)); deps.add(Dependency.cranPackage("rstudioapi", "0.5", true)); withDependencies( "Checking installed packages", "Executing addins", deps.toArray(new Dependency[deps.size()]), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private Dependency[] shinyDependenciesArray() { ArrayList<Dependency> deps = shinyDependencies(); return deps.toArray(new Dependency[deps.size()]); } private ArrayList<Dependency> shinyDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("Rcpp", "0.11.5")); deps.add(Dependency.cranPackage("httpuv", "1.3.3")); deps.add(Dependency.cranPackage("mime", "0.3")); deps.add(Dependency.cranPackage("jsonlite", "0.9.19")); deps.add(Dependency.cranPackage("xtable", "1.7")); deps.add(Dependency.cranPackage("digest", "0.6")); deps.add(Dependency.cranPackage("R6", "2.0")); deps.add(Dependency.cranPackage("sourcetools", "0.1.5")); deps.add(Dependency.cranPackage("htmltools", "0.3.5")); deps.add(Dependency.cranPackage("shiny", "0.13", true)); return deps; } @Override public void onInstallShiny(InstallShinyEvent event) { withShiny(event.getUserAction(), new Command() { public void execute() {}}); } @Override public void onPackageStateChanged(PackageStateChangedEvent event) { // when the package state changes, clear the dependency cache -- this // is extremely conservative as it's unlikely most (or any) of the // packages have been invalidated, but it's safe to do so since it'll // just cause us to hit the server once more to verify satisfied_.clear(); } public void withDataImportCSV(String userAction, final Command command) { withDependencies( "Preparing Import from CSV", userAction, dataImportCsvDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportCsvDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("readr", "0.2.2")); deps.add(Dependency.cranPackage("Rcpp", "0.11.5")); return deps; } private Dependency[] dataImportCsvDependenciesArray() { ArrayList<Dependency> deps = dataImportCsvDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportSAV(String userAction, final Command command) { withDependencies( "Preparing Import from SPSS, SAS and Stata", userAction, dataImportSavDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportSavDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("haven", "0.2.0")); deps.add(Dependency.cranPackage("Rcpp", "0.11.5")); return deps; } private Dependency[] dataImportSavDependenciesArray() { ArrayList<Dependency> deps = dataImportSavDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportXLS(String userAction, final Command command) { withDependencies( "Preparing Import from Excel", userAction, dataImportXlsDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportXlsDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("readxl", "0.1.0")); deps.add(Dependency.cranPackage("Rcpp", "0.11.5")); return deps; } private Dependency[] dataImportXlsDependenciesArray() { ArrayList<Dependency> deps = dataImportXlsDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportXML(String userAction, final Command command) { withDependencies( "Preparing Import from XML", userAction, dataImportXmlDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportXmlDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("xml2", "0.1.2")); return deps; } private Dependency[] dataImportXmlDependenciesArray() { ArrayList<Dependency> deps = dataImportXmlDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportJSON(String userAction, final Command command) { withDependencies( "Preparing Import from JSON", userAction, dataImportJsonDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportJsonDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("jsonlite", "0.9.19")); return deps; } private Dependency[] dataImportJsonDependenciesArray() { ArrayList<Dependency> deps = dataImportJsonDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportJDBC(String userAction, final Command command) { withDependencies( "Preparing Import from JDBC", userAction, dataImportJdbcDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportJdbcDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("RJDBC", "0.2-5")); deps.add(Dependency.cranPackage("rJava", "0.4-15")); return deps; } private Dependency[] dataImportJdbcDependenciesArray() { ArrayList<Dependency> deps = dataImportJdbcDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportODBC(String userAction, final Command command) { withDependencies( "Preparing Import from ODBC", userAction, dataImportOdbcDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportOdbcDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("RODBC", "1.3-12")); return deps; } private Dependency[] dataImportOdbcDependenciesArray() { ArrayList<Dependency> deps = dataImportOdbcDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withDataImportMongo(String userAction, final Command command) { withDependencies( "Preparing Import from Mongo DB", userAction, dataImportMongoDependenciesArray(), false, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private ArrayList<Dependency> dataImportMongoDependencies() { ArrayList<Dependency> deps = new ArrayList<Dependency>(); deps.add(Dependency.cranPackage("mongolite", "0.8")); deps.add(Dependency.cranPackage("jsonlite", "0.9.19")); return deps; } private Dependency[] dataImportMongoDependenciesArray() { ArrayList<Dependency> deps = dataImportMongoDependencies(); return deps.toArray(new Dependency[deps.size()]); } public void withProfvis(String userAction, final Command command) { withDependencies( "Preparing Profiler", userAction, new Dependency[] { Dependency.cranPackage("stringr", "0.6"), Dependency.cranPackage("jsonlite", "0.9.19"), Dependency.cranPackage("htmltools", "0.3"), Dependency.cranPackage("yaml", "2.1.5"), Dependency.cranPackage("htmlwidgets", "0.6", true), Dependency.cranPackage("profvis", "0.3.2", true) }, true, // update profvis if needed new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); } private void withDependencies(String progressCaption, final String userAction, final CommandWith2Args<String,Command> userPrompt, Dependency[] dependencies, final boolean silentEmbeddedUpdate, final CommandWithArg<Boolean> onComplete) { // add the request to the queue rather than processing it right away; // this frees us of the burden of trying to de-dupe requests for the // same packages which may occur simultaneously (since we also cache // results, all such duplicate requests will return simultaneously, fed // by a single RPC) requestQueue_.add(new DependencyRequest(progressCaption, userAction, userPrompt, dependencies, silentEmbeddedUpdate, new CommandWithArg<Boolean>() { @Override public void execute(Boolean arg) { // complete the user action, if any onComplete.execute(arg); // process the next request in the queue processingQueue_ = false; processRequestQueue(); } })); processRequestQueue(); } private void processRequestQueue() { if (processingQueue_ == true || requestQueue_.isEmpty()) return; processingQueue_ = true; processDependencyRequest(requestQueue_.pop()); } private void processDependencyRequest(final DependencyRequest req) { // convert dependencies to JsArray, excluding satisfied dependencies final JsArray<Dependency> deps = JsArray.createArray().cast(); for (int i = 0; i < req.dependencies.length; i++) { boolean satisfied = false; for (Dependency d: satisfied_) { if (req.dependencies[i].isEqualTo(d)) { satisfied = true; break; } } if (!satisfied) deps.push(req.dependencies[i]); } // if no unsatisfied dependencies were found, we're done already if (deps.length() == 0) { req.onComplete.execute(true); return; } // create progress indicator final ProgressIndicator progress = new GlobalProgressDelayer( globalDisplay_, 250, req.progressCaption + "...").getIndicator(); // query for unsatisfied dependencies server_.unsatisfiedDependencies( deps, req.silentEmbeddedUpdate, new ServerRequestCallback<JsArray<Dependency>>() { @Override public void onResponseReceived( final JsArray<Dependency> unsatisfiedDeps) { progress.onCompleted(); updateSatisfied(deps, unsatisfiedDeps); // if we've satisfied all dependencies then execute the command if (unsatisfiedDeps.length() == 0) { req.onComplete.execute(true); return; } // check to see if we can satisfy the version requirement for all // dependencies String unsatisfiedVersions = ""; for (int i = 0; i < unsatisfiedDeps.length(); i++) { if (!unsatisfiedDeps.get(i).getVersionSatisfied()) { unsatisfiedVersions += unsatisfiedDeps.get(i).getName() + " " + unsatisfiedDeps.get(i).getVersion(); String version = unsatisfiedDeps.get(i).getAvailableVersion(); if (version.isEmpty()) unsatisfiedVersions += " is not available\n"; else unsatisfiedVersions += " is required but " + version + " is available\n"; } } if (!unsatisfiedVersions.isEmpty()) { // error if we can't satisfy requirements globalDisplay_.showErrorMessage( StringUtil.isNullOrEmpty(req.userAction) ? "Packages Not Found" : req.userAction, "Required package versions could not be found:\n\n" + unsatisfiedVersions + "\n" + "Check that getOption(\"repos\") refers to a CRAN " + "repository that contains the needed package versions."); req.onComplete.execute(false); } else { // otherwise ask the user if they want to install the // unsatisifed dependencies final CommandWithArg<Boolean> installCommand = new CommandWithArg<Boolean>() { @Override public void execute(Boolean confirmed) { // bail if user didn't confirm if (!confirmed) { req.onComplete.execute(false); return; } // the incoming JsArray from the server may not serialize // as expected when this code is executed from a satellite // (see RemoteServer.sendRequestViaMainWorkbench), so we // clone it before passing to the dependency installer JsArray<Dependency> newArray = JsArray.createArray().cast(); newArray.setLength(unsatisfiedDeps.length()); for (int i = 0; i < unsatisfiedDeps.length(); i++) { newArray.set(i, unsatisfiedDeps.get(i)); } installDependencies( newArray, req.silentEmbeddedUpdate, req.onComplete); } }; if (req.userPrompt != null) { req.userPrompt.execute(describeDepPkgs(unsatisfiedDeps), new Command() { @Override public void execute() { installCommand.execute(true); } }); } else { confirmPackageInstallation(req.userAction, unsatisfiedDeps, installCommand); } } } @Override public void onError(ServerError error) { progress.onError(error.getUserMessage()); req.onComplete.execute(false); } }); } private void installDependencies(final JsArray<Dependency> dependencies, final boolean silentEmbeddedUpdate, final CommandWithArg<Boolean> onComplete) { server_.installDependencies( dependencies, new ServerRequestCallback<ConsoleProcess>() { @Override public void onResponseReceived(ConsoleProcess proc) { final ConsoleProgressDialog dialog = new ConsoleProgressDialog(proc, server_); dialog.showModal(); proc.addProcessExitHandler( new ProcessExitEvent.Handler() { @Override public void onProcessExit(ProcessExitEvent event) { ifDependenciesSatisifed(dependencies, silentEmbeddedUpdate, new CommandWithArg<Boolean>(){ @Override public void execute(Boolean succeeded) { dialog.hide(); onComplete.execute(succeeded); } }); } }); } @Override public void onError(ServerError error) { Debug.logError(error); globalDisplay_.showErrorMessage( "Dependency installation failed", error.getUserMessage()); onComplete.execute(false); } }); } private void ifDependenciesSatisifed(JsArray<Dependency> dependencies, boolean silentEmbeddedUpdate, final CommandWithArg<Boolean> onComplete) { server_.unsatisfiedDependencies( dependencies, silentEmbeddedUpdate, new ServerRequestCallback<JsArray<Dependency>>() { @Override public void onResponseReceived(JsArray<Dependency> dependencies) { onComplete.execute(dependencies.length() == 0); } @Override public void onError(ServerError error) { Debug.logError(error); globalDisplay_.showErrorMessage( "Could not determine available packages", error.getUserMessage()); onComplete.execute(false); } }); } private void confirmPackageInstallation( String userAction, final JsArray<Dependency> dependencies, final CommandWithArg<Boolean> onComplete) { String msg = null; if (dependencies.length() == 1) { msg = "requires an updated version of the " + dependencies.get(0).getName() + " package. " + "\n\nDo you want to install this package now?"; } else { msg = "requires updated versions of the following packages: " + describeDepPkgs(dependencies) + ". " + "\n\nDo you want to install these packages now?"; } if (userAction != null) { globalDisplay_.showYesNoMessage( MessageDialog.QUESTION, "Install Required Packages", userAction + " " + msg, false, new Operation() { @Override public void execute() { onComplete.execute(true); } }, new Operation() { @Override public void execute() { onComplete.execute(false); } }, true); } else { onComplete.execute(false); } } private String describeDepPkgs(JsArray<Dependency> dependencies) { ArrayList<String> deps = new ArrayList<String>(); for (int i = 0; i < dependencies.length(); i++) deps.add(dependencies.get(i).getName()); return StringUtil.join(deps, ", "); } public void withUnsatisfiedDependencies(final Dependency dependency, final ServerRequestCallback<JsArray<Dependency>> requestCallback) { // determine if already satisfied for (Dependency d: satisfied_) { if (d.isEqualTo(dependency)) { JsArray<Dependency> empty = JsArray.createArray().cast(); requestCallback.onResponseReceived(empty); return; } } List<Dependency> dependencies = new ArrayList<Dependency>(); dependencies.add(dependency); withUnsatisfiedDependencies(dependencies, requestCallback); } private void withUnsatisfiedDependencies(final List<Dependency> dependencies, final ServerRequestCallback<JsArray<Dependency>> requestCallback) { final JsArray<Dependency> jsDependencies = JsArray.createArray(dependencies.size()).cast(); for (int i = 0; i < dependencies.size(); i++) jsDependencies.set(i, dependencies.get(i)); server_.unsatisfiedDependencies( jsDependencies, false, new ServerRequestCallback<JsArray<Dependency>>() { @Override public void onResponseReceived(JsArray<Dependency> unsatisfied) { updateSatisfied(jsDependencies, unsatisfied); requestCallback.onResponseReceived(unsatisfied); } @Override public void onError(ServerError error) { requestCallback.onError(error); } }); } /** * Updates the cache of satisfied dependencies. * * @param all The dependencies that were requested * @param unsatisfied The dependencies that were not satisfied */ private void updateSatisfied(JsArray<Dependency> all, JsArray<Dependency> unsatisfied) { for (int i = 0; i < all.length(); i++) { boolean satisfied = true; for (int j = 0; j < unsatisfied.length(); j++) { if (unsatisfied.get(j).isEqualTo(all.get(i))) { satisfied = false; break; } } if (satisfied) { satisfied_.add(all.get(i)); } } } private boolean processingQueue_ = false; private final LinkedList<DependencyRequest> requestQueue_; private final GlobalDisplay globalDisplay_; private final DependencyServerOperations server_; private final ArrayList<Dependency> satisfied_; }
'formatR' no longer required by rmarkdown
src/gwt/src/org/rstudio/studio/client/common/dependencies/DependencyManager.java
'formatR' no longer required by rmarkdown
Java
lgpl-2.1
16aae89aa74444bcfc8b34c2a60d30a807051875
0
janissl/languagetool,meg0man/languagetool,meg0man/languagetool,meg0man/languagetool,janissl/languagetool,lopescan/languagetool,janissl/languagetool,languagetool-org/languagetool,meg0man/languagetool,languagetool-org/languagetool,meg0man/languagetool,languagetool-org/languagetool,jimregan/languagetool,lopescan/languagetool,jimregan/languagetool,jimregan/languagetool,lopescan/languagetool,janissl/languagetool,janissl/languagetool,jimregan/languagetool,languagetool-org/languagetool,lopescan/languagetool,languagetool-org/languagetool,jimregan/languagetool,janissl/languagetool,lopescan/languagetool
/* LanguageTool, a natural language style checker * Copyright (C) 2006 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.dev; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.*; import org.languagetool.JLanguageTool; import org.languagetool.Language; import org.languagetool.language.Contributor; import org.languagetool.tools.LanguageIdentifierTools; import org.languagetool.tools.StringTools; import org.languagetool.tools.Tools; import org.apache.tika.language.LanguageIdentifier; /** * Command line tool to list supported languages and their number of rules. * * @author Daniel Naber */ public final class RuleOverview { public static void main(final String[] args) throws IOException { final RuleOverview prg = new RuleOverview(); prg.run(); } private RuleOverview() { // no public constructor } private void run() throws IOException { System.out.println("<b>Rules in LanguageTool " + JLanguageTool.VERSION + "</b><br />"); System.out.println("Date: " + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "<br /><br />\n"); System.out.println("<table>"); System.out.println("<tr>"); System.out.println(" <th></th>"); System.out.println(" <th valign='bottom' align=\"right\" width=\"140\">XML rules</th>"); System.out.println(" <th>&nbsp;&nbsp;</th>"); System.out.println(" <th align=\"right\">Java<br/>rules</th>"); System.out.println(" <th>&nbsp;&nbsp;</th>"); System.out.println(" <th align=\"right\">" + "<a href=\"http://languagetool.svn.sourceforge.net/viewvc/languagetool/trunk/JLanguageTool/src/rules/false-friends.xml?content-type=text%2Fplain" + "\">False<br/>friends</a></th>"); System.out.println(" <th>&nbsp;&nbsp;</th>"); System.out.println(" <th valign='bottom'>Auto-<br/>detected</th>"); System.out.println(" <th>&nbsp;&nbsp;</th>"); System.out.println(" <th valign='bottom' align=\"left\">Rule Maintainers</th>"); System.out.println("</tr>"); final List<String> sortedLanguages = getSortedLanguages(); //setup false friends counting final String falseFriendFile = JLanguageTool.getDataBroker().getRulesDir() + File.separator + "false-friends.xml"; final URL falseFriendUrl = this.getClass().getResource(falseFriendFile); final String falseFriendRules = StringTools.readFile(Tools.getStream(falseFriendFile)) .replaceAll("(?s)<!--.*?-->", "") .replaceAll("(?s)<rules.*?>", ""); int overallJavaCount = 0; for (final String langName : sortedLanguages) { final Language lang = Language.getLanguageForName(langName); System.out.print("<tr>"); System.out.print("<td valign=\"top\">" + lang.getName() + "</td>"); final String xmlFile = JLanguageTool.getDataBroker().getRulesDir() + File.separator + lang.getShortName() + File.separator + "grammar.xml"; final URL url = this.getClass().getResource(xmlFile); if (url == null) { System.out.println("<td valign=\"top\" align=\"right\">0</td>"); } else { // count XML rules: String xmlRules = StringTools.readFile(Tools.getStream(xmlFile)); xmlRules = xmlRules.replaceAll("(?s)<!--.*?-->", ""); xmlRules = xmlRules.replaceAll("(?s)<rules.*?>", ""); final int count = countXmlRules(xmlRules); final int countInRuleGroup = countXmlRuleGroupRules(xmlRules); System.out.print("<td valign=\"top\" align=\"right\">" + (count + countInRuleGroup) + " (" + "<a href=\"http://languagetool.svn.sourceforge.net/viewvc/languagetool/trunk/JLanguageTool/src/rules/" + lang.getShortName() + "/grammar.xml?content-type=text%2Fplain" + "\">show</a>/" + "<a href=\"http://community.languagetool.org/rule/list?lang=" + lang.getShortName() + "\">browse</a>" + ")</td>"); } System.out.print("<td></td>"); // count Java rules: final File dir = new File("src/java/org/languagetool" + JLanguageTool.getDataBroker().getRulesDir() + "/" + lang.getShortName()); if (!dir.exists()) { System.out.print("<td valign=\"top\" align=\"right\">0</td>"); } else { final File[] javaRules = dir.listFiles(new JavaFilter()); final int javaCount = javaRules.length - 1; // minus 1: one is always "<Language>Rule.java" System.out.print("<td valign=\"top\" align=\"right\">" + javaCount + "</td>"); overallJavaCount++; } // false friends System.out.println("<td></td>"); if (falseFriendUrl == null) { System.out.println("<td valign=\"top\" align=\"right\">0</td>"); } else { final int count = countFalseFriendRules(falseFriendRules, lang); System.out.print("<td valign=\"top\" align=\"right\">" + count + "</td>"); System.out.print("<td></td>"); System.out.print("<td valign=\"top\">" + (isAutoDetected(lang.getShortName()) ? "yes" : "-") + "</td>"); // maintainer information: System.out.print("<td></td>"); final StringBuilder maintainerInfo = getMaintainerInfo(lang); System.out.print("<td valign=\"top\" align=\"left\">" + maintainerInfo.toString() + "</td>"); } System.out.println("</tr>"); } if (overallJavaCount == 0) { throw new RuntimeException("No Java rules found"); } System.out.println("</table>"); } private List<String> getSortedLanguages() { final List<String> sortedLanguages = new ArrayList<String>(); for (Language element : Language.LANGUAGES) { if (element == Language.DEMO) { continue; } sortedLanguages.add(element.getName()); } Collections.sort(sortedLanguages); return sortedLanguages; } private int countXmlRules(String xmlRules) { int pos = 0; int count = 0; while (true) { pos = xmlRules.indexOf("<rule ", pos + 1); if (pos == -1) { break; } count++; } return count; } private int countXmlRuleGroupRules(String xmlRules) { int pos = 0; int countInRuleGroup = 0; while (true) { pos = xmlRules.indexOf("<rule>", pos + 1); if (pos == -1) { break; } countInRuleGroup++; } return countInRuleGroup; } private int countFalseFriendRules(String falseFriendRules, Language lang) { int pos = 0; int count = 0; while (true) { pos = falseFriendRules.indexOf("<pattern lang=\"" + lang.getShortName(), pos + 1); if (pos == -1) { break; } count++; } return count; } private StringBuilder getMaintainerInfo(Language lang) { final StringBuilder maintainerInfo = new StringBuilder(); if (lang.getMaintainers() != null) { for (Contributor contributor : lang.getMaintainers()) { if (!StringTools.isEmpty(maintainerInfo.toString())) { maintainerInfo.append(", "); } if (contributor.getUrl() != null) { maintainerInfo.append("<a href=\""); maintainerInfo.append(contributor.getUrl()); maintainerInfo.append("\">"); } maintainerInfo.append(contributor.getName()); if (contributor.getUrl() != null) { maintainerInfo.append("</a>"); } if (contributor.getRemark() != null) { maintainerInfo.append("&nbsp;(" + contributor.getRemark() + ")"); } } } return maintainerInfo; } private boolean isAutoDetected(String code) { if (LanguageIdentifier.getSupportedLanguages().contains(code)) { return true; } final Set<String> additionalCodes = new HashSet<String>(Arrays.asList(LanguageIdentifierTools.ADDITIONAL_LANGUAGES)); if (additionalCodes.contains(code)) { return true; } return false; } } class JavaFilter implements FileFilter { public boolean accept(final File f) { if (f.getName().endsWith(".java")) { return true; } return false; } }
trunk/JLanguageTool/src/dev/org/languagetool/dev/RuleOverview.java
/* LanguageTool, a natural language style checker * Copyright (C) 2006 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.dev; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.*; import org.languagetool.JLanguageTool; import org.languagetool.Language; import org.languagetool.language.Contributor; import org.languagetool.tools.LanguageIdentifierTools; import org.languagetool.tools.StringTools; import org.languagetool.tools.Tools; import org.apache.tika.language.LanguageIdentifier; /** * Command line tool to list supported languages and their number of rules. * * @author Daniel Naber */ public final class RuleOverview { public static void main(final String[] args) throws IOException { final RuleOverview prg = new RuleOverview(); prg.run(); } private RuleOverview() { // no constructor } private void run() throws IOException { System.out.println("<b>Rules in LanguageTool " + JLanguageTool.VERSION + "</b><br />"); System.out.println("Date: " + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "<br /><br />\n"); System.out.println("<table>"); System.out.println("<tr>"); System.out.println(" <th></th>"); System.out.println(" <th valign='bottom' align=\"right\" width=\"140\">XML rules</th>"); System.out.println(" <th>&nbsp;&nbsp;</th>"); System.out.println(" <th align=\"right\">Java<br/>rules</th>"); System.out.println(" <th>&nbsp;&nbsp;</th>"); System.out.println(" <th align=\"right\">" + "<a href=\"http://languagetool.svn.sourceforge.net/viewvc/languagetool/trunk/JLanguageTool/src/rules/false-friends.xml?content-type=text%2Fplain" + "\">False<br/>friends</a></th>"); System.out.println(" <th>&nbsp;&nbsp;</th>"); System.out.println(" <th valign='bottom'>Auto-<br/>detected</th>"); System.out.println(" <th>&nbsp;&nbsp;</th>"); System.out.println(" <th valign='bottom' align=\"left\">Rule Maintainers</th>"); System.out.println("</tr>"); final List<String> sortedLanguages = new ArrayList<String>(); for (Language element : Language.LANGUAGES) { if (element == Language.DEMO) { continue; } sortedLanguages.add(element.getName()); } Collections.sort(sortedLanguages); //setup false friends counting final String falseFriendFile = JLanguageTool.getDataBroker().getRulesDir() + File.separator + "false-friends.xml"; final java.net.URL falseFriendUrl = this.getClass().getResource(falseFriendFile); final String falseFriendRules = StringTools.readFile(Tools.getStream(falseFriendFile)) .replaceAll("(?s)<!--.*?-->", "") .replaceAll("(?s)<rules.*?>", ""); int overallJavaCount = 0; for (final String langName : sortedLanguages) { final Language lang = Language.getLanguageForName(langName); System.out.print("<tr>"); System.out.print("<td valign=\"top\">" + lang.getName() + "</td>"); final String xmlFile = JLanguageTool.getDataBroker().getRulesDir() + File.separator + lang.getShortName() + File.separator + "grammar.xml"; final java.net.URL url = this.getClass().getResource(xmlFile); if (url == null) { System.out.println("<td valign=\"top\" align=\"right\">0</td>"); } else { // count XML rules: String xmlRules = StringTools.readFile(Tools.getStream(xmlFile)); xmlRules = xmlRules.replaceAll("(?s)<!--.*?-->", ""); xmlRules = xmlRules.replaceAll("(?s)<rules.*?>", ""); int pos = 0; int count = 0; while (true) { pos = xmlRules.indexOf("<rule ", pos + 1); if (pos == -1) { break; } count++; } pos = 0; int countInRuleGroup = 0; while (true) { pos = xmlRules.indexOf("<rule>", pos + 1); if (pos == -1) { break; } countInRuleGroup++; } System.out.print("<td valign=\"top\" align=\"right\">" + (count + countInRuleGroup) + " (" + "<a href=\"http://languagetool.svn.sourceforge.net/viewvc/languagetool/trunk/JLanguageTool/src/rules/" + lang.getShortName() + "/grammar.xml?content-type=text%2Fplain" + "\">show</a>/" + "<a href=\"http://community.languagetool.org/rule/list?lang=" + lang.getShortName() + "\">browse</a>" + ")</td>"); } System.out.print("<td></td>"); // count Java rules: final File dir = new File("src/java/org/languagetool" + JLanguageTool.getDataBroker().getRulesDir() + "/" + lang.getShortName()); if (!dir.exists()) { System.out.print("<td valign=\"top\" align=\"right\">0</td>"); } else { final File[] javaRules = dir.listFiles(new JavaFilter()); final int javaCount = javaRules.length-1; // minus 1: one is always "<Language>Rule.java" System.out.print("<td valign=\"top\" align=\"right\">" + javaCount + "</td>"); overallJavaCount++; } // false friends System.out.println("<td></td>"); if (falseFriendUrl == null) { System.out.println("<td valign=\"top\" align=\"right\">0</td>"); } else { // count XML rules: int pos = 0; int count = 0; while (true) { pos = falseFriendRules.indexOf("<pattern lang=\""+ lang.getShortName(), pos + 1); if (pos == -1) { break; } count++; } System.out.print("<td valign=\"top\" align=\"right\">" + count + "</td>"); System.out.print("<td></td>"); System.out.print("<td valign=\"top\">" + (isAutoDetected(lang.getShortName()) ? "yes" : "-") + "</td>"); // maintainer information: System.out.print("<td></td>"); final StringBuilder maintainerInfo = new StringBuilder(); if (lang.getMaintainers() != null) { for (Contributor contributor : lang.getMaintainers()) { if (!StringTools.isEmpty(maintainerInfo. toString())) { maintainerInfo.append(", "); } if (contributor.getUrl() != null) { maintainerInfo.append("<a href=\""); maintainerInfo.append(contributor.getUrl()); maintainerInfo.append("\">"); } maintainerInfo.append(contributor.getName()); if (contributor.getUrl() != null) { maintainerInfo.append("</a>"); } if (contributor.getRemark() != null) { maintainerInfo.append("&nbsp;(" + contributor.getRemark() + ")"); } } } System.out.print("<td valign=\"top\" align=\"left\">" + maintainerInfo.toString() + "</td>"); } System.out.println("</tr>"); } if (overallJavaCount == 0) { throw new RuntimeException("No Java rules found"); } System.out.println("</table>"); } private boolean isAutoDetected(String code) { if (LanguageIdentifier.getSupportedLanguages().contains(code)) { return true; } final Set<String> additionalCodes = new HashSet<String>(Arrays.asList(LanguageIdentifierTools.ADDITIONAL_LANGUAGES)); if (additionalCodes.contains(code)) { return true; } return false; } } class JavaFilter implements FileFilter { public boolean accept(final File f) { if (f.getName().endsWith(".java")) { return true; } return false; } }
some refactoring: extract code to private methods
trunk/JLanguageTool/src/dev/org/languagetool/dev/RuleOverview.java
some refactoring: extract code to private methods
Java
unlicense
51fcc8e7b176e70220884e221e53e6c66452ab78
0
shimatai/react-native-android-datausage,shimatai/react-native-android-datausage
package br.com.oi.reactnative.module.datausage; import android.annotation.TargetApi; import android.app.AppOpsManager; import android.app.usage.NetworkStatsManager; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.TrafficStats; import android.os.AsyncTask; import android.os.Build; import android.provider.Settings; import android.support.v4.app.ActivityCompat; import android.util.Base64; import android.util.Log; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.util.Arrays; import java.util.Date; import java.util.List; import br.com.oi.reactnative.module.datausage.helper.NetworkStatsHelper; import static android.content.pm.PackageManager.GET_META_DATA; public class DataUsageModule extends ReactContextBaseJavaModule { private static final String TAG = "DataUsageModule"; private static final int READ_PHONE_STATE_REQUEST = 37; public DataUsageModule(ReactApplicationContext reactContext) { super(reactContext); } @Override public String getName() { return TAG; } @ReactMethod public void getDataUsageByApp(final ReadableMap map, final Callback callback) { AsyncTask.execute(new Runnable() { @Override public void run() { final PackageManager packageManager = getReactApplicationContext().getPackageManager(); JSONArray apps = new JSONArray(); try { ReadableArray packageNames = map.hasKey("packages") ? map.getArray("packages") : null; Date startDate = map.hasKey("startDate") ? new Date(Double.valueOf(map.getDouble("startDate")).longValue()) : null; Date endDate = map.hasKey("endDate") ? new Date(Double.valueOf(map.getDouble("endDate")).longValue()) : null; if (packageNames != null && packageNames.size() > 0) { for (int i = 0; i < packageNames.size(); i++) { String packageName = packageNames.getString(i); final PackageInfo packageInfo = packageManager.getPackageInfo(packageName, GET_META_DATA); int uid = packageInfo.applicationInfo.uid; ApplicationInfo appInfo = null; try { appInfo = packageManager.getApplicationInfo(packageName, 0); } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Error getting application info: " + e.getMessage(), e); } String name = (String) packageManager.getApplicationLabel(appInfo); Drawable icon = packageManager.getApplicationIcon(appInfo); Bitmap bitmap = drawableToBitmap(icon); String encodedImage = encodeBitmapToBase64(bitmap); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { // < Android 6.0 Log.i(TAG, "##### Android 5- App: " + name + " packageName: " + packageName); JSONObject appStats = getTrafficStats(uid, name, packageName, encodedImage); if (appStats != null) apps.put(appStats); } else { // Android 6+ Log.i(TAG, "##### Android 6+ App: " + name + " packageName: " + packageName); JSONObject appStats = getNetworkManagerStats(uid, name, packageName, encodedImage, startDate, endDate); if (appStats != null) apps.put(appStats); } } } } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Error getting app info: " + e.getMessage(), e); } callback.invoke(null, apps.toString()); } }); } @ReactMethod public void getDataUsageByAppWithTotal(final ReadableMap map, final Callback callback) { AsyncTask.execute(new Runnable() { @Override public void run() { final PackageManager packageManager = getReactApplicationContext().getPackageManager(); JSONObject result = new JSONObject(); JSONArray apps = new JSONArray(); Double totalGeral = 0D; try { ReadableArray packageNames = map.hasKey("packages") ? map.getArray("packages") : null; Date startDate = map.hasKey("startDate") ? new Date(Double.valueOf(map.getDouble("startDate")).longValue()) : null; Date endDate = map.hasKey("endDate") ? new Date(Double.valueOf(map.getDouble("endDate")).longValue()) : null; if (packageNames != null && packageNames.size() > 0) { Log.i(TAG, "##### Qtd. de aplicativos a analisar: " + packageNames.size()); for (int i = 0; i < packageNames.size(); i++) { String packageName = packageNames.getString(i); final PackageInfo packageInfo = packageManager.getPackageInfo(packageName, GET_META_DATA); int uid = packageInfo.applicationInfo.uid; ApplicationInfo appInfo = null; try { appInfo = packageManager.getApplicationInfo(packageName, 0); } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Error getting application info: " + e.getMessage(), e); } String name = (String) packageManager.getApplicationLabel(appInfo); Drawable icon = packageManager.getApplicationIcon(appInfo); Bitmap bitmap = drawableToBitmap(icon); String encodedImage = encodeBitmapToBase64(bitmap); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { // < Android 6.0 Log.i(TAG, "##### Android 5- App: " + name + " packageName: " + packageName); JSONObject appStats = getTrafficStats(uid, name, packageName, encodedImage); if (appStats != null) { totalGeral += appStats.getDouble("total"); apps.put(appStats); } } else { // Android 6+ Log.i(TAG, "##### Android 6+ App: " + name + " packageName: " + packageName); JSONObject appStats = getNetworkManagerStats(uid, name, packageName, encodedImage, startDate, endDate); if (appStats != null) { totalGeral += appStats.getDouble("total"); apps.put(appStats); } } } } } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Error getting app info: " + e.getMessage(), e); } catch (JSONException e) { Log.e(TAG, "Error parsing JSON: " + e.getMessage(), e); } try { result.put("totalGeral", totalGeral) .put("totalGeralMb", String.format("%.2f MB", ((totalGeral / 1024D) / 1024D))) .put("apps", apps); } catch (JSONException e) { Log.e(TAG, "Error parsing JSON: " + e.getMessage(), e); } callback.invoke(null, result.toString()); } }); } @ReactMethod public void listDataUsageByApps(final ReadableMap map, final Callback callback) { AsyncTask.execute(new Runnable() { @Override public void run() { Log.i(TAG, "##### Listar todos os aplicativos por uso de dados..."); Context context = getReactApplicationContext(); final PackageManager packageManager = getReactApplicationContext().getPackageManager(); //List<ApplicationInfo> packages = packageManager.getInstalledApplications(0); JSONArray apps = new JSONArray(); Date startDate = map.hasKey("startDate") ? new Date(Double.valueOf(map.getDouble("startDate")).longValue()) : null; Date endDate = map.hasKey("endDate") ? new Date(Double.valueOf(map.getDouble("endDate")).longValue()) : null; final List<PackageInfo> packageInfoList = packageManager.getInstalledPackages(PackageManager.GET_PERMISSIONS); for (PackageInfo packageInfo : packageInfoList) { if (packageInfo.requestedPermissions == null) continue; List<String> permissions = Arrays.asList(packageInfo.requestedPermissions); if (permissions.contains(android.Manifest.permission.INTERNET)) { int uid = packageInfo.applicationInfo.uid; String packageName = packageInfo.packageName; ApplicationInfo appInfo = null; try { appInfo = packageManager.getApplicationInfo(packageName, 0); String name = (String) packageManager.getApplicationLabel(appInfo); Drawable icon = packageManager.getApplicationIcon(appInfo); Bitmap bitmap = drawableToBitmap(icon); String encodedImage = encodeBitmapToBase64(bitmap); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { // < Android 6.0 Log.i(TAG, "##### Android 5- App: " + name + " packageName: " + packageName); JSONObject appStats = getTrafficStats(uid, name, packageName, encodedImage); if (appStats != null) apps.put(appStats); } else { // Android 6+ Log.i(TAG, "##### Android 6+ App: " + name + " packageName: " + packageName); JSONObject appStats = getNetworkManagerStats(uid, name, packageName, encodedImage, startDate, endDate); if (appStats != null) apps.put(appStats); } } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Error getting application info: " + e.getMessage(), e); } } } callback.invoke(null, apps.toString()); } }); } private JSONObject getNetworkManagerStats(int uid, String name, String packageName, String encodedImage, Date startDate, Date endDate) { //Log.i(TAG, "##### Step getNetworkManagerStats(" + uid + ", " + name + ", ...)"); NetworkStatsManager networkStatsManager = (NetworkStatsManager) getReactApplicationContext().getSystemService(Context.NETWORK_STATS_SERVICE); NetworkStatsHelper networkStatsHelper = new NetworkStatsHelper(networkStatsManager, uid); //long wifiBytesRx = networkStatsHelper.getAllRxBytesMobile(getReactApplicationContext()) + networkStatsHelper.getAllRxBytesWifi(); //long wifiBytesTx = networkStatsHelper.getAllRxBytesMobile(getReactApplicationContext()) + networkStatsHelper.getAllRxBytesWifi(); double gsmBytesRx = (double) networkStatsHelper.getPackageRxBytesMobile(getReactApplicationContext()) + networkStatsHelper.getPackageRxBytesMobile(getReactApplicationContext(), startDate, endDate); double gsmBytesTx = (double) networkStatsHelper.getPackageTxBytesMobile(getReactApplicationContext()) + networkStatsHelper.getPackageRxBytesMobile(getReactApplicationContext(), startDate, endDate); double total = gsmBytesRx + gsmBytesTx; Log.i(TAG, "##### getNetworkManagerStats - " + packageName + " - tx: " + gsmBytesTx + " | rx: " + gsmBytesRx + " | total: " + total); try { if (total > 0D) { return new JSONObject().put("name", name) .put("packageName", packageName) .put("rx", gsmBytesRx) .put("rxMb", String.format("%.2f MB", ((gsmBytesRx / 1024D) / 1024D))) .put("tx", gsmBytesTx) .put("txMb", String.format("%.2f MB", ((gsmBytesTx / 1024D) / 1024D))) .put("total", total) .put("totalMb", String.format("%.2f MB", (total / 1024D) / 1024D)) .put("icon", encodedImage); } } catch (JSONException e) { Log.e(TAG, "Error putting app info: " + e.getMessage(), e); } return null; } private JSONObject getTrafficStats(int uid, String name, String packageName, String encodedImage) { double rx = (double) TrafficStats.getUidRxBytes(uid); double tx = (double) TrafficStats.getUidTxBytes(uid); double total = rx + tx; try { if (total > 0) { Log.i(TAG, "##### getTrafficStats - " + packageName + " - tx: " + tx + " | rx: " + rx + " | total: " + total); return new JSONObject().put("name", name) .put("packageName", packageName) .put("rx", rx) .put("received", String.format("%.2f MB", ((rx / 1024D) / 1024D) )) .put("tx", tx) .put("sent", String.format("%.2f MB", ((tx / 1024D) / 1024D) )) .put("total", total) .put("totalMb", String.format("%.2f MB", (total / 1024D) / 1024D )) .put("icon", encodedImage); } } catch (JSONException e) { Log.e(TAG, "Error putting app info: " + e.getMessage(), e); } return null; } private String encodeBitmapToBase64(Bitmap bitmap) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] b = baos.toByteArray(); return Base64.encodeToString(b, Base64.DEFAULT); } private Bitmap drawableToBitmap(Drawable drawable) { Bitmap bitmap = null; if (drawable instanceof BitmapDrawable) { BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; if(bitmapDrawable.getBitmap() != null) { return bitmapDrawable.getBitmap(); } } if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) { bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); } else { bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); } Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } @ReactMethod public void requestPermissions(final ReadableMap map, final Callback callback) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { boolean requestPermission = map.hasKey("requestPermission") ? Boolean.parseBoolean(map.getString("requestPermission")) : true; if (!hasPermissionToReadNetworkHistory(requestPermission)) { return; } if (requestPermission && !hasPermissionToReadPhoneStats()) { requestPhoneStateStats(); return; } try { callback.invoke(null, new JSONObject().put("permissions", true).toString()); } catch (JSONException e) { Log.e(TAG, "Error requesting permissions: " + e.getMessage(), e); } } } private boolean hasPermissionToReadNetworkHistory(boolean requestPermission) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return true; } final AppOpsManager appOps = (AppOpsManager) getCurrentActivity().getSystemService(Context.APP_OPS_SERVICE); int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), getCurrentActivity().getPackageName()); if (mode == AppOpsManager.MODE_ALLOWED) { return true; } appOps.startWatchingMode(AppOpsManager.OPSTR_GET_USAGE_STATS, getCurrentActivity().getApplicationContext().getPackageName(), new AppOpsManager.OnOpChangedListener() { @Override @TargetApi(Build.VERSION_CODES.M) public void onOpChanged(String op, String packageName) { int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), getCurrentActivity().getPackageName()); if (mode != AppOpsManager.MODE_ALLOWED) { return; } appOps.stopWatchingMode(this); Intent intent = new Intent(getCurrentActivity(), getCurrentActivity().getClass()); if (getCurrentActivity().getIntent().getExtras() != null) { intent.putExtras(getCurrentActivity().getIntent().getExtras()); } intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); getCurrentActivity().getApplicationContext().startActivity(intent); } }); if (requestPermission) requestReadNetworkHistoryAccess(); return false; } private boolean hasPermissionToReadPhoneStats() { if (ActivityCompat.checkSelfPermission(getCurrentActivity(), android.Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_DENIED) { return false; } else { return true; } } private void requestReadNetworkHistoryAccess() { Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS); getCurrentActivity().startActivity(intent); } private void requestPhoneStateStats() { ActivityCompat.requestPermissions(getCurrentActivity(), new String[]{ android.Manifest.permission.READ_PHONE_STATE }, READ_PHONE_STATE_REQUEST); } }
android/src/main/java/br/com/oi/reactnative/module/datausage/DataUsageModule.java
package br.com.oi.reactnative.module.datausage; import android.annotation.TargetApi; import android.app.AppOpsManager; import android.app.usage.NetworkStatsManager; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.TrafficStats; import android.os.AsyncTask; import android.os.Build; import android.provider.Settings; import android.support.v4.app.ActivityCompat; import android.util.Base64; import android.util.Log; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.util.Arrays; import java.util.Date; import java.util.List; import br.com.oi.reactnative.module.datausage.helper.NetworkStatsHelper; import static android.content.pm.PackageManager.GET_META_DATA; public class DataUsageModule extends ReactContextBaseJavaModule { private static final String TAG = "DataUsageModule"; private static final int READ_PHONE_STATE_REQUEST = 37; public DataUsageModule(ReactApplicationContext reactContext) { super(reactContext); } @Override public String getName() { return TAG; } @ReactMethod public void getDataUsageByApp(final ReadableMap map, final Callback callback) { AsyncTask.execute(new Runnable() { @Override public void run() { final PackageManager packageManager = getReactApplicationContext().getPackageManager(); JSONArray apps = new JSONArray(); try { ReadableArray packageNames = map.hasKey("packages") ? map.getArray("packages") : null; Date startDate = map.hasKey("startDate") ? new Date(Double.valueOf(map.getDouble("startDate")).longValue()) : null; Date endDate = map.hasKey("endDate") ? new Date(Double.valueOf(map.getDouble("endDate")).longValue()) : null; if (packageNames != null && packageNames.size() > 0) { for (int i = 0; i < packageNames.size(); i++) { String packageName = packageNames.getString(i); final PackageInfo packageInfo = packageManager.getPackageInfo(packageName, GET_META_DATA); int uid = packageInfo.applicationInfo.uid; ApplicationInfo appInfo = null; try { appInfo = packageManager.getApplicationInfo(packageName, 0); } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Error getting application info: " + e.getMessage(), e); } String name = (String) packageManager.getApplicationLabel(appInfo); Drawable icon = packageManager.getApplicationIcon(appInfo); Bitmap bitmap = drawableToBitmap(icon); String encodedImage = encodeBitmapToBase64(bitmap); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { // < Android 6.0 Log.i(TAG, "##### Android 5- App: " + name + " packageName: " + packageName); JSONObject appStats = getTrafficStats(uid, name, packageName, encodedImage); if (appStats != null) apps.put(appStats); } else { // Android 6+ Log.i(TAG, "##### Android 6+ App: " + name + " packageName: " + packageName); JSONObject appStats = getNetworkManagerStats(uid, name, packageName, encodedImage, startDate, endDate); if (appStats != null) apps.put(appStats); } } } } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Error getting app info: " + e.getMessage(), e); } callback.invoke(null, apps.toString()); } }); } @ReactMethod public void getDataUsageByAppWithTotal(final ReadableMap map, final Callback callback) { AsyncTask.execute(new Runnable() { @Override public void run() { final PackageManager packageManager = getReactApplicationContext().getPackageManager(); JSONObject result = new JSONObject(); JSONArray apps = new JSONArray(); Double totalGeral = 0D; try { ReadableArray packageNames = map.hasKey("packages") ? map.getArray("packages") : null; Date startDate = map.hasKey("startDate") ? new Date(Double.valueOf(map.getDouble("startDate")).longValue()) : null; Date endDate = map.hasKey("endDate") ? new Date(Double.valueOf(map.getDouble("endDate")).longValue()) : null; if (packageNames != null && packageNames.size() > 0) { Log.i(TAG, "##### Qtd. de aplicativos a analisar: " + packageNames.size()); for (int i = 0; i < packageNames.size(); i++) { String packageName = packageNames.getString(i); final PackageInfo packageInfo = packageManager.getPackageInfo(packageName, GET_META_DATA); int uid = packageInfo.applicationInfo.uid; ApplicationInfo appInfo = null; try { appInfo = packageManager.getApplicationInfo(packageName, 0); } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Error getting application info: " + e.getMessage(), e); } String name = (String) packageManager.getApplicationLabel(appInfo); Drawable icon = packageManager.getApplicationIcon(appInfo); Bitmap bitmap = drawableToBitmap(icon); String encodedImage = encodeBitmapToBase64(bitmap); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { // < Android 6.0 Log.i(TAG, "##### Android 5- App: " + name + " packageName: " + packageName); JSONObject appStats = getTrafficStats(uid, name, packageName, encodedImage); if (appStats != null) { totalGeral += appStats.getDouble("total"); apps.put(appStats); } } else { // Android 6+ Log.i(TAG, "##### Android 6+ App: " + name + " packageName: " + packageName); JSONObject appStats = getNetworkManagerStats(uid, name, packageName, encodedImage, startDate, endDate); if (appStats != null) { totalGeral += appStats.getDouble("total"); apps.put(appStats); } } } } } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Error getting app info: " + e.getMessage(), e); } catch (JSONException e) { Log.e(TAG, "Error parsing JSON: " + e.getMessage(), e); } try { result.put("totalGeral", totalGeral) .put("totalGeralMb", String.format("%.2f MB", ((totalGeral / 1024D) / 1024D))) .put("apps", apps); } catch (JSONException e) { Log.e(TAG, "Error parsing JSON: " + e.getMessage(), e); } callback.invoke(null, result.toString()); } }); } @ReactMethod public void listDataUsageByApps(final ReadableMap map, final Callback callback) { AsyncTask.execute(new Runnable() { @Override public void run() { Log.i(TAG, "##### Listar todos os aplicativos por uso de dados..."); Context context = getReactApplicationContext(); final PackageManager packageManager = getReactApplicationContext().getPackageManager(); //List<ApplicationInfo> packages = packageManager.getInstalledApplications(0); JSONArray apps = new JSONArray(); Date startDate = map.hasKey("startDate") ? new Date(Double.valueOf(map.getDouble("startDate")).longValue()) : null; Date endDate = map.hasKey("endDate") ? new Date(Double.valueOf(map.getDouble("endDate")).longValue()) : null; final List<PackageInfo> packageInfoList = packageManager.getInstalledPackages(PackageManager.GET_PERMISSIONS); for (PackageInfo packageInfo : packageInfoList) { if (packageInfo.requestedPermissions == null) continue; List<String> permissions = Arrays.asList(packageInfo.requestedPermissions); if (permissions.contains(android.Manifest.permission.INTERNET)) { int uid = packageInfo.applicationInfo.uid; String packageName = packageInfo.packageName; ApplicationInfo appInfo = null; try { appInfo = packageManager.getApplicationInfo(packageName, 0); String name = (String) packageManager.getApplicationLabel(appInfo); Drawable icon = packageManager.getApplicationIcon(appInfo); Bitmap bitmap = drawableToBitmap(icon); String encodedImage = encodeBitmapToBase64(bitmap); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { // < Android 6.0 Log.i(TAG, "##### Android 5- App: " + name + " packageName: " + packageName); JSONObject appStats = getTrafficStats(uid, name, packageName, encodedImage); if (appStats != null) apps.put(appStats); } else { // Android 6+ Log.i(TAG, "##### Android 6+ App: " + name + " packageName: " + packageName); JSONObject appStats = getNetworkManagerStats(uid, name, packageName, encodedImage, startDate, endDate); if (appStats != null) apps.put(appStats); } } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Error getting application info: " + e.getMessage(), e); } } } callback.invoke(null, apps.toString()); } }); } private JSONObject getNetworkManagerStats(int uid, String name, String packageName, String encodedImage, Date startDate, Date endDate) { //Log.i(TAG, "##### Step getNetworkManagerStats(" + uid + ", " + name + ", ...)"); NetworkStatsManager networkStatsManager = (NetworkStatsManager) getReactApplicationContext().getSystemService(Context.NETWORK_STATS_SERVICE); NetworkStatsHelper networkStatsHelper = new NetworkStatsHelper(networkStatsManager, uid); //long wifiBytesRx = networkStatsHelper.getAllRxBytesMobile(getReactApplicationContext()) + networkStatsHelper.getAllRxBytesWifi(); //long wifiBytesTx = networkStatsHelper.getAllRxBytesMobile(getReactApplicationContext()) + networkStatsHelper.getAllRxBytesWifi(); double gsmBytesRx = (double) networkStatsHelper.getPackageRxBytesMobile(getReactApplicationContext()) + networkStatsHelper.getPackageRxBytesMobile(getReactApplicationContext(), startDate, endDate); double gsmBytesTx = (double) networkStatsHelper.getPackageTxBytesMobile(getReactApplicationContext()) + networkStatsHelper.getPackageRxBytesMobile(getReactApplicationContext(), startDate, endDate); double total = gsmBytesRx + gsmBytesTx; Log.i(TAG, "##### getNetworkManagerStats - " + packageName + " - tx: " + gsmBytesTx + " | rx: " + gsmBytesRx + " | total: " + total); try { if (total > 0D) { return new JSONObject().put("name", name) .put("packageName", packageName) .put("rx", gsmBytesRx) .put("rxMb", String.format("%.2f MB", ((gsmBytesRx / 1024D) / 1024D))) .put("tx", gsmBytesTx) .put("txMb", String.format("%.2f MB", ((gsmBytesTx / 1024D) / 1024D))) .put("total", total) .put("totalMb", String.format("%.2f MB", (total / 1024D) / 1024D)) .put("icon", encodedImage); } } catch (JSONException e) { Log.e(TAG, "Error putting app info: " + e.getMessage(), e); } return null; } private JSONObject getTrafficStats(int uid, String name, String packageName, String encodedImage) { double rx = (double) TrafficStats.getUidRxBytes(uid); double tx = (double) TrafficStats.getUidTxBytes(uid); double total = rx + tx; try { if (total > 0) { Log.i(TAG, "##### getTrafficStats - " + packageName + " - tx: " + tx + " | rx: " + rx + " | total: " + total); return new JSONObject().put("name", name) .put("packageName", packageName) .put("rx", rx) .put("received", String.format("%.2f MB", ((rx / 1024D) / 1024D) )) .put("tx", tx) .put("sent", String.format("%.2f MB", ((tx / 1024D) / 1024D) )) .put("total", total) .put("totalMb", String.format("%.2f MB", (total / 1024D) / 1024D )) .put("icon", encodedImage); } } catch (JSONException e) { Log.e(TAG, "Error putting app info: " + e.getMessage(), e); } return null; } private String encodeBitmapToBase64(Bitmap bitmap) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] b = baos.toByteArray(); return Base64.encodeToString(b, Base64.DEFAULT); } private Bitmap drawableToBitmap(Drawable drawable) { Bitmap bitmap = null; if (drawable instanceof BitmapDrawable) { BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; if(bitmapDrawable.getBitmap() != null) { return bitmapDrawable.getBitmap(); } } if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) { bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); } else { bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); } Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } @ReactMethod public void requestPermissions(final ReadableMap map, final Callback callback) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { boolean requestPermission = map.hasKey("requestPermission") ? map.getBoolean("requestPermission") : true; if (!hasPermissionToReadNetworkHistory(requestPermission)) { return; } if (requestPermission && !hasPermissionToReadPhoneStats()) { requestPhoneStateStats(); return; } try { callback.invoke(null, new JSONObject().put("permissions", true).toString()); } catch (JSONException e) { Log.e(TAG, "Error requesting permissions: " + e.getMessage(), e); } } } private boolean hasPermissionToReadNetworkHistory(boolean requestPermission) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return true; } final AppOpsManager appOps = (AppOpsManager) getCurrentActivity().getSystemService(Context.APP_OPS_SERVICE); int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), getCurrentActivity().getPackageName()); if (mode == AppOpsManager.MODE_ALLOWED) { return true; } appOps.startWatchingMode(AppOpsManager.OPSTR_GET_USAGE_STATS, getCurrentActivity().getApplicationContext().getPackageName(), new AppOpsManager.OnOpChangedListener() { @Override @TargetApi(Build.VERSION_CODES.M) public void onOpChanged(String op, String packageName) { int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), getCurrentActivity().getPackageName()); if (mode != AppOpsManager.MODE_ALLOWED) { return; } appOps.stopWatchingMode(this); Intent intent = new Intent(getCurrentActivity(), getCurrentActivity().getClass()); if (getCurrentActivity().getIntent().getExtras() != null) { intent.putExtras(getCurrentActivity().getIntent().getExtras()); } intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); getCurrentActivity().getApplicationContext().startActivity(intent); } }); if (requestPermission) requestReadNetworkHistoryAccess(); return false; } private boolean hasPermissionToReadPhoneStats() { if (ActivityCompat.checkSelfPermission(getCurrentActivity(), android.Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_DENIED) { return false; } else { return true; } } private void requestReadNetworkHistoryAccess() { Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS); getCurrentActivity().startActivity(intent); } private void requestPhoneStateStats() { ActivityCompat.requestPermissions(getCurrentActivity(), new String[]{ android.Manifest.permission.READ_PHONE_STATE }, READ_PHONE_STATE_REQUEST); } }
Enhancement in request permissions
android/src/main/java/br/com/oi/reactnative/module/datausage/DataUsageModule.java
Enhancement in request permissions
Java
apache-2.0
3398dfc6846b5f106e879449631453e061d394fc
0
lmjacksoniii/hazelcast,tombujok/hazelcast,emre-aydin/hazelcast,juanavelez/hazelcast,emrahkocaman/hazelcast,tkountis/hazelcast,tombujok/hazelcast,tufangorel/hazelcast,emre-aydin/hazelcast,tkountis/hazelcast,dsukhoroslov/hazelcast,dbrimley/hazelcast,mesutcelik/hazelcast,dsukhoroslov/hazelcast,Donnerbart/hazelcast,Donnerbart/hazelcast,Donnerbart/hazelcast,mesutcelik/hazelcast,dbrimley/hazelcast,mdogan/hazelcast,emre-aydin/hazelcast,mesutcelik/hazelcast,mdogan/hazelcast,juanavelez/hazelcast,tufangorel/hazelcast,tufangorel/hazelcast,dbrimley/hazelcast,emrahkocaman/hazelcast,mdogan/hazelcast,tkountis/hazelcast,lmjacksoniii/hazelcast
/* * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.nio; import com.hazelcast.logging.Logger; import com.hazelcast.util.EmptyStatement; import com.hazelcast.util.QuickMath; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.UTFDataFormatException; import java.lang.reflect.Constructor; import java.lang.reflect.Field; /** * Class to encode/decode UTF-Strings to and from byte-arrays. */ public final class UTFEncoderDecoder { private static final int STRING_CHUNK_SIZE = 16 * 1024; private static final UTFEncoderDecoder INSTANCE; // Because this flag is not set for Non-Buffered Data Output classes // but results may be compared in unit tests. // Buffered Data Output may set this flag // but Non-Buffered Data Output class always set this flag to "false". // So their results may be different. private static final boolean ASCII_AWARE = Boolean.parseBoolean(System.getProperty("hazelcast.nio.asciiaware", "false")); static { INSTANCE = buildUTFUtil(); } private final StringCreator stringCreator; private final UtfWriter utfWriter; private final boolean hazelcastEnterpriseActive; UTFEncoderDecoder(StringCreator stringCreator, UtfWriter utfWriter) { this(stringCreator, utfWriter, false); } UTFEncoderDecoder(StringCreator stringCreator, UtfWriter utfWriter, boolean hazelcastEnterpriseActive) { this.stringCreator = stringCreator; this.utfWriter = utfWriter; this.hazelcastEnterpriseActive = hazelcastEnterpriseActive; } public boolean isHazelcastEnterpriseActive() { return hazelcastEnterpriseActive; } public static void writeUTF(final DataOutput out, final String str, final byte[] buffer) throws IOException { INSTANCE.writeUTF0(out, str, buffer); } public static String readUTF(final DataInput in, final byte[] buffer) throws IOException { return INSTANCE.readUTF0(in, buffer); } // ********************************************************************* // public void writeUTF0(final DataOutput out, final String str, final byte[] buffer) throws IOException { if (!QuickMath.isPowerOfTwo(buffer.length)) { throw new IllegalArgumentException( "Size of the buffer has to be power of two, was " + buffer.length); } boolean isNull = str == null; out.writeBoolean(isNull); if (isNull) { return; } int length = str.length(); out.writeInt(length); out.writeInt(length); if (length > 0) { int chunkSize = (length / STRING_CHUNK_SIZE) + 1; for (int i = 0; i < chunkSize; i++) { int beginIndex = Math.max(0, i * STRING_CHUNK_SIZE - 1); int endIndex = Math.min((i + 1) * STRING_CHUNK_SIZE - 1, length); utfWriter.writeShortUTF(out, str, beginIndex, endIndex, buffer); } } } // ********************************************************************* // interface UtfWriter { void writeShortUTF(final DataOutput out, final String str, final int beginIndex, final int endIndex, final byte[] buffer) throws IOException; } private abstract static class AbstractCharArrayUtfWriter implements UtfWriter { //CHECKSTYLE:OFF @Override public final void writeShortUTF(final DataOutput out, final String str, final int beginIndex, final int endIndex, final byte[] buffer) throws IOException { final boolean isBufferObjectDataOutput = out instanceof BufferObjectDataOutput; final BufferObjectDataOutput bufferObjectDataOutput = isBufferObjectDataOutput ? (BufferObjectDataOutput) out : null; final char[] value = getCharArray(str); int i; int c; int bufferPos = 0; int utfLength = 0; int utfLengthLimit; int pos = 0; if (isBufferObjectDataOutput) { // At most, one character can hold 3 bytes utfLengthLimit = str.length() * 3; // We save current position of buffer data output. // Then we write the length of UTF and ASCII state to here pos = bufferObjectDataOutput.position(); // Moving position explicitly is not good way // since it may cause overflow exceptions for example "ByteArrayObjectDataOutput". // So, write dummy data and let DataOutput handle it by expanding or etc ... bufferObjectDataOutput.writeShort(0); if (ASCII_AWARE) { bufferObjectDataOutput.writeBoolean(false); } } else { utfLength = calculateUtf8Length(value, beginIndex, endIndex); if (utfLength > 65535) { throw new UTFDataFormatException( "encoded string too long:" + utfLength + " bytes"); } utfLengthLimit = utfLength; out.writeShort(utfLength); if (ASCII_AWARE) { // We cannot determine that all characters are ASCII or not without iterating over it // So, we mark it as not ASCII, so all characters will be checked. out.writeBoolean(false); } } if (buffer.length >= utfLengthLimit) { for (i = beginIndex; i < endIndex; i++) { c = value[i]; if (!(c <= 0x007F && c >= 0x0001)) { break; } buffer[bufferPos++] = (byte) c; } for (; i < endIndex; i++) { c = value[i]; if (c <= 0x007F && c >= 0x0001) { buffer[bufferPos++] = (byte) c; } else if (c > 0x07FF) { buffer[bufferPos++] = (byte) (0xE0 | ((c >> 12) & 0x0F)); buffer[bufferPos++] = (byte) (0x80 | ((c >> 6) & 0x3F)); buffer[bufferPos++] = (byte) (0x80 | ((c) & 0x3F)); } else { buffer[bufferPos++] = (byte) (0xC0 | ((c >> 6) & 0x1F)); buffer[bufferPos++] = (byte) (0x80 | ((c) & 0x3F)); } } out.write(buffer, 0, bufferPos); if (isBufferObjectDataOutput) { utfLength = bufferPos; } } else { for (i = beginIndex; i < endIndex; i++) { c = value[i]; if (!(c <= 0x007F && c >= 0x0001)) { break; } bufferPos = buffering(buffer, bufferPos, (byte) c, out); } if (isBufferObjectDataOutput) { utfLength = i - beginIndex; } for (; i < endIndex; i++) { c = value[i]; if (c <= 0x007F && c >= 0x0001) { bufferPos = buffering(buffer, bufferPos, (byte) c, out); if (isBufferObjectDataOutput) { utfLength++; } } else if (c > 0x07FF) { bufferPos = buffering(buffer, bufferPos, (byte) (0xE0 | ((c >> 12) & 0x0F)), out); bufferPos = buffering(buffer, bufferPos, (byte) (0x80 | ((c >> 6) & 0x3F)), out); bufferPos = buffering(buffer, bufferPos, (byte) (0x80 | ((c) & 0x3F)), out); if (isBufferObjectDataOutput) { utfLength += 3; } } else { bufferPos = buffering(buffer, bufferPos, (byte) (0xC0 | ((c >> 6) & 0x1F)), out); bufferPos = buffering(buffer, bufferPos, (byte) (0x80 | ((c) & 0x3F)), out); if (isBufferObjectDataOutput) { utfLength += 2; } } } int length = bufferPos % buffer.length; out.write(buffer, 0, length == 0 ? buffer.length : length); } if (isBufferObjectDataOutput) { if (utfLength > 65535) { throw new UTFDataFormatException( "encoded string too long:" + utfLength + " bytes"); } // Write the length of UTF to saved position before bufferObjectDataOutput.writeShort(pos, utfLength); // Write the ASCII status of UTF to saved position before if (ASCII_AWARE) { bufferObjectDataOutput.writeBoolean(pos + 2, utfLength == str.length()); } } } protected abstract boolean isAvailable(); protected abstract char[] getCharArray(String str); //CHECKSTYLE:ON } static class UnsafeBasedCharArrayUtfWriter extends AbstractCharArrayUtfWriter { private static final sun.misc.Unsafe UNSAFE = UnsafeHelper.UNSAFE; private static final long VALUE_FIELD_OFFSET; static { long offset = -1; if (UnsafeHelper.UNSAFE_AVAILABLE) { try { offset = UNSAFE.objectFieldOffset(String.class.getDeclaredField("value")); } catch (Throwable t) { EmptyStatement.ignore(t); } } VALUE_FIELD_OFFSET = offset; } @Override public boolean isAvailable() { return UnsafeHelper.UNSAFE_AVAILABLE && VALUE_FIELD_OFFSET != -1; } @Override protected char[] getCharArray(String str) { char[] chars = (char[]) UNSAFE.getObject(str, VALUE_FIELD_OFFSET); if (chars.length > str.length()) { // substring detected! // jdk6 substring shares the same value array // with the original string (this is not the case for jdk7+) // we need to get copy of substring array chars = str.toCharArray(); } return chars; } } static class ReflectionBasedCharArrayUtfWriter extends AbstractCharArrayUtfWriter { private static final Field VALUE_FIELD; static { Field field; try { field = String.class.getDeclaredField("value"); field.setAccessible(true); } catch (Throwable t) { EmptyStatement.ignore(t); field = null; } VALUE_FIELD = field; } @Override public boolean isAvailable() { return VALUE_FIELD != null; } @Override protected char[] getCharArray(String str) { try { char[] chars = (char[]) VALUE_FIELD.get(str); if (chars.length > str.length()) { // substring detected! // jdk6 substring shares the same value array // with the original string (this is not the case for jdk7+) // we need to get copy of substring array chars = str.toCharArray(); } return chars; } catch (IllegalAccessException e) { throw new IllegalStateException(e); } } } static class StringBasedUtfWriter implements UtfWriter { //CHECKSTYLE:OFF @Override public void writeShortUTF(final DataOutput out, final String str, final int beginIndex, final int endIndex, final byte[] buffer) throws IOException { final boolean isBufferObjectDataOutput = out instanceof BufferObjectDataOutput; final BufferObjectDataOutput bufferObjectDataOutput = isBufferObjectDataOutput ? (BufferObjectDataOutput) out : null; int i; int c; int bufferPos = 0; int utfLength = 0; int utfLengthLimit; int pos = 0; if (isBufferObjectDataOutput) { // At most, one character can hold 3 bytes utfLengthLimit = str.length() * 3; // We save current position of buffer data output. // Then we write the length of UTF and ASCII state to here pos = bufferObjectDataOutput.position(); // Moving position explicitly is not good way // since it may cause overflow exceptions for example "ByteArrayObjectDataOutput". // So, write dummy data and let DataOutput handle it by expanding or etc ... bufferObjectDataOutput.writeShort(0); if (ASCII_AWARE) { bufferObjectDataOutput.writeBoolean(false); } } else { utfLength = calculateUtf8Length(str, beginIndex, endIndex); if (utfLength > 65535) { throw new UTFDataFormatException( "encoded string too long:" + utfLength + " bytes"); } utfLengthLimit = utfLength; out.writeShort(utfLength); if (ASCII_AWARE) { // We cannot determine that all characters are ASCII or not without iterating over it // So, we mark it as not ASCII, so all characters will be checked. out.writeBoolean(false); } } if (buffer.length >= utfLengthLimit) { for (i = beginIndex; i < endIndex; i++) { c = str.charAt(i); if (!(c <= 0x007F && c >= 0x0001)) { break; } buffer[bufferPos++] = (byte) c; } for (; i < endIndex; i++) { c = str.charAt(i); if ((c >= 0x0001) && (c <= 0x007F)) { // 0x0001 <= X <= 0x007F buffer[bufferPos++] = (byte) c; } else if (c > 0x07FF) { // 0x007F < X <= 0x7FFF buffer[bufferPos++] = (byte) (0xE0 | ((c >> 12) & 0x0F)); buffer[bufferPos++] = (byte) (0x80 | ((c >> 6) & 0x3F)); buffer[bufferPos++] = (byte) (0x80 | ((c) & 0x3F)); } else { // X == 0 or 0x007F < X < 0x7FFF buffer[bufferPos++] = (byte) (0xC0 | ((c >> 6) & 0x1F)); buffer[bufferPos++] = (byte) (0x80 | ((c) & 0x3F)); } } out.write(buffer, 0, bufferPos); if (isBufferObjectDataOutput) { utfLength = bufferPos; } } else { for (i = beginIndex; i < endIndex; i++) { c = str.charAt(i); if (!(c <= 0x007F && c >= 0x0001)) { break; } bufferPos = buffering(buffer, bufferPos, (byte) c, out); } if (isBufferObjectDataOutput) { utfLength = i - beginIndex; } for (; i < endIndex; i++) { c = str.charAt(i); if (c <= 0x007F && c >= 0x0001) { // 0x0001 <= X <= 0x007F bufferPos = buffering(buffer, bufferPos, (byte) c, out); if (isBufferObjectDataOutput) { utfLength++; } } else if (c > 0x07FF) { // 0x007F < X <= 0x7FFF bufferPos = buffering(buffer, bufferPos, (byte) (0xE0 | ((c >> 12) & 0x0F)), out); bufferPos = buffering(buffer, bufferPos, (byte) (0x80 | ((c >> 6) & 0x3F)), out); bufferPos = buffering(buffer, bufferPos, (byte) (0x80 | ((c) & 0x3F)), out); if (isBufferObjectDataOutput) { utfLength += 3; } } else { // X == 0 or 0x007F < X < 0x7FFF bufferPos = buffering(buffer, bufferPos, (byte) (0xC0 | ((c >> 6) & 0x1F)), out); bufferPos = buffering(buffer, bufferPos, (byte) (0x80 | ((c) & 0x3F)), out); if (isBufferObjectDataOutput) { utfLength += 2; } } } int length = bufferPos % buffer.length; out.write(buffer, 0, length == 0 ? buffer.length : length); } if (isBufferObjectDataOutput) { if (utfLength > 65535) { throw new UTFDataFormatException( "encoded string too long:" + utfLength + " bytes"); } // Write the length of UTF to saved position before bufferObjectDataOutput.writeShort(pos, utfLength); // Write the ASCII status of UTF to saved position before if (ASCII_AWARE) { bufferObjectDataOutput.writeBoolean(pos + 2, utfLength == str.length()); } } } //CHECKSTYLE:ON } // ********************************************************************* // public String readUTF0(final DataInput in, final byte[] buffer) throws IOException { if (!QuickMath.isPowerOfTwo(buffer.length)) { throw new IllegalArgumentException( "Size of the buffer has to be power of two, was " + buffer.length); } boolean isNull = in.readBoolean(); if (isNull) { return null; } int length = in.readInt(); int lengthCheck = in.readInt(); if (length != lengthCheck) { throw new UTFDataFormatException( "Length check failed, maybe broken bytestream or wrong stream position"); } final char[] data = new char[length]; if (length > 0) { int chunkSize = length / STRING_CHUNK_SIZE + 1; for (int i = 0; i < chunkSize; i++) { int beginIndex = Math.max(0, i * STRING_CHUNK_SIZE - 1); readShortUTF(in, data, beginIndex, buffer); } } return stringCreator.buildString(data); } //CHECKSTYLE:OFF private void readShortUTF(final DataInput in, final char[] data, final int beginIndex, final byte[] buffer) throws IOException { final int utfLength = in.readShort() & 0xFFFF; final boolean allAscii = ASCII_AWARE ? in.readBoolean() : false; // buffer[0] is used to hold read data // so actual useful length of buffer is as "length - 1" final int minUtfLenght = Math.min(utfLength, buffer.length - 1); final int bufferLimit = minUtfLenght + 1; int readCount = 0; // We use buffer[0] to hold read data, so position starts from 1 int bufferPos = 1; int c1 = 0; int c2 = 0; int c3 = 0; int cTemp = 0; int charArrCount = beginIndex; // The first readable data is at 1. index since 0. index is used to hold read data. in.readFully(buffer, 1, minUtfLenght); if (allAscii) { while (bufferPos != bufferLimit) { data[charArrCount++] = (char) (buffer[bufferPos++] & 0xFF); } for (readCount = bufferPos - 1; readCount < utfLength; readCount++) { bufferPos = buffered(buffer, bufferPos, utfLength, readCount, in); data[charArrCount++] = (char) (buffer[0] & 0xFF); } } else { c1 = buffer[bufferPos++] & 0xFF; while (bufferPos != bufferLimit) { if (c1 > 127) { break; } data[charArrCount++] = (char) c1; c1 = buffer[bufferPos++] & 0xFF; } bufferPos--; readCount = bufferPos - 1; while (readCount < utfLength) { bufferPos = buffered(buffer, bufferPos, utfLength, readCount++, in); c1 = buffer[0] & 0xFF; cTemp = c1 >> 4; if (cTemp >> 3 == 0) { // ((cTemp & 0xF8) == 0) or (cTemp <= 7 && cTemp >= 0) /* 0xxxxxxx */ data[charArrCount++] = (char) c1; } else if (cTemp == 12 || cTemp == 13) { /* 110x xxxx 10xx xxxx */ if (readCount + 1 > utfLength) { throw new UTFDataFormatException( "malformed input: partial character at end"); } bufferPos = buffered(buffer, bufferPos, utfLength, readCount++, in); c2 = buffer[0] & 0xFF; if ((c2 & 0xC0) != 0x80) { throw new UTFDataFormatException( "malformed input around byte " + beginIndex + readCount + 1); } data[charArrCount++] = (char) (((c1 & 0x1F) << 6) | (c2 & 0x3F)); } else if (cTemp == 14) { /* 1110 xxxx 10xx xxxx 10xx xxxx */ if (readCount + 2 > utfLength) { throw new UTFDataFormatException( "malformed input: partial character at end"); } bufferPos = buffered(buffer, bufferPos, utfLength, readCount++, in); c2 = buffer[0] & 0xFF; bufferPos = buffered(buffer, bufferPos, utfLength, readCount++, in); c3 = buffer[0] & 0xFF; if (((c2 & 0xC0) != 0x80) || ((c3 & 0xC0) != 0x80)) { throw new UTFDataFormatException( "malformed input around byte " + (beginIndex + readCount + 1)); } data[charArrCount++] = (char) (((c1 & 0x0F) << 12) | ((c2 & 0x3F) << 6) | ((c3 & 0x3F))); } else { /* 10xx xxxx, 1111 xxxx */ throw new UTFDataFormatException( "malformed input around byte " + (beginIndex + readCount)); } } } } //CHECKSTYLE:ON // ********************************************************************* // private static int calculateUtf8Length(final char[] value, final int beginIndex, final int endIndex) { int utfLength = 0; for (int i = beginIndex; i < endIndex; i++) { int c = value[i]; if (c <= 0x007F && c >= 0x0001) { utfLength += 1; } else if (c > 0x07FF) { utfLength += 3; } else { utfLength += 2; } } return utfLength; } private static int calculateUtf8Length(final String str, final int beginIndex, final int endIndex) { int utfLength = 0; for (int i = beginIndex; i < endIndex; i++) { int c = str.charAt(i); if (c <= 0x007F && c >= 0x0001) { utfLength += 1; } else if (c > 0x07FF) { utfLength += 3; } else { utfLength += 2; } } return utfLength; } private static int buffering(final byte[] buffer, final int pos, final byte value, final DataOutput out) throws IOException { try { buffer[pos] = value; return pos + 1; } catch (ArrayIndexOutOfBoundsException e) { // Array bounds check by programmatically is not needed like // "if (pos < buffer.length)". // JVM checks instead of us, so it is unnecessary. out.write(buffer, 0, buffer.length); buffer[0] = value; return 1; } } private int buffered(final byte[] buffer, final int pos, final int utfLength, final int readCount, final DataInput in) throws IOException { try { // 0. index of buffer is used to hold read data // so copy read data to there. buffer[0] = buffer[pos]; return pos + 1; } catch (ArrayIndexOutOfBoundsException e) { // Array bounds check by programmatically is not needed like // "if (pos < buffer.length)". // JVM checks instead of us, so it is unnecessary. in.readFully(buffer, 1, Math.min(buffer.length - 1, utfLength - readCount)); // The first readable data is at 1. index since 0. index is used to // hold read data. // So the next one will be 2. index. buffer[0] = buffer[1]; return 2; } } private static boolean useOldStringConstructor() { try { Class<String> clazz = String.class; clazz.getDeclaredConstructor(int.class, int.class, char[].class); return true; } catch (Throwable t) { Logger.getLogger(UTFEncoderDecoder.class). finest("Old String constructor doesn't seem available", t); } return false; } private static UTFEncoderDecoder buildUTFUtil() { UtfWriter utfWriter = createUtfWriter(); StringCreator stringCreator = createStringCreator(); return new UTFEncoderDecoder(stringCreator, utfWriter, false); } static StringCreator createStringCreator() { boolean fastStringEnabled = Boolean.parseBoolean(System.getProperty("hazelcast.nio.faststring", "true")); return createStringCreator(fastStringEnabled); } static StringCreator createStringCreator(boolean fastStringEnabled) { return fastStringEnabled ? buildFastStringCreator() : new DefaultStringCreator(); } static UtfWriter createUtfWriter() { // Try Unsafe based implementation UnsafeBasedCharArrayUtfWriter unsafeBasedUtfWriter = new UnsafeBasedCharArrayUtfWriter(); if (unsafeBasedUtfWriter.isAvailable()) { return unsafeBasedUtfWriter; } // If Unsafe based implementation is not available for usage // Try Reflection based implementation ReflectionBasedCharArrayUtfWriter reflectionBasedUtfWriter = new ReflectionBasedCharArrayUtfWriter(); if (reflectionBasedUtfWriter.isAvailable()) { return reflectionBasedUtfWriter; } // If Reflection based implementation is not available for usage return new StringBasedUtfWriter(); } private static StringCreator buildFastStringCreator() { try { // Give access to the package private String constructor Constructor<String> constructor; if (UTFEncoderDecoder.useOldStringConstructor()) { constructor = String.class.getDeclaredConstructor(int.class, int.class, char[].class); } else { constructor = String.class.getDeclaredConstructor(char[].class, boolean.class); } if (constructor != null) { constructor.setAccessible(true); return new FastStringCreator(constructor); } } catch (Throwable t) { Logger. getLogger(UTFEncoderDecoder.class). finest("No fast string creator seems to available, falling back to reflection", t); } return null; } interface StringCreator { String buildString(final char[] chars); } private static class DefaultStringCreator implements StringCreator { @Override public String buildString(final char[] chars) { return new String(chars); } } private static class FastStringCreator implements StringCreator { private final Constructor<String> constructor; private final boolean useOldStringConstructor; public FastStringCreator(Constructor<String> constructor) { this.constructor = constructor; this.useOldStringConstructor = constructor.getParameterTypes().length == 3; } @Override public String buildString(final char[] chars) { try { if (useOldStringConstructor) { return constructor.newInstance(0, chars.length, chars); } else { return constructor.newInstance(chars, Boolean.TRUE); } } catch (Exception e) { throw new RuntimeException(e); } } } }
hazelcast/src/main/java/com/hazelcast/nio/UTFEncoderDecoder.java
/* * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.nio; import com.hazelcast.logging.Logger; import com.hazelcast.util.EmptyStatement; import com.hazelcast.util.QuickMath; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.UTFDataFormatException; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * Class to encode/decode UTF-Strings to and from byte-arrays. */ public final class UTFEncoderDecoder { private static final int STRING_CHUNK_SIZE = 16 * 1024; private static final UTFEncoderDecoder INSTANCE; // Because this flag is not set for Non-Buffered Data Output classes // but results may be compared in unit tests. // Buffered Data Output may set this flag // but Non-Buffered Data Output class always set this flag to "false". // So their results may be different. private static final boolean ASCII_AWARE = Boolean.parseBoolean(System.getProperty("hazelcast.nio.asciiaware", "false")); static { INSTANCE = buildUTFUtil(); } private final StringCreator stringCreator; private final UtfWriter utfWriter; private final boolean hazelcastEnterpriseActive; UTFEncoderDecoder(StringCreator stringCreator, UtfWriter utfWriter) { this(stringCreator, utfWriter, false); } UTFEncoderDecoder(StringCreator stringCreator, UtfWriter utfWriter, boolean hazelcastEnterpriseActive) { this.stringCreator = stringCreator; this.utfWriter = utfWriter; this.hazelcastEnterpriseActive = hazelcastEnterpriseActive; } public boolean isHazelcastEnterpriseActive() { return hazelcastEnterpriseActive; } public static void writeUTF(final DataOutput out, final String str, final byte[] buffer) throws IOException { INSTANCE.writeUTF0(out, str, buffer); } public static String readUTF(final DataInput in, final byte[] buffer) throws IOException { return INSTANCE.readUTF0(in, buffer); } // ********************************************************************* // public void writeUTF0(final DataOutput out, final String str, final byte[] buffer) throws IOException { if (!QuickMath.isPowerOfTwo(buffer.length)) { throw new IllegalArgumentException( "Size of the buffer has to be power of two, was " + buffer.length); } boolean isNull = str == null; out.writeBoolean(isNull); if (isNull) { return; } int length = str.length(); out.writeInt(length); out.writeInt(length); if (length > 0) { int chunkSize = (length / STRING_CHUNK_SIZE) + 1; for (int i = 0; i < chunkSize; i++) { int beginIndex = Math.max(0, i * STRING_CHUNK_SIZE - 1); int endIndex = Math.min((i + 1) * STRING_CHUNK_SIZE - 1, length); utfWriter.writeShortUTF(out, str, beginIndex, endIndex, buffer); } } } // ********************************************************************* // interface UtfWriter { void writeShortUTF(final DataOutput out, final String str, final int beginIndex, final int endIndex, final byte[] buffer) throws IOException; } private abstract static class AbstractCharArrayUtfWriter implements UtfWriter { //CHECKSTYLE:OFF @Override public final void writeShortUTF(final DataOutput out, final String str, final int beginIndex, final int endIndex, final byte[] buffer) throws IOException { final boolean isBufferObjectDataOutput = out instanceof BufferObjectDataOutput; final BufferObjectDataOutput bufferObjectDataOutput = isBufferObjectDataOutput ? (BufferObjectDataOutput) out : null; final char[] value = getCharArray(str); int i; int c; int bufferPos = 0; int utfLength = 0; int utfLengthLimit; int pos = 0; if (isBufferObjectDataOutput) { // At most, one character can hold 3 bytes utfLengthLimit = str.length() * 3; // We save current position of buffer data output. // Then we write the length of UTF and ASCII state to here pos = bufferObjectDataOutput.position(); // Moving position explicitly is not good way // since it may cause overflow exceptions for example "ByteArrayObjectDataOutput". // So, write dummy data and let DataOutput handle it by expanding or etc ... bufferObjectDataOutput.writeShort(0); if (ASCII_AWARE) { bufferObjectDataOutput.writeBoolean(false); } } else { utfLength = calculateUtf8Length(value, beginIndex, endIndex); if (utfLength > 65535) { throw new UTFDataFormatException( "encoded string too long:" + utfLength + " bytes"); } utfLengthLimit = utfLength; out.writeShort(utfLength); if (ASCII_AWARE) { // We cannot determine that all characters are ASCII or not without iterating over it // So, we mark it as not ASCII, so all characters will be checked. out.writeBoolean(false); } } if (buffer.length >= utfLengthLimit) { for (i = beginIndex; i < endIndex; i++) { c = value[i]; if (!(c <= 0x007F && c >= 0x0001)) { break; } buffer[bufferPos++] = (byte) c; } for (; i < endIndex; i++) { c = value[i]; if (c <= 0x007F && c >= 0x0001) { buffer[bufferPos++] = (byte) c; } else if (c > 0x07FF) { buffer[bufferPos++] = (byte) (0xE0 | ((c >> 12) & 0x0F)); buffer[bufferPos++] = (byte) (0x80 | ((c >> 6) & 0x3F)); buffer[bufferPos++] = (byte) (0x80 | ((c) & 0x3F)); } else { buffer[bufferPos++] = (byte) (0xC0 | ((c >> 6) & 0x1F)); buffer[bufferPos++] = (byte) (0x80 | ((c) & 0x3F)); } } out.write(buffer, 0, bufferPos); if (isBufferObjectDataOutput) { utfLength = bufferPos; } } else { for (i = beginIndex; i < endIndex; i++) { c = value[i]; if (!(c <= 0x007F && c >= 0x0001)) { break; } bufferPos = buffering(buffer, bufferPos, (byte) c, out); } if (isBufferObjectDataOutput) { utfLength = i - beginIndex; } for (; i < endIndex; i++) { c = value[i]; if (c <= 0x007F && c >= 0x0001) { bufferPos = buffering(buffer, bufferPos, (byte) c, out); if (isBufferObjectDataOutput) { utfLength++; } } else if (c > 0x07FF) { bufferPos = buffering(buffer, bufferPos, (byte) (0xE0 | ((c >> 12) & 0x0F)), out); bufferPos = buffering(buffer, bufferPos, (byte) (0x80 | ((c >> 6) & 0x3F)), out); bufferPos = buffering(buffer, bufferPos, (byte) (0x80 | ((c) & 0x3F)), out); if (isBufferObjectDataOutput) { utfLength += 3; } } else { bufferPos = buffering(buffer, bufferPos, (byte) (0xC0 | ((c >> 6) & 0x1F)), out); bufferPos = buffering(buffer, bufferPos, (byte) (0x80 | ((c) & 0x3F)), out); if (isBufferObjectDataOutput) { utfLength += 2; } } } int length = bufferPos % buffer.length; out.write(buffer, 0, length == 0 ? buffer.length : length); } if (isBufferObjectDataOutput) { if (utfLength > 65535) { throw new UTFDataFormatException( "encoded string too long:" + utfLength + " bytes"); } // Write the length of UTF to saved position before bufferObjectDataOutput.writeShort(pos, utfLength); // Write the ASCII status of UTF to saved position before if (ASCII_AWARE) { bufferObjectDataOutput.writeBoolean(pos + 2, utfLength == str.length()); } } } protected abstract boolean isAvailable(); protected abstract char[] getCharArray(String str); //CHECKSTYLE:ON } static class UnsafeBasedCharArrayUtfWriter extends AbstractCharArrayUtfWriter { private static final sun.misc.Unsafe UNSAFE = UnsafeHelper.UNSAFE; private static final long VALUE_FIELD_OFFSET; static { long offset = -1; if (UnsafeHelper.UNSAFE_AVAILABLE) { try { offset = UNSAFE.objectFieldOffset(String.class.getDeclaredField("value")); } catch (Throwable t) { EmptyStatement.ignore(t); } } VALUE_FIELD_OFFSET = offset; } @Override public boolean isAvailable() { return UnsafeHelper.UNSAFE_AVAILABLE && VALUE_FIELD_OFFSET != -1; } @Override protected char[] getCharArray(String str) { char[] chars = (char[]) UNSAFE.getObject(str, VALUE_FIELD_OFFSET); if (chars.length > str.length()) { // substring detected! // jdk6 substring shares the same value array // with the original string (this is not the case for jdk7+) // we need to get copy of substring array chars = str.toCharArray(); } return chars; } } static class ReflectionBasedCharArrayUtfWriter extends AbstractCharArrayUtfWriter { private static final Field VALUE_FIELD; static { Field field; try { field = String.class.getDeclaredField("value"); field.setAccessible(true); } catch (Throwable t) { EmptyStatement.ignore(t); field = null; } VALUE_FIELD = field; } @Override public boolean isAvailable() { return VALUE_FIELD != null; } @Override protected char[] getCharArray(String str) { try { char[] chars = (char[]) VALUE_FIELD.get(str); if (chars.length > str.length()) { // substring detected! // jdk6 substring shares the same value array // with the original string (this is not the case for jdk7+) // we need to get copy of substring array chars = str.toCharArray(); } return chars; } catch (IllegalAccessException e) { throw new IllegalStateException(e); } } } static class StringBasedUtfWriter implements UtfWriter { //CHECKSTYLE:OFF @Override public void writeShortUTF(final DataOutput out, final String str, final int beginIndex, final int endIndex, final byte[] buffer) throws IOException { final boolean isBufferObjectDataOutput = out instanceof BufferObjectDataOutput; final BufferObjectDataOutput bufferObjectDataOutput = isBufferObjectDataOutput ? (BufferObjectDataOutput) out : null; int i; int c; int bufferPos = 0; int utfLength = 0; int utfLengthLimit; int pos = 0; if (isBufferObjectDataOutput) { // At most, one character can hold 3 bytes utfLengthLimit = str.length() * 3; // We save current position of buffer data output. // Then we write the length of UTF and ASCII state to here pos = bufferObjectDataOutput.position(); // Moving position explicitly is not good way // since it may cause overflow exceptions for example "ByteArrayObjectDataOutput". // So, write dummy data and let DataOutput handle it by expanding or etc ... bufferObjectDataOutput.writeShort(0); if (ASCII_AWARE) { bufferObjectDataOutput.writeBoolean(false); } } else { utfLength = calculateUtf8Length(str, beginIndex, endIndex); if (utfLength > 65535) { throw new UTFDataFormatException( "encoded string too long:" + utfLength + " bytes"); } utfLengthLimit = utfLength; out.writeShort(utfLength); if (ASCII_AWARE) { // We cannot determine that all characters are ASCII or not without iterating over it // So, we mark it as not ASCII, so all characters will be checked. out.writeBoolean(false); } } if (buffer.length >= utfLengthLimit) { for (i = beginIndex; i < endIndex; i++) { c = str.charAt(i); if (!(c <= 0x007F && c >= 0x0001)) { break; } buffer[bufferPos++] = (byte) c; } for (; i < endIndex; i++) { c = str.charAt(i); if ((c >= 0x0001) && (c <= 0x007F)) { // 0x0001 <= X <= 0x007F buffer[bufferPos++] = (byte) c; } else if (c > 0x07FF) { // 0x007F < X <= 0x7FFF buffer[bufferPos++] = (byte) (0xE0 | ((c >> 12) & 0x0F)); buffer[bufferPos++] = (byte) (0x80 | ((c >> 6) & 0x3F)); buffer[bufferPos++] = (byte) (0x80 | ((c) & 0x3F)); } else { // X == 0 or 0x007F < X < 0x7FFF buffer[bufferPos++] = (byte) (0xC0 | ((c >> 6) & 0x1F)); buffer[bufferPos++] = (byte) (0x80 | ((c) & 0x3F)); } } out.write(buffer, 0, bufferPos); if (isBufferObjectDataOutput) { utfLength = bufferPos; } } else { for (i = beginIndex; i < endIndex; i++) { c = str.charAt(i); if (!(c <= 0x007F && c >= 0x0001)) { break; } bufferPos = buffering(buffer, bufferPos, (byte) c, out); } if (isBufferObjectDataOutput) { utfLength = i - beginIndex; } for (; i < endIndex; i++) { c = str.charAt(i); if (c <= 0x007F && c >= 0x0001) { // 0x0001 <= X <= 0x007F bufferPos = buffering(buffer, bufferPos, (byte) c, out); if (isBufferObjectDataOutput) { utfLength++; } } else if (c > 0x07FF) { // 0x007F < X <= 0x7FFF bufferPos = buffering(buffer, bufferPos, (byte) (0xE0 | ((c >> 12) & 0x0F)), out); bufferPos = buffering(buffer, bufferPos, (byte) (0x80 | ((c >> 6) & 0x3F)), out); bufferPos = buffering(buffer, bufferPos, (byte) (0x80 | ((c) & 0x3F)), out); if (isBufferObjectDataOutput) { utfLength += 3; } } else { // X == 0 or 0x007F < X < 0x7FFF bufferPos = buffering(buffer, bufferPos, (byte) (0xC0 | ((c >> 6) & 0x1F)), out); bufferPos = buffering(buffer, bufferPos, (byte) (0x80 | ((c) & 0x3F)), out); if (isBufferObjectDataOutput) { utfLength += 2; } } } int length = bufferPos % buffer.length; out.write(buffer, 0, length == 0 ? buffer.length : length); } if (isBufferObjectDataOutput) { if (utfLength > 65535) { throw new UTFDataFormatException( "encoded string too long:" + utfLength + " bytes"); } // Write the length of UTF to saved position before bufferObjectDataOutput.writeShort(pos, utfLength); // Write the ASCII status of UTF to saved position before if (ASCII_AWARE) { bufferObjectDataOutput.writeBoolean(pos + 2, utfLength == str.length()); } } } //CHECKSTYLE:ON } // ********************************************************************* // public String readUTF0(final DataInput in, final byte[] buffer) throws IOException { if (!QuickMath.isPowerOfTwo(buffer.length)) { throw new IllegalArgumentException( "Size of the buffer has to be power of two, was " + buffer.length); } boolean isNull = in.readBoolean(); if (isNull) { return null; } int length = in.readInt(); int lengthCheck = in.readInt(); if (length != lengthCheck) { throw new UTFDataFormatException( "Length check failed, maybe broken bytestream or wrong stream position"); } final char[] data = new char[length]; if (length > 0) { int chunkSize = length / STRING_CHUNK_SIZE + 1; for (int i = 0; i < chunkSize; i++) { int beginIndex = Math.max(0, i * STRING_CHUNK_SIZE - 1); readShortUTF(in, data, beginIndex, buffer); } } return stringCreator.buildString(data); } //CHECKSTYLE:OFF private void readShortUTF(final DataInput in, final char[] data, final int beginIndex, final byte[] buffer) throws IOException { final int utfLength = in.readShort() & 0xFFFF; final boolean allAscii = ASCII_AWARE ? in.readBoolean() : false; // buffer[0] is used to hold read data // so actual useful length of buffer is as "length - 1" final int minUtfLenght = Math.min(utfLength, buffer.length - 1); final int bufferLimit = minUtfLenght + 1; int readCount = 0; // We use buffer[0] to hold read data, so position starts from 1 int bufferPos = 1; int c1 = 0; int c2 = 0; int c3 = 0; int cTemp = 0; int charArrCount = beginIndex; // The first readable data is at 1. index since 0. index is used to hold read data. in.readFully(buffer, 1, minUtfLenght); if (allAscii) { while (bufferPos != bufferLimit) { data[charArrCount++] = (char)(buffer[bufferPos++] & 0xFF); } for (readCount = bufferPos - 1; readCount < utfLength; readCount++) { bufferPos = buffered(buffer, bufferPos, utfLength, readCount, in); data[charArrCount++] = (char) (buffer[0] & 0xFF); } } else { c1 = buffer[bufferPos++] & 0xFF; while (bufferPos != bufferLimit) { if (c1 > 127) { break; } data[charArrCount++] = (char) c1; c1 = buffer[bufferPos++] & 0xFF; } bufferPos--; readCount = bufferPos - 1; while (readCount < utfLength) { bufferPos = buffered(buffer, bufferPos, utfLength, readCount++, in); c1 = buffer[0] & 0xFF; cTemp = c1 >> 4; if (cTemp >> 3 == 0) { // ((cTemp & 0xF8) == 0) or (cTemp <= 7 && cTemp >= 0) /* 0xxxxxxx */ data[charArrCount++] = (char) c1; } else if (cTemp == 12 || cTemp == 13) { /* 110x xxxx 10xx xxxx */ if (readCount + 1 > utfLength) { throw new UTFDataFormatException( "malformed input: partial character at end"); } bufferPos = buffered(buffer, bufferPos, utfLength, readCount++, in); c2 = buffer[0] & 0xFF; if ((c2 & 0xC0) != 0x80) { throw new UTFDataFormatException( "malformed input around byte " + beginIndex + readCount + 1); } data[charArrCount++] = (char) (((c1 & 0x1F) << 6) | (c2 & 0x3F)); } else if (cTemp == 14) { /* 1110 xxxx 10xx xxxx 10xx xxxx */ if (readCount + 2 > utfLength) { throw new UTFDataFormatException( "malformed input: partial character at end"); } bufferPos = buffered(buffer, bufferPos, utfLength, readCount++, in); c2 = buffer[0] & 0xFF; bufferPos = buffered(buffer, bufferPos, utfLength, readCount++, in); c3 = buffer[0] & 0xFF; if (((c2 & 0xC0) != 0x80) || ((c3 & 0xC0) != 0x80)) { throw new UTFDataFormatException( "malformed input around byte " + (beginIndex + readCount + 1)); } data[charArrCount++] = (char) (((c1 & 0x0F) << 12) | ((c2 & 0x3F) << 6) | ((c3 & 0x3F))); } else { /* 10xx xxxx, 1111 xxxx */ throw new UTFDataFormatException( "malformed input around byte " + (beginIndex + readCount)); } } } } //CHECKSTYLE:ON // ********************************************************************* // private static int calculateUtf8Length(final char[] value, final int beginIndex, final int endIndex) { int utfLength = 0; for (int i = beginIndex; i < endIndex; i++) { int c = value[i]; if (c <= 0x007F && c >= 0x0001) { utfLength += 1; } else if (c > 0x07FF) { utfLength += 3; } else { utfLength += 2; } } return utfLength; } private static int calculateUtf8Length(final String str, final int beginIndex, final int endIndex) { int utfLength = 0; for (int i = beginIndex; i < endIndex; i++) { int c = str.charAt(i); if (c <= 0x007F && c >= 0x0001) { utfLength += 1; } else if (c > 0x07FF) { utfLength += 3; } else { utfLength += 2; } } return utfLength; } private static int buffering(final byte[] buffer, final int pos, final byte value, final DataOutput out) throws IOException { try { buffer[pos] = value; return pos + 1; } catch (ArrayIndexOutOfBoundsException e) { // Array bounds check by programmatically is not needed like // "if (pos < buffer.length)". // JVM checks instead of us, so it is unnecessary. out.write(buffer, 0, buffer.length); buffer[0] = value; return 1; } } private int buffered(final byte[] buffer, final int pos, final int utfLength, final int readCount, final DataInput in) throws IOException { try { // 0. index of buffer is used to hold read data // so copy read data to there. buffer[0] = buffer[pos]; return pos + 1; } catch (ArrayIndexOutOfBoundsException e) { // Array bounds check by programmatically is not needed like // "if (pos < buffer.length)". // JVM checks instead of us, so it is unnecessary. in.readFully(buffer, 1, Math.min(buffer.length - 1, utfLength - readCount)); // The first readable data is at 1. index since 0. index is used to // hold read data. // So the next one will be 2. index. buffer[0] = buffer[1]; return 2; } } private static boolean useOldStringConstructor() { try { Class<String> clazz = String.class; clazz.getDeclaredConstructor(int.class, int.class, char[].class); return true; } catch (Throwable t) { Logger.getLogger(UTFEncoderDecoder.class). finest("Old String constructor doesn't seem available", t); } return false; } private static UTFEncoderDecoder buildUTFUtil() { UtfWriter utfWriter = createUtfWriter(); StringCreator stringCreator = createStringCreator(); return new UTFEncoderDecoder(stringCreator, utfWriter, false); } static StringCreator createStringCreator() { boolean fastStringEnabled = Boolean.parseBoolean(System.getProperty("hazelcast.nio.faststring", "true")); return createStringCreator(fastStringEnabled); } static StringCreator createStringCreator(boolean fastStringEnabled) { return fastStringEnabled ? buildFastStringCreator() : new DefaultStringCreator(); } static UtfWriter createUtfWriter() { // Try Unsafe based implementation UnsafeBasedCharArrayUtfWriter unsafeBasedUtfWriter = new UnsafeBasedCharArrayUtfWriter(); if (unsafeBasedUtfWriter.isAvailable()) { return unsafeBasedUtfWriter; } // If Unsafe based implementation is not available for usage // Try Reflection based implementation ReflectionBasedCharArrayUtfWriter reflectionBasedUtfWriter = new ReflectionBasedCharArrayUtfWriter(); if (reflectionBasedUtfWriter.isAvailable()) { return reflectionBasedUtfWriter; } // If Reflection based implementation is not available for usage return new StringBasedUtfWriter(); } private static StringCreator buildFastStringCreator() { try { // Give access to the package private String constructor Constructor<String> constructor; if (UTFEncoderDecoder.useOldStringConstructor()) { constructor = String.class.getDeclaredConstructor(int.class, int.class, char[].class); } else { constructor = String.class.getDeclaredConstructor(char[].class, boolean.class); } if (constructor != null) { constructor.setAccessible(true); return new FastStringCreator(constructor); } } catch (Throwable t) { Logger. getLogger(UTFEncoderDecoder.class). finest("No fast string creator seems to available, falling back to reflection", t); } return null; } interface StringCreator { String buildString(final char[] chars); } private static class DefaultStringCreator implements StringCreator { @Override public String buildString(final char[] chars) { return new String(chars); } } private static class FastStringCreator implements StringCreator { private final Constructor<String> constructor; private final boolean useOldStringConstructor; public FastStringCreator(Constructor<String> constructor) { this.constructor = constructor; this.useOldStringConstructor = constructor.getParameterTypes().length == 3; } @Override public String buildString(final char[] chars) { try { if (useOldStringConstructor) { return constructor.newInstance(0, chars.length, chars); } else { return constructor.newInstance(chars, Boolean.TRUE); } } catch (Exception e) { throw new RuntimeException(e); } } } }
checkstyle fix: unused import
hazelcast/src/main/java/com/hazelcast/nio/UTFEncoderDecoder.java
checkstyle fix: unused import
Java
apache-2.0
09a6575659a18b9ee74a80569caaf6902a5b433c
0
mikepenz/MaterialDrawer,mikepenz/MaterialDrawer,yunarta/MaterialDrawer,McUsaVsUrss/MaterialDrawer,MaTriXy/MaterialDrawer,yunarta/MaterialDrawer,mychaelgo/MaterialDrawer,MaTriXy/MaterialDrawer,mikepenz/MaterialDrawer
package com.mikepenz.materialdrawer; import android.app.Activity; import android.content.Context; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.annotation.ColorInt; import android.support.annotation.ColorRes; import android.support.annotation.DimenRes; import android.support.annotation.DrawableRes; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.mikepenz.iconics.IconicsDrawable; import com.mikepenz.materialdrawer.holder.ColorHolder; import com.mikepenz.materialdrawer.holder.DimenHolder; import com.mikepenz.materialdrawer.holder.ImageHolder; import com.mikepenz.materialdrawer.holder.StringHolder; import com.mikepenz.materialdrawer.icons.MaterialDrawerFont; import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem; import com.mikepenz.materialdrawer.model.interfaces.IProfile; import com.mikepenz.materialdrawer.util.DrawerImageLoader; import com.mikepenz.materialdrawer.util.DrawerUIUtils; import com.mikepenz.materialdrawer.view.BezelImageView; import com.mikepenz.materialize.util.UIUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Stack; /** * Created by mikepenz on 23.05.15. */ public class AccountHeaderBuilder { // global references to views we need later protected View mAccountHeader; protected ImageView mAccountHeaderBackground; protected BezelImageView mCurrentProfileView; protected View mAccountHeaderTextSection; protected ImageView mAccountSwitcherArrow; protected TextView mCurrentProfileName; protected TextView mCurrentProfileEmail; protected BezelImageView mProfileFirstView; protected BezelImageView mProfileSecondView; protected BezelImageView mProfileThirdView; // global references to the profiles protected IProfile mCurrentProfile; protected IProfile mProfileFirst; protected IProfile mProfileSecond; protected IProfile mProfileThird; // global stuff protected boolean mSelectionListShown = false; protected int mAccountHeaderTextSectionBackgroundResource = -1; // the activity to use protected Activity mActivity; /** * Pass the activity you use the drawer in ;) * * @param activity * @return */ public AccountHeaderBuilder withActivity(@NonNull Activity activity) { this.mActivity = activity; return this; } // defines if we use the compactStyle protected boolean mCompactStyle = false; /** * Defines if we should use the compact style for the header. * * @param compactStyle * @return */ public AccountHeaderBuilder withCompactStyle(boolean compactStyle) { this.mCompactStyle = compactStyle; return this; } // the typeface used for textViews within the AccountHeader protected Typeface mTypeface; // the typeface used for name textView only. overrides mTypeface protected Typeface mNameTypeface; // the typeface used for email textView only. overrides mTypeface protected Typeface mEmailTypeface; /** * Define the typeface which will be used for all textViews in the AccountHeader * * @param typeface * @return */ public AccountHeaderBuilder withTypeface(@NonNull Typeface typeface) { this.mTypeface = typeface; return this; } /** * Define the typeface which will be used for name textView in the AccountHeader. * Overrides typeface supplied to {@link AccountHeaderBuilder#withTypeface(android.graphics.Typeface)} * * @param typeface * @return * @see #withTypeface(android.graphics.Typeface) */ public AccountHeaderBuilder withNameTypeface(@NonNull Typeface typeface) { this.mNameTypeface = typeface; return this; } /** * Define the typeface which will be used for email textView in the AccountHeader. * Overrides typeface supplied to {@link AccountHeaderBuilder#withTypeface(android.graphics.Typeface)} * * @param typeface * @return * @see #withTypeface(android.graphics.Typeface) */ public AccountHeaderBuilder withEmailTypeface(@NonNull Typeface typeface) { this.mEmailTypeface = typeface; return this; } // set the account header height protected DimenHolder mHeight; /** * set the height for the header * * @param heightPx * @return */ public AccountHeaderBuilder withHeightPx(int heightPx) { this.mHeight = DimenHolder.fromPixel(heightPx); return this; } /** * set the height for the header * * @param heightDp * @return */ public AccountHeaderBuilder withHeightDp(int heightDp) { this.mHeight = DimenHolder.fromDp(heightDp); return this; } /** * set the height for the header by resource * * @param heightRes * @return */ public AccountHeaderBuilder withHeightRes(@DimenRes int heightRes) { this.mHeight = DimenHolder.fromResource(heightRes); return this; } //the background color for the slider protected ColorHolder mTextColor; /** * set the background for the slider as color * * @param textColor * @return */ public AccountHeaderBuilder withTextColor(@ColorInt int textColor) { this.mTextColor = ColorHolder.fromColor(textColor); return this; } /** * set the background for the slider as resource * * @param textColorRes * @return */ public AccountHeaderBuilder withTextColorRes(@ColorRes int textColorRes) { this.mTextColor = ColorHolder.fromColorRes(textColorRes); return this; } //the current selected profile is visible in the list protected boolean mCurrentHiddenInList = false; /** * hide the current selected profile from the list * * @param currentProfileHiddenInList * @return */ public AccountHeaderBuilder withCurrentProfileHiddenInList(boolean currentProfileHiddenInList) { mCurrentHiddenInList = currentProfileHiddenInList; return this; } //set to hide the first or second line protected boolean mSelectionFirstLineShown = true; protected boolean mSelectionSecondLineShown = true; /** * set this to false if you want to hide the first line of the selection box in the header (first line would be the name) * * @param selectionFirstLineShown * @return * @deprecated replaced by {@link #withSelectionFirstLineShown} */ @Deprecated public AccountHeaderBuilder withSelectionFistLineShown(boolean selectionFirstLineShown) { this.mSelectionFirstLineShown = selectionFirstLineShown; return this; } /** * set this to false if you want to hide the first line of the selection box in the header (first line would be the name) * * @param selectionFirstLineShown * @return */ public AccountHeaderBuilder withSelectionFirstLineShown(boolean selectionFirstLineShown) { this.mSelectionFirstLineShown = selectionFirstLineShown; return this; } /** * set this to false if you want to hide the second line of the selection box in the header (second line would be the e-mail) * * @param selectionSecondLineShown * @return */ public AccountHeaderBuilder withSelectionSecondLineShown(boolean selectionSecondLineShown) { this.mSelectionSecondLineShown = selectionSecondLineShown; return this; } //set one of these to define the text in the first or second line with in the account selector protected String mSelectionFirstLine; protected String mSelectionSecondLine; /** * set this to define the first line in the selection area if there is no profile * note this will block any values from profiles! * * @param selectionFirstLine * @return */ public AccountHeaderBuilder withSelectionFirstLine(String selectionFirstLine) { this.mSelectionFirstLine = selectionFirstLine; return this; } /** * set this to define the second line in the selection area if there is no profile * note this will block any values from profiles! * * @param selectionSecondLine * @return */ public AccountHeaderBuilder withSelectionSecondLine(String selectionSecondLine) { this.mSelectionSecondLine = selectionSecondLine; return this; } // set no divider below the header protected boolean mPaddingBelowHeader = true; /** * Set this to false if you want no padding below the Header * * @param paddingBelowHeader * @return */ public AccountHeaderBuilder withPaddingBelowHeader(boolean paddingBelowHeader) { this.mPaddingBelowHeader = paddingBelowHeader; return this; } // set no divider below the header protected boolean mDividerBelowHeader = true; /** * Set this to false if you want no divider below the Header * * @param dividerBelowHeader * @return */ public AccountHeaderBuilder withDividerBelowHeader(boolean dividerBelowHeader) { this.mDividerBelowHeader = dividerBelowHeader; return this; } // set non translucent statusBar mode protected boolean mTranslucentStatusBar = true; /** * Set or disable this if you use a translucent statusbar * * @param translucentStatusBar * @return */ public AccountHeaderBuilder withTranslucentStatusBar(boolean translucentStatusBar) { this.mTranslucentStatusBar = translucentStatusBar; return this; } //the background for the header protected ImageHolder mHeaderBackground; /** * set the background for the slider as color * * @param headerBackground * @return */ public AccountHeaderBuilder withHeaderBackground(Drawable headerBackground) { this.mHeaderBackground = new ImageHolder(headerBackground); return this; } /** * set the background for the header as resource * * @param headerBackgroundRes * @return */ public AccountHeaderBuilder withHeaderBackground(@DrawableRes int headerBackgroundRes) { this.mHeaderBackground = new ImageHolder(headerBackgroundRes); return this; } /** * set the background for the header via the ImageHolder class * * @param headerBackground * @return */ public AccountHeaderBuilder withHeaderBackground(ImageHolder headerBackground) { this.mHeaderBackground = headerBackground; return this; } //background scale type protected ImageView.ScaleType mHeaderBackgroundScaleType = null; /** * define the ScaleType for the header background * * @param headerBackgroundScaleType * @return */ public AccountHeaderBuilder withHeaderBackgroundScaleType(ImageView.ScaleType headerBackgroundScaleType) { this.mHeaderBackgroundScaleType = headerBackgroundScaleType; return this; } //profile images in the header are shown or not protected boolean mProfileImagesVisible = true; /** * define if the profile images in the header are shown or not * * @param profileImagesVisible * @return */ public AccountHeaderBuilder withProfileImagesVisible(boolean profileImagesVisible) { this.mProfileImagesVisible = profileImagesVisible; return this; } //only the main profile image is visible protected boolean mOnlyMainProfileImageVisible = false; /** * define if only the main (current selected) profile image should be visible * * @param onlyMainProfileImageVisible * @return */ public AccountHeaderBuilder withOnlyMainProfileImageVisible(boolean onlyMainProfileImageVisible) { this.mOnlyMainProfileImageVisible = onlyMainProfileImageVisible; return this; } //show small profile images but hide MainProfileImage protected boolean mOnlySmallProfileImagesVisible = false; /** * define if only the small profile images should be visible * * @param onlySmallProfileImagesVisible * @return */ public AccountHeaderBuilder withOnlySmallProfileImagesVisible(boolean onlySmallProfileImagesVisible) { this.mOnlySmallProfileImagesVisible = onlySmallProfileImagesVisible; return this; } //close the drawer after a profile was clicked in the list protected Boolean mCloseDrawerOnProfileListClick = null; /** * define if the drawer should close if the user clicks on a profile item if the selection list is shown * * @param closeDrawerOnProfileListClick * @return */ public AccountHeaderBuilder withCloseDrawerOnProfileListClick(boolean closeDrawerOnProfileListClick) { this.mCloseDrawerOnProfileListClick = closeDrawerOnProfileListClick; return this; } //reset the drawer list to the main drawer list after the profile was clicked in the list protected boolean mResetDrawerOnProfileListClick = true; /** * define if the drawer selection list should be reseted after the user clicks on a profile item if the selection list is shown * * @param resetDrawerOnProfileListClick * @return */ public AccountHeaderBuilder withResetDrawerOnProfileListClick(boolean resetDrawerOnProfileListClick) { this.mResetDrawerOnProfileListClick = resetDrawerOnProfileListClick; return this; } // set the profile images clickable or not protected boolean mProfileImagesClickable = true; /** * enable or disable the profile images to be clickable * * @param profileImagesClickable * @return */ public AccountHeaderBuilder withProfileImagesClickable(boolean profileImagesClickable) { this.mProfileImagesClickable = profileImagesClickable; return this; } // set to use the alternative profile header switching protected boolean mAlternativeProfileHeaderSwitching = false; /** * enable the alternative profile header switching * * @param alternativeProfileHeaderSwitching * @return */ public AccountHeaderBuilder withAlternativeProfileHeaderSwitching(boolean alternativeProfileHeaderSwitching) { this.mAlternativeProfileHeaderSwitching = alternativeProfileHeaderSwitching; return this; } // enable 3 small header previews protected boolean mThreeSmallProfileImages = false; /** * enable the extended profile icon view with 3 small header images instead of two * * @param threeSmallProfileImages * @return */ public AccountHeaderBuilder withThreeSmallProfileImages(boolean threeSmallProfileImages) { this.mThreeSmallProfileImages = threeSmallProfileImages; return this; } //the delay which is waited before the drawer is closed protected int mOnProfileClickDrawerCloseDelay = 100; /** * Define the delay for the drawer close operation after a click. * This is a small trick to improve the speed (and remove lag) if you open a new activity after a DrawerItem * was selected. * NOTE: Disable this by passing -1 * * @param onProfileClickDrawerCloseDelay the delay in MS (-1 to disable) * @return */ public AccountHeaderBuilder withOnProfileClickDrawerCloseDelay(int onProfileClickDrawerCloseDelay) { this.mOnProfileClickDrawerCloseDelay = onProfileClickDrawerCloseDelay; return this; } // the onAccountHeaderProfileImageListener to set protected AccountHeader.OnAccountHeaderProfileImageListener mOnAccountHeaderProfileImageListener; /** * set click / longClick listener for the header images * * @param onAccountHeaderProfileImageListener * @return */ public AccountHeaderBuilder withOnAccountHeaderProfileImageListener(AccountHeader.OnAccountHeaderProfileImageListener onAccountHeaderProfileImageListener) { this.mOnAccountHeaderProfileImageListener = onAccountHeaderProfileImageListener; return this; } // the onAccountHeaderSelectionListener to set protected AccountHeader.OnAccountHeaderSelectionViewClickListener mOnAccountHeaderSelectionViewClickListener; /** * set a onSelection listener for the selection box * * @param onAccountHeaderSelectionViewClickListener * @return */ public AccountHeaderBuilder withOnAccountHeaderSelectionViewClickListener(AccountHeader.OnAccountHeaderSelectionViewClickListener onAccountHeaderSelectionViewClickListener) { this.mOnAccountHeaderSelectionViewClickListener = onAccountHeaderSelectionViewClickListener; return this; } //set the selection list enabled if there is only a single profile protected boolean mSelectionListEnabledForSingleProfile = true; /** * enable or disable the selection list if there is only a single profile * * @param selectionListEnabledForSingleProfile * @return */ public AccountHeaderBuilder withSelectionListEnabledForSingleProfile(boolean selectionListEnabledForSingleProfile) { this.mSelectionListEnabledForSingleProfile = selectionListEnabledForSingleProfile; return this; } //set the selection enabled disabled protected boolean mSelectionListEnabled = true; /** * enable or disable the selection list * * @param selectionListEnabled * @return */ public AccountHeaderBuilder withSelectionListEnabled(boolean selectionListEnabled) { this.mSelectionListEnabled = selectionListEnabled; return this; } // the drawerLayout to use protected View mAccountHeaderContainer; /** * You can pass a custom view for the drawer lib. note this requires the same structure as the drawer.xml * * @param accountHeader * @return */ public AccountHeaderBuilder withAccountHeader(@NonNull View accountHeader) { this.mAccountHeaderContainer = accountHeader; return this; } /** * You can pass a custom layout for the drawer lib. see the drawer.xml in layouts of this lib on GitHub * * @param resLayout * @return */ public AccountHeaderBuilder withAccountHeader(@LayoutRes int resLayout) { if (mActivity == null) { throw new RuntimeException("please pass an activity first to use this call"); } if (resLayout != -1) { this.mAccountHeaderContainer = mActivity.getLayoutInflater().inflate(resLayout, null, false); } else { if (mCompactStyle) { this.mAccountHeaderContainer = mActivity.getLayoutInflater().inflate(R.layout.material_drawer_compact_header, null, false); } else { this.mAccountHeaderContainer = mActivity.getLayoutInflater().inflate(R.layout.material_drawer_header, null, false); } } return this; } // the profiles to display protected ArrayList<IProfile> mProfiles; /** * set the arrayList of DrawerItems for the drawer * * @param profiles * @return */ public AccountHeaderBuilder withProfiles(@NonNull ArrayList<IProfile> profiles) { this.mProfiles = profiles; return this; } /** * add single ore more DrawerItems to the Drawer * * @param profiles * @return */ public AccountHeaderBuilder addProfiles(@NonNull IProfile... profiles) { if (this.mProfiles == null) { this.mProfiles = new ArrayList<>(); } Collections.addAll(this.mProfiles, profiles); return this; } // the click listener to be fired on profile or selection click protected AccountHeader.OnAccountHeaderListener mOnAccountHeaderListener; /** * add a listener for the accountHeader * * @param onAccountHeaderListener * @return */ public AccountHeaderBuilder withOnAccountHeaderListener(AccountHeader.OnAccountHeaderListener onAccountHeaderListener) { this.mOnAccountHeaderListener = onAccountHeaderListener; return this; } //the on long click listener to be fired on profile longClick inside the list protected AccountHeader.OnAccountHeaderItemLongClickListener mOnAccountHeaderItemLongClickListener; /** * the on long click listener to be fired on profile longClick inside the list * * @param onAccountHeaderItemLongClickListener * @return */ public AccountHeaderBuilder withOnAccountHeaderItemLongClickListener(AccountHeader.OnAccountHeaderItemLongClickListener onAccountHeaderItemLongClickListener) { this.mOnAccountHeaderItemLongClickListener = onAccountHeaderItemLongClickListener; return this; } // the drawer to set the AccountSwitcher for protected Drawer mDrawer; /** * @param drawer * @return */ public AccountHeaderBuilder withDrawer(@NonNull Drawer drawer) { this.mDrawer = drawer; return this; } // savedInstance to restore state protected Bundle mSavedInstance; /** * create the drawer with the values of a savedInstance * * @param savedInstance * @return */ public AccountHeaderBuilder withSavedInstance(Bundle savedInstance) { this.mSavedInstance = savedInstance; return this; } /** * helper method to set the height for the header! * * @param height */ private void setHeaderHeight(int height) { if (mAccountHeaderContainer != null) { ViewGroup.LayoutParams params = mAccountHeaderContainer.getLayoutParams(); if (params != null) { params.height = height; mAccountHeaderContainer.setLayoutParams(params); } View accountHeader = mAccountHeaderContainer.findViewById(R.id.material_drawer_account_header); if (accountHeader != null) { params = accountHeader.getLayoutParams(); params.height = height; accountHeader.setLayoutParams(params); } View accountHeaderBackground = mAccountHeaderContainer.findViewById(R.id.material_drawer_account_header_background); if (accountHeaderBackground != null) { params = accountHeaderBackground.getLayoutParams(); params.height = height; accountHeaderBackground.setLayoutParams(params); } } } /** * a small helper to handle the selectionView * * @param on */ private void handleSelectionView(IProfile profile, boolean on) { if (on) { if (Build.VERSION.SDK_INT >= 21) { ((FrameLayout) mAccountHeaderContainer).setForeground(UIUtils.getCompatDrawable(mAccountHeaderContainer.getContext(), mAccountHeaderTextSectionBackgroundResource)); mAccountHeaderContainer.setOnClickListener(onSelectionClickListener); mAccountHeaderContainer.setTag(R.id.material_drawer_profile_header, profile); } else { mAccountHeaderTextSection.setBackgroundResource(mAccountHeaderTextSectionBackgroundResource); mAccountHeaderTextSection.setOnClickListener(onSelectionClickListener); mAccountHeaderTextSection.setTag(R.id.material_drawer_profile_header, profile); } } else { if (Build.VERSION.SDK_INT >= 21) { ((FrameLayout) mAccountHeaderContainer).setForeground(null); mAccountHeaderContainer.setOnClickListener(null); } else { UIUtils.setBackground(mAccountHeaderTextSection, null); mAccountHeaderTextSection.setOnClickListener(null); } } } /** * method to build the header view * * @return */ public AccountHeader build() { // if the user has not set a accountHeader use the default one :D if (mAccountHeaderContainer == null) { withAccountHeader(-1); } // get the header view within the container mAccountHeader = mAccountHeaderContainer.findViewById(R.id.material_drawer_account_header); //the default min header height by default 148dp int defaultHeaderMinHeight = mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_account_header_height); int statusBarHeight = UIUtils.getStatusBarHeight(mActivity, true); // handle the height for the header int height; if (mHeight != null) { height = mHeight.asPixel(mActivity); } else { if (mCompactStyle) { height = mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_account_header_height_compact); } else { //calculate the header height by getting the optimal drawer width and calculating it * 9 / 16 height = (int) (DrawerUIUtils.getOptimalDrawerWidth(mActivity) * AccountHeader.NAVIGATION_DRAWER_ACCOUNT_ASPECT_RATIO); //if we are lower than api 19 (>= 19 we have a translucentStatusBar) the height should be a bit lower //probably even if we are non translucent on > 19 devices? if (Build.VERSION.SDK_INT < 19) { int tempHeight = height - statusBarHeight; //if we are lower than api 19 we are not able to have a translucent statusBar so we remove the height of the statusBar from the padding //to prevent display issues we only reduce the height if we still fit the required minHeight of 148dp (R.dimen.material_drawer_account_header_height) //we remove additional 8dp from the defaultMinHeaderHeight as there is some buffer in the header and to prevent to large spacings if (tempHeight > defaultHeaderMinHeight - UIUtils.convertDpToPixel(8, mActivity)) { height = tempHeight; } } } } // handle everything if we have a translucent status bar which only is possible on API >= 19 if (mTranslucentStatusBar && Build.VERSION.SDK_INT >= 19) { mAccountHeader.setPadding(mAccountHeader.getPaddingLeft(), mAccountHeader.getPaddingTop() + statusBarHeight, mAccountHeader.getPaddingRight(), mAccountHeader.getPaddingBottom()); //in fact it makes no difference if we have a translucent statusBar or not. we want 9/16 just if we are not compact if (mCompactStyle) { height = height + statusBarHeight; } else if ((height - statusBarHeight) <= defaultHeaderMinHeight) { //if the height + statusBar of the header is lower than the required 148dp + statusBar we change the height to be able to display all the data height = defaultHeaderMinHeight + statusBarHeight; } } //set the height for the header setHeaderHeight(height); // get the background view mAccountHeaderBackground = (ImageView) mAccountHeaderContainer.findViewById(R.id.material_drawer_account_header_background); // set the background ImageHolder.applyTo(mHeaderBackground, mAccountHeaderBackground, DrawerImageLoader.Tags.ACCOUNT_HEADER.name()); if (mHeaderBackgroundScaleType != null) { mAccountHeaderBackground.setScaleType(mHeaderBackgroundScaleType); } // get the text color to use for the text section int textColor = ColorHolder.color(mTextColor, mActivity, R.attr.material_drawer_header_selection_text, R.color.material_drawer_header_selection_text); // set the background for the section if (mCompactStyle) { mAccountHeaderTextSection = mAccountHeader; } else { mAccountHeaderTextSection = mAccountHeaderContainer.findViewById(R.id.material_drawer_account_header_text_section); } mAccountHeaderTextSectionBackgroundResource = DrawerUIUtils.getSelectableBackground(mActivity); handleSelectionView(mCurrentProfile, true); // set the arrow :D mAccountSwitcherArrow = (ImageView) mAccountHeaderContainer.findViewById(R.id.material_drawer_account_header_text_switcher); mAccountSwitcherArrow.setImageDrawable(new IconicsDrawable(mActivity, MaterialDrawerFont.Icon.mdf_arrow_drop_down).sizeRes(R.dimen.material_drawer_account_header_dropdown).paddingRes(R.dimen.material_drawer_account_header_dropdown_padding).color(textColor)); //get the fields for the name mCurrentProfileView = (BezelImageView) mAccountHeader.findViewById(R.id.material_drawer_account_header_current); mCurrentProfileName = (TextView) mAccountHeader.findViewById(R.id.material_drawer_account_header_name); mCurrentProfileEmail = (TextView) mAccountHeader.findViewById(R.id.material_drawer_account_header_email); //set the typeface for the AccountHeader if (mNameTypeface != null) { mCurrentProfileName.setTypeface(mNameTypeface); } else if (mTypeface != null) { mCurrentProfileName.setTypeface(mTypeface); } if (mEmailTypeface != null) { mCurrentProfileEmail.setTypeface(mEmailTypeface); } else if (mTypeface != null) { mCurrentProfileEmail.setTypeface(mTypeface); } mCurrentProfileName.setTextColor(textColor); mCurrentProfileEmail.setTextColor(textColor); mProfileFirstView = (BezelImageView) mAccountHeader.findViewById(R.id.material_drawer_account_header_small_first); mProfileSecondView = (BezelImageView) mAccountHeader.findViewById(R.id.material_drawer_account_header_small_second); mProfileThirdView = (BezelImageView) mAccountHeader.findViewById(R.id.material_drawer_account_header_small_third); //calculate the profiles to set calculateProfiles(); //process and build the profiles buildProfiles(); // try to restore all saved values again if (mSavedInstance != null) { int selection = mSavedInstance.getInt(AccountHeader.BUNDLE_SELECTION_HEADER, -1); if (selection != -1) { //predefine selection (should be the first element if (mProfiles != null && (selection) > -1 && selection < mProfiles.size()) { switchProfiles(mProfiles.get(selection)); } } } //everything created. now set the header if (mDrawer != null) { mDrawer.setHeader(mAccountHeaderContainer, mPaddingBelowHeader, mDividerBelowHeader); } //forget the reference to the activity mActivity = null; return new AccountHeader(this); } /** * helper method to calculate the order of the profiles */ protected void calculateProfiles() { if (mProfiles == null) { mProfiles = new ArrayList<>(); } if (mCurrentProfile == null) { int setCount = 0; for (int i = 0; i < mProfiles.size(); i++) { if (mProfiles.size() > i && mProfiles.get(i).isSelectable()) { if (setCount == 0 && (mCurrentProfile == null)) { mCurrentProfile = mProfiles.get(i); } else if (setCount == 1 && (mProfileFirst == null)) { mProfileFirst = mProfiles.get(i); } else if (setCount == 2 && (mProfileSecond == null)) { mProfileSecond = mProfiles.get(i); } else if (setCount == 3 && (mProfileThird == null)) { mProfileThird = mProfiles.get(i); } setCount++; } } return; } IProfile[] previousActiveProfiles = new IProfile[]{ mCurrentProfile, mProfileFirst, mProfileSecond, mProfileThird }; IProfile[] newActiveProfiles = new IProfile[4]; Stack<IProfile> unusedProfiles = new Stack<>(); // try to keep existing active profiles in the same positions for (int i = 0; i < mProfiles.size(); i++) { IProfile p = mProfiles.get(i); if (p.isSelectable()) { boolean used = false; for (int j = 0; j < 4; j++) { if (previousActiveProfiles[j] == p) { newActiveProfiles[j] = p; used = true; break; } } if (!used) { unusedProfiles.push(p); } } } Stack<IProfile> activeProfiles = new Stack<>(); // try to fill the gaps with new available profiles for (int i = 0; i < 4; i++) { if (newActiveProfiles[i] != null) { activeProfiles.push(newActiveProfiles[i]); } else if (!unusedProfiles.isEmpty()) { activeProfiles.push(unusedProfiles.pop()); } } Stack<IProfile> reversedActiveProfiles = new Stack<>(); while (!activeProfiles.empty()) { reversedActiveProfiles.push(activeProfiles.pop()); } // reassign active profiles if (reversedActiveProfiles.isEmpty()) { mCurrentProfile = null; } else { mCurrentProfile = reversedActiveProfiles.pop(); } if (reversedActiveProfiles.isEmpty()) { mProfileFirst = null; } else { mProfileFirst = reversedActiveProfiles.pop(); } if (reversedActiveProfiles.isEmpty()) { mProfileSecond = null; } else { mProfileSecond = reversedActiveProfiles.pop(); } if (reversedActiveProfiles.isEmpty()) { mProfileThird = null; } else { mProfileThird = reversedActiveProfiles.pop(); } } /** * helper method to switch the profiles * * @param newSelection * @return true if the new selection was the current profile */ protected boolean switchProfiles(IProfile newSelection) { if (newSelection == null) { return false; } if (mCurrentProfile == newSelection) { return true; } if (mAlternativeProfileHeaderSwitching) { int prevSelection = -1; if (mProfileFirst == newSelection) { prevSelection = 1; } else if (mProfileSecond == newSelection) { prevSelection = 2; } else if (mProfileThird == newSelection) { prevSelection = 3; } IProfile tmp = mCurrentProfile; mCurrentProfile = newSelection; if (prevSelection == 1) { mProfileFirst = tmp; } else if (prevSelection == 2) { mProfileSecond = tmp; } else if (prevSelection == 3) { mProfileThird = tmp; } } else { if (mProfiles != null) { ArrayList<IProfile> previousActiveProfiles = new ArrayList<>(Arrays.asList(mCurrentProfile, mProfileFirst, mProfileSecond, mProfileThird)); if (previousActiveProfiles.contains(newSelection)) { int position = -1; for (int i = 0; i < 4; i++) { if (previousActiveProfiles.get(i) == newSelection) { position = i; break; } } if (position != -1) { previousActiveProfiles.remove(position); previousActiveProfiles.add(0, newSelection); mCurrentProfile = previousActiveProfiles.get(0); mProfileFirst = previousActiveProfiles.get(1); mProfileSecond = previousActiveProfiles.get(2); mProfileThird = previousActiveProfiles.get(3); } } else { mProfileThird = mProfileSecond; mProfileSecond = mProfileFirst; mProfileFirst = mCurrentProfile; mCurrentProfile = newSelection; } } } //if we only show the small profile images we have to make sure the first (would be the current selected) profile is also shown if (mOnlySmallProfileImagesVisible) { mProfileThird = mProfileSecond; mProfileSecond = mProfileFirst; mProfileFirst = mCurrentProfile; mCurrentProfile = mProfileThird; } buildProfiles(); return false; } /** * helper method to build the views for the ui */ protected void buildProfiles() { mCurrentProfileView.setVisibility(View.INVISIBLE); mAccountHeaderTextSection.setVisibility(View.INVISIBLE); mAccountSwitcherArrow.setVisibility(View.INVISIBLE); mProfileFirstView.setVisibility(View.GONE); mProfileFirstView.setOnClickListener(null); mProfileSecondView.setVisibility(View.GONE); mProfileSecondView.setOnClickListener(null); mProfileThirdView.setVisibility(View.GONE); mProfileThirdView.setOnClickListener(null); mCurrentProfileName.setText(""); mCurrentProfileEmail.setText(""); handleSelectionView(mCurrentProfile, true); if (mCurrentProfile != null) { if ((mProfileImagesVisible || mOnlyMainProfileImageVisible) && !mOnlySmallProfileImagesVisible) { setImageOrPlaceholder(mCurrentProfileView, mCurrentProfile.getIcon()); if (mProfileImagesClickable) { mCurrentProfileView.setOnClickListener(onCurrentProfileClickListener); mCurrentProfileView.setOnLongClickListener(onCurrentProfileLongClickListener); mCurrentProfileView.disableTouchFeedback(false); } else { mCurrentProfileView.disableTouchFeedback(true); } mCurrentProfileView.setVisibility(View.VISIBLE); mCurrentProfileView.invalidate(); } else if (mCompactStyle) { mCurrentProfileView.setVisibility(View.GONE); } mAccountHeaderTextSection.setVisibility(View.VISIBLE); handleSelectionView(mCurrentProfile, true); mAccountSwitcherArrow.setVisibility(View.VISIBLE); mCurrentProfileView.setTag(R.id.material_drawer_profile_header, mCurrentProfile); StringHolder.applyTo(mCurrentProfile.getName(), mCurrentProfileName); StringHolder.applyTo(mCurrentProfile.getEmail(), mCurrentProfileEmail); if (mProfileFirst != null && mProfileImagesVisible && !mOnlyMainProfileImageVisible) { setImageOrPlaceholder(mProfileFirstView, mProfileFirst.getIcon()); mProfileFirstView.setTag(R.id.material_drawer_profile_header, mProfileFirst); if (mProfileImagesClickable) { mProfileFirstView.setOnClickListener(onProfileClickListener); mProfileFirstView.setOnLongClickListener(onProfileLongClickListener); mProfileFirstView.disableTouchFeedback(false); } else { mProfileFirstView.disableTouchFeedback(true); } mProfileFirstView.setVisibility(View.VISIBLE); mProfileFirstView.invalidate(); } if (mProfileSecond != null && mProfileImagesVisible && !mOnlyMainProfileImageVisible) { setImageOrPlaceholder(mProfileSecondView, mProfileSecond.getIcon()); mProfileSecondView.setTag(R.id.material_drawer_profile_header, mProfileSecond); if (mProfileImagesClickable) { mProfileSecondView.setOnClickListener(onProfileClickListener); mProfileSecondView.setOnLongClickListener(onProfileLongClickListener); mProfileSecondView.disableTouchFeedback(false); } else { mProfileSecondView.disableTouchFeedback(true); } mProfileSecondView.setVisibility(View.VISIBLE); mProfileSecondView.invalidate(); } if (mProfileThird != null && mThreeSmallProfileImages && mProfileImagesVisible && !mOnlyMainProfileImageVisible) { setImageOrPlaceholder(mProfileThirdView, mProfileThird.getIcon()); mProfileThirdView.setTag(R.id.material_drawer_profile_header, mProfileThird); if (mProfileImagesClickable) { mProfileThirdView.setOnClickListener(onProfileClickListener); mProfileThirdView.setOnLongClickListener(onProfileLongClickListener); mProfileThirdView.disableTouchFeedback(false); } else { mProfileThirdView.disableTouchFeedback(true); } mProfileThirdView.setVisibility(View.VISIBLE); mProfileThirdView.invalidate(); } } else if (mProfiles != null && mProfiles.size() > 0) { IProfile profile = mProfiles.get(0); mAccountHeaderTextSection.setTag(R.id.material_drawer_profile_header, profile); mAccountHeaderTextSection.setVisibility(View.VISIBLE); handleSelectionView(mCurrentProfile, true); mAccountSwitcherArrow.setVisibility(View.VISIBLE); if (mCurrentProfile != null) { StringHolder.applyTo(mCurrentProfile.getName(), mCurrentProfileName); StringHolder.applyTo(mCurrentProfile.getEmail(), mCurrentProfileEmail); } } if (!mSelectionFirstLineShown) { mCurrentProfileName.setVisibility(View.GONE); } if (!TextUtils.isEmpty(mSelectionFirstLine)) { mCurrentProfileName.setText(mSelectionFirstLine); mAccountHeaderTextSection.setVisibility(View.VISIBLE); } if (!mSelectionSecondLineShown) { mCurrentProfileEmail.setVisibility(View.GONE); } if (!TextUtils.isEmpty(mSelectionSecondLine)) { mCurrentProfileEmail.setText(mSelectionSecondLine); mAccountHeaderTextSection.setVisibility(View.VISIBLE); } //if we disabled the list if (!mSelectionListEnabled) { mAccountSwitcherArrow.setVisibility(View.INVISIBLE); handleSelectionView(null, false); } if (!mSelectionListEnabledForSingleProfile && mProfileFirst == null && (mProfiles == null || mProfiles.size() == 1)) { mAccountSwitcherArrow.setVisibility(View.INVISIBLE); handleSelectionView(null, false); } //if we disabled the list but still have set a custom listener if (mOnAccountHeaderSelectionViewClickListener != null) { handleSelectionView(mCurrentProfile, true); } } /** * small helper method to set an profile image or a placeholder * * @param iv * @param imageHolder */ private void setImageOrPlaceholder(ImageView iv, ImageHolder imageHolder) { //cancel previous started image loading processes DrawerImageLoader.getInstance().cancelImage(iv); //set the placeholder iv.setImageDrawable(DrawerUIUtils.getPlaceHolder(iv.getContext())); //set the real image (probably also the uri) ImageHolder.applyTo(imageHolder, iv, DrawerImageLoader.Tags.PROFILE.name()); } /** * onProfileClickListener to notify onClick on the current profile image */ private View.OnClickListener onCurrentProfileClickListener = new View.OnClickListener() { @Override public void onClick(final View v) { onProfileImageClick(v, true); } }; /** * onProfileClickListener to notify onClick on a profile image */ private View.OnClickListener onProfileClickListener = new View.OnClickListener() { @Override public void onClick(final View v) { onProfileImageClick(v, false); } }; /** * calls the mOnAccountHEaderProfileImageListener and continues with the actions afterwards * * @param v * @param current */ private void onProfileImageClick(View v, boolean current) { IProfile profile = (IProfile) v.getTag(R.id.material_drawer_profile_header); boolean consumed = false; if (mOnAccountHeaderProfileImageListener != null) { consumed = mOnAccountHeaderProfileImageListener.onProfileImageClick(v, profile, current); } //if the event was already consumed by the click don't continue. note that this will also stop the profile change event if (!consumed) { onProfileClick(v, current); } } /** * onProfileLongClickListener to call the onProfileImageLongClick on the current profile image */ private View.OnLongClickListener onCurrentProfileLongClickListener = new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (mOnAccountHeaderProfileImageListener != null) { IProfile profile = (IProfile) v.getTag(R.id.material_drawer_profile_header); return mOnAccountHeaderProfileImageListener.onProfileImageLongClick(v, profile, true); } return false; } }; /** * onProfileLongClickListener to call the onProfileImageLongClick on a profile image */ private View.OnLongClickListener onProfileLongClickListener = new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (mOnAccountHeaderProfileImageListener != null) { IProfile profile = (IProfile) v.getTag(R.id.material_drawer_profile_header); return mOnAccountHeaderProfileImageListener.onProfileImageLongClick(v, profile, false); } return false; } }; protected void onProfileClick(View v, boolean current) { final IProfile profile = (IProfile) v.getTag(R.id.material_drawer_profile_header); switchProfiles(profile); //reset the drawer content resetDrawerContent(v.getContext()); //notify the MiniDrawer about the clicked profile (only if one exists and is hooked to the Drawer if (mDrawer != null && mDrawer.getDrawerBuilder() != null && mDrawer.getDrawerBuilder().mMiniDrawer != null) { mDrawer.getDrawerBuilder().mMiniDrawer.onProfileClick(); } //notify about the changed profile boolean consumed = false; if (mOnAccountHeaderListener != null) { consumed = mOnAccountHeaderListener.onProfileChanged(v, profile, current); } if (!consumed) { if (mOnProfileClickDrawerCloseDelay > 0) { new Handler().postDelayed(new Runnable() { @Override public void run() { if (mDrawer != null) { mDrawer.closeDrawer(); } } }, mOnProfileClickDrawerCloseDelay); } else { if (mDrawer != null) { mDrawer.closeDrawer(); } } } } /** * get the current selection * * @return */ protected int getCurrentSelection() { if (mCurrentProfile != null && mProfiles != null) { int i = 0; for (IProfile profile : mProfiles) { if (profile == mCurrentProfile) { return i; } i++; } } return -1; } /** * onSelectionClickListener to notify the onClick on the checkbox */ private View.OnClickListener onSelectionClickListener = new View.OnClickListener() { @Override public void onClick(View v) { boolean consumed = false; if (mOnAccountHeaderSelectionViewClickListener != null) { consumed = mOnAccountHeaderSelectionViewClickListener.onClick(v, (IProfile) v.getTag(R.id.material_drawer_profile_header)); } if (mAccountSwitcherArrow.getVisibility() == View.VISIBLE && !consumed) { toggleSelectionList(v.getContext()); } } }; /** * helper method to toggle the collection * * @param ctx */ protected void toggleSelectionList(Context ctx) { if (mDrawer != null) { //if we already show the list. reset everything instead if (mDrawer.switchedDrawerContent()) { resetDrawerContent(ctx); mSelectionListShown = false; } else { //build and set the drawer selection list buildDrawerSelectionList(); // update the arrow image within the drawer mAccountSwitcherArrow.setImageDrawable(new IconicsDrawable(ctx, MaterialDrawerFont.Icon.mdf_arrow_drop_up).sizeRes(R.dimen.material_drawer_account_header_dropdown).paddingRes(R.dimen.material_drawer_account_header_dropdown_padding).color(ColorHolder.color(mTextColor, ctx, R.attr.material_drawer_header_selection_text, R.color.material_drawer_header_selection_text))); mSelectionListShown = true; } } } /** * helper method to build and set the drawer selection list */ protected void buildDrawerSelectionList() { int selectedPosition = -1; int position = 0; ArrayList<IDrawerItem> profileDrawerItems = new ArrayList<>(); if (mProfiles != null) { for (IProfile profile : mProfiles) { if (profile == mCurrentProfile) { if (mCurrentHiddenInList) { continue; } else { selectedPosition = mDrawer.mDrawerBuilder.getItemAdapter().getGlobalPosition(position); } } if (profile instanceof IDrawerItem) { ((IDrawerItem) profile).withSetSelected(false); profileDrawerItems.add((IDrawerItem) profile); } position = position + 1; } } mDrawer.switchDrawerContent(onDrawerItemClickListener, onDrawerItemLongClickListener, profileDrawerItems, selectedPosition); } /** * onDrawerItemClickListener to catch the selection for the new profile! */ private Drawer.OnDrawerItemClickListener onDrawerItemClickListener = new Drawer.OnDrawerItemClickListener() { @Override public boolean onItemClick(final View view, int position, final IDrawerItem drawerItem) { final boolean isCurrentSelectedProfile; if (drawerItem != null && drawerItem instanceof IProfile && drawerItem.isSelectable()) { isCurrentSelectedProfile = switchProfiles((IProfile) drawerItem); } else { isCurrentSelectedProfile = false; } if (mResetDrawerOnProfileListClick) { mDrawer.setOnDrawerItemClickListener(null); } //wrap the onSelection call and the reset stuff within a handler to prevent lag if (mResetDrawerOnProfileListClick && mDrawer != null && view != null && view.getContext() != null) { resetDrawerContent(view.getContext()); } //notify the MiniDrawer about the clicked profile (only if one exists and is hooked to the Drawer if (mDrawer != null && mDrawer.getDrawerBuilder() != null && mDrawer.getDrawerBuilder().mMiniDrawer != null) { mDrawer.getDrawerBuilder().mMiniDrawer.onProfileClick(); } boolean consumed = false; if (drawerItem != null && drawerItem instanceof IProfile) { if (mOnAccountHeaderListener != null) { consumed = mOnAccountHeaderListener.onProfileChanged(view, (IProfile) drawerItem, isCurrentSelectedProfile); } } //if a custom behavior was chosen via the CloseDrawerOnProfileListClick then use this. else react on the result of the onProfileChanged listener if (mCloseDrawerOnProfileListClick != null) { return !mCloseDrawerOnProfileListClick; } else { return consumed; } } }; /** * onDrawerItemLongClickListener to catch the longClick for a profile */ private Drawer.OnDrawerItemLongClickListener onDrawerItemLongClickListener = new Drawer.OnDrawerItemLongClickListener() { @Override public boolean onItemLongClick(View view, int position, IDrawerItem drawerItem) { //if a longClickListener was defined use it if (mOnAccountHeaderItemLongClickListener != null) { final boolean isCurrentSelectedProfile; isCurrentSelectedProfile = drawerItem != null && drawerItem.isSelected(); if (drawerItem != null && drawerItem instanceof IProfile) { return mOnAccountHeaderItemLongClickListener.onProfileLongClick(view, (IProfile) drawerItem, isCurrentSelectedProfile); } } return false; } }; /** * helper method to reset the drawer content */ private void resetDrawerContent(Context ctx) { if (mDrawer != null) { mDrawer.resetDrawerContent(); } mAccountSwitcherArrow.setImageDrawable(new IconicsDrawable(ctx, MaterialDrawerFont.Icon.mdf_arrow_drop_down).sizeRes(R.dimen.material_drawer_account_header_dropdown).paddingRes(R.dimen.material_drawer_account_header_dropdown_padding).color(ColorHolder.color(mTextColor, ctx, R.attr.material_drawer_header_selection_text, R.color.material_drawer_header_selection_text))); } /** * small helper class to update the header and the list */ protected void updateHeaderAndList() { //recalculate the profiles calculateProfiles(); //update the profiles in the header buildProfiles(); //if we currently show the list add the new item directly to it if (mSelectionListShown) { buildDrawerSelectionList(); } } }
library/src/main/java/com/mikepenz/materialdrawer/AccountHeaderBuilder.java
package com.mikepenz.materialdrawer; import android.app.Activity; import android.content.Context; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.annotation.ColorInt; import android.support.annotation.ColorRes; import android.support.annotation.DimenRes; import android.support.annotation.DrawableRes; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.mikepenz.iconics.IconicsDrawable; import com.mikepenz.materialdrawer.holder.ColorHolder; import com.mikepenz.materialdrawer.holder.DimenHolder; import com.mikepenz.materialdrawer.holder.ImageHolder; import com.mikepenz.materialdrawer.holder.StringHolder; import com.mikepenz.materialdrawer.icons.MaterialDrawerFont; import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem; import com.mikepenz.materialdrawer.model.interfaces.IProfile; import com.mikepenz.materialdrawer.util.DrawerImageLoader; import com.mikepenz.materialdrawer.util.DrawerUIUtils; import com.mikepenz.materialdrawer.view.BezelImageView; import com.mikepenz.materialize.util.UIUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Stack; /** * Created by mikepenz on 23.05.15. */ public class AccountHeaderBuilder { // global references to views we need later protected View mAccountHeader; protected ImageView mAccountHeaderBackground; protected BezelImageView mCurrentProfileView; protected View mAccountHeaderTextSection; protected ImageView mAccountSwitcherArrow; protected TextView mCurrentProfileName; protected TextView mCurrentProfileEmail; protected BezelImageView mProfileFirstView; protected BezelImageView mProfileSecondView; protected BezelImageView mProfileThirdView; // global references to the profiles protected IProfile mCurrentProfile; protected IProfile mProfileFirst; protected IProfile mProfileSecond; protected IProfile mProfileThird; // global stuff protected boolean mSelectionListShown = false; protected int mAccountHeaderTextSectionBackgroundResource = -1; // the activity to use protected Activity mActivity; /** * Pass the activity you use the drawer in ;) * * @param activity * @return */ public AccountHeaderBuilder withActivity(@NonNull Activity activity) { this.mActivity = activity; return this; } // defines if we use the compactStyle protected boolean mCompactStyle = false; /** * Defines if we should use the compact style for the header. * * @param compactStyle * @return */ public AccountHeaderBuilder withCompactStyle(boolean compactStyle) { this.mCompactStyle = compactStyle; return this; } // the typeface used for textViews within the AccountHeader protected Typeface mTypeface; // the typeface used for name textView only. overrides mTypeface protected Typeface mNameTypeface; // the typeface used for email textView only. overrides mTypeface protected Typeface mEmailTypeface; /** * Define the typeface which will be used for all textViews in the AccountHeader * * @param typeface * @return */ public AccountHeaderBuilder withTypeface(@NonNull Typeface typeface) { this.mTypeface = typeface; return this; } /** * Define the typeface which will be used for name textView in the AccountHeader. * Overrides typeface supplied to {@link AccountHeaderBuilder#withTypeface(android.graphics.Typeface)} * * @param typeface * @return * @see #withTypeface(android.graphics.Typeface) */ public AccountHeaderBuilder withNameTypeface(@NonNull Typeface typeface) { this.mNameTypeface = typeface; return this; } /** * Define the typeface which will be used for email textView in the AccountHeader. * Overrides typeface supplied to {@link AccountHeaderBuilder#withTypeface(android.graphics.Typeface)} * * @param typeface * @return * @see #withTypeface(android.graphics.Typeface) */ public AccountHeaderBuilder withEmailTypeface(@NonNull Typeface typeface) { this.mEmailTypeface = typeface; return this; } // set the account header height protected DimenHolder mHeight; /** * set the height for the header * * @param heightPx * @return */ public AccountHeaderBuilder withHeightPx(int heightPx) { this.mHeight = DimenHolder.fromPixel(heightPx); return this; } /** * set the height for the header * * @param heightDp * @return */ public AccountHeaderBuilder withHeightDp(int heightDp) { this.mHeight = DimenHolder.fromDp(heightDp); return this; } /** * set the height for the header by resource * * @param heightRes * @return */ public AccountHeaderBuilder withHeightRes(@DimenRes int heightRes) { this.mHeight = DimenHolder.fromResource(heightRes); return this; } //the background color for the slider protected ColorHolder mTextColor; /** * set the background for the slider as color * * @param textColor * @return */ public AccountHeaderBuilder withTextColor(@ColorInt int textColor) { this.mTextColor = ColorHolder.fromColor(textColor); return this; } /** * set the background for the slider as resource * * @param textColorRes * @return */ public AccountHeaderBuilder withTextColorRes(@ColorRes int textColorRes) { this.mTextColor = ColorHolder.fromColorRes(textColorRes); return this; } //the current selected profile is visible in the list protected boolean mCurrentHiddenInList = false; /** * hide the current selected profile from the list * * @param currentProfileHiddenInList * @return */ public AccountHeaderBuilder withCurrentProfileHiddenInList(boolean currentProfileHiddenInList) { mCurrentHiddenInList = currentProfileHiddenInList; return this; } //set to hide the first or second line protected boolean mSelectionFirstLineShown = true; protected boolean mSelectionSecondLineShown = true; /** * set this to false if you want to hide the first line of the selection box in the header (first line would be the name) * * @param selectionFirstLineShown * @return * @deprecated replaced by {@link #withSelectionFirstLineShown} */ @Deprecated public AccountHeaderBuilder withSelectionFistLineShown(boolean selectionFirstLineShown) { this.mSelectionFirstLineShown = selectionFirstLineShown; return this; } /** * set this to false if you want to hide the first line of the selection box in the header (first line would be the name) * * @param selectionFirstLineShown * @return */ public AccountHeaderBuilder withSelectionFirstLineShown(boolean selectionFirstLineShown) { this.mSelectionFirstLineShown = selectionFirstLineShown; return this; } /** * set this to false if you want to hide the second line of the selection box in the header (second line would be the e-mail) * * @param selectionSecondLineShown * @return */ public AccountHeaderBuilder withSelectionSecondLineShown(boolean selectionSecondLineShown) { this.mSelectionSecondLineShown = selectionSecondLineShown; return this; } //set one of these to define the text in the first or second line with in the account selector protected String mSelectionFirstLine; protected String mSelectionSecondLine; /** * set this to define the first line in the selection area if there is no profile * note this will block any values from profiles! * * @param selectionFirstLine * @return */ public AccountHeaderBuilder withSelectionFirstLine(String selectionFirstLine) { this.mSelectionFirstLine = selectionFirstLine; return this; } /** * set this to define the second line in the selection area if there is no profile * note this will block any values from profiles! * * @param selectionSecondLine * @return */ public AccountHeaderBuilder withSelectionSecondLine(String selectionSecondLine) { this.mSelectionSecondLine = selectionSecondLine; return this; } // set no divider below the header protected boolean mPaddingBelowHeader = true; /** * Set this to false if you want no padding below the Header * * @param paddingBelowHeader * @return */ public AccountHeaderBuilder withPaddingBelowHeader(boolean paddingBelowHeader) { this.mPaddingBelowHeader = paddingBelowHeader; return this; } // set no divider below the header protected boolean mDividerBelowHeader = true; /** * Set this to false if you want no divider below the Header * * @param dividerBelowHeader * @return */ public AccountHeaderBuilder withDividerBelowHeader(boolean dividerBelowHeader) { this.mDividerBelowHeader = dividerBelowHeader; return this; } // set non translucent statusBar mode protected boolean mTranslucentStatusBar = true; /** * Set or disable this if you use a translucent statusbar * * @param translucentStatusBar * @return */ public AccountHeaderBuilder withTranslucentStatusBar(boolean translucentStatusBar) { this.mTranslucentStatusBar = translucentStatusBar; return this; } //the background for the header protected ImageHolder mHeaderBackground; /** * set the background for the slider as color * * @param headerBackground * @return */ public AccountHeaderBuilder withHeaderBackground(Drawable headerBackground) { this.mHeaderBackground = new ImageHolder(headerBackground); return this; } /** * set the background for the header as resource * * @param headerBackgroundRes * @return */ public AccountHeaderBuilder withHeaderBackground(@DrawableRes int headerBackgroundRes) { this.mHeaderBackground = new ImageHolder(headerBackgroundRes); return this; } /** * set the background for the header via the ImageHolder class * * @param headerBackground * @return */ public AccountHeaderBuilder withHeaderBackground(ImageHolder headerBackground) { this.mHeaderBackground = headerBackground; return this; } //background scale type protected ImageView.ScaleType mHeaderBackgroundScaleType = null; /** * define the ScaleType for the header background * * @param headerBackgroundScaleType * @return */ public AccountHeaderBuilder withHeaderBackgroundScaleType(ImageView.ScaleType headerBackgroundScaleType) { this.mHeaderBackgroundScaleType = headerBackgroundScaleType; return this; } //profile images in the header are shown or not protected boolean mProfileImagesVisible = true; /** * define if the profile images in the header are shown or not * * @param profileImagesVisible * @return */ public AccountHeaderBuilder withProfileImagesVisible(boolean profileImagesVisible) { this.mProfileImagesVisible = profileImagesVisible; return this; } //only the main profile image is visible protected boolean mOnlyMainProfileImageVisible = false; /** * define if only the main (current selected) profile image should be visible * * @param onlyMainProfileImageVisible * @return */ public AccountHeaderBuilder withOnlyMainProfileImageVisible(boolean onlyMainProfileImageVisible) { this.mOnlyMainProfileImageVisible = onlyMainProfileImageVisible; return this; } //show small profile images but hide MainProfileImage protected boolean mOnlySmallProfileImagesVisible = false; /** * define if only the small profile images should be visible * * @param onlySmallProfileImagesVisible * @return */ public AccountHeaderBuilder withOnlySmallProfileImagesVisible(boolean onlySmallProfileImagesVisible) { this.mOnlySmallProfileImagesVisible = onlySmallProfileImagesVisible; return this; } //close the drawer after a profile was clicked in the list protected Boolean mCloseDrawerOnProfileListClick = null; /** * define if the drawer should close if the user clicks on a profile item if the selection list is shown * * @param closeDrawerOnProfileListClick * @return */ public AccountHeaderBuilder withCloseDrawerOnProfileListClick(boolean closeDrawerOnProfileListClick) { this.mCloseDrawerOnProfileListClick = closeDrawerOnProfileListClick; return this; } //reset the drawer list to the main drawer list after the profile was clicked in the list protected boolean mResetDrawerOnProfileListClick = true; /** * define if the drawer selection list should be reseted after the user clicks on a profile item if the selection list is shown * * @param resetDrawerOnProfileListClick * @return */ public AccountHeaderBuilder withResetDrawerOnProfileListClick(boolean resetDrawerOnProfileListClick) { this.mResetDrawerOnProfileListClick = resetDrawerOnProfileListClick; return this; } // set the profile images clickable or not protected boolean mProfileImagesClickable = true; /** * enable or disable the profile images to be clickable * * @param profileImagesClickable * @return */ public AccountHeaderBuilder withProfileImagesClickable(boolean profileImagesClickable) { this.mProfileImagesClickable = profileImagesClickable; return this; } // set to use the alternative profile header switching protected boolean mAlternativeProfileHeaderSwitching = false; /** * enable the alternative profile header switching * * @param alternativeProfileHeaderSwitching * @return */ public AccountHeaderBuilder withAlternativeProfileHeaderSwitching(boolean alternativeProfileHeaderSwitching) { this.mAlternativeProfileHeaderSwitching = alternativeProfileHeaderSwitching; return this; } // enable 3 small header previews protected boolean mThreeSmallProfileImages = false; /** * enable the extended profile icon view with 3 small header images instead of two * * @param threeSmallProfileImages * @return */ public AccountHeaderBuilder withThreeSmallProfileImages(boolean threeSmallProfileImages) { this.mThreeSmallProfileImages = threeSmallProfileImages; return this; } //the delay which is waited before the drawer is closed protected int mOnProfileClickDrawerCloseDelay = 100; /** * Define the delay for the drawer close operation after a click. * This is a small trick to improve the speed (and remove lag) if you open a new activity after a DrawerItem * was selected. * NOTE: Disable this by passing -1 * * @param onProfileClickDrawerCloseDelay the delay in MS (-1 to disable) * @return */ public AccountHeaderBuilder withOnProfileClickDrawerCloseDelay(int onProfileClickDrawerCloseDelay) { this.mOnProfileClickDrawerCloseDelay = onProfileClickDrawerCloseDelay; return this; } // the onAccountHeaderProfileImageListener to set protected AccountHeader.OnAccountHeaderProfileImageListener mOnAccountHeaderProfileImageListener; /** * set click / longClick listener for the header images * * @param onAccountHeaderProfileImageListener * @return */ public AccountHeaderBuilder withOnAccountHeaderProfileImageListener(AccountHeader.OnAccountHeaderProfileImageListener onAccountHeaderProfileImageListener) { this.mOnAccountHeaderProfileImageListener = onAccountHeaderProfileImageListener; return this; } // the onAccountHeaderSelectionListener to set protected AccountHeader.OnAccountHeaderSelectionViewClickListener mOnAccountHeaderSelectionViewClickListener; /** * set a onSelection listener for the selection box * * @param onAccountHeaderSelectionViewClickListener * @return */ public AccountHeaderBuilder withOnAccountHeaderSelectionViewClickListener(AccountHeader.OnAccountHeaderSelectionViewClickListener onAccountHeaderSelectionViewClickListener) { this.mOnAccountHeaderSelectionViewClickListener = onAccountHeaderSelectionViewClickListener; return this; } //set the selection list enabled if there is only a single profile protected boolean mSelectionListEnabledForSingleProfile = true; /** * enable or disable the selection list if there is only a single profile * * @param selectionListEnabledForSingleProfile * @return */ public AccountHeaderBuilder withSelectionListEnabledForSingleProfile(boolean selectionListEnabledForSingleProfile) { this.mSelectionListEnabledForSingleProfile = selectionListEnabledForSingleProfile; return this; } //set the selection enabled disabled protected boolean mSelectionListEnabled = true; /** * enable or disable the selection list * * @param selectionListEnabled * @return */ public AccountHeaderBuilder withSelectionListEnabled(boolean selectionListEnabled) { this.mSelectionListEnabled = selectionListEnabled; return this; } // the drawerLayout to use protected View mAccountHeaderContainer; /** * You can pass a custom view for the drawer lib. note this requires the same structure as the drawer.xml * * @param accountHeader * @return */ public AccountHeaderBuilder withAccountHeader(@NonNull View accountHeader) { this.mAccountHeaderContainer = accountHeader; return this; } /** * You can pass a custom layout for the drawer lib. see the drawer.xml in layouts of this lib on GitHub * * @param resLayout * @return */ public AccountHeaderBuilder withAccountHeader(@LayoutRes int resLayout) { if (mActivity == null) { throw new RuntimeException("please pass an activity first to use this call"); } if (resLayout != -1) { this.mAccountHeaderContainer = mActivity.getLayoutInflater().inflate(resLayout, null, false); } else { if (mCompactStyle) { this.mAccountHeaderContainer = mActivity.getLayoutInflater().inflate(R.layout.material_drawer_compact_header, null, false); } else { this.mAccountHeaderContainer = mActivity.getLayoutInflater().inflate(R.layout.material_drawer_header, null, false); } } return this; } // the profiles to display protected ArrayList<IProfile> mProfiles; /** * set the arrayList of DrawerItems for the drawer * * @param profiles * @return */ public AccountHeaderBuilder withProfiles(@NonNull ArrayList<IProfile> profiles) { this.mProfiles = profiles; return this; } /** * add single ore more DrawerItems to the Drawer * * @param profiles * @return */ public AccountHeaderBuilder addProfiles(@NonNull IProfile... profiles) { if (this.mProfiles == null) { this.mProfiles = new ArrayList<>(); } Collections.addAll(this.mProfiles, profiles); return this; } // the click listener to be fired on profile or selection click protected AccountHeader.OnAccountHeaderListener mOnAccountHeaderListener; /** * add a listener for the accountHeader * * @param onAccountHeaderListener * @return */ public AccountHeaderBuilder withOnAccountHeaderListener(AccountHeader.OnAccountHeaderListener onAccountHeaderListener) { this.mOnAccountHeaderListener = onAccountHeaderListener; return this; } //the on long click listener to be fired on profile longClick inside the list protected AccountHeader.OnAccountHeaderItemLongClickListener mOnAccountHeaderItemLongClickListener; /** * the on long click listener to be fired on profile longClick inside the list * * @param onAccountHeaderItemLongClickListener * @return */ public AccountHeaderBuilder withOnAccountHeaderItemLongClickListener(AccountHeader.OnAccountHeaderItemLongClickListener onAccountHeaderItemLongClickListener) { this.mOnAccountHeaderItemLongClickListener = onAccountHeaderItemLongClickListener; return this; } // the drawer to set the AccountSwitcher for protected Drawer mDrawer; /** * @param drawer * @return */ public AccountHeaderBuilder withDrawer(@NonNull Drawer drawer) { this.mDrawer = drawer; return this; } // savedInstance to restore state protected Bundle mSavedInstance; /** * create the drawer with the values of a savedInstance * * @param savedInstance * @return */ public AccountHeaderBuilder withSavedInstance(Bundle savedInstance) { this.mSavedInstance = savedInstance; return this; } /** * helper method to set the height for the header! * * @param height */ private void setHeaderHeight(int height) { if (mAccountHeaderContainer != null) { ViewGroup.LayoutParams params = mAccountHeaderContainer.getLayoutParams(); if (params != null) { params.height = height; mAccountHeaderContainer.setLayoutParams(params); } View accountHeader = mAccountHeaderContainer.findViewById(R.id.material_drawer_account_header); if (accountHeader != null) { params = accountHeader.getLayoutParams(); params.height = height; accountHeader.setLayoutParams(params); } View accountHeaderBackground = mAccountHeaderContainer.findViewById(R.id.material_drawer_account_header_background); if (accountHeaderBackground != null) { params = accountHeaderBackground.getLayoutParams(); params.height = height; accountHeaderBackground.setLayoutParams(params); } } } /** * a small helper to handle the selectionView * * @param on */ private void handleSelectionView(IProfile profile, boolean on) { if (on) { if (Build.VERSION.SDK_INT >= 21) { ((FrameLayout) mAccountHeaderContainer).setForeground(UIUtils.getCompatDrawable(mAccountHeaderContainer.getContext(), mAccountHeaderTextSectionBackgroundResource)); mAccountHeaderContainer.setOnClickListener(onSelectionClickListener); mAccountHeaderContainer.setTag(R.id.material_drawer_profile_header, profile); } else { mAccountHeaderTextSection.setBackgroundResource(mAccountHeaderTextSectionBackgroundResource); mAccountHeaderTextSection.setOnClickListener(onSelectionClickListener); mAccountHeaderTextSection.setTag(R.id.material_drawer_profile_header, profile); } } else { if (Build.VERSION.SDK_INT >= 21) { ((FrameLayout) mAccountHeaderContainer).setForeground(null); mAccountHeaderContainer.setOnClickListener(null); } else { UIUtils.setBackground(mAccountHeaderTextSection, null); mAccountHeaderTextSection.setOnClickListener(null); } } } /** * method to build the header view * * @return */ public AccountHeader build() { // if the user has not set a accountHeader use the default one :D if (mAccountHeaderContainer == null) { withAccountHeader(-1); } // get the header view within the container mAccountHeader = mAccountHeaderContainer.findViewById(R.id.material_drawer_account_header); //the default min header height by default 148dp int defaultHeaderMinHeight = mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_account_header_height); int statusBarHeight = UIUtils.getStatusBarHeight(mActivity, true); // handle the height for the header int height; if (mHeight != null) { height = mHeight.asPixel(mActivity); } else { if (mCompactStyle) { height = mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_account_header_height_compact); } else { //calculate the header height by getting the optimal drawer width and calculating it * 9 / 16 height = (int) (DrawerUIUtils.getOptimalDrawerWidth(mActivity) * AccountHeader.NAVIGATION_DRAWER_ACCOUNT_ASPECT_RATIO); //if we are lower than api 19 (>= 19 we have a translucentStatusBar) the height should be a bit lower //probably even if we are non translucent on > 19 devices? if (Build.VERSION.SDK_INT < 19) { int tempHeight = height - statusBarHeight; //if we are lower than api 19 we are not able to have a translucent statusBar so we remove the height of the statusBar from the padding //to prevent display issues we only reduce the height if we still fit the required minHeight of 148dp (R.dimen.material_drawer_account_header_height) //we remove additional 8dp from the defaultMinHeaderHeight as there is some buffer in the header and to prevent to large spacings if (tempHeight > defaultHeaderMinHeight - UIUtils.convertDpToPixel(8, mActivity)) { height = tempHeight; } } } } // handle everything if we have a translucent status bar which only is possible on API >= 19 if (mTranslucentStatusBar && Build.VERSION.SDK_INT >= 19) { mAccountHeader.setPadding(mAccountHeader.getPaddingLeft(), mAccountHeader.getPaddingTop() + statusBarHeight, mAccountHeader.getPaddingRight(), mAccountHeader.getPaddingBottom()); //in fact it makes no difference if we have a translucent statusBar or not. we want 9/16 just if we are not compact if (mCompactStyle) { height = height + statusBarHeight; } else if ((height - statusBarHeight) <= defaultHeaderMinHeight) { //if the height + statusBar of the header is lower than the required 148dp + statusBar we change the height to be able to display all the data height = defaultHeaderMinHeight + statusBarHeight; } } //set the height for the header setHeaderHeight(height); // get the background view mAccountHeaderBackground = (ImageView) mAccountHeaderContainer.findViewById(R.id.material_drawer_account_header_background); // set the background ImageHolder.applyTo(mHeaderBackground, mAccountHeaderBackground, DrawerImageLoader.Tags.ACCOUNT_HEADER.name()); if (mHeaderBackgroundScaleType != null) { mAccountHeaderBackground.setScaleType(mHeaderBackgroundScaleType); } // get the text color to use for the text section int textColor = ColorHolder.color(mTextColor, mActivity, R.attr.material_drawer_header_selection_text, R.color.material_drawer_header_selection_text); // set the background for the section if (mCompactStyle) { mAccountHeaderTextSection = mAccountHeader; } else { mAccountHeaderTextSection = mAccountHeaderContainer.findViewById(R.id.material_drawer_account_header_text_section); } mAccountHeaderTextSectionBackgroundResource = DrawerUIUtils.getSelectableBackground(mActivity); handleSelectionView(mCurrentProfile, true); // set the arrow :D mAccountSwitcherArrow = (ImageView) mAccountHeaderContainer.findViewById(R.id.material_drawer_account_header_text_switcher); mAccountSwitcherArrow.setImageDrawable(new IconicsDrawable(mActivity, MaterialDrawerFont.Icon.mdf_arrow_drop_down).sizeRes(R.dimen.material_drawer_account_header_dropdown).paddingRes(R.dimen.material_drawer_account_header_dropdown_padding).color(textColor)); //get the fields for the name mCurrentProfileView = (BezelImageView) mAccountHeader.findViewById(R.id.material_drawer_account_header_current); mCurrentProfileName = (TextView) mAccountHeader.findViewById(R.id.material_drawer_account_header_name); mCurrentProfileEmail = (TextView) mAccountHeader.findViewById(R.id.material_drawer_account_header_email); //set the typeface for the AccountHeader if (mNameTypeface != null) { mCurrentProfileName.setTypeface(mNameTypeface); } else if (mTypeface != null) { mCurrentProfileName.setTypeface(mTypeface); } if (mEmailTypeface != null) { mCurrentProfileEmail.setTypeface(mEmailTypeface); } else if (mTypeface != null) { mCurrentProfileEmail.setTypeface(mTypeface); } mCurrentProfileName.setTextColor(textColor); mCurrentProfileEmail.setTextColor(textColor); mProfileFirstView = (BezelImageView) mAccountHeader.findViewById(R.id.material_drawer_account_header_small_first); mProfileSecondView = (BezelImageView) mAccountHeader.findViewById(R.id.material_drawer_account_header_small_second); mProfileThirdView = (BezelImageView) mAccountHeader.findViewById(R.id.material_drawer_account_header_small_third); //calculate the profiles to set calculateProfiles(); //process and build the profiles buildProfiles(); // try to restore all saved values again if (mSavedInstance != null) { int selection = mSavedInstance.getInt(AccountHeader.BUNDLE_SELECTION_HEADER, -1); if (selection != -1) { //predefine selection (should be the first element if (mProfiles != null && (selection) > -1 && selection < mProfiles.size()) { switchProfiles(mProfiles.get(selection)); } } } //everything created. now set the header if (mDrawer != null) { mDrawer.setHeader(mAccountHeaderContainer, mPaddingBelowHeader, mDividerBelowHeader); } //forget the reference to the activity mActivity = null; return new AccountHeader(this); } /** * helper method to calculate the order of the profiles */ protected void calculateProfiles() { if (mProfiles == null) { mProfiles = new ArrayList<>(); } if (mCurrentProfile == null) { int setCount = 0; for (int i = 0; i < mProfiles.size(); i++) { if (mProfiles.size() > i && mProfiles.get(i).isSelectable()) { if (setCount == 0 && (mCurrentProfile == null)) { mCurrentProfile = mProfiles.get(i); } else if (setCount == 1 && (mProfileFirst == null)) { mProfileFirst = mProfiles.get(i); } else if (setCount == 2 && (mProfileSecond == null)) { mProfileSecond = mProfiles.get(i); } else if (setCount == 3 && (mProfileThird == null)) { mProfileThird = mProfiles.get(i); } setCount++; } } return; } IProfile[] previousActiveProfiles = new IProfile[]{ mCurrentProfile, mProfileFirst, mProfileSecond, mProfileThird }; IProfile[] newActiveProfiles = new IProfile[4]; Stack<IProfile> unusedProfiles = new Stack<>(); // try to keep existing active profiles in the same positions for (int i = 0; i < mProfiles.size(); i++) { IProfile p = mProfiles.get(i); if (p.isSelectable()) { boolean used = false; for (int j = 0; j < 4; j++) { if (previousActiveProfiles[j] == p) { newActiveProfiles[j] = p; used = true; break; } } if (!used) { unusedProfiles.push(p); } } } Stack<IProfile> activeProfiles = new Stack<>(); // try to fill the gaps with new available profiles for (int i = 0; i < 4; i++) { if (newActiveProfiles[i] != null) { activeProfiles.push(newActiveProfiles[i]); } else if (!unusedProfiles.isEmpty()) { activeProfiles.push(unusedProfiles.pop()); } } Stack<IProfile> reversedActiveProfiles = new Stack<>(); while (!activeProfiles.empty()) { reversedActiveProfiles.push(activeProfiles.pop()); } // reassign active profiles if (reversedActiveProfiles.isEmpty()) { mCurrentProfile = null; } else { mCurrentProfile = reversedActiveProfiles.pop(); } if (reversedActiveProfiles.isEmpty()) { mProfileFirst = null; } else { mProfileFirst = reversedActiveProfiles.pop(); } if (reversedActiveProfiles.isEmpty()) { mProfileSecond = null; } else { mProfileSecond = reversedActiveProfiles.pop(); } if (reversedActiveProfiles.isEmpty()) { mProfileThird = null; } else { mProfileThird = reversedActiveProfiles.pop(); } } /** * helper method to switch the profiles * * @param newSelection * @return true if the new selection was the current profile */ protected boolean switchProfiles(IProfile newSelection) { if (newSelection == null) { return false; } if (mCurrentProfile == newSelection) { return true; } if (mAlternativeProfileHeaderSwitching) { int prevSelection = -1; if (mProfileFirst == newSelection) { prevSelection = 1; } else if (mProfileSecond == newSelection) { prevSelection = 2; } else if (mProfileThird == newSelection) { prevSelection = 3; } IProfile tmp = mCurrentProfile; mCurrentProfile = newSelection; if (prevSelection == 1) { mProfileFirst = tmp; } else if (prevSelection == 2) { mProfileSecond = tmp; } else if (prevSelection == 3) { mProfileThird = tmp; } } else { if (mProfiles != null) { ArrayList<IProfile> previousActiveProfiles = new ArrayList<>(Arrays.asList(mCurrentProfile, mProfileFirst, mProfileSecond, mProfileThird)); if (previousActiveProfiles.contains(newSelection)) { int position = -1; for (int i = 0; i < 4; i++) { if (previousActiveProfiles.get(i) == newSelection) { position = i; break; } } if (position != -1) { previousActiveProfiles.remove(position); previousActiveProfiles.add(0, newSelection); mCurrentProfile = previousActiveProfiles.get(0); mProfileFirst = previousActiveProfiles.get(1); mProfileSecond = previousActiveProfiles.get(2); mProfileThird = previousActiveProfiles.get(3); } } else { mProfileThird = mProfileSecond; mProfileSecond = mProfileFirst; mProfileFirst = mCurrentProfile; mCurrentProfile = newSelection; } } } //if we only show the small profile images we have to make sure the first (would be the current selected) profile is also shown if (mOnlySmallProfileImagesVisible) { mProfileThird = mProfileSecond; mProfileSecond = mProfileFirst; mProfileFirst = mCurrentProfile; mCurrentProfile = mProfileThird; } buildProfiles(); return false; } /** * helper method to build the views for the ui */ protected void buildProfiles() { mCurrentProfileView.setVisibility(View.INVISIBLE); mAccountHeaderTextSection.setVisibility(View.INVISIBLE); mAccountSwitcherArrow.setVisibility(View.INVISIBLE); mProfileFirstView.setVisibility(View.GONE); mProfileFirstView.setOnClickListener(null); mProfileSecondView.setVisibility(View.GONE); mProfileSecondView.setOnClickListener(null); mProfileThirdView.setVisibility(View.GONE); mProfileThirdView.setOnClickListener(null); mCurrentProfileName.setText(""); mCurrentProfileEmail.setText(""); handleSelectionView(mCurrentProfile, true); if (mCurrentProfile != null) { if ((mProfileImagesVisible || mOnlyMainProfileImageVisible) && !mOnlySmallProfileImagesVisible) { setImageOrPlaceholder(mCurrentProfileView, mCurrentProfile.getIcon()); if (mProfileImagesClickable) { mCurrentProfileView.setOnClickListener(onCurrentProfileClickListener); mCurrentProfileView.setOnLongClickListener(onCurrentProfileLongClickListener); mCurrentProfileView.disableTouchFeedback(false); } else { mCurrentProfileView.disableTouchFeedback(true); } mCurrentProfileView.setVisibility(View.VISIBLE); mCurrentProfileView.invalidate(); } else if (mCompactStyle) { mCurrentProfileView.setVisibility(View.GONE); } mAccountHeaderTextSection.setVisibility(View.VISIBLE); handleSelectionView(mCurrentProfile, true); mAccountSwitcherArrow.setVisibility(View.VISIBLE); mCurrentProfileView.setTag(R.id.material_drawer_profile_header, mCurrentProfile); StringHolder.applyTo(mCurrentProfile.getName(), mCurrentProfileName); StringHolder.applyTo(mCurrentProfile.getEmail(), mCurrentProfileEmail); if (mProfileFirst != null && mProfileImagesVisible && !mOnlyMainProfileImageVisible) { setImageOrPlaceholder(mProfileFirstView, mProfileFirst.getIcon()); mProfileFirstView.setTag(R.id.material_drawer_profile_header, mProfileFirst); if (mProfileImagesClickable) { mProfileFirstView.setOnClickListener(onProfileClickListener); mProfileFirstView.setOnLongClickListener(onProfileLongClickListener); mProfileFirstView.disableTouchFeedback(false); } else { mProfileFirstView.disableTouchFeedback(true); } mProfileFirstView.setVisibility(View.VISIBLE); mProfileFirstView.invalidate(); } if (mProfileSecond != null && mProfileImagesVisible && !mOnlyMainProfileImageVisible) { setImageOrPlaceholder(mProfileSecondView, mProfileSecond.getIcon()); mProfileSecondView.setTag(R.id.material_drawer_profile_header, mProfileSecond); if (mProfileImagesClickable) { mProfileSecondView.setOnClickListener(onProfileClickListener); mProfileSecondView.setOnLongClickListener(onProfileLongClickListener); mProfileSecondView.disableTouchFeedback(false); } else { mProfileSecondView.disableTouchFeedback(true); } mProfileSecondView.setVisibility(View.VISIBLE); mProfileSecondView.invalidate(); } if (mProfileThird != null && mThreeSmallProfileImages && mProfileImagesVisible && !mOnlyMainProfileImageVisible) { setImageOrPlaceholder(mProfileThirdView, mProfileThird.getIcon()); mProfileThirdView.setTag(R.id.material_drawer_profile_header, mProfileThird); if (mProfileImagesClickable) { mProfileThirdView.setOnClickListener(onProfileClickListener); mProfileThirdView.setOnLongClickListener(onProfileLongClickListener); mProfileThirdView.disableTouchFeedback(false); } else { mProfileThirdView.disableTouchFeedback(true); } mProfileThirdView.setVisibility(View.VISIBLE); mProfileThirdView.invalidate(); } } else if (mProfiles != null && mProfiles.size() > 0) { IProfile profile = mProfiles.get(0); mAccountHeaderTextSection.setTag(R.id.material_drawer_profile_header, profile); mAccountHeaderTextSection.setVisibility(View.VISIBLE); handleSelectionView(mCurrentProfile, true); mAccountSwitcherArrow.setVisibility(View.VISIBLE); if (mCurrentProfile != null) { StringHolder.applyTo(mCurrentProfile.getName(), mCurrentProfileName); StringHolder.applyTo(mCurrentProfile.getEmail(), mCurrentProfileEmail); } } if (!mSelectionFirstLineShown) { mCurrentProfileName.setVisibility(View.GONE); } if (!TextUtils.isEmpty(mSelectionFirstLine)) { mCurrentProfileName.setText(mSelectionFirstLine); mAccountHeaderTextSection.setVisibility(View.VISIBLE); } if (!mSelectionSecondLineShown) { mCurrentProfileEmail.setVisibility(View.GONE); } if (!TextUtils.isEmpty(mSelectionSecondLine)) { mCurrentProfileEmail.setText(mSelectionSecondLine); mAccountHeaderTextSection.setVisibility(View.VISIBLE); } //if we disabled the list if (!mSelectionListEnabled) { mAccountSwitcherArrow.setVisibility(View.INVISIBLE); handleSelectionView(null, false); } if (!mSelectionListEnabledForSingleProfile && mProfileFirst == null && (mProfiles == null || mProfiles.size() == 1)) { mAccountSwitcherArrow.setVisibility(View.INVISIBLE); handleSelectionView(null, false); } //if we disabled the list but still have set a custom listener if (mOnAccountHeaderSelectionViewClickListener != null) { handleSelectionView(mCurrentProfile, true); } } /** * small helper method to set an profile image or a placeholder * * @param iv * @param imageHolder */ private void setImageOrPlaceholder(ImageView iv, ImageHolder imageHolder) { //cancel previous started image loading processes DrawerImageLoader.getInstance().cancelImage(iv); //set the placeholder iv.setImageDrawable(DrawerUIUtils.getPlaceHolder(iv.getContext())); //set the real image (probably also the uri) ImageHolder.applyTo(imageHolder, iv, DrawerImageLoader.Tags.PROFILE.name()); } /** * onProfileClickListener to notify onClick on the current profile image */ private View.OnClickListener onCurrentProfileClickListener = new View.OnClickListener() { @Override public void onClick(final View v) { onProfileImageClick(v, true); } }; /** * onProfileClickListener to notify onClick on a profile image */ private View.OnClickListener onProfileClickListener = new View.OnClickListener() { @Override public void onClick(final View v) { onProfileImageClick(v, false); } }; /** * calls the mOnAccountHEaderProfileImageListener and continues with the actions afterwards * * @param v * @param current */ private void onProfileImageClick(View v, boolean current) { IProfile profile = (IProfile) v.getTag(R.id.material_drawer_profile_header); boolean consumed = false; if (mOnAccountHeaderProfileImageListener != null) { consumed = mOnAccountHeaderProfileImageListener.onProfileImageClick(v, profile, current); } //if the event was already consumed by the click don't continue. note that this will also stop the profile change event if (!consumed) { onProfileClick(v, current); } } /** * onProfileLongClickListener to call the onProfileImageLongClick on the current profile image */ private View.OnLongClickListener onCurrentProfileLongClickListener = new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (mOnAccountHeaderProfileImageListener != null) { IProfile profile = (IProfile) v.getTag(R.id.material_drawer_profile_header); return mOnAccountHeaderProfileImageListener.onProfileImageLongClick(v, profile, true); } return false; } }; /** * onProfileLongClickListener to call the onProfileImageLongClick on a profile image */ private View.OnLongClickListener onProfileLongClickListener = new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (mOnAccountHeaderProfileImageListener != null) { IProfile profile = (IProfile) v.getTag(R.id.material_drawer_profile_header); return mOnAccountHeaderProfileImageListener.onProfileImageLongClick(v, profile, false); } return false; } }; protected void onProfileClick(View v, boolean current) { final IProfile profile = (IProfile) v.getTag(R.id.material_drawer_profile_header); switchProfiles(profile); //reset the drawer content resetDrawerContent(v.getContext()); //notify the MiniDrawer about the clicked profile (only if one exists and is hooked to the Drawer if (mDrawer != null && mDrawer.getDrawerBuilder() != null && mDrawer.getDrawerBuilder().mMiniDrawer != null) { mDrawer.getDrawerBuilder().mMiniDrawer.onProfileClick(); } //notify about the changed profile boolean consumed = false; if (mOnAccountHeaderListener != null) { consumed = mOnAccountHeaderListener.onProfileChanged(v, profile, current); } if (!consumed) { if (mOnProfileClickDrawerCloseDelay > 0) { new Handler().postDelayed(new Runnable() { @Override public void run() { if (mDrawer != null) { mDrawer.closeDrawer(); } } }, mOnProfileClickDrawerCloseDelay); } else { if (mDrawer != null) { mDrawer.closeDrawer(); } } } } /** * get the current selection * * @return */ protected int getCurrentSelection() { if (mCurrentProfile != null && mProfiles != null) { int i = 0; for (IProfile profile : mProfiles) { if (profile == mCurrentProfile) { return i; } i++; } } return -1; } /** * onSelectionClickListener to notify the onClick on the checkbox */ private View.OnClickListener onSelectionClickListener = new View.OnClickListener() { @Override public void onClick(View v) { boolean consumed = false; if (mOnAccountHeaderSelectionViewClickListener != null) { consumed = mOnAccountHeaderSelectionViewClickListener.onClick(v, (IProfile) v.getTag(R.id.material_drawer_profile_header)); } if (mAccountSwitcherArrow.getVisibility() == View.VISIBLE && !consumed) { toggleSelectionList(v.getContext()); } } }; /** * helper method to toggle the collection * * @param ctx */ protected void toggleSelectionList(Context ctx) { if (mDrawer != null) { //if we already show the list. reset everything instead if (mDrawer.switchedDrawerContent()) { resetDrawerContent(ctx); mSelectionListShown = false; } else { //build and set the drawer selection list buildDrawerSelectionList(); // update the arrow image within the drawer mAccountSwitcherArrow.setImageDrawable(new IconicsDrawable(ctx, MaterialDrawerFont.Icon.mdf_arrow_drop_up).sizeRes(R.dimen.material_drawer_account_header_dropdown).paddingRes(R.dimen.material_drawer_account_header_dropdown_padding).color(ColorHolder.color(mTextColor, ctx, R.attr.material_drawer_header_selection_text, R.color.material_drawer_header_selection_text))); mSelectionListShown = true; } } } /** * helper method to build and set the drawer selection list */ protected void buildDrawerSelectionList() { int selectedPosition = -1; int position = 0; ArrayList<IDrawerItem> profileDrawerItems = new ArrayList<>(); if (mProfiles != null) { for (IProfile profile : mProfiles) { if (profile == mCurrentProfile) { if (mCurrentHiddenInList) { continue; } else { //TODO THIS //selectedPosition = position + mDrawer.getAdapter().getHeaderOffset(); } } if (profile instanceof IDrawerItem) { ((IDrawerItem) profile).withSetSelected(false); profileDrawerItems.add((IDrawerItem) profile); } position = position + 1; } } mDrawer.switchDrawerContent(onDrawerItemClickListener, onDrawerItemLongClickListener, profileDrawerItems, selectedPosition); } /** * onDrawerItemClickListener to catch the selection for the new profile! */ private Drawer.OnDrawerItemClickListener onDrawerItemClickListener = new Drawer.OnDrawerItemClickListener() { @Override public boolean onItemClick(final View view, int position, final IDrawerItem drawerItem) { final boolean isCurrentSelectedProfile; if (drawerItem != null && drawerItem instanceof IProfile && drawerItem.isSelectable()) { isCurrentSelectedProfile = switchProfiles((IProfile) drawerItem); } else { isCurrentSelectedProfile = false; } if (mResetDrawerOnProfileListClick) { mDrawer.setOnDrawerItemClickListener(null); } //wrap the onSelection call and the reset stuff within a handler to prevent lag if (mResetDrawerOnProfileListClick && mDrawer != null && view != null && view.getContext() != null) { resetDrawerContent(view.getContext()); } //notify the MiniDrawer about the clicked profile (only if one exists and is hooked to the Drawer if (mDrawer != null && mDrawer.getDrawerBuilder() != null && mDrawer.getDrawerBuilder().mMiniDrawer != null) { mDrawer.getDrawerBuilder().mMiniDrawer.onProfileClick(); } boolean consumed = false; if (drawerItem != null && drawerItem instanceof IProfile) { if (mOnAccountHeaderListener != null) { consumed = mOnAccountHeaderListener.onProfileChanged(view, (IProfile) drawerItem, isCurrentSelectedProfile); } } //if a custom behavior was chosen via the CloseDrawerOnProfileListClick then use this. else react on the result of the onProfileChanged listener if (mCloseDrawerOnProfileListClick != null) { return !mCloseDrawerOnProfileListClick; } else { return consumed; } } }; /** * onDrawerItemLongClickListener to catch the longClick for a profile */ private Drawer.OnDrawerItemLongClickListener onDrawerItemLongClickListener = new Drawer.OnDrawerItemLongClickListener() { @Override public boolean onItemLongClick(View view, int position, IDrawerItem drawerItem) { //if a longClickListener was defined use it if (mOnAccountHeaderItemLongClickListener != null) { final boolean isCurrentSelectedProfile; isCurrentSelectedProfile = drawerItem != null && drawerItem.isSelected(); if (drawerItem != null && drawerItem instanceof IProfile) { return mOnAccountHeaderItemLongClickListener.onProfileLongClick(view, (IProfile) drawerItem, isCurrentSelectedProfile); } } return false; } }; /** * helper method to reset the drawer content */ private void resetDrawerContent(Context ctx) { if (mDrawer != null) { mDrawer.resetDrawerContent(); } mAccountSwitcherArrow.setImageDrawable(new IconicsDrawable(ctx, MaterialDrawerFont.Icon.mdf_arrow_drop_down).sizeRes(R.dimen.material_drawer_account_header_dropdown).paddingRes(R.dimen.material_drawer_account_header_dropdown_padding).color(ColorHolder.color(mTextColor, ctx, R.attr.material_drawer_header_selection_text, R.color.material_drawer_header_selection_text))); } /** * small helper class to update the header and the list */ protected void updateHeaderAndList() { //recalculate the profiles calculateProfiles(); //update the profiles in the header buildProfiles(); //if we currently show the list add the new item directly to it if (mSelectionListShown) { buildDrawerSelectionList(); } } }
* correctly select items when we switch to the Profile list
library/src/main/java/com/mikepenz/materialdrawer/AccountHeaderBuilder.java
* correctly select items when we switch to the Profile list
Java
apache-2.0
b66b41674f80f0f6dc0c92feb85a54758069b32f
0
xyczero/DanmakuFlameMaster,zzuli4519/DanmakuFlameMaster,Bilibili/DanmakuFlameMaster,whstudy/DanmakuFlameMaster,ctiao/DanmakuFlameMaster
/* * Copyright (C) 2013 Chen Hui <calmer91@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package master.flame.danmaku.ui.widget; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.os.Build; import android.os.HandlerThread; import android.os.Looper; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import java.util.LinkedList; import java.util.Locale; import master.flame.danmaku.controller.DrawHandler; import master.flame.danmaku.controller.DrawHandler.Callback; import master.flame.danmaku.controller.DrawHelper; import master.flame.danmaku.controller.IDanmakuView; import master.flame.danmaku.controller.IDanmakuViewController; import master.flame.danmaku.danmaku.model.BaseDanmaku; import master.flame.danmaku.danmaku.model.IDanmakus; import master.flame.danmaku.danmaku.model.android.DanmakuContext; import master.flame.danmaku.danmaku.parser.BaseDanmakuParser; import master.flame.danmaku.danmaku.renderer.IRenderer.RenderingState; public class DanmakuView extends View implements IDanmakuView, IDanmakuViewController { public static final String TAG = "DanmakuView"; private Callback mCallback; private HandlerThread mHandlerThread; private DrawHandler handler; private boolean isSurfaceCreated; private boolean mEnableDanmakuDrwaingCache = true; private OnDanmakuClickListener mOnDanmakuClickListener; private DanmakuTouchHelper mTouchHelper; private boolean mShowFps; private boolean mDanmakuVisible = true; protected int mDrawingThreadType = THREAD_TYPE_NORMAL_PRIORITY; private Object mDrawMonitor = new Object(); private boolean mDrawFinished = false; private boolean mRequestRender = false; private long mUiThreadId; public DanmakuView(Context context) { super(context); init(); } private void init() { mUiThreadId = Thread.currentThread().getId(); setBackgroundColor(Color.TRANSPARENT); setDrawingCacheBackgroundColor(Color.TRANSPARENT); DrawHelper.useDrawColorToClearCanvas(true, false); mTouchHelper = DanmakuTouchHelper.instance(this); } public DanmakuView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public DanmakuView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public void addDanmaku(BaseDanmaku item) { if (handler != null) { handler.addDanmaku(item); } } @Override public void removeAllDanmakus() { if (handler != null) { handler.removeAllDanmakus(); } } @Override public void removeAllLiveDanmakus() { if (handler != null) { handler.removeAllLiveDanmakus(); } } @Override public IDanmakus getCurrentVisibleDanmakus() { if (handler != null) { return handler.getCurrentVisibleDanmakus(); } return null; } public void setCallback(Callback callback) { mCallback = callback; if (handler != null) { handler.setCallback(callback); } } @Override public void release() { stop(); if(mDrawTimes!= null) mDrawTimes.clear(); } @Override public void stop() { stopDraw(); } private void stopDraw() { if (handler != null) { handler.quit(); handler = null; } if (mHandlerThread != null) { try { mHandlerThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } mHandlerThread.quit(); mHandlerThread = null; } } protected Looper getLooper(int type){ if (mHandlerThread != null) { mHandlerThread.quit(); mHandlerThread = null; } int priority; switch (type) { case THREAD_TYPE_MAIN_THREAD: return Looper.getMainLooper(); case THREAD_TYPE_HIGH_PRIORITY: priority = android.os.Process.THREAD_PRIORITY_URGENT_DISPLAY; break; case THREAD_TYPE_LOW_PRIORITY: priority = android.os.Process.THREAD_PRIORITY_LOWEST; break; case THREAD_TYPE_NORMAL_PRIORITY: default: priority = android.os.Process.THREAD_PRIORITY_DEFAULT; break; } String threadName = "DFM Handler Thread #"+priority; mHandlerThread = new HandlerThread(threadName, priority); mHandlerThread.start(); return mHandlerThread.getLooper(); } private void prepare() { if (handler == null) handler = new DrawHandler(getLooper(mDrawingThreadType), this, mDanmakuVisible); } @Override public void prepare(BaseDanmakuParser parser, DanmakuContext config) { prepare(); handler.setConfig(config); handler.setParser(parser); handler.setCallback(mCallback); handler.prepare(); } @Override public boolean isPrepared() { return handler != null && handler.isPrepared(); } @Override public DanmakuContext getConfig() { if (handler == null) { return null; } return handler.getConfig(); } @Override public void showFPS(boolean show){ mShowFps = show; } private static final int MAX_RECORD_SIZE = 50; private static final int ONE_SECOND = 1000; private LinkedList<Long> mDrawTimes; private boolean mClearFlag; private float fps() { long lastTime = System.currentTimeMillis(); mDrawTimes.addLast(lastTime); float dtime = lastTime - mDrawTimes.getFirst(); int frames = mDrawTimes.size(); if (frames > MAX_RECORD_SIZE) { mDrawTimes.removeFirst(); } return dtime > 0 ? mDrawTimes.size() * ONE_SECOND / dtime : 0.0f; } @Override public long drawDanmakus() { if (!isSurfaceCreated) return 0; if (!isShown()) return -1; long stime = System.currentTimeMillis(); lockCanvas(); return System.currentTimeMillis() - stime; } @SuppressLint("NewApi") private void postInvalidateCompat() { mRequestRender = true; if(Build.VERSION.SDK_INT >= 16) { this.postInvalidateOnAnimation(); } else { this.postInvalidate(); } } private void lockCanvas() { if(mDanmakuVisible == false) { return; } postInvalidateCompat(); synchronized (mDrawMonitor) { while ((!mDrawFinished) && (handler != null)) { try { mDrawMonitor.wait(200); } catch (InterruptedException e) { if (mDanmakuVisible == false || handler == null || handler.isStop()) { break; } else { Thread.currentThread().interrupt(); } } } mDrawFinished = false; } } private void lockCanvasAndClear() { mClearFlag = true; lockCanvas(); } private void unlockCanvasAndPost() { synchronized (mDrawMonitor) { mDrawFinished = true; mDrawMonitor.notifyAll(); } } @Override protected void onDraw(Canvas canvas) { if ((!mDanmakuVisible) && (!mRequestRender)) { super.onDraw(canvas); return; } if (mClearFlag) { DrawHelper.clearCanvas(canvas); mClearFlag = false; } else { if (handler != null) { RenderingState rs = handler.draw(canvas); if (mShowFps) { if (mDrawTimes == null) mDrawTimes = new LinkedList<Long>(); String fps = String.format(Locale.getDefault(), "fps %.2f,time:%d s,cache:%d,miss:%d", fps(), getCurrentTime() / 1000, rs.cacheHitCount, rs.cacheMissCount); DrawHelper.drawFPS(canvas, fps); } } } mRequestRender = false; unlockCanvasAndPost(); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (handler != null) { handler.notifyDispSizeChanged(right - left, bottom - top); } isSurfaceCreated = true; } public void toggle() { if (isSurfaceCreated) { if (handler == null) start(); else if (handler.isStop()) { resume(); } else pause(); } } @Override public void pause() { if (handler != null) handler.pause(); } private int mResumeTryCount = 0; private Runnable mResumeRunnable = new Runnable() { @Override public void run() { if (handler == null) { return; } mResumeTryCount++; if (mResumeTryCount > 4 || DanmakuView.super.isShown()) { handler.resume(); } else { handler.postDelayed(this, 100 * mResumeTryCount); } } }; @Override public void resume() { if (handler != null && handler.isPrepared()) { mResumeTryCount = 0; handler.postDelayed(mResumeRunnable, 100); } else if (handler == null) { restart(); } } @Override public boolean isPaused() { if(handler != null) { return handler.isStop(); } return false; } public void restart() { stop(); start(); } @Override public void start() { start(0); } @Override public void start(long postion) { if (handler == null) { prepare(); }else{ handler.removeCallbacksAndMessages(null); } handler.obtainMessage(DrawHandler.START, postion).sendToTarget(); } @Override public boolean onTouchEvent(MotionEvent event) { if (null != mTouchHelper) { mTouchHelper.onTouchEvent(event); } return super.onTouchEvent(event); } public void seekTo(Long ms) { if(handler != null){ handler.seekTo(ms); } } public void enableDanmakuDrawingCache(boolean enable) { mEnableDanmakuDrwaingCache = enable; } @Override public boolean isDanmakuDrawingCacheEnabled() { return mEnableDanmakuDrwaingCache; } @Override public boolean isViewReady() { return isSurfaceCreated; } @Override public View getView() { return this; } @Override public void show() { showAndResumeDrawTask(null); } @Override public void showAndResumeDrawTask(Long position) { mDanmakuVisible = true; mClearFlag = false; if (handler == null) { return; } handler.showDanmakus(position); } @Override public void hide() { mDanmakuVisible = false; if (handler == null) { return; } handler.hideDanmakus(false); } @Override public long hideAndPauseDrawTask() { mDanmakuVisible = false; if (handler == null) { return 0; } return handler.hideDanmakus(true); } @Override public void clear() { if (!isViewReady()) { return; } if (!mDanmakuVisible || Thread.currentThread().getId() == mUiThreadId) { mClearFlag = true; postInvalidateCompat(); } else { lockCanvasAndClear(); } } @Override public boolean isShown() { return mDanmakuVisible && super.isShown(); } @Override public void setDrawingThreadType(int type) { mDrawingThreadType = type; } @Override public long getCurrentTime() { if (handler != null) { return handler.getCurrentTime(); } return 0; } @Override @SuppressLint("NewApi") public boolean isHardwareAccelerated() { // >= 3.0 if (Build.VERSION.SDK_INT >= 11) { return super.isHardwareAccelerated(); } else { return false; } } @Override public void clearDanmakusOnScreen() { if (handler != null) { handler.clearDanmakusOnScreen(); } } @Override public void setOnDanmakuClickListener(OnDanmakuClickListener listener) { mOnDanmakuClickListener = listener; setClickable(null != listener); } @Override public OnDanmakuClickListener getOnDanmakuClickListener() { return mOnDanmakuClickListener; } }
DanmakuFlameMaster/src/main/java/master/flame/danmaku/ui/widget/DanmakuView.java
/* * Copyright (C) 2013 Chen Hui <calmer91@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package master.flame.danmaku.ui.widget; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.os.Build; import android.os.HandlerThread; import android.os.Looper; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import java.util.LinkedList; import java.util.Locale; import master.flame.danmaku.controller.DrawHandler; import master.flame.danmaku.controller.DrawHandler.Callback; import master.flame.danmaku.controller.DrawHelper; import master.flame.danmaku.controller.IDanmakuView; import master.flame.danmaku.controller.IDanmakuViewController; import master.flame.danmaku.danmaku.model.BaseDanmaku; import master.flame.danmaku.danmaku.model.IDanmakus; import master.flame.danmaku.danmaku.model.android.DanmakuContext; import master.flame.danmaku.danmaku.parser.BaseDanmakuParser; import master.flame.danmaku.danmaku.renderer.IRenderer.RenderingState; public class DanmakuView extends View implements IDanmakuView, IDanmakuViewController { public static final String TAG = "DanmakuView"; private Callback mCallback; private HandlerThread mHandlerThread; private DrawHandler handler; private boolean isSurfaceCreated; private boolean mEnableDanmakuDrwaingCache = true; private OnDanmakuClickListener mOnDanmakuClickListener; private DanmakuTouchHelper mTouchHelper; private boolean mShowFps; private boolean mDanmakuVisible = true; protected int mDrawingThreadType = THREAD_TYPE_NORMAL_PRIORITY; private Object mDrawMonitor = new Object(); private boolean mDrawFinished = false; private boolean mRequestRender = false; private long mUiThreadId; public DanmakuView(Context context) { super(context); init(); } private void init() { mUiThreadId = Thread.currentThread().getId(); setBackgroundColor(Color.TRANSPARENT); setDrawingCacheBackgroundColor(Color.TRANSPARENT); DrawHelper.useDrawColorToClearCanvas(true, false); mTouchHelper = DanmakuTouchHelper.instance(this); } public DanmakuView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public DanmakuView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public void addDanmaku(BaseDanmaku item) { if (handler != null) { handler.addDanmaku(item); } } @Override public void removeAllDanmakus() { if (handler != null) { handler.removeAllDanmakus(); } } @Override public void removeAllLiveDanmakus() { if (handler != null) { handler.removeAllLiveDanmakus(); } } @Override public IDanmakus getCurrentVisibleDanmakus() { if (handler != null) { return handler.getCurrentVisibleDanmakus(); } return null; } public void setCallback(Callback callback) { mCallback = callback; if (handler != null) { handler.setCallback(callback); } } @Override public void release() { stop(); if(mDrawTimes!= null) mDrawTimes.clear(); } @Override public void stop() { stopDraw(); } private void stopDraw() { if (handler != null) { handler.quit(); handler = null; } if (mHandlerThread != null) { try { mHandlerThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } mHandlerThread.quit(); mHandlerThread = null; } } protected Looper getLooper(int type){ if (mHandlerThread != null) { mHandlerThread.quit(); mHandlerThread = null; } int priority; switch (type) { case THREAD_TYPE_MAIN_THREAD: return Looper.getMainLooper(); case THREAD_TYPE_HIGH_PRIORITY: priority = android.os.Process.THREAD_PRIORITY_URGENT_DISPLAY; break; case THREAD_TYPE_LOW_PRIORITY: priority = android.os.Process.THREAD_PRIORITY_LOWEST; break; case THREAD_TYPE_NORMAL_PRIORITY: default: priority = android.os.Process.THREAD_PRIORITY_DEFAULT; break; } String threadName = "DFM Handler Thread #"+priority; mHandlerThread = new HandlerThread(threadName, priority); mHandlerThread.start(); return mHandlerThread.getLooper(); } private void prepare() { if (handler == null) handler = new DrawHandler(getLooper(mDrawingThreadType), this, mDanmakuVisible); } @Override public void prepare(BaseDanmakuParser parser, DanmakuContext config) { prepare(); handler.setConfig(config); handler.setParser(parser); handler.setCallback(mCallback); handler.prepare(); } @Override public boolean isPrepared() { return handler != null && handler.isPrepared(); } @Override public DanmakuContext getConfig() { if (handler == null) { return null; } return handler.getConfig(); } @Override public void showFPS(boolean show){ mShowFps = show; } private static final int MAX_RECORD_SIZE = 50; private static final int ONE_SECOND = 1000; private LinkedList<Long> mDrawTimes; private boolean mClearFlag; private float fps() { long lastTime = System.currentTimeMillis(); mDrawTimes.addLast(lastTime); float dtime = lastTime - mDrawTimes.getFirst(); int frames = mDrawTimes.size(); if (frames > MAX_RECORD_SIZE) { mDrawTimes.removeFirst(); } return dtime > 0 ? mDrawTimes.size() * ONE_SECOND / dtime : 0.0f; } @Override public long drawDanmakus() { if (!isSurfaceCreated) return 0; if (!isShown()) return -1; long stime = System.currentTimeMillis(); lockCanvas(); return System.currentTimeMillis() - stime; } @SuppressLint("NewApi") private void postInvalidateCompat() { mRequestRender = true; if(Build.VERSION.SDK_INT >= 16) { this.postInvalidateOnAnimation(); } else { this.postInvalidate(); } } private void lockCanvas() { if(mDanmakuVisible == false) { return; } postInvalidateCompat(); synchronized (mDrawMonitor) { while ((!mDrawFinished) && (handler != null)) { try { mDrawMonitor.wait(200); } catch (InterruptedException e) { if (mDanmakuVisible == false || handler == null || handler.isStop()) { break; } else { Thread.currentThread().interrupt(); } } } mDrawFinished = false; } } private void lockCanvasAndClear() { mClearFlag = true; lockCanvas(); } private void unlockCanvasAndPost() { synchronized (mDrawMonitor) { mDrawFinished = true; mDrawMonitor.notifyAll(); } } @Override protected void onDraw(Canvas canvas) { if ((!mDanmakuVisible) && (!mRequestRender)) { super.onDraw(canvas); return; } if (mClearFlag) { DrawHelper.clearCanvas(canvas); mClearFlag = false; } else { if (handler != null) { RenderingState rs = handler.draw(canvas); if (mShowFps) { if (mDrawTimes == null) mDrawTimes = new LinkedList<Long>(); String fps = String.format(Locale.getDefault(), "fps %.2f,time:%d s,cache:%d,miss:%d", fps(), getCurrentTime() / 1000, rs.cacheHitCount, rs.cacheMissCount); DrawHelper.drawFPS(canvas, fps); } } } mRequestRender = false; unlockCanvasAndPost(); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (handler != null) { handler.notifyDispSizeChanged(right - left, bottom - top); } isSurfaceCreated = true; } public void toggle() { if (isSurfaceCreated) { if (handler == null) start(); else if (handler.isStop()) { resume(); } else pause(); } } @Override public void pause() { if (handler != null) handler.pause(); } @Override public void resume() { if (handler != null && handler.isPrepared()) handler.resume(); else if (handler == null) { restart(); } } @Override public boolean isPaused() { if(handler != null) { return handler.isStop(); } return false; } public void restart() { stop(); start(); } @Override public void start() { start(0); } @Override public void start(long postion) { if (handler == null) { prepare(); }else{ handler.removeCallbacksAndMessages(null); } handler.obtainMessage(DrawHandler.START, postion).sendToTarget(); } @Override public boolean onTouchEvent(MotionEvent event) { if (null != mTouchHelper) { mTouchHelper.onTouchEvent(event); } return super.onTouchEvent(event); } public void seekTo(Long ms) { if(handler != null){ handler.seekTo(ms); } } public void enableDanmakuDrawingCache(boolean enable) { mEnableDanmakuDrwaingCache = enable; } @Override public boolean isDanmakuDrawingCacheEnabled() { return mEnableDanmakuDrwaingCache; } @Override public boolean isViewReady() { return isSurfaceCreated; } @Override public View getView() { return this; } @Override public void show() { showAndResumeDrawTask(null); } @Override public void showAndResumeDrawTask(Long position) { mDanmakuVisible = true; mClearFlag = false; if (handler == null) { return; } handler.showDanmakus(position); } @Override public void hide() { mDanmakuVisible = false; if (handler == null) { return; } handler.hideDanmakus(false); } @Override public long hideAndPauseDrawTask() { mDanmakuVisible = false; if (handler == null) { return 0; } return handler.hideDanmakus(true); } @Override public void clear() { if (!isViewReady()) { return; } if (!mDanmakuVisible || Thread.currentThread().getId() == mUiThreadId) { mClearFlag = true; postInvalidateCompat(); } else { lockCanvasAndClear(); } } @Override public boolean isShown() { return mDanmakuVisible && super.isShown(); } @Override public void setDrawingThreadType(int type) { mDrawingThreadType = type; } @Override public long getCurrentTime() { if (handler != null) { return handler.getCurrentTime(); } return 0; } @Override @SuppressLint("NewApi") public boolean isHardwareAccelerated() { // >= 3.0 if (Build.VERSION.SDK_INT >= 11) { return super.isHardwareAccelerated(); } else { return false; } } @Override public void clearDanmakusOnScreen() { if (handler != null) { handler.clearDanmakusOnScreen(); } } @Override public void setOnDanmakuClickListener(OnDanmakuClickListener listener) { mOnDanmakuClickListener = listener; setClickable(null != listener); } @Override public OnDanmakuClickListener getOnDanmakuClickListener() { return mOnDanmakuClickListener; } }
DanmakuView: avoid some resume issue while view is not shown
DanmakuFlameMaster/src/main/java/master/flame/danmaku/ui/widget/DanmakuView.java
DanmakuView: avoid some resume issue while view is not shown
Java
apache-2.0
fa93da1d098d1624320c17bb442d46dbdf7be6b6
0
scalio/storypath,StoryMaker/storypath,n8fr8/storypath,StoryMaker/storypath,n8fr8/storypath,scalio/storypath,n8fr8/storypath,scalio/storypath,StoryMaker/storypath
package scal.io.liger.view; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.text.Html; import android.text.Spanned; import android.text.method.LinkMovementMethod; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import scal.io.liger.R; import scal.io.liger.Utility; import scal.io.liger.ZipHelper; import scal.io.liger.model.Card; import scal.io.liger.model.MarkdownCard; import com.commonsware.cwac.anddown.AndDown; public class MarkdownCardView implements DisplayableCard { private MarkdownCard mCardModel; private Context mContext; public MarkdownCardView(Context context, Card cardModel) { mContext = context; mCardModel = (MarkdownCard) cardModel; } @Override public View getCardView(Context context) { if (mCardModel == null) { return null; } /* View view = LayoutInflater.from(context).inflate(R.layout.card_markdown, null); WebView webview = (WebView) view.findViewById(R.id.webView); AndDown andDown = new AndDown(); String[] splits = "Line 1\n* bullet 1\n* bullet 2".split("\n"); String html = ""; for (String s: splits) { html += andDown.markdownToHtml(s); } webview.loadData(html, "text/html", "UTF-8"); webview.invalidate(); */ View view = LayoutInflater.from(context).inflate(R.layout.card_markdown, null); TextView tvText = ((TextView) view.findViewById(R.id.tv_text)); AndDown andDown = new AndDown(); String html = andDown.markdownToHtml(mCardModel.getText()); /* String[] splits = "Line 1\n## header 1\n### header 2".split("\n"); String html = ""; for (String s: splits) { html += andDown.markdownToHtml(s); Spanned htmlSpanned = Html.fromHtml(html); tvText.append(htmlSpanned); } */ tvText.setLinksClickable(true); tvText.setMovementMethod(LinkMovementMethod.getInstance()); Spanned htmlSpanned = Html.fromHtml(html, new Html.ImageGetter() { @Override public Drawable getDrawable(final String source) { String absPath = mCardModel.getStoryPath().buildZipPath(source); Bitmap myBitmap = BitmapFactory.decodeStream(ZipHelper.getFileInputStream(absPath, mContext)); Drawable d = new BitmapDrawable(mContext.getResources(), myBitmap); d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); return d; } }, null); tvText.setText(Utility.trimTrailingWhitespace(htmlSpanned)); // supports automated testing view.setTag(mCardModel.getId()); return view; } }
lib/src/main/java/scal/io/liger/view/MarkdownCardView.java
package scal.io.liger.view; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.text.Html; import android.text.Spanned; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import scal.io.liger.R; import scal.io.liger.Utility; import scal.io.liger.ZipHelper; import scal.io.liger.model.Card; import scal.io.liger.model.MarkdownCard; import com.commonsware.cwac.anddown.AndDown; public class MarkdownCardView implements DisplayableCard { private MarkdownCard mCardModel; private Context mContext; public MarkdownCardView(Context context, Card cardModel) { mContext = context; mCardModel = (MarkdownCard) cardModel; } @Override public View getCardView(Context context) { if (mCardModel == null) { return null; } /* View view = LayoutInflater.from(context).inflate(R.layout.card_markdown, null); WebView webview = (WebView) view.findViewById(R.id.webView); AndDown andDown = new AndDown(); String[] splits = "Line 1\n* bullet 1\n* bullet 2".split("\n"); String html = ""; for (String s: splits) { html += andDown.markdownToHtml(s); } webview.loadData(html, "text/html", "UTF-8"); webview.invalidate(); */ View view = LayoutInflater.from(context).inflate(R.layout.card_markdown, null); TextView tvText = ((TextView) view.findViewById(R.id.tv_text)); AndDown andDown = new AndDown(); String html = andDown.markdownToHtml(mCardModel.getText()); /* String[] splits = "Line 1\n## header 1\n### header 2".split("\n"); String html = ""; for (String s: splits) { html += andDown.markdownToHtml(s); Spanned htmlSpanned = Html.fromHtml(html); tvText.append(htmlSpanned); } */ Spanned htmlSpanned = Html.fromHtml(html, new Html.ImageGetter() { @Override public Drawable getDrawable(final String source) { String absPath = mCardModel.getStoryPath().buildZipPath(source); Bitmap myBitmap = BitmapFactory.decodeStream(ZipHelper.getFileInputStream(absPath, mContext)); Drawable d = new BitmapDrawable(mContext.getResources(), myBitmap); d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); return d; } }, null); tvText.setText(Utility.trimTrailingWhitespace(htmlSpanned)); // supports automated testing view.setTag(mCardModel.getId()); return view; } }
make links clickable in markdowncards
lib/src/main/java/scal/io/liger/view/MarkdownCardView.java
make links clickable in markdowncards
Java
apache-2.0
89c932c682a8079d04ff122d373d7bbe40bbcb13
0
wyzssw/orientdb,cstamas/orientdb,sanyaade-g2g-repos/orientdb,joansmith/orientdb,cstamas/orientdb,intfrr/orientdb,giastfader/orientdb,joansmith/orientdb,wouterv/orientdb,tempbottle/orientdb,wyzssw/orientdb,mbhulin/orientdb,wouterv/orientdb,mbhulin/orientdb,tempbottle/orientdb,joansmith/orientdb,intfrr/orientdb,intfrr/orientdb,alonsod86/orientdb,jdillon/orientdb,tempbottle/orientdb,sanyaade-g2g-repos/orientdb,orientechnologies/orientdb,giastfader/orientdb,joansmith/orientdb,allanmoso/orientdb,rprabhat/orientdb,orientechnologies/orientdb,mmacfadden/orientdb,mmacfadden/orientdb,mbhulin/orientdb,alonsod86/orientdb,orientechnologies/orientdb,rprabhat/orientdb,wouterv/orientdb,alonsod86/orientdb,sanyaade-g2g-repos/orientdb,tempbottle/orientdb,alonsod86/orientdb,wouterv/orientdb,mbhulin/orientdb,sanyaade-g2g-repos/orientdb,jdillon/orientdb,intfrr/orientdb,cstamas/orientdb,rprabhat/orientdb,giastfader/orientdb,rprabhat/orientdb,mmacfadden/orientdb,wyzssw/orientdb,orientechnologies/orientdb,jdillon/orientdb,allanmoso/orientdb,allanmoso/orientdb,allanmoso/orientdb,cstamas/orientdb,wyzssw/orientdb,giastfader/orientdb,mmacfadden/orientdb
/* * Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.orient.server.task; import java.io.IOException; import java.util.Map; import java.util.Map.Entry; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.orient.core.db.record.ORecordOperation; import com.orientechnologies.orient.core.id.ORecordId; import com.orientechnologies.orient.core.version.ORecordVersion; import com.orientechnologies.orient.server.distributed.*; import com.orientechnologies.orient.server.distributed.ODistributedServerManager.EXECUTION_MODE; import com.orientechnologies.orient.server.journal.ODatabaseJournal.OPERATION_TYPES; /** * Distributed create record task used for synchronization. * * @author Luca Garulli (l.garulli--at--orientechnologies.com) * */ public abstract class OAbstractRecordDistributedTask<T> extends OAbstractDistributedTask<T> { protected ORecordId rid; protected ORecordVersion version; public OAbstractRecordDistributedTask() { } public OAbstractRecordDistributedTask(final String nodeSource, final String iDbName, final EXECUTION_MODE iMode, final ORecordId iRid, final ORecordVersion iVersion) { super(nodeSource, iDbName, iMode); this.rid = iRid; this.version = iVersion; } public OAbstractRecordDistributedTask(final long iRunId, final long iOperationId, final ORecordId iRid, final ORecordVersion iVersion) { super(iRunId, iOperationId); this.rid = iRid; this.version = iVersion; } protected abstract OPERATION_TYPES getOperationType(); protected abstract T executeOnLocalNode(final OStorageSynchronizer dbSynchronizer); public T call() { if (OLogManager.instance().isDebugEnabled()) OLogManager.instance().debug(this, "DISTRIBUTED <-[%s] %s %s v.%d", nodeSource, getName(), rid, version); final ODistributedServerManager dManager = getDistributedServerManager(); if (status != STATUS.ALIGN && !dManager.checkStatus("online") && !nodeSource.equals(dManager.getLocalNodeId())) // NODE NOT ONLINE, REFUSE THE OPEPRATION throw new OServerOfflineException(dManager.getLocalNodeId(), "Cannot execute the operation because the server is offline: current status: " + dManager.getStatus()); final OStorageSynchronizer dbSynchronizer = getDatabaseSynchronizer(); final OPERATION_TYPES opType = getOperationType(); // LOG THE OPERATION BEFORE TO SEND TO OTHER NODES final long operationLogOffset; if (opType != null) try { operationLogOffset = dbSynchronizer.getLog().journalOperation(runId, operationSerial, opType, this); } catch (IOException e) { OLogManager.instance().error(this, "DISTRIBUTED <-[%s] error on logging operation %s %s v.%s", e, nodeSource, getName(), rid, version); throw new ODistributedException("Error on logging operation", e); } else operationLogOffset = -1; ODistributedThreadLocal.INSTANCE.distributedExecution = true; try { // EXECUTE IT LOCALLY final T localResult = executeOnLocalNode(dbSynchronizer); if (opType != null) try { setAsCompleted(dbSynchronizer, operationLogOffset); } catch (IOException e) { OLogManager.instance().error(this, "DISTRIBUTED <-[%s] error on changing the log status for operation %s %s v.%d", e, nodeSource, getName(), rid, version); throw new ODistributedException("Error on changing the log status", e); } // TODO if (status == STATUS.DISTRIBUTE) { // SEND OPERATION ACROSS THE CLUSTER TO THE TARGET NODES final Map<String, Object> distributedResult = dbSynchronizer.distributeOperation(ORecordOperation.CREATED, rid, this); if (distributedResult != null) for (Entry<String, Object> entry : distributedResult.entrySet()) { final String remoteNode = entry.getKey(); final Object remoteResult = entry.getValue(); if (localResult != remoteResult && (localResult == null && remoteResult != null || localResult != null && remoteResult == null)) { // CONFLICT handleConflict(remoteNode, localResult, remoteResult); } } } if (mode != EXECUTION_MODE.FIRE_AND_FORGET) return localResult; // FIRE AND FORGET MODE: AVOID THE PAYLOAD AS RESULT return null; } finally { ODistributedThreadLocal.INSTANCE.distributedExecution = false; } } @Override public String toString() { return getName() + "(" + rid + " v." + version + ")"; } public ORecordId getRid() { return rid; } public void setRid(ORecordId rid) { this.rid = rid; } public ORecordVersion getVersion() { return version; } public void setVersion(ORecordVersion version) { this.version = version; } }
server/src/main/java/com/orientechnologies/orient/server/task/OAbstractRecordDistributedTask.java
/* * Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.orient.server.task; import java.io.IOException; import java.util.Map; import java.util.Map.Entry; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.orient.core.db.record.ORecordOperation; import com.orientechnologies.orient.core.id.ORecordId; import com.orientechnologies.orient.core.version.ORecordVersion; import com.orientechnologies.orient.server.distributed.*; import com.orientechnologies.orient.server.distributed.ODistributedServerManager.EXECUTION_MODE; import com.orientechnologies.orient.server.journal.ODatabaseJournal.OPERATION_TYPES; /** * Distributed create record task used for synchronization. * * @author Luca Garulli (l.garulli--at--orientechnologies.com) * */ public abstract class OAbstractRecordDistributedTask<T> extends OAbstractDistributedTask<T> { protected ORecordId rid; protected ORecordVersion version; public OAbstractRecordDistributedTask() { } public OAbstractRecordDistributedTask(final String nodeSource, final String iDbName, final EXECUTION_MODE iMode, final ORecordId iRid, final ORecordVersion iVersion) { super(nodeSource, iDbName, iMode); this.rid = iRid; this.version = iVersion; } public OAbstractRecordDistributedTask(final long iRunId, final long iOperationId, final ORecordId iRid, final ORecordVersion iVersion) { super(iRunId, iOperationId); this.rid = iRid; this.version = iVersion; } protected abstract OPERATION_TYPES getOperationType(); protected abstract T executeOnLocalNode(final OStorageSynchronizer dbSynchronizer); public T call() { if (OLogManager.instance().isDebugEnabled()) OLogManager.instance().debug(this, "DISTRIBUTED <-[%s] %s %s v.%d", nodeSource, getName(), rid, version); final ODistributedServerManager dManager = getDistributedServerManager(); if (status != STATUS.ALIGN && !dManager.checkStatus("online") && !nodeSource.equals(dManager.getLocalNodeId())) // NODE NOT ONLINE, REFUSE THE OPEPRATION throw new OServerOfflineException(dManager.getLocalNodeId(), "Cannot execute the operation because the server is offline: current status: " + dManager.getStatus()); final OStorageSynchronizer dbSynchronizer = getDatabaseSynchronizer(); final OPERATION_TYPES opType = getOperationType(); // LOG THE OPERATION BEFORE TO SEND TO OTHER NODES final long operationLogOffset; if (opType != null) try { operationLogOffset = dbSynchronizer.getLog().journalOperation(runId, operationSerial, opType, this); } catch (IOException e) { OLogManager.instance().error(this, "DISTRIBUTED <-[%s] error on logging operation %s %s v.%d", e, nodeSource, getName(), rid, version); throw new ODistributedException("Error on logging operation", e); } else operationLogOffset = -1; ODistributedThreadLocal.INSTANCE.distributedExecution = true; try { // EXECUTE IT LOCALLY final T localResult = executeOnLocalNode(dbSynchronizer); if (opType != null) try { setAsCompleted(dbSynchronizer, operationLogOffset); } catch (IOException e) { OLogManager.instance().error(this, "DISTRIBUTED <-[%s] error on changing the log status for operation %s %s v.%d", e, nodeSource, getName(), rid, version); throw new ODistributedException("Error on changing the log status", e); } // TODO if (status == STATUS.DISTRIBUTE) { // SEND OPERATION ACROSS THE CLUSTER TO THE TARGET NODES final Map<String, Object> distributedResult = dbSynchronizer.distributeOperation(ORecordOperation.CREATED, rid, this); if (distributedResult != null) for (Entry<String, Object> entry : distributedResult.entrySet()) { final String remoteNode = entry.getKey(); final Object remoteResult = entry.getValue(); if (localResult != remoteResult && (localResult == null && remoteResult != null || localResult != null && remoteResult == null)) { // CONFLICT handleConflict(remoteNode, localResult, remoteResult); } } } if (mode != EXECUTION_MODE.FIRE_AND_FORGET) return localResult; // FIRE AND FORGET MODE: AVOID THE PAYLOAD AS RESULT return null; } finally { ODistributedThreadLocal.INSTANCE.distributedExecution = false; } } @Override public String toString() { return getName() + "(" + rid + " v." + version + ")"; } public ORecordId getRid() { return rid; } public void setRid(ORecordId rid) { this.rid = rid; } public ORecordVersion getVersion() { return version; } public void setVersion(ORecordVersion version) { this.version = version; } }
Fixed issue #1260
server/src/main/java/com/orientechnologies/orient/server/task/OAbstractRecordDistributedTask.java
Fixed issue #1260
Java
apache-2.0
9ac22ab0e53995b0ab6a66a7aba304ba77b3f8aa
0
nextreports/nextreports-server,nextreports/nextreports-server,nextreports/nextreports-server,nextreports/nextreports-server
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.nextreports.server.licence; import java.io.File; import java.io.InputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import licence.nextserver.LicenceException; import licence.nextserver.LicenseLoader; import licence.nextserver.NextServerLicense; public class NextServerModuleLicence implements ModuleLicence { private static final Logger LOG = LoggerFactory.getLogger(NextServerModuleLicence.class); public static final String LICENCES_FOLDER = "licences"; public static final String ANALYSIS_MODULE = "analysismdl"; public static final String BATCH_MODULE = "batchmdl"; public static final String AUDIT_MODULE = "auditmdl"; @Override public boolean isValid(String moduleName) { File f = new File("./" + LICENCES_FOLDER + "/" + moduleName + ".key"); LOG.info("* Licence " + moduleName + " : " + f.exists()); try { NextServerLicense licence = LicenseLoader.decodeLicence(f); if (licence.isValid() && moduleName.equals(licence.getPCODE())) { return true; } } catch (LicenceException e) { // try to get from classpath (need for war version) LOG.info("* Licence " + moduleName + " : try to get it from classpath."); InputStream input = getClass().getResourceAsStream("/" + moduleName + ".key"); if (input == null) { LOG.info("* Licence " + moduleName + " : not found in classpath."); } try { NextServerLicense licence = LicenseLoader.decodeLicence(input); if (licence.isValid() && moduleName.equals(licence.getPCODE())) { return true; } } catch (LicenceException ex) { LOG.info("Invalid licence for " + moduleName + " module."); } } return false; } }
src/ro/nextreports/server/licence/NextServerModuleLicence.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.nextreports.server.licence; import java.io.File; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import licence.nextserver.LicenceException; import licence.nextserver.LicenseLoader; import licence.nextserver.NextServerLicense; public class NextServerModuleLicence implements ModuleLicence { private static final Logger LOG = LoggerFactory.getLogger(NextServerModuleLicence.class); public static final String LICENCES_FOLDER = "licences"; public static final String ANALYSIS_MODULE = "analysismdl"; public static final String BATCH_MODULE = "batchmdl"; public static final String AUDIT_MODULE = "auditmdl"; @Override public boolean isValid(String moduleName) { File f = new File("./" + LICENCES_FOLDER + "/" + moduleName + ".key"); LOG.info("* Licence " + moduleName + " : " + f.exists()); try { NextServerLicense licence = LicenseLoader.decodeLicence(f); if (licence.isValid() && moduleName.equals(licence.getPCODE())) { return true; } } catch (LicenceException e) { LOG.info("Invalid licence for " + moduleName + " module."); } return false; } }
try to get licence from classpath
src/ro/nextreports/server/licence/NextServerModuleLicence.java
try to get licence from classpath
Java
apache-2.0
e81d7e95c56ba5c37bbe7d25b55e522a7f716471
0
VinodKumarS-Huawei/ietf96yang,sdnwiselab/onos,mengmoya/onos,gkatsikas/onos,kuujo/onos,opennetworkinglab/onos,y-higuchi/onos,maheshraju-Huawei/actn,LorenzReinhart/ONOSnew,sdnwiselab/onos,LorenzReinhart/ONOSnew,oplinkoms/onos,y-higuchi/onos,Shashikanth-Huawei/bmp,opennetworkinglab/onos,y-higuchi/onos,VinodKumarS-Huawei/ietf96yang,oplinkoms/onos,kuujo/onos,maheshraju-Huawei/actn,kuujo/onos,mengmoya/onos,Shashikanth-Huawei/bmp,osinstom/onos,Shashikanth-Huawei/bmp,donNewtonAlpha/onos,Shashikanth-Huawei/bmp,y-higuchi/onos,Shashikanth-Huawei/bmp,mengmoya/onos,kuujo/onos,sdnwiselab/onos,osinstom/onos,donNewtonAlpha/onos,opennetworkinglab/onos,maheshraju-Huawei/actn,osinstom/onos,sdnwiselab/onos,maheshraju-Huawei/actn,mengmoya/onos,oplinkoms/onos,VinodKumarS-Huawei/ietf96yang,kuujo/onos,opennetworkinglab/onos,mengmoya/onos,sdnwiselab/onos,gkatsikas/onos,oplinkoms/onos,donNewtonAlpha/onos,sdnwiselab/onos,osinstom/onos,gkatsikas/onos,opennetworkinglab/onos,oplinkoms/onos,LorenzReinhart/ONOSnew,kuujo/onos,opennetworkinglab/onos,VinodKumarS-Huawei/ietf96yang,osinstom/onos,donNewtonAlpha/onos,donNewtonAlpha/onos,VinodKumarS-Huawei/ietf96yang,maheshraju-Huawei/actn,gkatsikas/onos,y-higuchi/onos,LorenzReinhart/ONOSnew,gkatsikas/onos,gkatsikas/onos,oplinkoms/onos,LorenzReinhart/ONOSnew,oplinkoms/onos,kuujo/onos
/* * Copyright 2016-present Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.driver.extensions; import com.google.common.base.MoreObjects; import com.google.common.collect.Maps; import org.onlab.util.KryoNamespace; import org.onosproject.net.flow.AbstractExtension; import org.onosproject.net.flow.instructions.ExtensionTreatmentType; import java.util.Map; import java.util.Objects; /** * Default implementation of Move treatment. */ public class DefaultMoveExtensionTreatment extends AbstractExtension implements MoveExtensionTreatment { private int srcOfs; private int dstOfs; private int nBits; private int src; private int dst; private ExtensionTreatmentType type; private final KryoNamespace appKryo = new KryoNamespace.Builder() .register(byte[].class) .register(Map.class) .build("DefaultMoveExtensionTreatment"); /** * Creates a new move Treatment. * * @param srcOfs source offset * @param dstOfs destination offset * @param nBits nbits * @param src source * @param dst destination * @param type extension treatment type */ public DefaultMoveExtensionTreatment(int srcOfs, int dstOfs, int nBits, int src, int dst, ExtensionTreatmentType type) { this.srcOfs = srcOfs; this.dstOfs = dstOfs; this.nBits = nBits; this.src = src; this.dst = dst; this.type = type; } @Override public ExtensionTreatmentType type() { return type; } @Override public byte[] serialize() { Map<String, Integer> values = Maps.newHashMap(); values.put("srcOfs", srcOfs); values.put("dstOfs", dstOfs); values.put("nBits", nBits); values.put("src", src); values.put("dst", dst); values.put("type", ExtensionTreatmentType.ExtensionTreatmentTypes.valueOf(type.toString()).ordinal()); return appKryo.serialize(values); } @Override public void deserialize(byte[] data) { Map<String, Integer> values = appKryo.deserialize(data); srcOfs = values.get("srcOfs"); dstOfs = values.get("dstOfs"); nBits = values.get("nBits"); src = values.get("src"); dst = values.get("dst"); type = new ExtensionTreatmentType(values.get("type").intValue()); } @Override public int srcOffset() { return srcOfs; } @Override public int dstOffset() { return dstOfs; } @Override public int src() { return src; } @Override public int dst() { return dst; } @Override public int nBits() { return nBits; } @Override public int hashCode() { return Objects.hash(srcOfs, dstOfs, src, dst, nBits); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof DefaultMoveExtensionTreatment) { DefaultMoveExtensionTreatment that = (DefaultMoveExtensionTreatment) obj; return Objects.equals(srcOfs, that.srcOfs) && Objects.equals(dstOfs, that.dstOfs) && Objects.equals(src, that.src) && Objects.equals(dst, that.dst) && Objects.equals(nBits, that.nBits); } return false; } @Override public String toString() { return MoreObjects.toStringHelper(getClass()).add("srcOfs", srcOfs) .add("dstOfs", dstOfs).add("nBits", nBits).add("src", src) .add("dst", dst).toString(); } }
drivers/default/src/main/java/org/onosproject/driver/extensions/DefaultMoveExtensionTreatment.java
/* * Copyright 2016-present Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.driver.extensions; import com.google.common.base.MoreObjects; import com.google.common.collect.Maps; import org.onlab.util.KryoNamespace; import org.onosproject.net.flow.AbstractExtension; import org.onosproject.net.flow.instructions.ExtensionTreatmentType; import java.util.Map; import java.util.Objects; /** * Default implementation of Move treatment. */ public class DefaultMoveExtensionTreatment extends AbstractExtension implements MoveExtensionTreatment { private int srcOfs; private int dstOfs; private int nBits; private int src; private int dst; private ExtensionTreatmentType type; private final KryoNamespace appKryo = new KryoNamespace.Builder() .register(byte[].class).register(Integer.class).register(Map.class) .build("DefaultMoveExtensionTreatment"); /** * Creates a new move Treatment. * * @param srcOfs source offset * @param dstOfs destination offset * @param nBits nbits * @param src source * @param dst destination * @param type extension treatment type */ public DefaultMoveExtensionTreatment(int srcOfs, int dstOfs, int nBits, int src, int dst, ExtensionTreatmentType type) { this.srcOfs = srcOfs; this.dstOfs = dstOfs; this.nBits = nBits; this.src = src; this.dst = dst; this.type = type; } @Override public ExtensionTreatmentType type() { return type; } @Override public byte[] serialize() { Map<String, Integer> values = Maps.newHashMap(); values.put("srcOfs", srcOfs); values.put("dstOfs", dstOfs); values.put("nBits", nBits); values.put("src", src); values.put("dst", dst); values.put("type", ExtensionTreatmentType.ExtensionTreatmentTypes.valueOf(type.toString()).ordinal()); return appKryo.serialize(values); } @Override public void deserialize(byte[] data) { Map<String, Integer> values = appKryo.deserialize(data); srcOfs = values.get("srcOfs"); dstOfs = values.get("dstOfs"); nBits = values.get("nBits"); src = values.get("src"); dst = values.get("dst"); type = new ExtensionTreatmentType(values.get("type").intValue()); } @Override public int srcOffset() { return srcOfs; } @Override public int dstOffset() { return dstOfs; } @Override public int src() { return src; } @Override public int dst() { return dst; } @Override public int nBits() { return nBits; } @Override public int hashCode() { return Objects.hash(srcOfs, dstOfs, src, dst, nBits); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof DefaultMoveExtensionTreatment) { DefaultMoveExtensionTreatment that = (DefaultMoveExtensionTreatment) obj; return Objects.equals(srcOfs, that.srcOfs) && Objects.equals(dstOfs, that.dstOfs) && Objects.equals(src, that.src) && Objects.equals(dst, that.dst) && Objects.equals(nBits, that.nBits); } return false; } @Override public String toString() { return MoreObjects.toStringHelper(getClass()).add("srcOfs", srcOfs) .add("dstOfs", dstOfs).add("nBits", nBits).add("src", src) .add("dst", dst).toString(); } }
int/Integer is pre-registered to Kryo. Change-Id: Ib66d8f3aac62ae837211d0e362207965403b4ead
drivers/default/src/main/java/org/onosproject/driver/extensions/DefaultMoveExtensionTreatment.java
int/Integer is pre-registered to Kryo.
Java
apache-2.0
2e881724e3a8fdb93c070d9c7dd7b7564c799ac5
0
uniqueid001/enunciate,nabilzhang/enunciate,uniqueid001/enunciate,nabilzhang/enunciate,nabilzhang/enunciate,uniqueid001/enunciate,uniqueid001/enunciate,nabilzhang/enunciate,uniqueid001/enunciate,nabilzhang/enunciate,nabilzhang/enunciate,nabilzhang/enunciate,uniqueid001/enunciate,uniqueid001/enunciate,uniqueid001/enunciate
package com.webcohesion.enunciate.mojo; import com.webcohesion.enunciate.module.DocumentationProviderModule; import com.webcohesion.enunciate.module.EnunciateModule; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.apache.maven.reporting.MavenReport; import org.apache.maven.reporting.MavenReportException; import org.codehaus.doxia.sink.Sink; import java.io.File; import java.util.Locale; /** * Generates the Enunciate documentation, including any client-side libraries. * * @author Ryan Heaton */ @Mojo ( name = "docs", defaultPhase = LifecyclePhase.PROCESS_SOURCES, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME ) public class DocsBaseMojo extends ConfigMojo implements MavenReport { /** * The directory where the docs are put. */ @Parameter( defaultValue = "${project.reporting.outputDirectory}", property = "enunciate.docsDir", required = true ) protected String docsDir; /** * The name of the subdirectory where the documentation is put. */ @Parameter protected String docsSubdir = "apidocs"; /** * The name of the index page. */ @Parameter protected String indexPageName; /** * The name of the docs report. */ @Parameter( defaultValue = "Web Service API") protected String reportName; /** * The description of the docs report. */ @Parameter( defaultValue = "Web Service API Documentation" ) protected String reportDescription; @Override public void execute() throws MojoExecutionException { if (skipEnunciate) { getLog().info("Skipping enunciate per configuration."); return; } //todo: set the docs output dir. super.execute(); } @Override protected void applyAdditionalConfiguration(EnunciateModule module) { super.applyAdditionalConfiguration(module); if (module instanceof DocumentationProviderModule) { DocumentationProviderModule docsProvider = (DocumentationProviderModule) module; docsProvider.setDefaultDocsDir(new File(this.docsDir)); if (this.docsSubdir != null) { docsProvider.setDefaultDocsSubdir(this.docsSubdir); } } } public void generate(Sink sink, Locale locale) throws MavenReportException { //first get rid of the empty page the the site plugin puts there, in order to make room for the documentation. new File(getReportOutputDirectory(), this.indexPageName == null ? "index.html" : this.indexPageName).delete(); // for some reason, when running in the "site" lifecycle, the context classloader // doesn't get set up the same way it does when doing the default lifecycle // so we have to set it up manually here. ClassLoader old = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); execute(); } catch (MojoExecutionException e) { throw new MavenReportException("Unable to generate web service documentation report", e); } finally { Thread.currentThread().setContextClassLoader(old); } } public String getOutputName() { String indexName = "index"; if (this.indexPageName != null) { if (this.indexPageName.indexOf('.') > 0) { indexName = this.indexPageName.substring(0, this.indexPageName.indexOf('.')); } else { indexName = this.indexPageName; } } return this.docsSubdir == null ? indexName : (this.docsSubdir + "/" + indexName); } public String getName(Locale locale) { return this.reportName; } public String getCategoryName() { return CATEGORY_PROJECT_REPORTS; } public String getDescription(Locale locale) { return this.reportDescription; } public void setReportOutputDirectory(File outputDirectory) { this.docsDir = outputDirectory.getAbsolutePath(); } public File getReportOutputDirectory() { File outputDir = new File(this.docsDir); if (this.docsSubdir != null) { outputDir = new File(outputDir, this.docsSubdir); } return outputDir; } public boolean isExternalReport() { return true; } public boolean canGenerateReport() { return true; } }
slim-maven-plugin/src/main/java/com/webcohesion/enunciate/mojo/DocsBaseMojo.java
package com.webcohesion.enunciate.mojo; import com.webcohesion.enunciate.module.DocumentationProviderModule; import com.webcohesion.enunciate.module.EnunciateModule; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.apache.maven.reporting.MavenReport; import org.apache.maven.reporting.MavenReportException; import org.codehaus.doxia.sink.Sink; import java.io.File; import java.util.Locale; /** * Generates the Enunciate documentation, including any client-side libraries. * * @author Ryan Heaton */ @Mojo ( name = "docs", defaultPhase = LifecyclePhase.PROCESS_SOURCES, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME ) public class DocsBaseMojo extends ConfigMojo implements MavenReport { /** * The directory where the docs are put. */ @Parameter( defaultValue = "${project.reporting.outputDirectory}/apidocs", property = "enunciate.docsDir", required = true ) protected String docsDir; /** * The name of the subdirectory where the documentation is put. */ @Parameter protected String docsSubdir; /** * The name of the index page. */ @Parameter protected String indexPageName; /** * The name of the docs report. */ @Parameter( defaultValue = "Web Service API") protected String reportName; /** * The description of the docs report. */ @Parameter( defaultValue = "Web Service API Documentation" ) protected String reportDescription; @Override public void execute() throws MojoExecutionException { if (skipEnunciate) { getLog().info("Skipping enunciate per configuration."); return; } //todo: set the docs output dir. super.execute(); } @Override protected void applyAdditionalConfiguration(EnunciateModule module) { super.applyAdditionalConfiguration(module); if (module instanceof DocumentationProviderModule) { DocumentationProviderModule docsProvider = (DocumentationProviderModule) module; docsProvider.setDefaultDocsDir(new File(this.docsDir)); if (this.docsSubdir != null) { docsProvider.setDefaultDocsSubdir(this.docsSubdir); } } } public void generate(Sink sink, Locale locale) throws MavenReportException { // for some reason, when running in the "site" lifecycle, the context classloader // doesn't get set up the same way it does when doing the default lifecycle // so we have to set it up manually here. ClassLoader old = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); execute(); } catch (MojoExecutionException e) { throw new MavenReportException("Unable to generate web service documentation report", e); } finally { Thread.currentThread().setContextClassLoader(old); } } public String getOutputName() { String indexName = "index"; if (this.indexPageName != null) { if (this.indexPageName.indexOf('.') > 0) { indexName = this.indexPageName.substring(0, this.indexPageName.indexOf('.')); } else { indexName = this.indexPageName; } } return this.docsSubdir == null ? indexName : (this.docsSubdir + "/" + indexName); } public String getName(Locale locale) { return this.reportName; } public String getCategoryName() { return CATEGORY_PROJECT_REPORTS; } public String getDescription(Locale locale) { return this.reportDescription; } public void setReportOutputDirectory(File outputDirectory) { this.docsDir = outputDirectory.getAbsolutePath(); } public File getReportOutputDirectory() { File outputDir = new File(this.docsDir); if (this.docsSubdir != null) { outputDir = new File(outputDir, this.docsSubdir); } return outputDir; } public boolean isExternalReport() { return true; } public boolean canGenerateReport() { return true; } }
updating the docs base mojo to remove empty files to make room for the docs module
slim-maven-plugin/src/main/java/com/webcohesion/enunciate/mojo/DocsBaseMojo.java
updating the docs base mojo to remove empty files to make room for the docs module
Java
apache-2.0
cdb854857dfdc89d567e252a2af63d46497a5538
0
consulo/consulo-sql,consulo/consulo-sql
package com.dci.intellij.dbn.code.sql.color; import com.intellij.openapi.editor.HighlighterColors; import com.intellij.openapi.editor.SyntaxHighlighterColors; import com.intellij.openapi.editor.colors.CodeInsightColors; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.editor.markup.TextAttributes; import java.awt.Color; import java.awt.Font; public interface SQLTextAttributesKeys { TextAttributesKey LINE_COMMENT = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.LineComment", SyntaxHighlighterColors.LINE_COMMENT.getDefaultAttributes()); TextAttributesKey BLOCK_COMMENT = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.BlockComment", SyntaxHighlighterColors.DOC_COMMENT.getDefaultAttributes()); TextAttributesKey STRING = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.String", SyntaxHighlighterColors.STRING.getDefaultAttributes()); TextAttributesKey NUMBER = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.Number", SyntaxHighlighterColors.NUMBER.getDefaultAttributes()); TextAttributesKey DATA_TYPE = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.DataType", SyntaxHighlighterColors.KEYWORD.getDefaultAttributes()); TextAttributesKey ALIAS = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.Alias", HighlighterColors.TEXT.getDefaultAttributes()); TextAttributesKey IDENTIFIER = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.Identifier", HighlighterColors.TEXT.getDefaultAttributes()); TextAttributesKey QUOTED_IDENTIFIER = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.QuotedIdentifier", HighlighterColors.TEXT.getDefaultAttributes()); TextAttributesKey KEYWORD = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.Keyword", SyntaxHighlighterColors.KEYWORD.getDefaultAttributes()); TextAttributesKey FUNCTION = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.Function", new TextAttributes(Color.BLACK, null, null, null, Font.BOLD)); TextAttributesKey PARAMETER = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.Parameter", SyntaxHighlighterColors.KEYWORD.getDefaultAttributes()); TextAttributesKey OPERATOR = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.Operator", SyntaxHighlighterColors.OPERATION_SIGN.getDefaultAttributes()); TextAttributesKey PARENTHESIS = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.Parenthesis", SyntaxHighlighterColors.PARENTHS.getDefaultAttributes()); TextAttributesKey BRACKET = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.Brackets", SyntaxHighlighterColors.BRACKETS.getDefaultAttributes()); TextAttributesKey UNKNOWN_IDENTIFIER = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.UnknownIdentifier", new TextAttributes(Color.RED, null, null, null, 0)); TextAttributesKey CHAMELEON = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.Chameleon", new TextAttributes(null, null, null, null, 0)); TextAttributesKey VARIABLE = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.Variable", CodeInsightColors.INSTANCE_FIELD_ATTRIBUTES); TextAttributesKey BAD_CHARACTER = HighlighterColors.BAD_CHARACTER; }
src/com/dci/intellij/dbn/code/sql/color/SQLTextAttributesKeys.java
package com.dci.intellij.dbn.code.sql.color; import com.intellij.openapi.editor.HighlighterColors; import com.intellij.openapi.editor.SyntaxHighlighterColors; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.editor.colors.TextAttributesKey; import java.awt.Color; import java.awt.Font; public interface SQLTextAttributesKeys { TextAttributesKey LINE_COMMENT = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.LineComment", SyntaxHighlighterColors.LINE_COMMENT.getDefaultAttributes()); TextAttributesKey BLOCK_COMMENT = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.BlockComment", SyntaxHighlighterColors.DOC_COMMENT.getDefaultAttributes()); TextAttributesKey STRING = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.String", SyntaxHighlighterColors.STRING.getDefaultAttributes()); TextAttributesKey NUMBER = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.Number", SyntaxHighlighterColors.NUMBER.getDefaultAttributes()); TextAttributesKey DATA_TYPE = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.DataType", SyntaxHighlighterColors.KEYWORD.getDefaultAttributes()); TextAttributesKey ALIAS = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.Alias", HighlighterColors.TEXT.getDefaultAttributes()); TextAttributesKey IDENTIFIER = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.Identifier", HighlighterColors.TEXT.getDefaultAttributes()); TextAttributesKey QUOTED_IDENTIFIER = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.QuotedIdentifier", HighlighterColors.TEXT.getDefaultAttributes()); TextAttributesKey KEYWORD = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.Keyword", SyntaxHighlighterColors.KEYWORD.getDefaultAttributes()); TextAttributesKey FUNCTION = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.Function", new TextAttributes(Color.BLACK, null, null, null, Font.BOLD)); TextAttributesKey PARAMETER = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.Parameter", SyntaxHighlighterColors.KEYWORD.getDefaultAttributes()); TextAttributesKey OPERATOR = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.Operator", SyntaxHighlighterColors.OPERATION_SIGN.getDefaultAttributes()); TextAttributesKey PARENTHESIS = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.Parenthesis", SyntaxHighlighterColors.PARENTHS.getDefaultAttributes()); TextAttributesKey BRACKET = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.Brackets", SyntaxHighlighterColors.BRACKETS.getDefaultAttributes()); TextAttributesKey UNKNOWN_IDENTIFIER = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.UnknownIdentifier", new TextAttributes(Color.RED, null, null, null, 0)); TextAttributesKey CHAMELEON = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.Chameleon", new TextAttributes(null, null, null, null, 0)); TextAttributesKey VARIABLE = TextAttributesKey.createTextAttributesKey("DBNavigator.TextAttributes.SQL.Variable", new TextAttributes(new Color(128, 0, 128), null, null, null, Font.BOLD)); TextAttributesKey BAD_CHARACTER = HighlighterColors.BAD_CHARACTER; }
git-svn-id: http://database-navigator.googlecode.com/svn/trunk@162 6bf550b9-897f-baaf-8eff-d39108dcfdf5
src/com/dci/intellij/dbn/code/sql/color/SQLTextAttributesKeys.java
Java
apache-2.0
3f60e2ea72139cc728d36297e1f1c3c8bfad1fa0
0
permazen/permazen,permazen/permazen,permazen/permazen,archiecobbs/jsimpledb,archiecobbs/jsimpledb,archiecobbs/jsimpledb
/* * Copyright (C) 2015 Archie L. Cobbs. All rights reserved. */ package org.jsimpledb; import com.google.common.base.Preconditions; import java.util.Arrays; import javax.validation.ValidatorFactory; import org.jsimpledb.core.Database; import org.jsimpledb.kv.simple.SimpleKVDatabase; /** * Factory for {@link JSimpleDB} instances. * * <p> * If no {@link Database} is configured, newly created {@link JSimpleDB} instances will use an initially empty, * in-memory {@link SimpleKVDatabase}. * * @see JSimpleDB */ public class JSimpleDBFactory { private Database database; private int schemaVersion; private StorageIdGenerator storageIdGenerator = new DefaultStorageIdGenerator(); private Iterable<? extends Class<?>> modelClasses; private ValidatorFactory validatorFactory; /** * Configure the Java model classes. * * <p> * Note: {@link org.jsimpledb.annotation.JSimpleClass &#64;JSimpleClass}-annotated super-types of any * class in {@code modelClasses} will be included, even if the super-type is not explicitly specified in {@code modelClasses}. * * @param modelClasses classes annotated with {@link org.jsimpledb.annotation.JSimpleClass &#64;JSimpleClass} annotations * @return this instance */ public JSimpleDBFactory setModelClasses(Iterable<? extends Class<?>> modelClasses) { this.modelClasses = modelClasses; return this; } /** * Configure the Java model classes. * * <p> * Equivalent to {@link #setModelClasses(Iterable) setModelClasses}{@code (Arrays.asList(modelClasses))}. * * @param modelClasses classes annotated with {@link org.jsimpledb.annotation.JSimpleClass &#64;JSimpleClass} annotations * @return this instance * @see #setModelClasses(Iterable) */ public JSimpleDBFactory setModelClasses(Class<?>... modelClasses) { return this.setModelClasses(Arrays.asList(modelClasses)); } /** * Configure the underlying {@link Database} for this instance. * * <p> * By default this instance will use an initially empty, in-memory {@link SimpleKVDatabase}. * * @param database core API database to use * @return this instance */ public JSimpleDBFactory setDatabase(Database database) { this.database = database; return this; } /** * Configure the schema version number associated with the configured Java model classes. * * <p> * A value of zero means to use whatever is the highest version already recorded in the database. * However, if this instance has no {@link Database} configured, then an empty * {@link SimpleKVDatabase} is used and therefore a schema version of {@code 1} is assumed. * * <p> * A value of -1 means to {@linkplain org.jsimpledb.schema.SchemaModel#autogenerateVersion auto-generate} * a version number based on the {@linkplain org.jsimpledb.schema.SchemaModel#compatibilityHash compatibility hash} * of the {@link org.jsimpledb.schema.SchemaModel} generated from the {@linkplain #setModelClasses configured model classes}. * * @param schemaVersion the schema version number of the schema derived from the configured Java model classes, * zero to use the highest version already recorded in the database, * or -1 to use an {@linkplain org.jsimpledb.schema.SchemaModel#autogenerateVersion auto-generated} schema version * @return this instance */ public JSimpleDBFactory setSchemaVersion(int schemaVersion) { this.schemaVersion = schemaVersion; return this; } /** * Configure the {@link StorageIdGenerator} for auto-generating storage ID's when not explicitly * specified in {@link org.jsimpledb.annotation.JSimpleClass &#64;JSimpleClass}, * {@link org.jsimpledb.annotation.JField &#64;JField}, etc., annotations. * * <p> * This instance will initially be configured with a {@link DefaultStorageIdGenerator}. * To disable auto-generation of storage ID's altogether, configure a null value here. * * @param storageIdGenerator storage ID generator, or null to disable auto-generation of storage ID's * @return this instance */ public JSimpleDBFactory setStorageIdGenerator(StorageIdGenerator storageIdGenerator) { this.storageIdGenerator = storageIdGenerator; return this; } /** * Configure a custom {@link ValidatorFactory} used to create {@link javax.validation.Validator}s * for validation within transactions. * * @param validatorFactory factory for validators * @return this instance * @throws IllegalArgumentException if {@code validatorFactory} is null */ public JSimpleDBFactory setValidatorFactory(ValidatorFactory validatorFactory) { Preconditions.checkArgument(validatorFactory != null, "null validatorFactory"); this.validatorFactory = validatorFactory; return this; } /** * Construct a {@link JSimpleDB} instance using this instance's configuration. * * @return newly created {@link JSimpleDB} database * @throws IllegalArgumentException if this instance has an incomplete or invalid configuration * @throws IllegalArgumentException if any Java model class has an invalid annotation */ public JSimpleDB newJSimpleDB() { Database database1 = this.database; int schemaVersion1 = this.schemaVersion; if (database1 == null) { database1 = new Database(new SimpleKVDatabase()); if (schemaVersion1 == 0) schemaVersion1 = 1; } final JSimpleDB jdb = new JSimpleDB(database1, schemaVersion1, this.storageIdGenerator, this.modelClasses); if (this.validatorFactory != null) jdb.setValidatorFactory(this.validatorFactory); return jdb; } }
jsimpledb-main/src/main/java/org/jsimpledb/JSimpleDBFactory.java
/* * Copyright (C) 2015 Archie L. Cobbs. All rights reserved. */ package org.jsimpledb; import com.google.common.base.Preconditions; import java.util.Arrays; import javax.validation.ValidatorFactory; import org.jsimpledb.core.Database; import org.jsimpledb.kv.simple.SimpleKVDatabase; /** * Factory for {@link JSimpleDB} instances. * * <p> * If no {@link Database} is configured, newly created {@link JSimpleDB} instances will use an initially empty, * in-memory {@link SimpleKVDatabase}. * * @see JSimpleDB */ public class JSimpleDBFactory { private Database database; private int schemaVersion; private StorageIdGenerator storageIdGenerator = new DefaultStorageIdGenerator(); private Iterable<? extends Class<?>> modelClasses; private ValidatorFactory validatorFactory; /** * Configure the Java model classes. * * <p> * Note: {@link org.jsimpledb.annotation.JSimpleClass &#64;JSimpleClass}-annotated super-types of any * class in {@code modelClasses} will be included, even if the super-type is not explicitly specified in {@code modelClasses}. * * @param modelClasses classes annotated with {@link org.jsimpledb.annotation.JSimpleClass &#64;JSimpleClass} annotations * @return this instance */ public JSimpleDBFactory setModelClasses(Iterable<? extends Class<?>> modelClasses) { this.modelClasses = modelClasses; return this; } /** * Configure the Java model classes. * * <p> * Equivalent to {@link #setModelClasses(Iterable) setModelClasses}{@code (Arrays.asList(modelClasses))}. * * @param modelClasses classes annotated with {@link org.jsimpledb.annotation.JSimpleClass &#64;JSimpleClass} annotations * @return this instance * @see #setModelClasses(Iterable) */ public JSimpleDBFactory setModelClasses(Class<?>... modelClasses) { return this.setModelClasses(Arrays.asList(modelClasses)); } /** * Configure the underlying {@link Database} for this instance. * * <p> * By default this instance will use an initially empty, in-memory {@link SimpleKVDatabase}. * * @param database core API database to use * @return this instance */ public JSimpleDBFactory setDatabase(Database database) { this.database = database; return this; } /** * Configure the schema version number associated with the configured Java model classes. * * <p> * A value of zero means to use whatever is the highest version already recorded in the database. * However, if this instance has no {@link Database} configured, then an empty * {@link SimpleKVDatabase} is used and therefore a schema version of {@code 1} is assumed. * * <p> * A value of -1 means to {@linkplain org.jsimpledb.schema.SchemaModel#autogenerateVersion auto-generate} * a random version number based on the {@linkplain org.jsimpledb.schema.SchemaModel#compatibilityHash compatibility hash} * of the {@link org.jsimpledb.schema.SchemaModel} generated from the {@linkplain #setModelClasses configured model classes}. * * @param schemaVersion the schema version number of the schema derived from the configured Java model classes, * zero to use the highest version already recorded in the database, * or -1 to use an {@linkplain org.jsimpledb.schema.SchemaModel#autogenerateVersion auto-generated} schema version * @return this instance */ public JSimpleDBFactory setSchemaVersion(int schemaVersion) { this.schemaVersion = schemaVersion; return this; } /** * Configure the {@link StorageIdGenerator} for auto-generating storage ID's when not explicitly * specified in {@link org.jsimpledb.annotation.JSimpleClass &#64;JSimpleClass}, * {@link org.jsimpledb.annotation.JField &#64;JField}, etc., annotations. * * <p> * This instance will initially be configured with a {@link DefaultStorageIdGenerator}. * To disable auto-generation of storage ID's altogether, configure a null value here. * * @param storageIdGenerator storage ID generator, or null to disable auto-generation of storage ID's * @return this instance */ public JSimpleDBFactory setStorageIdGenerator(StorageIdGenerator storageIdGenerator) { this.storageIdGenerator = storageIdGenerator; return this; } /** * Configure a custom {@link ValidatorFactory} used to create {@link javax.validation.Validator}s * for validation within transactions. * * @param validatorFactory factory for validators * @return this instance * @throws IllegalArgumentException if {@code validatorFactory} is null */ public JSimpleDBFactory setValidatorFactory(ValidatorFactory validatorFactory) { Preconditions.checkArgument(validatorFactory != null, "null validatorFactory"); this.validatorFactory = validatorFactory; return this; } /** * Construct a {@link JSimpleDB} instance using this instance's configuration. * * @return newly created {@link JSimpleDB} database * @throws IllegalArgumentException if this instance has an incomplete or invalid configuration * @throws IllegalArgumentException if any Java model class has an invalid annotation */ public JSimpleDB newJSimpleDB() { Database database1 = this.database; int schemaVersion1 = this.schemaVersion; if (database1 == null) { database1 = new Database(new SimpleKVDatabase()); if (schemaVersion1 == 0) schemaVersion1 = 1; } final JSimpleDB jdb = new JSimpleDB(database1, schemaVersion1, this.storageIdGenerator, this.modelClasses); if (this.validatorFactory != null) jdb.setValidatorFactory(this.validatorFactory); return jdb; } }
Javadoc tweak.
jsimpledb-main/src/main/java/org/jsimpledb/JSimpleDBFactory.java
Javadoc tweak.
Java
apache-2.0
899e72fdb24c17fd99825332e001a32af6dd262d
0
JetBrains/ttorrent-lib,mpetazzoni/ttorrent,mpetazzoni/ttorrent,JetBrains/ttorrent-lib
package com.turn.ttorrent.client; import com.turn.ttorrent.common.AnnounceableInformation; import com.turn.ttorrent.common.Pair; import java.io.IOException; import java.util.*; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class TorrentsStorage { private final ReadWriteLock readWriteLock; private final Map<String, SharedTorrent> activeTorrents; private final Map<String, LoadedTorrent> loadedTorrents; public TorrentsStorage() { readWriteLock = new ReentrantReadWriteLock(); activeTorrents = new HashMap<String, SharedTorrent>(); loadedTorrents = new HashMap<String, LoadedTorrent>(); } public boolean hasTorrent(String hash) { try { readWriteLock.readLock().lock(); return loadedTorrents.containsKey(hash); } finally { readWriteLock.readLock().unlock(); } } public LoadedTorrent getLoadedTorrent(String hash) { try { readWriteLock.readLock().lock(); return loadedTorrents.get(hash); } finally { readWriteLock.readLock().unlock(); } } public void peerDisconnected(String torrentHash) { final SharedTorrent torrent; try { readWriteLock.writeLock().lock(); torrent = activeTorrents.get(torrentHash); if (torrent == null) return; boolean isTorrentFinished = torrent.isFinished(); if (torrent.getDownloadersCount() == 0 && isTorrentFinished) { activeTorrents.remove(torrentHash); } else { return; } } finally { readWriteLock.writeLock().unlock(); } torrent.close(); } public SharedTorrent getTorrent(String hash) { try { readWriteLock.readLock().lock(); return activeTorrents.get(hash); } finally { readWriteLock.readLock().unlock(); } } public void addTorrent(String hash, LoadedTorrent torrent) { try { readWriteLock.writeLock().lock(); loadedTorrents.put(hash, torrent); } finally { readWriteLock.writeLock().unlock(); } } public SharedTorrent putIfAbsentActiveTorrent(String hash, SharedTorrent torrent) { try { readWriteLock.writeLock().lock(); final SharedTorrent old = activeTorrents.get(hash); if (old != null) return old; return activeTorrents.put(hash, torrent); } finally { readWriteLock.writeLock().unlock(); } } public Pair<SharedTorrent, LoadedTorrent> remove(String hash) { final Pair<SharedTorrent, LoadedTorrent> result; try { readWriteLock.writeLock().lock(); final SharedTorrent sharedTorrent = activeTorrents.remove(hash); final LoadedTorrent loadedTorrent = loadedTorrents.remove(hash); result = new Pair<SharedTorrent, LoadedTorrent>(sharedTorrent, loadedTorrent); } finally { readWriteLock.writeLock().unlock(); } if (result.second() != null) { try { result.second().getPieceStorage().close(); } catch (IOException ignored) { } } if (result.first() != null) { result.first().close(); } return result; } public List<SharedTorrent> activeTorrents() { try { readWriteLock.readLock().lock(); return new ArrayList<SharedTorrent>(activeTorrents.values()); } finally { readWriteLock.readLock().unlock(); } } public List<AnnounceableInformation> announceableTorrents() { List<AnnounceableInformation> result = new ArrayList<AnnounceableInformation>(); try { readWriteLock.readLock().lock(); for (LoadedTorrent loadedTorrent : loadedTorrents.values()) { result.add(loadedTorrent.createAnnounceableInformation()); } return result; } finally { readWriteLock.readLock().unlock(); } } public List<LoadedTorrent> getLoadedTorrents() { try { readWriteLock.readLock().lock(); return new ArrayList<LoadedTorrent>(loadedTorrents.values()); } finally { readWriteLock.readLock().unlock(); } } public void clear() { final Collection<SharedTorrent> sharedTorrents; final Collection<LoadedTorrent> loadedTorrents; try { readWriteLock.writeLock().lock(); sharedTorrents = new ArrayList<SharedTorrent>(activeTorrents.values()); loadedTorrents = new ArrayList<LoadedTorrent>(this.loadedTorrents.values()); this.loadedTorrents.clear(); activeTorrents.clear(); } finally { readWriteLock.writeLock().unlock(); } for (SharedTorrent sharedTorrent : sharedTorrents) { sharedTorrent.close(); } for (LoadedTorrent loadedTorrent : loadedTorrents) { try { loadedTorrent.getPieceStorage().close(); } catch (IOException ignored) { } } } }
ttorrent-client/src/main/java/com/turn/ttorrent/client/TorrentsStorage.java
package com.turn.ttorrent.client; import com.turn.ttorrent.common.AnnounceableInformation; import com.turn.ttorrent.common.Pair; import org.apache.commons.io.IOUtils; import java.util.*; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class TorrentsStorage { private final ReadWriteLock readWriteLock; private final Map<String, SharedTorrent> activeTorrents; private final Map<String, LoadedTorrent> loadedTorrents; public TorrentsStorage() { readWriteLock = new ReentrantReadWriteLock(); activeTorrents = new HashMap<String, SharedTorrent>(); loadedTorrents = new HashMap<String, LoadedTorrent>(); } public boolean hasTorrent(String hash) { try { readWriteLock.readLock().lock(); return loadedTorrents.containsKey(hash); } finally { readWriteLock.readLock().unlock(); } } public LoadedTorrent getLoadedTorrent(String hash) { try { readWriteLock.readLock().lock(); return loadedTorrents.get(hash); } finally { readWriteLock.readLock().unlock(); } } public void peerDisconnected(String torrentHash) { final SharedTorrent torrent; try { readWriteLock.writeLock().lock(); torrent = activeTorrents.get(torrentHash); if (torrent == null) return; boolean isTorrentFinished = torrent.isFinished(); if (torrent.getDownloadersCount() == 0 && isTorrentFinished) { activeTorrents.remove(torrentHash); } else { return; } } finally { readWriteLock.writeLock().unlock(); } torrent.close(); } public SharedTorrent getTorrent(String hash) { try { readWriteLock.readLock().lock(); return activeTorrents.get(hash); } finally { readWriteLock.readLock().unlock(); } } public void addTorrent(String hash, LoadedTorrent torrent) { try { readWriteLock.writeLock().lock(); loadedTorrents.put(hash, torrent); } finally { readWriteLock.writeLock().unlock(); } } public SharedTorrent putIfAbsentActiveTorrent(String hash, SharedTorrent torrent) { try { readWriteLock.writeLock().lock(); final SharedTorrent old = activeTorrents.get(hash); if (old != null) return old; return activeTorrents.put(hash, torrent); } finally { readWriteLock.writeLock().unlock(); } } public Pair<SharedTorrent, LoadedTorrent> remove(String hash) { final Pair<SharedTorrent, LoadedTorrent> result; try { readWriteLock.writeLock().lock(); final SharedTorrent sharedTorrent = activeTorrents.remove(hash); final LoadedTorrent loadedTorrent = loadedTorrents.remove(hash); result = new Pair<SharedTorrent, LoadedTorrent>(sharedTorrent, loadedTorrent); } finally { readWriteLock.writeLock().unlock(); } if (result.second() != null) { IOUtils.closeQuietly(result.second().getPieceStorage()); } if (result.first() != null) { result.first().close(); } return result; } public List<SharedTorrent> activeTorrents() { try { readWriteLock.readLock().lock(); return new ArrayList<SharedTorrent>(activeTorrents.values()); } finally { readWriteLock.readLock().unlock(); } } public List<AnnounceableInformation> announceableTorrents() { List<AnnounceableInformation> result = new ArrayList<AnnounceableInformation>(); try { readWriteLock.readLock().lock(); for (LoadedTorrent loadedTorrent : loadedTorrents.values()) { result.add(loadedTorrent.createAnnounceableInformation()); } return result; } finally { readWriteLock.readLock().unlock(); } } public List<LoadedTorrent> getLoadedTorrents() { try { readWriteLock.readLock().lock(); return new ArrayList<LoadedTorrent>(loadedTorrents.values()); } finally { readWriteLock.readLock().unlock(); } } public void clear() { final Collection<SharedTorrent> sharedTorrents; final Collection<LoadedTorrent> loadedTorrents; try { readWriteLock.writeLock().lock(); sharedTorrents = new ArrayList<SharedTorrent>(activeTorrents.values()); loadedTorrents = new ArrayList<LoadedTorrent>(this.loadedTorrents.values()); this.loadedTorrents.clear(); activeTorrents.clear(); } finally { readWriteLock.writeLock().unlock(); } for (SharedTorrent sharedTorrent : sharedTorrents) { sharedTorrent.close(); } for (LoadedTorrent loadedTorrent : loadedTorrents) { IOUtils.closeQuietly(loadedTorrent.getPieceStorage()); } } }
remove using of closeQuietly method, looks like it's not exist in old versions of apache library
ttorrent-client/src/main/java/com/turn/ttorrent/client/TorrentsStorage.java
remove using of closeQuietly method, looks like it's not exist in old versions of apache library
Java
apache-2.0
feeccb95676b993f6b3d8ce6d6a509c889aaf8f5
0
apache/commons-pool,apache/commons-pool,apache/commons-pool
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool2.impl; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.management.ManagementFactory; import java.time.Duration; import java.util.ArrayList; import java.util.HashSet; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Random; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.management.MBeanServer; import javax.management.ObjectName; import org.apache.commons.pool2.BaseKeyedPooledObjectFactory; import org.apache.commons.pool2.DestroyMode; import org.apache.commons.pool2.KeyedObjectPool; import org.apache.commons.pool2.KeyedPooledObjectFactory; import org.apache.commons.pool2.PooledObject; import org.apache.commons.pool2.TestKeyedObjectPool; import org.apache.commons.pool2.VisitTracker; import org.apache.commons.pool2.VisitTrackerFactory; import org.apache.commons.pool2.Waiter; import org.apache.commons.pool2.WaiterFactory; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; /** */ public class TestGenericKeyedObjectPool extends TestKeyedObjectPool { private static class DaemonThreadFactory implements ThreadFactory { @Override public Thread newThread(final Runnable r) { final Thread t = new Thread(r); t.setDaemon(true); return t; } } private static class DummyFactory extends BaseKeyedPooledObjectFactory<Object, Object, RuntimeException> { @Override public Object create(final Object key) { return null; } @Override public PooledObject<Object> wrap(final Object value) { return new DefaultPooledObject<>(value); } } /** * Factory that creates HashSets. Note that this means * 0) All instances are initially equal (not discernible by equals) * 1) Instances are mutable and mutation can cause change in identity / hashcode. */ private static final class HashSetFactory extends BaseKeyedPooledObjectFactory<String, HashSet<String>, RuntimeException> { @Override public HashSet<String> create(final String key) { return new HashSet<>(); } @Override public PooledObject<HashSet<String>> wrap(final HashSet<String> value) { return new DefaultPooledObject<>(value); } } /** * Attempts to invalidate an object, swallowing IllegalStateException. */ static class InvalidateThread implements Runnable { private final String obj; private final KeyedObjectPool<String, String, Exception> pool; private final String key; private boolean done; public InvalidateThread(final KeyedObjectPool<String, String, Exception> pool, final String key, final String obj) { this.obj = obj; this.pool = pool; this.key = key; } public boolean complete() { return done; } @Override public void run() { try { pool.invalidateObject(key, obj); } catch (final IllegalStateException ex) { // Ignore } catch (final Exception ex) { fail("Unexpected exception " + ex.toString()); } finally { done = true; } } } private static class ObjectFactory extends BaseKeyedPooledObjectFactory<Integer, Object, RuntimeException> { @Override public Object create(final Integer key) { return new Object(); } @Override public PooledObject<Object> wrap(final Object value) { return new DefaultPooledObject<>(value); } } public static class SimpleFactory<K> implements KeyedPooledObjectFactory<K, String, Exception> { volatile int counter; final boolean valid; int activeCount; int validateCounter; boolean evenValid = true; boolean oddValid = true; boolean enableValidation; long destroyLatency; long makeLatency; long validateLatency; volatile int maxTotalPerKey = Integer.MAX_VALUE; boolean exceptionOnPassivate; boolean exceptionOnActivate; boolean exceptionOnDestroy; boolean exceptionOnValidate; boolean exceptionOnCreate; public SimpleFactory() { this(true); } public SimpleFactory(final boolean valid) { this.valid = valid; } @Override public void activateObject(final K key, final PooledObject<String> obj) throws Exception { if (exceptionOnActivate && !(validateCounter++ % 2 == 0 ? evenValid : oddValid)) { throw new Exception(); } } @Override public void destroyObject(final K key, final PooledObject<String> obj) throws Exception { doWait(destroyLatency); synchronized(this) { activeCount--; } if (exceptionOnDestroy) { throw new Exception(); } } private void doWait(final long latency) { Waiter.sleepQuietly(latency); } @Override public PooledObject<String> makeObject(final K key) throws Exception { if (exceptionOnCreate) { throw new Exception(); } doWait(makeLatency); String out = null; synchronized(this) { activeCount++; if (activeCount > maxTotalPerKey) { throw new IllegalStateException( "Too many active instances: " + activeCount); } out = String.valueOf(key) + String.valueOf(counter++); } return new DefaultPooledObject<>(out); } @Override public void passivateObject(final K key, final PooledObject<String> obj) throws Exception { if (exceptionOnPassivate) { throw new Exception(); } } public void setDestroyLatency(final long destroyLatency) { this.destroyLatency = destroyLatency; } void setEvenValid(final boolean valid) { evenValid = valid; } public void setMakeLatency(final long makeLatency) { this.makeLatency = makeLatency; } public void setMaxTotalPerKey(final int maxTotalPerKey) { this.maxTotalPerKey = maxTotalPerKey; } public void setThrowExceptionOnActivate(final boolean b) { exceptionOnActivate = b; } public void setThrowExceptionOnDestroy(final boolean b) { exceptionOnDestroy = b; } public void setThrowExceptionOnPassivate(final boolean b) { exceptionOnPassivate = b; } public void setThrowExceptionOnValidate(final boolean b) { exceptionOnValidate = b; } void setValid(final boolean valid) { evenValid = valid; oddValid = valid; } public void setValidateLatency(final long validateLatency) { this.validateLatency = validateLatency; } public void setValidationEnabled(final boolean b) { enableValidation = b; } @Override public boolean validateObject(final K key, final PooledObject<String> obj) { doWait(validateLatency); if (exceptionOnValidate) { throw new RuntimeException("validation failed"); } if (enableValidation) { return validateCounter++ % 2 == 0 ? evenValid : oddValid; } return valid; } } private static class SimplePerKeyFactory extends BaseKeyedPooledObjectFactory<Object, Object, RuntimeException> { final ConcurrentHashMap<Object, AtomicInteger> map = new ConcurrentHashMap<>(); @Override public Object create(final Object key) { int counter = 0; final AtomicInteger Counter = map.get(key); if(null != Counter) { counter = Counter.incrementAndGet(); } else { map.put(key, new AtomicInteger(0)); counter = 0; } return String.valueOf(key) + String.valueOf(counter); } @Override public PooledObject<Object> wrap(final Object value) { return new DefaultPooledObject<>(value); } } /* * Very simple test thread that just tries to borrow an object from * the provided pool with the specified key and returns it */ static class SimpleTestThread<T, E extends Exception> implements Runnable { private final KeyedObjectPool<String, T, E> pool; private final String key; public SimpleTestThread(final KeyedObjectPool<String, T, E> pool, final String key) { this.pool = pool; this.key = key; } @Override public void run() { try { pool.returnObject(key, pool.borrowObject(key)); } catch (final Exception e) { // Ignore } } } /* * DefaultEvictionPolicy modified to add latency */ private static class SlowEvictionPolicy<T> extends DefaultEvictionPolicy<T> { private final long delay; /** * Constructs SlowEvictionPolicy with the given delay in ms * * @param delay number of ms of latency to inject in evict */ public SlowEvictionPolicy(final long delay) { this.delay = delay; } @Override public boolean evict(final EvictionConfig config, final PooledObject<T> underTest, final int idleCount) { Waiter.sleepQuietly(delay); return super.evict(config, underTest, idleCount); } } static class TestThread<T, E extends Exception> implements Runnable { private final java.util.Random random = new java.util.Random(); /** GKOP to hit */ private final KeyedObjectPool<String, T, E> pool; /** number of borrow/return iterations */ private final int iter; /** delay before borrow */ private final int startDelay; /** delay before return */ private final int holdTime; /** whether or not delays are random (with max = configured values) */ private final boolean randomDelay; /** expected object */ private final T expectedObject; /** key used in borrow / return sequence - null means random */ private final String key; private volatile boolean complete; private volatile boolean failed; private volatile Exception exception; public TestThread(final KeyedObjectPool<String, T, E> pool) { this(pool, 100, 50, 50, true, null, null); } public TestThread(final KeyedObjectPool<String, T, E> pool, final int iter) { this(pool, iter, 50, 50, true, null, null); } public TestThread(final KeyedObjectPool<String, T, E> pool, final int iter, final int delay) { this(pool, iter, delay, delay, true, null, null); } public TestThread(final KeyedObjectPool<String, T, E> pool, final int iter, final int startDelay, final int holdTime, final boolean randomDelay, final T expectedObject, final String key) { this.pool = pool; this.iter = iter; this.startDelay = startDelay; this.holdTime = holdTime; this.randomDelay = randomDelay; this.expectedObject = expectedObject; this.key = key; } public boolean complete() { return complete; } public boolean failed() { return failed; } @Override public void run() { for (int i = 0; i < iter; i++) { final String actualKey = key == null ? String.valueOf(random.nextInt(3)) : key; Waiter.sleepQuietly(randomDelay ? random.nextInt(startDelay) : startDelay); T obj = null; try { obj = pool.borrowObject(actualKey); } catch (final Exception e) { exception = e; failed = true; complete = true; break; } if (expectedObject != null && !expectedObject.equals(obj)) { exception = new Exception("Expected: " + expectedObject + " found: " + obj); failed = true; complete = true; break; } Waiter.sleepQuietly(randomDelay ? random.nextInt(holdTime) : holdTime); try { pool.returnObject(actualKey, obj); } catch (final Exception e) { exception = e; failed = true; complete = true; break; } } complete = true; } } /* * Very simple test thread that just tries to borrow an object from * the provided pool with the specified key and returns it after a wait */ static class WaitingTestThread<E extends Exception> extends Thread { private final KeyedObjectPool<String, String, E> pool; private final String key; private final long pause; private Throwable thrown; private long preBorrowMillis; // just before borrow private long postBorrowMillis; // borrow returned private long postReturnMillis; // after object was returned private long endedMillis; private String objectId; public WaitingTestThread(final KeyedObjectPool<String, String, E> pool, final String key, final long pause) { this.pool = pool; this.key = key; this.pause = pause; this.thrown = null; } @Override public void run() { try { preBorrowMillis = System.currentTimeMillis(); final String obj = pool.borrowObject(key); objectId = obj; postBorrowMillis = System.currentTimeMillis(); Thread.sleep(pause); pool.returnObject(key, obj); postReturnMillis = System.currentTimeMillis(); } catch (final Exception e) { thrown = e; } finally{ endedMillis = System.currentTimeMillis(); } } } private static final Integer KEY_ZERO = Integer.valueOf(0); private static final Integer KEY_ONE = Integer.valueOf(1); private static final Integer KEY_TWO = Integer.valueOf(2); private static final boolean DISPLAY_THREAD_DETAILS= Boolean.parseBoolean(System.getProperty("TestGenericKeyedObjectPool.display.thread.details", "false")); // To pass this to a Maven test, use: // mvn test -DargLine="-DTestGenericKeyedObjectPool.display.thread.details=true" // @see https://issues.apache.org/jira/browse/SUREFIRE-121 /** setUp(): {@code new GenericKeyedObjectPool<String,String>(factory)} */ private GenericKeyedObjectPool<String, String, Exception> gkoPool; /** setUp(): {@code new SimpleFactory<String>()} */ private SimpleFactory<String> simpleFactory; private void checkEvictionOrder(final boolean lifo) throws Exception { final SimpleFactory<Integer> intFactory = new SimpleFactory<>(); try (final GenericKeyedObjectPool<Integer, String, Exception> intPool = new GenericKeyedObjectPool<>(intFactory)) { intPool.setNumTestsPerEvictionRun(2); intPool.setMinEvictableIdleTime(Duration.ofMillis(100)); intPool.setLifo(lifo); for (int i = 0; i < 3; i++) { final Integer key = Integer.valueOf(i); for (int j = 0; j < 5; j++) { intPool.addObject(key); } } // Make all evictable Thread.sleep(200); /* * Initial state (Key, Object) pairs in order of age: * * (0,0), (0,1), (0,2), (0,3), (0,4) (1,5), (1,6), (1,7), (1,8), (1,9) (2,10), (2,11), (2,12), (2,13), * (2,14) */ intPool.evict(); // Kill (0,0),(0,1) assertEquals(3, intPool.getNumIdle(KEY_ZERO)); final String objZeroA = intPool.borrowObject(KEY_ZERO); assertTrue(lifo ? objZeroA.equals("04") : objZeroA.equals("02")); assertEquals(2, intPool.getNumIdle(KEY_ZERO)); final String objZeroB = intPool.borrowObject(KEY_ZERO); assertEquals("03", objZeroB); assertEquals(1, intPool.getNumIdle(KEY_ZERO)); intPool.evict(); // Kill remaining 0 survivor and (1,5) assertEquals(0, intPool.getNumIdle(KEY_ZERO)); assertEquals(4, intPool.getNumIdle(KEY_ONE)); final String objOneA = intPool.borrowObject(KEY_ONE); assertTrue(lifo ? objOneA.equals("19") : objOneA.equals("16")); assertEquals(3, intPool.getNumIdle(KEY_ONE)); final String objOneB = intPool.borrowObject(KEY_ONE); assertTrue(lifo ? objOneB.equals("18") : objOneB.equals("17")); assertEquals(2, intPool.getNumIdle(KEY_ONE)); intPool.evict(); // Kill remaining 1 survivors assertEquals(0, intPool.getNumIdle(KEY_ONE)); intPool.evict(); // Kill (2,10), (2,11) assertEquals(3, intPool.getNumIdle(KEY_TWO)); final String objTwoA = intPool.borrowObject(KEY_TWO); assertTrue(lifo ? objTwoA.equals("214") : objTwoA.equals("212")); assertEquals(2, intPool.getNumIdle(KEY_TWO)); intPool.evict(); // All dead now assertEquals(0, intPool.getNumIdle(KEY_TWO)); intPool.evict(); // Should do nothing - make sure no exception // Currently 2 zero, 2 one and 1 two active. Return them intPool.returnObject(KEY_ZERO, objZeroA); intPool.returnObject(KEY_ZERO, objZeroB); intPool.returnObject(KEY_ONE, objOneA); intPool.returnObject(KEY_ONE, objOneB); intPool.returnObject(KEY_TWO, objTwoA); // Remove all idle objects intPool.clear(); // Reload intPool.setMinEvictableIdleTime(Duration.ofMillis(500)); intFactory.counter = 0; // Reset counter for (int i = 0; i < 3; i++) { final Integer key = Integer.valueOf(i); for (int j = 0; j < 5; j++) { intPool.addObject(key); } Thread.sleep(200); } // 0's are evictable, others not intPool.evict(); // Kill (0,0),(0,1) assertEquals(3, intPool.getNumIdle(KEY_ZERO)); intPool.evict(); // Kill (0,2),(0,3) assertEquals(1, intPool.getNumIdle(KEY_ZERO)); intPool.evict(); // Kill (0,4), leave (1,5) assertEquals(0, intPool.getNumIdle(KEY_ZERO)); assertEquals(5, intPool.getNumIdle(KEY_ONE)); assertEquals(5, intPool.getNumIdle(KEY_TWO)); intPool.evict(); // (1,6), (1,7) assertEquals(5, intPool.getNumIdle(KEY_ONE)); assertEquals(5, intPool.getNumIdle(KEY_TWO)); intPool.evict(); // (1,8), (1,9) assertEquals(5, intPool.getNumIdle(KEY_ONE)); assertEquals(5, intPool.getNumIdle(KEY_TWO)); intPool.evict(); // (2,10), (2,11) assertEquals(5, intPool.getNumIdle(KEY_ONE)); assertEquals(5, intPool.getNumIdle(KEY_TWO)); intPool.evict(); // (2,12), (2,13) assertEquals(5, intPool.getNumIdle(KEY_ONE)); assertEquals(5, intPool.getNumIdle(KEY_TWO)); intPool.evict(); // (2,14), (1,5) assertEquals(5, intPool.getNumIdle(KEY_ONE)); assertEquals(5, intPool.getNumIdle(KEY_TWO)); Thread.sleep(200); // Ones now timed out intPool.evict(); // kill (1,6), (1,7) - (1,5) missed assertEquals(3, intPool.getNumIdle(KEY_ONE)); assertEquals(5, intPool.getNumIdle(KEY_TWO)); final String obj = intPool.borrowObject(KEY_ONE); if (lifo) { assertEquals("19", obj); } else { assertEquals("15", obj); } } } private void checkEvictorVisiting(final boolean lifo) throws Exception { VisitTrackerFactory<Integer> trackerFactory = new VisitTrackerFactory<>(); try (GenericKeyedObjectPool<Integer, VisitTracker<Integer>, RuntimeException> intPool = new GenericKeyedObjectPool<>( trackerFactory)) { intPool.setNumTestsPerEvictionRun(2); intPool.setMinEvictableIdleTime(Duration.ofMillis(-1)); intPool.setTestWhileIdle(true); intPool.setLifo(lifo); intPool.setTestOnReturn(false); intPool.setTestOnBorrow(false); for (int i = 0; i < 3; i++) { trackerFactory.resetId(); final Integer key = Integer.valueOf(i); for (int j = 0; j < 8; j++) { intPool.addObject(key); } } intPool.evict(); // Visit oldest 2 - 00 and 01 VisitTracker<Integer> obj = intPool.borrowObject(KEY_ZERO); intPool.returnObject(KEY_ZERO, obj); obj = intPool.borrowObject(KEY_ZERO); intPool.returnObject(KEY_ZERO, obj); // borrow, return, borrow, return // FIFO will move 0 and 1 to end - 2,3,4,5,6,7,0,1 // LIFO, 7 out, then in, then out, then in - 7,6,5,4,3,2,1,0 intPool.evict(); // Should visit 02 and 03 in either case for (int i = 0; i < 8; i++) { final VisitTracker<Integer> tracker = intPool.borrowObject(KEY_ZERO); if (tracker.getId() >= 4) { assertEquals( 0, tracker.getValidateCount(),"Unexpected instance visited " + tracker.getId()); } else { assertEquals( 1, tracker.getValidateCount(),"Instance " + tracker.getId() + " visited wrong number of times."); } } // 0's are all out intPool.setNumTestsPerEvictionRun(3); intPool.evict(); // 10, 11, 12 intPool.evict(); // 13, 14, 15 obj = intPool.borrowObject(KEY_ONE); intPool.returnObject(KEY_ONE, obj); obj = intPool.borrowObject(KEY_ONE); intPool.returnObject(KEY_ONE, obj); obj = intPool.borrowObject(KEY_ONE); intPool.returnObject(KEY_ONE, obj); // borrow, return, borrow, return // FIFO 3,4,5,^,6,7,0,1,2 // LIFO 7,6,^,5,4,3,2,1,0 // In either case, pointer should be at 6 intPool.evict(); // LIFO - 16, 17, 20 // FIFO - 16, 17, 10 intPool.evict(); // LIFO - 21, 22, 23 // FIFO - 11, 12, 20 intPool.evict(); // LIFO - 24, 25, 26 // FIFO - 21, 22, 23 intPool.evict(); // LIFO - 27, 10, 11 // FIFO - 24, 25, 26 for (int i = 0; i < 8; i++) { final VisitTracker<Integer> tracker = intPool.borrowObject(KEY_ONE); if ((lifo && tracker.getId() > 1) || (!lifo && tracker.getId() > 2)) { assertEquals( 1, tracker.getValidateCount(),"Instance " + tracker.getId() + " visited wrong number of times."); } else { assertEquals( 2, tracker.getValidateCount(),"Instance " + tracker.getId() + " visited wrong number of times."); } } } // Randomly generate some pools with random numTests // and make sure evictor cycles through elements appropriately final int[] smallPrimes = { 2, 3, 5, 7 }; final Random random = new Random(); random.setSeed(System.currentTimeMillis()); for (int i = 0; i < smallPrimes.length; i++) { for (int j = 0; j < 5; j++) {// Try the tests a few times // Can't use clear as some objects are still active so create // a new pool trackerFactory = new VisitTrackerFactory<>(); try (GenericKeyedObjectPool<Integer, VisitTracker<Integer>, RuntimeException> intPool = new GenericKeyedObjectPool<>( trackerFactory)) { intPool.setMaxIdlePerKey(-1); intPool.setMaxTotalPerKey(-1); intPool.setNumTestsPerEvictionRun(smallPrimes[i]); intPool.setMinEvictableIdleTime(Duration.ofMillis(-1)); intPool.setTestWhileIdle(true); intPool.setLifo(lifo); intPool.setTestOnReturn(false); intPool.setTestOnBorrow(false); final int zeroLength = 10 + random.nextInt(20); for (int k = 0; k < zeroLength; k++) { intPool.addObject(KEY_ZERO); } final int oneLength = 10 + random.nextInt(20); for (int k = 0; k < oneLength; k++) { intPool.addObject(KEY_ONE); } final int twoLength = 10 + random.nextInt(20); for (int k = 0; k < twoLength; k++) { intPool.addObject(KEY_TWO); } // Choose a random number of evictor runs final int runs = 10 + random.nextInt(50); for (int k = 0; k < runs; k++) { intPool.evict(); } // Total instances in pool final int totalInstances = zeroLength + oneLength + twoLength; // Number of times evictor should have cycled through pools final int cycleCount = (runs * intPool.getNumTestsPerEvictionRun()) / totalInstances; // Look at elements and make sure they are visited cycleCount // or cycleCount + 1 times VisitTracker<Integer> tracker = null; int visitCount = 0; for (int k = 0; k < zeroLength; k++) { tracker = intPool.borrowObject(KEY_ZERO); visitCount = tracker.getValidateCount(); if (visitCount < cycleCount || visitCount > cycleCount + 1) { fail(formatSettings("ZERO", "runs", runs, "lifo", lifo, "i", i, "j", j, "k", k, "visitCount", visitCount, "cycleCount", cycleCount, "totalInstances", totalInstances, zeroLength, oneLength, twoLength)); } } for (int k = 0; k < oneLength; k++) { tracker = intPool.borrowObject(KEY_ONE); visitCount = tracker.getValidateCount(); if (visitCount < cycleCount || visitCount > cycleCount + 1) { fail(formatSettings("ONE", "runs", runs, "lifo", lifo, "i", i, "j", j, "k", k, "visitCount", visitCount, "cycleCount", cycleCount, "totalInstances", totalInstances, zeroLength, oneLength, twoLength)); } } final int[] visits = new int[twoLength]; for (int k = 0; k < twoLength; k++) { tracker = intPool.borrowObject(KEY_TWO); visitCount = tracker.getValidateCount(); visits[k] = visitCount; if (visitCount < cycleCount || visitCount > cycleCount + 1) { final StringBuilder sb = new StringBuilder("Visits:"); for (int l = 0; l <= k; l++) { sb.append(visits[l]).append(' '); } fail(formatSettings("TWO " + sb.toString(), "runs", runs, "lifo", lifo, "i", i, "j", j, "k", k, "visitCount", visitCount, "cycleCount", cycleCount, "totalInstances", totalInstances, zeroLength, oneLength, twoLength)); } } } } } } private String formatSettings(final String title, final String s, final int i, final String s0, final boolean b0, final String s1, final int i1, final String s2, final int i2, final String s3, final int i3, final String s4, final int i4, final String s5, final int i5, final String s6, final int i6, final int zeroLength, final int oneLength, final int twoLength){ final StringBuilder sb = new StringBuilder(80); sb.append(title).append(' '); sb.append(s).append('=').append(i).append(' '); sb.append(s0).append('=').append(b0).append(' '); sb.append(s1).append('=').append(i1).append(' '); sb.append(s2).append('=').append(i2).append(' '); sb.append(s3).append('=').append(i3).append(' '); sb.append(s4).append('=').append(i4).append(' '); sb.append(s5).append('=').append(i5).append(' '); sb.append(s6).append('=').append(i6).append(' '); sb.append("Lengths=").append(zeroLength).append(',').append(oneLength).append(',').append(twoLength).append(' '); return sb.toString(); } private String getExceptionTrace(final Throwable t){ final StringWriter sw = new StringWriter(); t.printStackTrace(new PrintWriter(sw)); return sw.toString(); } @Override protected Object getNthObject(final Object key, final int n) { return String.valueOf(key) + String.valueOf(n); } @Override protected boolean isFifo() { return false; } @Override protected boolean isLifo() { return true; } @SuppressWarnings("unchecked") @Override protected <E extends Exception> KeyedObjectPool<Object, Object, E> makeEmptyPool(final int minCapacity) { final KeyedPooledObjectFactory<Object, Object, RuntimeException> perKeyFactory = new SimplePerKeyFactory(); final GenericKeyedObjectPool<Object, Object, RuntimeException> perKeyPool = new GenericKeyedObjectPool<>(perKeyFactory); perKeyPool.setMaxTotalPerKey(minCapacity); perKeyPool.setMaxIdlePerKey(minCapacity); return (KeyedObjectPool<Object, Object, E>) perKeyPool; } @Override protected <E extends Exception> KeyedObjectPool<Object, Object, E> makeEmptyPool(final KeyedPooledObjectFactory<Object, Object, E> fac) { return new GenericKeyedObjectPool<>(fac); } @Override protected Object makeKey(final int n) { return String.valueOf(n); } /** * Kicks off {@code numThreads} test threads, each of which will go * through {@code iterations} borrow-return cycles with random delay * times &lt;= delay in between. * * @param <T> Type of object in pool * @param numThreads Number of test threads * @param iterations Number of iterations for each thread * @param delay Maximum delay between iterations * @param gkopPool The keyed object pool to use */ public <T, E extends Exception> void runTestThreads(final int numThreads, final int iterations, final int delay, final GenericKeyedObjectPool<String, T, E> gkopPool) { final ArrayList<TestThread<T, E>> threads = new ArrayList<>(); for (int i = 0; i < numThreads; i++) { final TestThread<T, E> testThread = new TestThread<>(gkopPool, iterations, delay); threads.add(testThread); final Thread t = new Thread(testThread); t.start(); } for (final TestThread<T, E> testThread : threads) { while (!(testThread.complete())) { Waiter.sleepQuietly(500L); } if (testThread.failed()) { fail("Thread failed: " + threads.indexOf(testThread) + "\n" + getExceptionTrace(testThread.exception)); } } } @BeforeEach public void setUp() { simpleFactory = new SimpleFactory<>(); gkoPool = new GenericKeyedObjectPool<>(simpleFactory); } @AfterEach public void tearDownJmx() throws Exception { super.tearDown(); final ObjectName jmxName = gkoPool.getJmxName(); final String poolName = Objects.toString(jmxName, null); gkoPool.clear(); gkoPool.close(); gkoPool = null; simpleFactory = null; final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); final Set<ObjectName> result = mbs.queryNames(new ObjectName( "org.apache.commoms.pool2:type=GenericKeyedObjectPool,*"), null); // There should be no registered pools at this point final int registeredPoolCount = result.size(); final StringBuilder msg = new StringBuilder("Current pool is: "); msg.append(poolName); msg.append(" Still open pools are: "); for (final ObjectName name : result) { // Clean these up ready for the next test msg.append(name.toString()); msg.append(" created via\n"); msg.append(mbs.getAttribute(name, "CreationStackTrace")); msg.append('\n'); mbs.unregisterMBean(name); } assertEquals( 0, registeredPoolCount, msg.toString()); } @Test public void testAppendStats() { assertFalse(gkoPool.getMessageStatistics()); assertEquals("foo", (gkoPool.appendStats("foo"))); try (final GenericKeyedObjectPool<?, ?, Exception> pool = new GenericKeyedObjectPool<>(new SimpleFactory<>())) { pool.setMessagesStatistics(true); assertNotEquals("foo", (pool.appendStats("foo"))); pool.setMessagesStatistics(false); assertEquals("foo", (pool.appendStats("foo"))); } } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testBlockedKeyDoesNotBlockPool() throws Exception { gkoPool.setBlockWhenExhausted(true); gkoPool.setMaxWaitMillis(5000); gkoPool.setMaxTotalPerKey(1); gkoPool.setMaxTotal(-1); gkoPool.borrowObject("one"); final long startMillis = System.currentTimeMillis(); // Needs to be in a separate thread as this will block final Runnable simple = new SimpleTestThread<>(gkoPool, "one"); (new Thread(simple)).start(); // This should be almost instant. If it isn't it means this thread got // stuck behind the thread created above which is bad. // Give other thread a chance to start Thread.sleep(1000); gkoPool.borrowObject("two"); final long endMillis = System.currentTimeMillis(); // If it fails it will be more than 4000ms (5000 less the 1000 sleep) // If it passes it should be almost instant // Use 3000ms as the threshold - should avoid timing issues on most // (all? platforms) assertTrue((endMillis - startMillis) < 4000, "Elapsed time: " + (endMillis - startMillis) + " should be less than 4000"); } /* * Note: This test relies on timing for correct execution. There *should* be * enough margin for this to work correctly on most (all?) systems but be * aware of this if you see a failure of this test. */ @SuppressWarnings({ "rawtypes" }) @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testBorrowObjectFairness() throws Exception { final int numThreads = 40; final int maxTotal = 40; final GenericKeyedObjectPoolConfig<String> config = new GenericKeyedObjectPoolConfig<>(); config.setMaxTotalPerKey(maxTotal); config.setFairness(true); config.setLifo(false); config.setMaxIdlePerKey(maxTotal); gkoPool = new GenericKeyedObjectPool<>(simpleFactory, config); // Exhaust the pool final String[] objects = new String[maxTotal]; for (int i = 0; i < maxTotal; i++) { objects[i] = gkoPool.borrowObject("0"); } // Start and park threads waiting to borrow objects final TestThread[] threads = new TestThread[numThreads]; for(int i=0;i<numThreads;i++) { threads[i] = new TestThread<>(gkoPool, 1, 0, 2000, false, "0" + String.valueOf(i % maxTotal), "0"); final Thread t = new Thread(threads[i]); t.start(); // Short delay to ensure threads start in correct order try { Thread.sleep(10); } catch (final InterruptedException e) { fail(e.toString()); } } // Return objects, other threads should get served in order for (int i = 0; i < maxTotal; i++) { gkoPool.returnObject("0", objects[i]); } // Wait for threads to finish for (int i = 0; i < numThreads; i++) { while (!(threads[i]).complete()) { Waiter.sleepQuietly(500L); } if (threads[i].failed()) { fail("Thread " + i + " failed: " + threads[i].exception.toString()); } } } /** * POOL-192 * Verify that clear(key) does not leak capacity. * * @throws Exception May occur in some failure modes */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testClear() throws Exception { gkoPool.setMaxTotal(2); gkoPool.setMaxTotalPerKey(2); gkoPool.setBlockWhenExhausted(false); gkoPool.addObject("one"); gkoPool.addObject("one"); assertEquals(2, gkoPool.getNumIdle()); gkoPool.clear("one"); assertEquals(0, gkoPool.getNumIdle()); assertEquals(0, gkoPool.getNumIdle("one")); final String obj1 = gkoPool.borrowObject("one"); final String obj2 = gkoPool.borrowObject("one"); gkoPool.returnObject("one", obj1); gkoPool.returnObject("one", obj2); gkoPool.clear(); assertEquals(0, gkoPool.getNumIdle()); assertEquals(0, gkoPool.getNumIdle("one")); gkoPool.borrowObject("one"); gkoPool.borrowObject("one"); gkoPool.close(); } /** * Test to make sure that clearOldest does not destroy instances that have been checked out. * * @throws Exception May occur in some failure modes */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testClearOldest() throws Exception { // Make destroy have some latency so clearOldest takes some time final WaiterFactory<String> waiterFactory = new WaiterFactory<>(0, 20, 0, 0, 0, 0, 50, 5, 0); try (final GenericKeyedObjectPool<String, Waiter, RuntimeException> waiterPool = new GenericKeyedObjectPool<>(waiterFactory)) { waiterPool.setMaxTotalPerKey(5); waiterPool.setMaxTotal(50); waiterPool.setLifo(false); // Load the pool with idle instances - 5 each for 10 keys for (int i = 0; i < 10; i++) { final String key = Integer.toString(i); for (int j = 0; j < 5; j++) { waiterPool.addObject(key); } // Make sure order is maintained Thread.sleep(20); } // Now set up a race - one thread wants a new instance, triggering clearOldest // Other goes after an element on death row // See if we end up with dead man walking final SimpleTestThread<Waiter, RuntimeException> t2 = new SimpleTestThread<>(waiterPool, "51"); final Thread thread2 = new Thread(t2); thread2.start(); // Triggers clearOldest, killing all of the 0's and the 2 oldest 1's Thread.sleep(50); // Wait for clearOldest to kick off, but not long enough to reach the 1's final Waiter waiter = waiterPool.borrowObject("1"); Thread.sleep(200); // Wait for execution to happen waiterPool.returnObject("1", waiter); // Will throw IllegalStateException if dead } } /** * POOL-391 Verify that when clear(key) is called with reuseCapacity true, * capacity freed is reused and allocated to most loaded pools. * * @throws Exception May occur in some failure modes */ @Test public void testClearReuseCapacity() throws Exception { gkoPool.setMaxTotalPerKey(6); gkoPool.setMaxTotal(6); gkoPool.setMaxWait(Duration.ofSeconds(5)); // Create one thread to wait on "one", two on "two", three on "three" final ArrayList<Thread> testThreads = new ArrayList<>(); testThreads.add(new Thread(new SimpleTestThread<>(gkoPool, "one"))); testThreads.add(new Thread(new SimpleTestThread<>(gkoPool, "two"))); testThreads.add(new Thread(new SimpleTestThread<>(gkoPool, "two"))); testThreads.add(new Thread(new SimpleTestThread<>(gkoPool, "three"))); testThreads.add(new Thread(new SimpleTestThread<>(gkoPool, "three"))); testThreads.add(new Thread(new SimpleTestThread<>(gkoPool, "three"))); // Borrow two each from "four", "five", "six" - using all capacity final String four = gkoPool.borrowObject("four"); final String four2 = gkoPool.borrowObject("four"); final String five = gkoPool.borrowObject("five"); final String five2 = gkoPool.borrowObject("five"); final String six = gkoPool.borrowObject("six"); final String six2 = gkoPool.borrowObject("six"); Thread.sleep(100); // Launch the waiters - all will be blocked waiting for (Thread t : testThreads) { t.start(); } Thread.sleep(100); // Return and clear the fours - at least one "three" should get served // Other should be a two or a three (three was most loaded) gkoPool.returnObject("four", four); gkoPool.returnObject("four", four2); gkoPool.clear("four"); Thread.sleep(20); assertTrue(!testThreads.get(3).isAlive() || !testThreads.get(4).isAlive() || !testThreads.get(5).isAlive()); // Now clear the fives gkoPool.returnObject("five", five); gkoPool.returnObject("five", five2); gkoPool.clear("five"); Thread.sleep(20); // Clear the sixes gkoPool.returnObject("six", six); gkoPool.returnObject("six", six2); gkoPool.clear("six"); Thread.sleep(20); for (Thread t : testThreads) { assertFalse(t.isAlive()); } } /** * POOL-391 Adapted from code in the JIRA ticket. * * @throws Exception May occur in some failure modes */ @Test @Timeout(value = 2000, unit = TimeUnit.MILLISECONDS) public void testClearUnblocksWaiters() { final GenericKeyedObjectPoolConfig<Integer> config = new GenericKeyedObjectPoolConfig<>(); config.setMaxTotalPerKey(1); config.setMinIdlePerKey(0); config.setMaxIdlePerKey(-1); config.setMaxTotal(-1); config.setMaxWait(Duration.ofMillis(5)); GenericKeyedObjectPool<Integer, Integer, InterruptedException> testPool = new GenericKeyedObjectPool<>( new KeyedPooledObjectFactory<Integer, Integer, InterruptedException>() { @Override public void activateObject(Integer key, PooledObject<Integer> p) { // do nothing } @Override public void destroyObject(Integer key, PooledObject<Integer> p) throws InterruptedException { Thread.sleep(500); } @Override public PooledObject<Integer> makeObject(Integer key) { return new DefaultPooledObject<>(10); } @Override public void passivateObject(Integer key, PooledObject<Integer> p) { // do nothing } @Override public boolean validateObject(Integer key, PooledObject<Integer> p) { return true; } }, config); final int borrowKey = 10; Thread t = new Thread(() -> { try { while (true) { Integer integer = testPool.borrowObject(borrowKey); testPool.returnObject(borrowKey, integer); Thread.sleep(10); } } catch (Exception e) { fail(); } }); Thread t2 = new Thread(() -> { try { while (true) { testPool.clear(borrowKey); Thread.sleep(10); } } catch (Exception e) { fail(); } }); t.start(); t2.start(); } // POOL-259 @Test public void testClientWaitStats() throws Exception { final SimpleFactory<String> factory = new SimpleFactory<>(); // Give makeObject a little latency factory.setMakeLatency(200); try (final GenericKeyedObjectPool<String, String, Exception> pool = new GenericKeyedObjectPool<>(factory, new GenericKeyedObjectPoolConfig<>())) { final String s = pool.borrowObject("one"); // First borrow waits on create, so wait time should be at least 200 ms // Allow 100ms error in clock times assertTrue(pool.getMaxBorrowWaitTimeMillis() >= 100); assertTrue(pool.getMeanBorrowWaitTimeMillis() >= 100); pool.returnObject("one", s); pool.borrowObject("one"); // Second borrow does not have to wait on create, average should be about 100 assertTrue(pool.getMaxBorrowWaitTimeMillis() > 100); assertTrue(pool.getMeanBorrowWaitTimeMillis() < 200); assertTrue(pool.getMeanBorrowWaitTimeMillis() > 20); } } /** * POOL-231 - verify that concurrent invalidates of the same object do not * corrupt pool destroyCount. * * @throws Exception May occur in some failure modes */ @Test public void testConcurrentInvalidate() throws Exception { // Get allObjects and idleObjects loaded with some instances final int nObjects = 1000; final String key = "one"; gkoPool.setMaxTotal(nObjects); gkoPool.setMaxTotalPerKey(nObjects); gkoPool.setMaxIdlePerKey(nObjects); final String [] obj = new String[nObjects]; for (int i = 0; i < nObjects; i++) { obj[i] = gkoPool.borrowObject(key); } for (int i = 0; i < nObjects; i++) { if (i % 2 == 0) { gkoPool.returnObject(key, obj[i]); } } final int nThreads = 20; final int nIterations = 60; final InvalidateThread[] threads = new InvalidateThread[nThreads]; // Randomly generated list of distinct invalidation targets final ArrayList<Integer> targets = new ArrayList<>(); final Random random = new Random(); for (int j = 0; j < nIterations; j++) { // Get a random invalidation target Integer targ = Integer.valueOf(random.nextInt(nObjects)); while (targets.contains(targ)) { targ = Integer.valueOf(random.nextInt(nObjects)); } targets.add(targ); // Launch nThreads threads all trying to invalidate the target for (int i = 0; i < nThreads; i++) { threads[i] = new InvalidateThread(gkoPool, key, obj[targ.intValue()]); } for (int i = 0; i < nThreads; i++) { new Thread(threads[i]).start(); } boolean done = false; while (!done) { done = true; for (int i = 0; i < nThreads; i++) { done = done && threads[i].complete(); } Thread.sleep(100); } } assertEquals(nIterations, gkoPool.getDestroyedCount()); } @Test public void testConstructorNullFactory() { // add dummy assert (won't be invoked because of IAE) to avoid "unused" warning assertThrows(IllegalArgumentException.class, () -> new GenericKeyedObjectPool<>(null)); } @SuppressWarnings("deprecation") @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testConstructors() { // Make constructor arguments all different from defaults final int maxTotalPerKey = 1; final int minIdle = 2; final Duration maxWaitDuration = Duration.ofMillis(3); final long maxWaitMillis = maxWaitDuration.toMillis(); final int maxIdle = 4; final int maxTotal = 5; final long minEvictableIdleTimeMillis = 6; final int numTestsPerEvictionRun = 7; final boolean testOnBorrow = true; final boolean testOnReturn = true; final boolean testWhileIdle = true; final long timeBetweenEvictionRunsMillis = 8; final boolean blockWhenExhausted = false; final boolean lifo = false; final KeyedPooledObjectFactory<Object, Object, RuntimeException> dummyFactory = new DummyFactory(); try (GenericKeyedObjectPool<Object, Object, RuntimeException> objPool = new GenericKeyedObjectPool<>(dummyFactory)) { assertEquals(GenericKeyedObjectPoolConfig.DEFAULT_MAX_TOTAL_PER_KEY, objPool.getMaxTotalPerKey()); assertEquals(GenericKeyedObjectPoolConfig.DEFAULT_MAX_IDLE_PER_KEY, objPool.getMaxIdlePerKey()); assertEquals(BaseObjectPoolConfig.DEFAULT_MAX_WAIT_MILLIS, objPool.getMaxWaitMillis()); assertEquals(GenericKeyedObjectPoolConfig.DEFAULT_MIN_IDLE_PER_KEY, objPool.getMinIdlePerKey()); assertEquals(GenericKeyedObjectPoolConfig.DEFAULT_MAX_TOTAL, objPool.getMaxTotal()); // assertEquals(BaseObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, objPool.getMinEvictableIdleTimeMillis()); assertEquals(BaseObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_TIME, objPool.getMinEvictableIdleTime()); assertEquals(BaseObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_TIME, objPool.getMinEvictableIdleDuration()); // assertEquals(BaseObjectPoolConfig.DEFAULT_NUM_TESTS_PER_EVICTION_RUN, objPool.getNumTestsPerEvictionRun()); assertEquals(Boolean.valueOf(BaseObjectPoolConfig.DEFAULT_TEST_ON_BORROW), Boolean.valueOf(objPool.getTestOnBorrow())); assertEquals(Boolean.valueOf(BaseObjectPoolConfig.DEFAULT_TEST_ON_RETURN), Boolean.valueOf(objPool.getTestOnReturn())); assertEquals(Boolean.valueOf(BaseObjectPoolConfig.DEFAULT_TEST_WHILE_IDLE), Boolean.valueOf(objPool.getTestWhileIdle())); // assertEquals(BaseObjectPoolConfig.DEFAULT_TIME_BETWEEN_EVICTION_RUNS, objPool.getDurationBetweenEvictionRuns()); assertEquals(BaseObjectPoolConfig.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, objPool.getTimeBetweenEvictionRunsMillis()); assertEquals(BaseObjectPoolConfig.DEFAULT_TIME_BETWEEN_EVICTION_RUNS, objPool.getTimeBetweenEvictionRuns()); // assertEquals(Boolean.valueOf(BaseObjectPoolConfig.DEFAULT_BLOCK_WHEN_EXHAUSTED), Boolean.valueOf(objPool.getBlockWhenExhausted())); assertEquals(Boolean.valueOf(BaseObjectPoolConfig.DEFAULT_LIFO), Boolean.valueOf(objPool.getLifo())); } final GenericKeyedObjectPoolConfig<Object> config = new GenericKeyedObjectPoolConfig<>(); config.setLifo(lifo); config.setMaxTotalPerKey(maxTotalPerKey); config.setMaxIdlePerKey(maxIdle); config.setMinIdlePerKey(minIdle); config.setMaxTotal(maxTotal); config.setMaxWait(maxWaitDuration); config.setMinEvictableIdleTime(Duration.ofMillis(minEvictableIdleTimeMillis)); config.setNumTestsPerEvictionRun(numTestsPerEvictionRun); config.setTestOnBorrow(testOnBorrow); config.setTestOnReturn(testOnReturn); config.setTestWhileIdle(testWhileIdle); config.setTimeBetweenEvictionRuns(Duration.ofMillis(timeBetweenEvictionRunsMillis)); config.setBlockWhenExhausted(blockWhenExhausted); try (GenericKeyedObjectPool<Object, Object, RuntimeException> objPool = new GenericKeyedObjectPool<>(dummyFactory, config)) { assertEquals(maxTotalPerKey, objPool.getMaxTotalPerKey()); assertEquals(maxIdle, objPool.getMaxIdlePerKey()); assertEquals(maxWaitDuration, objPool.getMaxWaitDuration()); assertEquals(maxWaitMillis, objPool.getMaxWaitMillis()); assertEquals(minIdle, objPool.getMinIdlePerKey()); assertEquals(maxTotal, objPool.getMaxTotal()); assertEquals(minEvictableIdleTimeMillis, objPool.getMinEvictableIdleDuration().toMillis()); assertEquals(minEvictableIdleTimeMillis, objPool.getMinEvictableIdleTimeMillis()); assertEquals(minEvictableIdleTimeMillis, objPool.getMinEvictableIdleTime().toMillis()); assertEquals(numTestsPerEvictionRun, objPool.getNumTestsPerEvictionRun()); assertEquals(Boolean.valueOf(testOnBorrow), Boolean.valueOf(objPool.getTestOnBorrow())); assertEquals(Boolean.valueOf(testOnReturn), Boolean.valueOf(objPool.getTestOnReturn())); assertEquals(Boolean.valueOf(testWhileIdle), Boolean.valueOf(objPool.getTestWhileIdle())); assertEquals(timeBetweenEvictionRunsMillis, objPool.getDurationBetweenEvictionRuns().toMillis()); assertEquals(timeBetweenEvictionRunsMillis, objPool.getTimeBetweenEvictionRunsMillis()); assertEquals(timeBetweenEvictionRunsMillis, objPool.getTimeBetweenEvictionRuns().toMillis()); assertEquals(Boolean.valueOf(blockWhenExhausted), Boolean.valueOf(objPool.getBlockWhenExhausted())); assertEquals(Boolean.valueOf(lifo), Boolean.valueOf(objPool.getLifo())); } } /** * JIRA: POOL-270 - make sure constructor correctly sets run * frequency of evictor timer. */ @Test public void testContructorEvictionConfig() throws Exception { final GenericKeyedObjectPoolConfig<String> config = new GenericKeyedObjectPoolConfig<>(); config.setTimeBetweenEvictionRuns(Duration.ofMillis(500)); config.setMinEvictableIdleTime(Duration.ofMillis(50)); config.setNumTestsPerEvictionRun(5); try (final GenericKeyedObjectPool<String, String, Exception> p = new GenericKeyedObjectPool<>(simpleFactory, config)) { for (int i = 0; i < 5; i++) { p.addObject("one"); } Waiter.sleepQuietly(100); assertEquals(5, p.getNumIdle("one")); Waiter.sleepQuietly(500); assertEquals(0, p.getNumIdle("one")); } } /** * Verifies that when a factory's makeObject produces instances that are not * discernible by equals, the pool can handle them. * * JIRA: POOL-283 */ @Test public void testEqualsIndiscernible() throws Exception { final HashSetFactory factory = new HashSetFactory(); try (final GenericKeyedObjectPool<String, HashSet<String>, RuntimeException> pool = new GenericKeyedObjectPool<>(factory, new GenericKeyedObjectPoolConfig<>())) { final HashSet<String> s1 = pool.borrowObject("a"); final HashSet<String> s2 = pool.borrowObject("a"); pool.returnObject("a", s1); pool.returnObject("a", s2); } } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testEviction() throws Exception { gkoPool.setMaxIdlePerKey(500); gkoPool.setMaxTotalPerKey(500); gkoPool.setNumTestsPerEvictionRun(100); gkoPool.setMinEvictableIdleTime(Duration.ofMillis(250)); gkoPool.setTimeBetweenEvictionRuns(Duration.ofMillis(500)); final String[] active = new String[500]; for(int i=0;i<500;i++) { active[i] = gkoPool.borrowObject(""); } for(int i=0;i<500;i++) { gkoPool.returnObject("",active[i]); } Waiter.sleepQuietly(1000L); assertTrue(gkoPool.getNumIdle("") < 500, "Should be less than 500 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertTrue(gkoPool.getNumIdle("") < 400, "Should be less than 400 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertTrue(gkoPool.getNumIdle("") < 300,"Should be less than 300 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertTrue(gkoPool.getNumIdle("") < 200, "Should be less than 200 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertTrue(gkoPool.getNumIdle("") < 100 , "Should be less than 100 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertEquals(0,gkoPool.getNumIdle(""),"Should be zero idle, found " + gkoPool.getNumIdle("")); for(int i=0;i<500;i++) { active[i] = gkoPool.borrowObject(""); } for(int i=0;i<500;i++) { gkoPool.returnObject("",active[i]); } Waiter.sleepQuietly(1000L); assertTrue(gkoPool.getNumIdle("") < 500,"Should be less than 500 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertTrue(gkoPool.getNumIdle("") < 400,"Should be less than 400 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertTrue(gkoPool.getNumIdle("") < 300,"Should be less than 300 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertTrue(gkoPool.getNumIdle("") < 200,"Should be less than 200 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertTrue(gkoPool.getNumIdle("") < 100,"Should be less than 100 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertEquals(0,gkoPool.getNumIdle(""),"Should be zero idle, found " + gkoPool.getNumIdle("")); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testEviction2() throws Exception { gkoPool.setMaxIdlePerKey(500); gkoPool.setMaxTotalPerKey(500); gkoPool.setNumTestsPerEvictionRun(100); gkoPool.setMinEvictableIdleTime(Duration.ofMillis(500)); gkoPool.setTimeBetweenEvictionRuns(Duration.ofMillis(500)); final String[] active = new String[500]; final String[] active2 = new String[500]; for (int i = 0; i < 500; i++) { active[i] = gkoPool.borrowObject(""); active2[i] = gkoPool.borrowObject("2"); } for (int i = 0; i < 500; i++) { gkoPool.returnObject("", active[i]); gkoPool.returnObject("2", active2[i]); } Waiter.sleepQuietly(1100L); assertTrue(gkoPool.getNumIdle() < 1000, "Should be less than 1000 idle, found " + gkoPool.getNumIdle()); final long sleepMillisPart2 = 600L; Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 900, "Should be less than 900 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 800, "Should be less than 800 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 700, "Should be less than 700 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 600, "Should be less than 600 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 500, "Should be less than 500 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 400, "Should be less than 400 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 300, "Should be less than 300 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 200, "Should be less than 200 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 100, "Should be less than 100 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertEquals(0, gkoPool.getNumIdle(), "Should be zero idle, found " + gkoPool.getNumIdle()); } /** * Test to make sure evictor visits least recently used objects first, * regardless of FIFO/LIFO * * JIRA: POOL-86 * * @throws Exception May occur in some failure modes */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testEvictionOrder() throws Exception { checkEvictionOrder(false); checkEvictionOrder(true); } // POOL-326 @Test public void testEvictorClearOldestRace() throws Exception { gkoPool.setMinEvictableIdleTime(Duration.ofMillis(100)); gkoPool.setNumTestsPerEvictionRun(1); // Introduce latency between when evictor starts looking at an instance and when // it decides to destroy it gkoPool.setEvictionPolicy(new SlowEvictionPolicy<>(1000)); // Borrow an instance final String val = gkoPool.borrowObject("foo"); // Add another idle one gkoPool.addObject("foo"); // Sleep long enough so idle one is eligible for eviction Thread.sleep(1000); // Start evictor and race with clearOldest gkoPool.setTimeBetweenEvictionRuns(Duration.ofMillis(10)); // Wait for evictor to start Thread.sleep(100); gkoPool.clearOldest(); // Wait for slow evictor to complete Thread.sleep(1500); // See if we get NPE on return (POOL-326) gkoPool.returnObject("foo", val); } /** * Verifies that the evictor visits objects in expected order * and frequency. * * @throws Exception May occur in some failure modes */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testEvictorVisiting() throws Exception { checkEvictorVisiting(true); checkEvictorVisiting(false); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testExceptionInValidationDuringEviction() throws Exception { gkoPool.setMaxIdlePerKey(1); gkoPool.setMinEvictableIdleTime(Duration.ZERO); gkoPool.setTestWhileIdle(true); final String obj = gkoPool.borrowObject("one"); gkoPool.returnObject("one", obj); simpleFactory.setThrowExceptionOnValidate(true); assertThrows(RuntimeException.class, gkoPool::evict); assertEquals(0, gkoPool.getNumActive()); assertEquals(0, gkoPool.getNumIdle()); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testExceptionOnActivateDuringBorrow() throws Exception { final String obj1 = gkoPool.borrowObject("one"); final String obj2 = gkoPool.borrowObject("one"); gkoPool.returnObject("one", obj1); gkoPool.returnObject("one", obj2); simpleFactory.setThrowExceptionOnActivate(true); simpleFactory.setEvenValid(false); // Activation will now throw every other time // First attempt throws, but loop continues and second succeeds final String obj = gkoPool.borrowObject("one"); assertEquals(1, gkoPool.getNumActive("one")); assertEquals(0, gkoPool.getNumIdle("one")); assertEquals(1, gkoPool.getNumActive()); assertEquals(0, gkoPool.getNumIdle()); gkoPool.returnObject("one", obj); simpleFactory.setValid(false); // Validation will now fail on activation when borrowObject returns // an idle instance, and then when attempting to create a new instance assertThrows(NoSuchElementException.class, () -> gkoPool.borrowObject("one")); assertEquals(0, gkoPool.getNumActive("one")); assertEquals(0, gkoPool.getNumIdle("one")); assertEquals(0, gkoPool.getNumActive()); assertEquals(0, gkoPool.getNumIdle()); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testExceptionOnDestroyDuringBorrow() throws Exception { simpleFactory.setThrowExceptionOnDestroy(true); simpleFactory.setValidationEnabled(true); gkoPool.setTestOnBorrow(true); gkoPool.borrowObject("one"); simpleFactory.setValid(false); // Make validation fail on next borrow attempt assertThrows(NoSuchElementException.class, () -> gkoPool.borrowObject("one")); assertEquals(1, gkoPool.getNumActive("one")); assertEquals(0, gkoPool.getNumIdle("one")); assertEquals(1, gkoPool.getNumActive()); assertEquals(0, gkoPool.getNumIdle()); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testExceptionOnDestroyDuringReturn() throws Exception { simpleFactory.setThrowExceptionOnDestroy(true); simpleFactory.setValidationEnabled(true); gkoPool.setTestOnReturn(true); final String obj1 = gkoPool.borrowObject("one"); gkoPool.borrowObject("one"); simpleFactory.setValid(false); // Make validation fail gkoPool.returnObject("one", obj1); assertEquals(1, gkoPool.getNumActive("one")); assertEquals(0, gkoPool.getNumIdle("one")); assertEquals(1, gkoPool.getNumActive()); assertEquals(0, gkoPool.getNumIdle()); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testExceptionOnPassivateDuringReturn() throws Exception { final String obj = gkoPool.borrowObject("one"); simpleFactory.setThrowExceptionOnPassivate(true); gkoPool.returnObject("one", obj); assertEquals(0,gkoPool.getNumIdle()); gkoPool.close(); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testFIFO() throws Exception { gkoPool.setLifo(false); final String key = "key"; gkoPool.addObject(key); // "key0" gkoPool.addObject(key); // "key1" gkoPool.addObject(key); // "key2" assertEquals( "key0", gkoPool.borrowObject(key),"Oldest"); assertEquals( "key1", gkoPool.borrowObject(key),"Middle"); assertEquals( "key2", gkoPool.borrowObject(key),"Youngest"); final String s = gkoPool.borrowObject(key); assertEquals( "key3", s,"new-3"); gkoPool.returnObject(key, s); assertEquals( s, gkoPool.borrowObject(key),"returned"); assertEquals( "key4", gkoPool.borrowObject(key),"new-4"); } @Test @Timeout(value = 60, unit = TimeUnit.SECONDS) public void testGetKeys() throws Exception { gkoPool.addObject("one"); assertEquals(1, gkoPool.getKeys().size()); gkoPool.addObject("two"); assertEquals(2, gkoPool.getKeys().size()); gkoPool.clear("one"); assertEquals(1, gkoPool.getKeys().size()); assertEquals("two", gkoPool.getKeys().get(0)); gkoPool.clear(); } @Test public void testGetStatsString() { assertNotNull((gkoPool.getStatsString())); } /** * Verify that threads waiting on a depleted pool get served when a checked out object is * invalidated. * * JIRA: POOL-240 * * @throws Exception May occur in some failure modes */ @Test public void testInvalidateFreesCapacity() throws Exception { final SimpleFactory<String> factory = new SimpleFactory<>(); try (final GenericKeyedObjectPool<String, String, Exception> pool = new GenericKeyedObjectPool<>(factory)) { pool.setMaxTotalPerKey(2); pool.setMaxWaitMillis(500); // Borrow an instance and hold if for 5 seconds final WaitingTestThread<Exception> thread1 = new WaitingTestThread<>(pool, "one", 5000); thread1.start(); // Borrow another instance final String obj = pool.borrowObject("one"); // Launch another thread - will block, but fail in 500 ms final WaitingTestThread<Exception> thread2 = new WaitingTestThread<>(pool, "one", 100); thread2.start(); // Invalidate the object borrowed by this thread - should allow thread2 to create Thread.sleep(20); pool.invalidateObject("one", obj); Thread.sleep(600); // Wait for thread2 to timeout if (thread2.thrown != null) { fail(thread2.thrown.toString()); } } } @Test public void testInvalidateFreesCapacityForOtherKeys() throws Exception { gkoPool.setMaxTotal(1); gkoPool.setMaxWait(Duration.ofMillis(500)); Thread borrower = new Thread(new SimpleTestThread<>(gkoPool, "two")); String obj = gkoPool.borrowObject("one"); borrower.start(); // Will block Thread.sleep(100); // Make sure borrower has started gkoPool.invalidateObject("one", obj); // Should free capacity to serve the other key Thread.sleep(20); // Should have been served by now assertFalse(borrower.isAlive()); } @Test public void testInvalidateMissingKey() throws Exception { assertThrows(IllegalStateException.class, () -> gkoPool.invalidateObject("UnknownKey", "Ignored")); } @ParameterizedTest @EnumSource(DestroyMode.class) public void testInvalidateMissingKeyForDestroyMode(final DestroyMode destroyMode) throws Exception { assertThrows(IllegalStateException.class, () -> gkoPool.invalidateObject("UnknownKey", "Ignored", destroyMode)); } /** * Verify that threads blocked waiting on a depleted pool get served when a checked out instance * is invalidated. * * JIRA: POOL-240 * * @throws Exception May occur in some failure modes */ @Test public void testInvalidateWaiting() throws Exception { final GenericKeyedObjectPoolConfig<Object> config = new GenericKeyedObjectPoolConfig<>(); config.setMaxTotal(2); config.setBlockWhenExhausted(true); config.setMinIdlePerKey(0); config.setMaxWait(Duration.ofMillis(-1)); config.setNumTestsPerEvictionRun(Integer.MAX_VALUE); // always test all idle objects config.setTestOnBorrow(true); config.setTestOnReturn(false); config.setTestWhileIdle(true); config.setTimeBetweenEvictionRuns(Duration.ofMillis(-1)); try (final GenericKeyedObjectPool<Integer, Object, RuntimeException> pool = new GenericKeyedObjectPool<>(new ObjectFactory(), config)) { // Allocate both objects with this thread pool.borrowObject(Integer.valueOf(1)); // object1 final Object object2 = pool.borrowObject(Integer.valueOf(1)); // Cause a thread to block waiting for an object final ExecutorService executorService = Executors.newSingleThreadExecutor(new DaemonThreadFactory()); final Semaphore signal = new Semaphore(0); final Future<Exception> result = executorService.submit(() -> { try { signal.release(); final Object object3 = pool.borrowObject(Integer.valueOf(1)); pool.returnObject(Integer.valueOf(1), object3); signal.release(); } catch (final Exception e1) { return e1; } catch (final Throwable e2) { return new Exception(e2); } return null; }); // Wait for the thread to start assertTrue(signal.tryAcquire(5, TimeUnit.SECONDS)); // Attempt to ensure that test thread is blocked waiting for an object Thread.sleep(500); pool.invalidateObject(Integer.valueOf(1), object2); assertTrue(signal.tryAcquire(2, TimeUnit.SECONDS),"Call to invalidateObject did not unblock pool waiters."); if (result.get() != null) { throw new AssertionError(result.get()); } } } /** * Ensure the pool is registered. */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testJmxRegistration() { final ObjectName oname = gkoPool.getJmxName(); final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); final Set<ObjectName> result = mbs.queryNames(oname, null); assertEquals(1, result.size()); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testLIFO() throws Exception { gkoPool.setLifo(true); final String key = "key"; gkoPool.addObject(key); // "key0" gkoPool.addObject(key); // "key1" gkoPool.addObject(key); // "key2" assertEquals( "key2", gkoPool.borrowObject(key),"Youngest"); assertEquals( "key1", gkoPool.borrowObject(key),"Middle"); assertEquals( "key0", gkoPool.borrowObject(key),"Oldest"); final String s = gkoPool.borrowObject(key); assertEquals( "key3", s,"new-3"); gkoPool.returnObject(key, s); assertEquals( s, gkoPool.borrowObject(key),"returned"); assertEquals( "key4", gkoPool.borrowObject(key),"new-4"); } /** * Verifies that threads that get parked waiting for keys not in use * when the pool is at maxTotal eventually get served. * * @throws Exception May occur in some failure modes */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testLivenessPerKey() throws Exception { gkoPool.setMaxIdlePerKey(3); gkoPool.setMaxTotal(3); gkoPool.setMaxTotalPerKey(3); gkoPool.setMaxWaitMillis(3000); // Really a timeout for the test // Check out and briefly hold 3 "1"s final WaitingTestThread<Exception> t1 = new WaitingTestThread<>(gkoPool, "1", 100); final WaitingTestThread<Exception> t2 = new WaitingTestThread<>(gkoPool, "1", 100); final WaitingTestThread<Exception> t3 = new WaitingTestThread<>(gkoPool, "1", 100); t1.start(); t2.start(); t3.start(); // Try to get a "2" while all capacity is in use. // Thread will park waiting on empty queue. Verify it gets served. gkoPool.borrowObject("2"); } /** * Verify that factory exceptions creating objects do not corrupt per key create count. * * JIRA: POOL-243 * * @throws Exception May occur in some failure modes */ @Test public void testMakeObjectException() throws Exception { final SimpleFactory<String> factory = new SimpleFactory<>(); try (final GenericKeyedObjectPool<String, String, Exception> pool = new GenericKeyedObjectPool<>(factory)) { pool.setMaxTotalPerKey(1); pool.setBlockWhenExhausted(false); factory.exceptionOnCreate = true; assertThrows(Exception.class, () -> pool.borrowObject("One")); factory.exceptionOnCreate = false; pool.borrowObject("One"); } } /** * Test case for POOL-180. */ @Test @Timeout(value = 200000, unit = TimeUnit.MILLISECONDS) public void testMaxActivePerKeyExceeded() { final WaiterFactory<String> waiterFactory = new WaiterFactory<>(0, 20, 0, 0, 0, 0, 8, 5, 0); // TODO Fix this. Can't use local pool since runTestThreads uses the // protected pool field try (final GenericKeyedObjectPool<String, Waiter, RuntimeException> waiterPool = new GenericKeyedObjectPool<>(waiterFactory)) { waiterPool.setMaxTotalPerKey(5); waiterPool.setMaxTotal(8); waiterPool.setTestOnBorrow(true); waiterPool.setMaxIdlePerKey(5); waiterPool.setMaxWaitMillis(-1); runTestThreads(20, 300, 250, waiterPool); } } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMaxIdle() throws Exception { gkoPool.setMaxTotalPerKey(100); gkoPool.setMaxIdlePerKey(8); final String[] active = new String[100]; for(int i=0;i<100;i++) { active[i] = gkoPool.borrowObject(""); } assertEquals(100,gkoPool.getNumActive("")); assertEquals(0,gkoPool.getNumIdle("")); for(int i=0;i<100;i++) { gkoPool.returnObject("",active[i]); assertEquals(99 - i,gkoPool.getNumActive("")); assertEquals((i < 8 ? i+1 : 8),gkoPool.getNumIdle("")); } for(int i=0;i<100;i++) { active[i] = gkoPool.borrowObject("a"); } assertEquals(100,gkoPool.getNumActive("a")); assertEquals(0,gkoPool.getNumIdle("a")); for(int i=0;i<100;i++) { gkoPool.returnObject("a",active[i]); assertEquals(99 - i,gkoPool.getNumActive("a")); assertEquals((i < 8 ? i+1 : 8),gkoPool.getNumIdle("a")); } // total number of idle instances is twice maxIdle assertEquals(16, gkoPool.getNumIdle()); // Each pool is at the sup assertEquals(8, gkoPool.getNumIdle("")); assertEquals(8, gkoPool.getNumIdle("a")); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMaxTotal() throws Exception { gkoPool.setMaxTotalPerKey(2); gkoPool.setMaxTotal(3); gkoPool.setBlockWhenExhausted(false); final String o1 = gkoPool.borrowObject("a"); assertNotNull(o1); final String o2 = gkoPool.borrowObject("a"); assertNotNull(o2); final String o3 = gkoPool.borrowObject("b"); assertNotNull(o3); assertThrows(NoSuchElementException.class, () -> gkoPool.borrowObject("c")); assertEquals(0, gkoPool.getNumIdle()); gkoPool.returnObject("b", o3); assertEquals(1, gkoPool.getNumIdle()); assertEquals(1, gkoPool.getNumIdle("b")); final Object o4 = gkoPool.borrowObject("b"); assertNotNull(o4); assertEquals(0, gkoPool.getNumIdle()); assertEquals(0, gkoPool.getNumIdle("b")); gkoPool.setMaxTotal(4); final Object o5 = gkoPool.borrowObject("b"); assertNotNull(o5); assertEquals(2, gkoPool.getNumActive("a")); assertEquals(2, gkoPool.getNumActive("b")); assertEquals(gkoPool.getMaxTotal(), gkoPool.getNumActive("b") + gkoPool.getNumActive("b")); assertEquals(gkoPool.getNumActive(), gkoPool.getMaxTotal()); } /** * Verifies that maxTotal is not exceeded when factory destroyObject * has high latency, testOnReturn is set and there is high incidence of * validation failures. */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMaxTotalInvariant() { final int maxTotal = 15; simpleFactory.setEvenValid(false); // Every other validation fails simpleFactory.setDestroyLatency(100); // Destroy takes 100 ms simpleFactory.setMaxTotalPerKey(maxTotal); // (makes - destroys) bound simpleFactory.setValidationEnabled(true); gkoPool.setMaxTotal(maxTotal); gkoPool.setMaxIdlePerKey(-1); gkoPool.setTestOnReturn(true); gkoPool.setMaxWaitMillis(10000L); runTestThreads(5, 10, 50, gkoPool); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMaxTotalLRU() throws Exception { gkoPool.setMaxTotalPerKey(2); gkoPool.setMaxTotal(3); final String o1 = gkoPool.borrowObject("a"); assertNotNull(o1); gkoPool.returnObject("a", o1); Thread.sleep(25); final String o2 = gkoPool.borrowObject("b"); assertNotNull(o2); gkoPool.returnObject("b", o2); Thread.sleep(25); final String o3 = gkoPool.borrowObject("c"); assertNotNull(o3); gkoPool.returnObject("c", o3); Thread.sleep(25); final String o4 = gkoPool.borrowObject("a"); assertNotNull(o4); gkoPool.returnObject("a", o4); Thread.sleep(25); assertSame(o1, o4); // this should cause b to be bumped out of the pool final String o5 = gkoPool.borrowObject("d"); assertNotNull(o5); gkoPool.returnObject("d", o5); Thread.sleep(25); // now re-request b, we should get a different object because it should // have been expelled from pool (was oldest because a was requested after b) final String o6 = gkoPool.borrowObject("b"); assertNotNull(o6); gkoPool.returnObject("b", o6); assertNotSame(o1, o6); assertNotSame(o2, o6); // second a is still in there final String o7 = gkoPool.borrowObject("a"); assertNotNull(o7); gkoPool.returnObject("a", o7); assertSame(o4, o7); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMaxTotalPerKey() throws Exception { gkoPool.setMaxTotalPerKey(3); gkoPool.setBlockWhenExhausted(false); gkoPool.borrowObject(""); gkoPool.borrowObject(""); gkoPool.borrowObject(""); assertThrows(NoSuchElementException.class, () -> gkoPool.borrowObject("")); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMaxTotalPerKeyZero() { gkoPool.setMaxTotalPerKey(0); gkoPool.setBlockWhenExhausted(false); assertThrows(NoSuchElementException.class, () -> gkoPool.borrowObject("a")); } /** * Verifies that if a borrow of a new key is blocked because maxTotal has * been reached, that borrow continues once another object is returned. * * JIRA: POOL-310 */ @Test public void testMaxTotalWithThreads() throws Exception { gkoPool.setMaxTotalPerKey(2); gkoPool.setMaxTotal(1); final int holdTime = 2000; final TestThread<String, Exception> testA = new TestThread<>(gkoPool, 1, 0, holdTime, false, null, "a"); final TestThread<String, Exception> testB = new TestThread<>(gkoPool, 1, 0, holdTime, false, null, "b"); final Thread threadA = new Thread(testA); final Thread threadB = new Thread(testB); threadA.start(); threadB.start(); Thread.sleep(holdTime * 2); // Both threads should be complete now. boolean threadRunning = true; int count = 0; while (threadRunning && count < 15) { threadRunning = threadA.isAlive(); threadRunning = threadB.isAlive(); Thread.sleep(200); count++; } assertFalse(threadA.isAlive()); assertFalse(threadB.isAlive()); assertFalse(testA.failed); assertFalse(testB.failed); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMaxTotalZero() { gkoPool.setMaxTotal(0); gkoPool.setBlockWhenExhausted(false); assertThrows(NoSuchElementException.class, () -> gkoPool.borrowObject("a")); } /* * Test multi-threaded pool access. * Multiple keys, multiple threads, but maxActive only allows half the threads to succeed. * * This test was prompted by Continuum build failures in the Commons DBCP test case: * TestSharedPoolDataSource.testMultipleThreads2() * Let's see if the this fails on Continuum too! */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMaxWaitMultiThreaded() throws Exception { final long maxWait = 500; // wait for connection final long holdTime = 4 * maxWait; // how long to hold connection final int keyCount = 4; // number of different keys final int threadsPerKey = 5; // number of threads to grab the key initially gkoPool.setBlockWhenExhausted(true); gkoPool.setMaxWaitMillis(maxWait); gkoPool.setMaxTotalPerKey(threadsPerKey); // Create enough threads so half the threads will have to wait final WaitingTestThread<Exception>[] wtt = new WaitingTestThread[keyCount * threadsPerKey * 2]; for (int i = 0; i < wtt.length; i++) { wtt[i] = new WaitingTestThread(gkoPool, Integer.toString(i % keyCount), holdTime); } final long originMillis = System.currentTimeMillis() - 1000; for (final WaitingTestThread<Exception> element : wtt) { element.start(); } int failed = 0; for (final WaitingTestThread<Exception> element : wtt) { element.join(); if (element.thrown != null){ failed++; } } if (DISPLAY_THREAD_DETAILS || wtt.length/2 != failed){ System.out.println( "MaxWait: " + maxWait + " HoldTime: " + holdTime + " KeyCount: " + keyCount + " MaxActive: " + threadsPerKey + " Threads: " + wtt.length + " Failed: " + failed ); for (final WaitingTestThread<Exception> wt : wtt) { System.out.println( "Preborrow: " + (wt.preBorrowMillis - originMillis) + " Postborrow: " + (wt.postBorrowMillis != 0 ? wt.postBorrowMillis - originMillis : -1) + " BorrowTime: " + (wt.postBorrowMillis != 0 ? wt.postBorrowMillis - wt.preBorrowMillis : -1) + " PostReturn: " + (wt.postReturnMillis != 0 ? wt.postReturnMillis - originMillis : -1) + " Ended: " + (wt.endedMillis - originMillis) + " Key: " + (wt.key) + " ObjId: " + wt.objectId ); } } assertEquals(wtt.length/2,failed,"Expected half the threads to fail"); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMinIdle() throws Exception { gkoPool.setMaxIdlePerKey(500); gkoPool.setMinIdlePerKey(5); gkoPool.setMaxTotalPerKey(10); gkoPool.setNumTestsPerEvictionRun(0); gkoPool.setMinEvictableIdleTime(Duration.ofMillis(50)); gkoPool.setTimeBetweenEvictionRuns(Duration.ofMillis(100)); gkoPool.setTestWhileIdle(true); // Generate a random key final String key = "A"; gkoPool.preparePool(key); Waiter.sleepQuietly(150L); assertEquals(5, gkoPool.getNumIdle(), "Should be 5 idle, found " + gkoPool.getNumIdle()); final String[] active = new String[5]; active[0] = gkoPool.borrowObject(key); Waiter.sleepQuietly(150L); assertEquals(5, gkoPool.getNumIdle(), "Should be 5 idle, found " + gkoPool.getNumIdle()); for (int i = 1; i < 5; i++) { active[i] = gkoPool.borrowObject(key); } Waiter.sleepQuietly(150L); assertEquals(5, gkoPool.getNumIdle(), "Should be 5 idle, found " + gkoPool.getNumIdle()); for (int i = 0; i < 5; i++) { gkoPool.returnObject(key, active[i]); } Waiter.sleepQuietly(150L); assertEquals(10, gkoPool.getNumIdle(), "Should be 10 idle, found " + gkoPool.getNumIdle()); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMinIdleMaxTotalPerKey() throws Exception { gkoPool.setMaxIdlePerKey(500); gkoPool.setMinIdlePerKey(5); gkoPool.setMaxTotalPerKey(10); gkoPool.setNumTestsPerEvictionRun(0); gkoPool.setMinEvictableIdleTime(Duration.ofMillis(50)); gkoPool.setTimeBetweenEvictionRuns(Duration.ofMillis(100)); gkoPool.setTestWhileIdle(true); final String key = "A"; gkoPool.preparePool(key); assertEquals(5, gkoPool.getNumIdle(), "Should be 5 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(150L); assertEquals(5, gkoPool.getNumIdle(), "Should be 5 idle, found " + gkoPool.getNumIdle()); final String[] active = new String[10]; Waiter.sleepQuietly(150L); assertEquals(5, gkoPool.getNumIdle(), "Should be 5 idle, found " + gkoPool.getNumIdle()); for(int i=0 ; i<5 ; i++) { active[i] = gkoPool.borrowObject(key); } Waiter.sleepQuietly(150L); assertEquals(5, gkoPool.getNumIdle(), "Should be 5 idle, found " + gkoPool.getNumIdle()); for(int i=0 ; i<5 ; i++) { gkoPool.returnObject(key, active[i]); } Waiter.sleepQuietly(150L); assertEquals(10, gkoPool.getNumIdle(), "Should be 10 idle, found " + gkoPool.getNumIdle()); for(int i=0 ; i<10 ; i++) { active[i] = gkoPool.borrowObject(key); } Waiter.sleepQuietly(150L); assertEquals(0, gkoPool.getNumIdle(), "Should be 0 idle, found " + gkoPool.getNumIdle()); for(int i=0 ; i<10 ; i++) { gkoPool.returnObject(key, active[i]); } Waiter.sleepQuietly(150L); assertEquals(10, gkoPool.getNumIdle(), "Should be 10 idle, found " + gkoPool.getNumIdle()); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMinIdleNoPreparePool() throws Exception { gkoPool.setMaxIdlePerKey(500); gkoPool.setMinIdlePerKey(5); gkoPool.setMaxTotalPerKey(10); gkoPool.setNumTestsPerEvictionRun(0); gkoPool.setMinEvictableIdleTime(Duration.ofMillis(50)); gkoPool.setTimeBetweenEvictionRuns(Duration.ofMillis(100)); gkoPool.setTestWhileIdle(true); //Generate a random key final String key = "A"; Waiter.sleepQuietly(150L); assertEquals(0, gkoPool.getNumIdle(), "Should be 0 idle, found " + gkoPool.getNumIdle()); final Object active = gkoPool.borrowObject(key); assertNotNull(active); Waiter.sleepQuietly(150L); assertEquals(5, gkoPool.getNumIdle(), "Should be 5 idle, found " + gkoPool.getNumIdle()); } /** * Verifies that returning an object twice (without borrow in between) causes ISE * but does not re-validate or re-passivate the instance. * * JIRA: POOL-285 */ @Test public void testMultipleReturn() throws Exception { final WaiterFactory<String> factory = new WaiterFactory<>(0, 0, 0, 0, 0, 0); try (final GenericKeyedObjectPool<String, Waiter, RuntimeException> pool = new GenericKeyedObjectPool<>(factory)) { pool.setTestOnReturn(true); final Waiter waiter = pool.borrowObject("a"); pool.returnObject("a", waiter); assertEquals(1, waiter.getValidationCount()); assertEquals(1, waiter.getPassivationCount()); try { pool.returnObject("a", waiter); fail("Expecting IllegalStateException from multiple return"); } catch (final IllegalStateException ex) { // Exception is expected, now check no repeat validation/passivation assertEquals(1, waiter.getValidationCount()); assertEquals(1, waiter.getPassivationCount()); } } } /** * Verifies that when a borrowed object is mutated in a way that does not * preserve equality and hashcode, the pool can recognized it on return. * * JIRA: POOL-284 */ @Test public void testMutable() throws Exception { final HashSetFactory factory = new HashSetFactory(); try (final GenericKeyedObjectPool<String, HashSet<String>, RuntimeException> pool = new GenericKeyedObjectPool<>(factory, new GenericKeyedObjectPoolConfig<>())) { final HashSet<String> s1 = pool.borrowObject("a"); final HashSet<String> s2 = pool.borrowObject("a"); s1.add("One"); s2.add("One"); pool.returnObject("a", s1); pool.returnObject("a", s2); } } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testNegativeMaxTotalPerKey() throws Exception { gkoPool.setMaxTotalPerKey(-1); gkoPool.setBlockWhenExhausted(false); final String obj = gkoPool.borrowObject(""); assertEquals("0",obj); gkoPool.returnObject("",obj); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testNumActiveNumIdle2() throws Exception { assertEquals(0,gkoPool.getNumActive()); assertEquals(0,gkoPool.getNumIdle()); assertEquals(0,gkoPool.getNumActive("A")); assertEquals(0,gkoPool.getNumIdle("A")); assertEquals(0,gkoPool.getNumActive("B")); assertEquals(0,gkoPool.getNumIdle("B")); final String objA0 = gkoPool.borrowObject("A"); final String objB0 = gkoPool.borrowObject("B"); assertEquals(2,gkoPool.getNumActive()); assertEquals(0,gkoPool.getNumIdle()); assertEquals(1,gkoPool.getNumActive("A")); assertEquals(0,gkoPool.getNumIdle("A")); assertEquals(1,gkoPool.getNumActive("B")); assertEquals(0,gkoPool.getNumIdle("B")); final String objA1 = gkoPool.borrowObject("A"); final String objB1 = gkoPool.borrowObject("B"); assertEquals(4,gkoPool.getNumActive()); assertEquals(0,gkoPool.getNumIdle()); assertEquals(2,gkoPool.getNumActive("A")); assertEquals(0,gkoPool.getNumIdle("A")); assertEquals(2,gkoPool.getNumActive("B")); assertEquals(0,gkoPool.getNumIdle("B")); gkoPool.returnObject("A",objA0); gkoPool.returnObject("B",objB0); assertEquals(2,gkoPool.getNumActive()); assertEquals(2,gkoPool.getNumIdle()); assertEquals(1,gkoPool.getNumActive("A")); assertEquals(1,gkoPool.getNumIdle("A")); assertEquals(1,gkoPool.getNumActive("B")); assertEquals(1,gkoPool.getNumIdle("B")); gkoPool.returnObject("A",objA1); gkoPool.returnObject("B",objB1); assertEquals(0,gkoPool.getNumActive()); assertEquals(4,gkoPool.getNumIdle()); assertEquals(0,gkoPool.getNumActive("A")); assertEquals(2,gkoPool.getNumIdle("A")); assertEquals(0,gkoPool.getNumActive("B")); assertEquals(2,gkoPool.getNumIdle("B")); } @Test public void testReturnObjectThrowsIllegalStateException() { try (final GenericKeyedObjectPool<String, String, Exception> pool = new GenericKeyedObjectPool<>(new SimpleFactory<>())) { assertThrows(IllegalStateException.class, () -> pool.returnObject("Foo", "Bar")); } } @Test public void testReturnObjectWithBlockWhenExhausted() throws Exception { gkoPool.setBlockWhenExhausted(true); gkoPool.setMaxTotal(1); // Test return object with no take waiters String obj = gkoPool.borrowObject("0"); gkoPool.returnObject("0", obj); // Test return object with a take waiter final TestThread<String, Exception> testA = new TestThread<>(gkoPool, 1, 0, 500, false, null, "0"); final TestThread<String, Exception> testB = new TestThread<>(gkoPool, 1, 0, 0, false, null, "1"); final Thread threadA = new Thread(testA); final Thread threadB = new Thread(testB); threadA.start(); threadB.start(); threadA.join(); threadB.join(); } @Test public void testReturnObjectWithoutBlockWhenExhausted() throws Exception { gkoPool.setBlockWhenExhausted(false); // Test return object with no take waiters String obj = gkoPool.borrowObject("0"); gkoPool.returnObject("0", obj); } /** * JIRA: POOL-287 * * Verify that when an attempt is made to borrow an instance from the pool * while the evictor is visiting it, there is no capacity leak. * * Test creates the scenario described in POOL-287. */ @Test public void testReturnToHead() throws Exception { final SimpleFactory<String> factory = new SimpleFactory<>(); factory.setValidateLatency(100); factory.setValid(true); // Validation always succeeds try (final GenericKeyedObjectPool<String, String, Exception> pool = new GenericKeyedObjectPool<>(factory)) { pool.setMaxWaitMillis(1000); pool.setTestWhileIdle(true); pool.setMaxTotalPerKey(2); pool.setNumTestsPerEvictionRun(1); pool.setTimeBetweenEvictionRuns(Duration.ofMillis(500)); // Load pool with two objects pool.addObject("one"); // call this o1 pool.addObject("one"); // call this o2 // Default is LIFO, so "one" pool is now [o2, o1] in offer order. // Evictor will visit in oldest-to-youngest order, so o1 then o2 Thread.sleep(800); // Wait for first eviction run to complete // At this point, one eviction run should have completed, visiting o1 // and eviction cursor should be pointed at o2, which is the next offered instance Thread.sleep(250); // Wait for evictor to start final String o1 = pool.borrowObject("one"); // o2 is under eviction, so this will return o1 final String o2 = pool.borrowObject("one"); // Once validation completes, o2 should be offered pool.returnObject("one", o1); pool.returnObject("one", o2); } } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testSettersAndGetters() { { gkoPool.setMaxTotalPerKey(123); assertEquals(123, gkoPool.getMaxTotalPerKey()); } { gkoPool.setMaxIdlePerKey(12); assertEquals(12, gkoPool.getMaxIdlePerKey()); } { gkoPool.setMaxWaitMillis(1234L); assertEquals(1234L, gkoPool.getMaxWaitMillis()); } { gkoPool.setMinEvictableIdleTimeMillis(12345L); assertEquals(12345L, gkoPool.getMinEvictableIdleTimeMillis()); } { gkoPool.setMinEvictableIdleTime(Duration.ofMillis(12345L)); assertEquals(12345L, gkoPool.getMinEvictableIdleTime().toMillis()); } { gkoPool.setMinEvictableIdleTime(Duration.ofMillis(12345L)); assertEquals(12345L, gkoPool.getMinEvictableIdleDuration().toMillis()); } { gkoPool.setNumTestsPerEvictionRun(11); assertEquals(11, gkoPool.getNumTestsPerEvictionRun()); } { gkoPool.setTestOnBorrow(true); assertTrue(gkoPool.getTestOnBorrow()); gkoPool.setTestOnBorrow(false); assertFalse(gkoPool.getTestOnBorrow()); } { gkoPool.setTestOnReturn(true); assertTrue(gkoPool.getTestOnReturn()); gkoPool.setTestOnReturn(false); assertFalse(gkoPool.getTestOnReturn()); } { gkoPool.setTestWhileIdle(true); assertTrue(gkoPool.getTestWhileIdle()); gkoPool.setTestWhileIdle(false); assertFalse(gkoPool.getTestWhileIdle()); } { gkoPool.setTimeBetweenEvictionRunsMillis(11235L); assertEquals(11235L, gkoPool.getDurationBetweenEvictionRuns().toMillis()); assertEquals(11235L, gkoPool.getTimeBetweenEvictionRuns().toMillis()); assertEquals(11235L, gkoPool.getTimeBetweenEvictionRunsMillis()); } { gkoPool.setTimeBetweenEvictionRuns(Duration.ofMillis(11235L)); assertEquals(11235L, gkoPool.getDurationBetweenEvictionRuns().toMillis()); assertEquals(11235L, gkoPool.getTimeBetweenEvictionRuns().toMillis()); assertEquals(11235L, gkoPool.getTimeBetweenEvictionRunsMillis()); } { gkoPool.setBlockWhenExhausted(true); assertTrue(gkoPool.getBlockWhenExhausted()); gkoPool.setBlockWhenExhausted(false); assertFalse(gkoPool.getBlockWhenExhausted()); } } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testThreaded1() { gkoPool.setMaxTotalPerKey(15); gkoPool.setMaxIdlePerKey(15); gkoPool.setMaxWaitMillis(1000L); runTestThreads(20, 100, 50, gkoPool); } // Pool-361 @Test public void testValidateOnCreate() throws Exception { gkoPool.setTestOnCreate(true); simpleFactory.setValidationEnabled(true); gkoPool.addObject("one"); assertEquals(1, simpleFactory.validateCounter); } @Test public void testValidateOnCreateFailure() throws Exception { gkoPool.setTestOnCreate(true); gkoPool.setTestOnBorrow(false); gkoPool.setMaxTotal(2); simpleFactory.setValidationEnabled(true); simpleFactory.setValid(false); // Make sure failed validations do not leak capacity gkoPool.addObject("one"); gkoPool.addObject("one"); assertEquals(0, gkoPool.getNumIdle()); assertEquals(0, gkoPool.getNumActive()); simpleFactory.setValid(true); final String obj = gkoPool.borrowObject("one"); assertNotNull(obj); gkoPool.addObject("one"); // Should have one idle, one out now assertEquals(1, gkoPool.getNumIdle()); assertEquals(1, gkoPool.getNumActive()); } /** * Verify that threads waiting on a depleted pool get served when a returning object fails * validation. * * JIRA: POOL-240 * * @throws Exception May occur in some failure modes */ @Test public void testValidationFailureOnReturnFreesCapacity() throws Exception { final SimpleFactory<String> factory = new SimpleFactory<>(); factory.setValid(false); // Validate will always fail factory.setValidationEnabled(true); try (final GenericKeyedObjectPool<String, String, Exception> pool = new GenericKeyedObjectPool<>(factory)) { pool.setMaxTotalPerKey(2); pool.setMaxWaitMillis(1500); pool.setTestOnReturn(true); pool.setTestOnBorrow(false); // Borrow an instance and hold if for 5 seconds final WaitingTestThread<Exception> thread1 = new WaitingTestThread<>(pool, "one", 5000); thread1.start(); // Borrow another instance and return it after 500 ms (validation will fail) final WaitingTestThread<Exception> thread2 = new WaitingTestThread<>(pool, "one", 500); thread2.start(); Thread.sleep(50); // Try to borrow an object final String obj = pool.borrowObject("one"); pool.returnObject("one", obj); } } // POOL-276 @Test public void testValidationOnCreateOnly() throws Exception { simpleFactory.enableValidation = true; gkoPool.setMaxTotal(1); gkoPool.setTestOnCreate(true); gkoPool.setTestOnBorrow(false); gkoPool.setTestOnReturn(false); gkoPool.setTestWhileIdle(false); final String o1 = gkoPool.borrowObject("KEY"); assertEquals("KEY0", o1); final Timer t = new Timer(); t.schedule( new TimerTask() { @Override public void run() { gkoPool.returnObject("KEY", o1); } }, 3000); final String o2 = gkoPool.borrowObject("KEY"); assertEquals("KEY0", o2); assertEquals(1, simpleFactory.validateCounter); } /** * POOL-189 * * @throws Exception May occur in some failure modes */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testWhenExhaustedBlockClosePool() throws Exception { gkoPool.setMaxTotalPerKey(1); gkoPool.setBlockWhenExhausted(true); gkoPool.setMaxWaitMillis(-1); final String obj1 = gkoPool.borrowObject("a"); // Make sure an object was obtained assertNotNull(obj1); // Create a separate thread to try and borrow another object final WaitingTestThread<Exception> wtt = new WaitingTestThread<>(gkoPool, "a", 200); wtt.start(); // Give wtt time to start Thread.sleep(200); // close the pool (Bug POOL-189) gkoPool.close(); // Give interrupt time to take effect Thread.sleep(200); // Check thread was interrupted assertTrue(wtt.thrown instanceof InterruptedException); } }
src/test/java/org/apache/commons/pool2/impl/TestGenericKeyedObjectPool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool2.impl; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.management.ManagementFactory; import java.time.Duration; import java.util.ArrayList; import java.util.HashSet; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Random; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.management.MBeanServer; import javax.management.ObjectName; import org.apache.commons.pool2.BaseKeyedPooledObjectFactory; import org.apache.commons.pool2.DestroyMode; import org.apache.commons.pool2.KeyedObjectPool; import org.apache.commons.pool2.KeyedPooledObjectFactory; import org.apache.commons.pool2.PooledObject; import org.apache.commons.pool2.TestKeyedObjectPool; import org.apache.commons.pool2.VisitTracker; import org.apache.commons.pool2.VisitTrackerFactory; import org.apache.commons.pool2.Waiter; import org.apache.commons.pool2.WaiterFactory; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; /** */ public class TestGenericKeyedObjectPool extends TestKeyedObjectPool { private static class DaemonThreadFactory implements ThreadFactory { @Override public Thread newThread(final Runnable r) { final Thread t = new Thread(r); t.setDaemon(true); return t; } } private static class DummyFactory extends BaseKeyedPooledObjectFactory<Object, Object, RuntimeException> { @Override public Object create(final Object key) { return null; } @Override public PooledObject<Object> wrap(final Object value) { return new DefaultPooledObject<>(value); } } /** * Factory that creates HashSets. Note that this means * 0) All instances are initially equal (not discernible by equals) * 1) Instances are mutable and mutation can cause change in identity / hashcode. */ private static final class HashSetFactory extends BaseKeyedPooledObjectFactory<String, HashSet<String>, RuntimeException> { @Override public HashSet<String> create(final String key) { return new HashSet<>(); } @Override public PooledObject<HashSet<String>> wrap(final HashSet<String> value) { return new DefaultPooledObject<>(value); } } /** * Attempts to invalidate an object, swallowing IllegalStateException. */ static class InvalidateThread implements Runnable { private final String obj; private final KeyedObjectPool<String, String, Exception> pool; private final String key; private boolean done; public InvalidateThread(final KeyedObjectPool<String, String, Exception> pool, final String key, final String obj) { this.obj = obj; this.pool = pool; this.key = key; } public boolean complete() { return done; } @Override public void run() { try { pool.invalidateObject(key, obj); } catch (final IllegalStateException ex) { // Ignore } catch (final Exception ex) { fail("Unexpected exception " + ex.toString()); } finally { done = true; } } } private static class ObjectFactory extends BaseKeyedPooledObjectFactory<Integer, Object, RuntimeException> { @Override public Object create(final Integer key) { return new Object(); } @Override public PooledObject<Object> wrap(final Object value) { return new DefaultPooledObject<>(value); } } public static class SimpleFactory<K> implements KeyedPooledObjectFactory<K, String, Exception> { volatile int counter; final boolean valid; int activeCount; int validateCounter; boolean evenValid = true; boolean oddValid = true; boolean enableValidation; long destroyLatency; long makeLatency; long validateLatency; volatile int maxTotalPerKey = Integer.MAX_VALUE; boolean exceptionOnPassivate; boolean exceptionOnActivate; boolean exceptionOnDestroy; boolean exceptionOnValidate; boolean exceptionOnCreate; public SimpleFactory() { this(true); } public SimpleFactory(final boolean valid) { this.valid = valid; } @Override public void activateObject(final K key, final PooledObject<String> obj) throws Exception { if (exceptionOnActivate && !(validateCounter++ % 2 == 0 ? evenValid : oddValid)) { throw new Exception(); } } @Override public void destroyObject(final K key, final PooledObject<String> obj) throws Exception { doWait(destroyLatency); synchronized(this) { activeCount--; } if (exceptionOnDestroy) { throw new Exception(); } } private void doWait(final long latency) { Waiter.sleepQuietly(latency); } @Override public PooledObject<String> makeObject(final K key) throws Exception { if (exceptionOnCreate) { throw new Exception(); } doWait(makeLatency); String out = null; synchronized(this) { activeCount++; if (activeCount > maxTotalPerKey) { throw new IllegalStateException( "Too many active instances: " + activeCount); } out = String.valueOf(key) + String.valueOf(counter++); } return new DefaultPooledObject<>(out); } @Override public void passivateObject(final K key, final PooledObject<String> obj) throws Exception { if (exceptionOnPassivate) { throw new Exception(); } } public void setDestroyLatency(final long destroyLatency) { this.destroyLatency = destroyLatency; } void setEvenValid(final boolean valid) { evenValid = valid; } public void setMakeLatency(final long makeLatency) { this.makeLatency = makeLatency; } public void setMaxTotalPerKey(final int maxTotalPerKey) { this.maxTotalPerKey = maxTotalPerKey; } public void setThrowExceptionOnActivate(final boolean b) { exceptionOnActivate = b; } public void setThrowExceptionOnDestroy(final boolean b) { exceptionOnDestroy = b; } public void setThrowExceptionOnPassivate(final boolean b) { exceptionOnPassivate = b; } public void setThrowExceptionOnValidate(final boolean b) { exceptionOnValidate = b; } void setValid(final boolean valid) { evenValid = valid; oddValid = valid; } public void setValidateLatency(final long validateLatency) { this.validateLatency = validateLatency; } public void setValidationEnabled(final boolean b) { enableValidation = b; } @Override public boolean validateObject(final K key, final PooledObject<String> obj) { doWait(validateLatency); if (exceptionOnValidate) { throw new RuntimeException("validation failed"); } if (enableValidation) { return validateCounter++ % 2 == 0 ? evenValid : oddValid; } return valid; } } private static class SimplePerKeyFactory extends BaseKeyedPooledObjectFactory<Object, Object, RuntimeException> { final ConcurrentHashMap<Object, AtomicInteger> map = new ConcurrentHashMap<>(); @Override public Object create(final Object key) { int counter = 0; final AtomicInteger Counter = map.get(key); if(null != Counter) { counter = Counter.incrementAndGet(); } else { map.put(key, new AtomicInteger(0)); counter = 0; } return String.valueOf(key) + String.valueOf(counter); } @Override public PooledObject<Object> wrap(final Object value) { return new DefaultPooledObject<>(value); } } /* * Very simple test thread that just tries to borrow an object from * the provided pool with the specified key and returns it */ static class SimpleTestThread<T, E extends Exception> implements Runnable { private final KeyedObjectPool<String, T, E> pool; private final String key; public SimpleTestThread(final KeyedObjectPool<String, T, E> pool, final String key) { this.pool = pool; this.key = key; } @Override public void run() { try { pool.returnObject(key, pool.borrowObject(key)); } catch (final Exception e) { // Ignore } } } /* * DefaultEvictionPolicy modified to add latency */ private static class SlowEvictionPolicy<T> extends DefaultEvictionPolicy<T> { private final long delay; /** * Constructs SlowEvictionPolicy with the given delay in ms * * @param delay number of ms of latency to inject in evict */ public SlowEvictionPolicy(final long delay) { this.delay = delay; } @Override public boolean evict(final EvictionConfig config, final PooledObject<T> underTest, final int idleCount) { Waiter.sleepQuietly(delay); return super.evict(config, underTest, idleCount); } } static class TestThread<T, E extends Exception> implements Runnable { private final java.util.Random random = new java.util.Random(); /** GKOP to hit */ private final KeyedObjectPool<String, T, E> pool; /** number of borrow/return iterations */ private final int iter; /** delay before borrow */ private final int startDelay; /** delay before return */ private final int holdTime; /** whether or not delays are random (with max = configured values) */ private final boolean randomDelay; /** expected object */ private final T expectedObject; /** key used in borrow / return sequence - null means random */ private final String key; private volatile boolean complete; private volatile boolean failed; private volatile Exception exception; public TestThread(final KeyedObjectPool<String, T, E> pool) { this(pool, 100, 50, 50, true, null, null); } public TestThread(final KeyedObjectPool<String, T, E> pool, final int iter) { this(pool, iter, 50, 50, true, null, null); } public TestThread(final KeyedObjectPool<String, T, E> pool, final int iter, final int delay) { this(pool, iter, delay, delay, true, null, null); } public TestThread(final KeyedObjectPool<String, T, E> pool, final int iter, final int startDelay, final int holdTime, final boolean randomDelay, final T expectedObject, final String key) { this.pool = pool; this.iter = iter; this.startDelay = startDelay; this.holdTime = holdTime; this.randomDelay = randomDelay; this.expectedObject = expectedObject; this.key = key; } public boolean complete() { return complete; } public boolean failed() { return failed; } @Override public void run() { for (int i = 0; i < iter; i++) { final String actualKey = key == null ? String.valueOf(random.nextInt(3)) : key; Waiter.sleepQuietly(randomDelay ? random.nextInt(startDelay) : startDelay); T obj = null; try { obj = pool.borrowObject(actualKey); } catch (final Exception e) { exception = e; failed = true; complete = true; break; } if (expectedObject != null && !expectedObject.equals(obj)) { exception = new Exception("Expected: " + expectedObject + " found: " + obj); failed = true; complete = true; break; } Waiter.sleepQuietly(randomDelay ? random.nextInt(holdTime) : holdTime); try { pool.returnObject(actualKey, obj); } catch (final Exception e) { exception = e; failed = true; complete = true; break; } } complete = true; } } /* * Very simple test thread that just tries to borrow an object from * the provided pool with the specified key and returns it after a wait */ static class WaitingTestThread<E extends Exception> extends Thread { private final KeyedObjectPool<String, String, E> pool; private final String key; private final long pause; private Throwable thrown; private long preBorrowMillis; // just before borrow private long postBorrowMillis; // borrow returned private long postReturnMillis; // after object was returned private long endedMillis; private String objectId; public WaitingTestThread(final KeyedObjectPool<String, String, E> pool, final String key, final long pause) { this.pool = pool; this.key = key; this.pause = pause; this.thrown = null; } @Override public void run() { try { preBorrowMillis = System.currentTimeMillis(); final String obj = pool.borrowObject(key); objectId = obj; postBorrowMillis = System.currentTimeMillis(); Thread.sleep(pause); pool.returnObject(key, obj); postReturnMillis = System.currentTimeMillis(); } catch (final Exception e) { thrown = e; } finally{ endedMillis = System.currentTimeMillis(); } } } private static final Integer KEY_ZERO = Integer.valueOf(0); private static final Integer KEY_ONE = Integer.valueOf(1); private static final Integer KEY_TWO = Integer.valueOf(2); private static final boolean DISPLAY_THREAD_DETAILS= Boolean.parseBoolean(System.getProperty("TestGenericKeyedObjectPool.display.thread.details", "false")); // To pass this to a Maven test, use: // mvn test -DargLine="-DTestGenericKeyedObjectPool.display.thread.details=true" // @see https://issues.apache.org/jira/browse/SUREFIRE-121 /** setUp(): {@code new GenericKeyedObjectPool<String,String>(factory)} */ private GenericKeyedObjectPool<String, String, Exception> gkoPool; /** setUp(): {@code new SimpleFactory<String>()} */ private SimpleFactory<String> simpleFactory; private void checkEvictionOrder(final boolean lifo) throws Exception { final SimpleFactory<Integer> intFactory = new SimpleFactory<>(); try (final GenericKeyedObjectPool<Integer, String, Exception> intPool = new GenericKeyedObjectPool<>(intFactory)) { intPool.setNumTestsPerEvictionRun(2); intPool.setMinEvictableIdleTime(Duration.ofMillis(100)); intPool.setLifo(lifo); for (int i = 0; i < 3; i++) { final Integer key = Integer.valueOf(i); for (int j = 0; j < 5; j++) { intPool.addObject(key); } } // Make all evictable Thread.sleep(200); /* * Initial state (Key, Object) pairs in order of age: * * (0,0), (0,1), (0,2), (0,3), (0,4) (1,5), (1,6), (1,7), (1,8), (1,9) (2,10), (2,11), (2,12), (2,13), * (2,14) */ intPool.evict(); // Kill (0,0),(0,1) assertEquals(3, intPool.getNumIdle(KEY_ZERO)); final String objZeroA = intPool.borrowObject(KEY_ZERO); assertTrue(lifo ? objZeroA.equals("04") : objZeroA.equals("02")); assertEquals(2, intPool.getNumIdle(KEY_ZERO)); final String objZeroB = intPool.borrowObject(KEY_ZERO); assertEquals("03", objZeroB); assertEquals(1, intPool.getNumIdle(KEY_ZERO)); intPool.evict(); // Kill remaining 0 survivor and (1,5) assertEquals(0, intPool.getNumIdle(KEY_ZERO)); assertEquals(4, intPool.getNumIdle(KEY_ONE)); final String objOneA = intPool.borrowObject(KEY_ONE); assertTrue(lifo ? objOneA.equals("19") : objOneA.equals("16")); assertEquals(3, intPool.getNumIdle(KEY_ONE)); final String objOneB = intPool.borrowObject(KEY_ONE); assertTrue(lifo ? objOneB.equals("18") : objOneB.equals("17")); assertEquals(2, intPool.getNumIdle(KEY_ONE)); intPool.evict(); // Kill remaining 1 survivors assertEquals(0, intPool.getNumIdle(KEY_ONE)); intPool.evict(); // Kill (2,10), (2,11) assertEquals(3, intPool.getNumIdle(KEY_TWO)); final String objTwoA = intPool.borrowObject(KEY_TWO); assertTrue(lifo ? objTwoA.equals("214") : objTwoA.equals("212")); assertEquals(2, intPool.getNumIdle(KEY_TWO)); intPool.evict(); // All dead now assertEquals(0, intPool.getNumIdle(KEY_TWO)); intPool.evict(); // Should do nothing - make sure no exception // Currently 2 zero, 2 one and 1 two active. Return them intPool.returnObject(KEY_ZERO, objZeroA); intPool.returnObject(KEY_ZERO, objZeroB); intPool.returnObject(KEY_ONE, objOneA); intPool.returnObject(KEY_ONE, objOneB); intPool.returnObject(KEY_TWO, objTwoA); // Remove all idle objects intPool.clear(); // Reload intPool.setMinEvictableIdleTime(Duration.ofMillis(500)); intFactory.counter = 0; // Reset counter for (int i = 0; i < 3; i++) { final Integer key = Integer.valueOf(i); for (int j = 0; j < 5; j++) { intPool.addObject(key); } Thread.sleep(200); } // 0's are evictable, others not intPool.evict(); // Kill (0,0),(0,1) assertEquals(3, intPool.getNumIdle(KEY_ZERO)); intPool.evict(); // Kill (0,2),(0,3) assertEquals(1, intPool.getNumIdle(KEY_ZERO)); intPool.evict(); // Kill (0,4), leave (1,5) assertEquals(0, intPool.getNumIdle(KEY_ZERO)); assertEquals(5, intPool.getNumIdle(KEY_ONE)); assertEquals(5, intPool.getNumIdle(KEY_TWO)); intPool.evict(); // (1,6), (1,7) assertEquals(5, intPool.getNumIdle(KEY_ONE)); assertEquals(5, intPool.getNumIdle(KEY_TWO)); intPool.evict(); // (1,8), (1,9) assertEquals(5, intPool.getNumIdle(KEY_ONE)); assertEquals(5, intPool.getNumIdle(KEY_TWO)); intPool.evict(); // (2,10), (2,11) assertEquals(5, intPool.getNumIdle(KEY_ONE)); assertEquals(5, intPool.getNumIdle(KEY_TWO)); intPool.evict(); // (2,12), (2,13) assertEquals(5, intPool.getNumIdle(KEY_ONE)); assertEquals(5, intPool.getNumIdle(KEY_TWO)); intPool.evict(); // (2,14), (1,5) assertEquals(5, intPool.getNumIdle(KEY_ONE)); assertEquals(5, intPool.getNumIdle(KEY_TWO)); Thread.sleep(200); // Ones now timed out intPool.evict(); // kill (1,6), (1,7) - (1,5) missed assertEquals(3, intPool.getNumIdle(KEY_ONE)); assertEquals(5, intPool.getNumIdle(KEY_TWO)); final String obj = intPool.borrowObject(KEY_ONE); if (lifo) { assertEquals("19", obj); } else { assertEquals("15", obj); } } } private void checkEvictorVisiting(final boolean lifo) throws Exception { VisitTrackerFactory<Integer> trackerFactory = new VisitTrackerFactory<>(); try (GenericKeyedObjectPool<Integer, VisitTracker<Integer>, RuntimeException> intPool = new GenericKeyedObjectPool<>( trackerFactory)) { intPool.setNumTestsPerEvictionRun(2); intPool.setMinEvictableIdleTime(Duration.ofMillis(-1)); intPool.setTestWhileIdle(true); intPool.setLifo(lifo); intPool.setTestOnReturn(false); intPool.setTestOnBorrow(false); for (int i = 0; i < 3; i++) { trackerFactory.resetId(); final Integer key = Integer.valueOf(i); for (int j = 0; j < 8; j++) { intPool.addObject(key); } } intPool.evict(); // Visit oldest 2 - 00 and 01 VisitTracker<Integer> obj = intPool.borrowObject(KEY_ZERO); intPool.returnObject(KEY_ZERO, obj); obj = intPool.borrowObject(KEY_ZERO); intPool.returnObject(KEY_ZERO, obj); // borrow, return, borrow, return // FIFO will move 0 and 1 to end - 2,3,4,5,6,7,0,1 // LIFO, 7 out, then in, then out, then in - 7,6,5,4,3,2,1,0 intPool.evict(); // Should visit 02 and 03 in either case for (int i = 0; i < 8; i++) { final VisitTracker<Integer> tracker = intPool.borrowObject(KEY_ZERO); if (tracker.getId() >= 4) { assertEquals( 0, tracker.getValidateCount(),"Unexpected instance visited " + tracker.getId()); } else { assertEquals( 1, tracker.getValidateCount(),"Instance " + tracker.getId() + " visited wrong number of times."); } } // 0's are all out intPool.setNumTestsPerEvictionRun(3); intPool.evict(); // 10, 11, 12 intPool.evict(); // 13, 14, 15 obj = intPool.borrowObject(KEY_ONE); intPool.returnObject(KEY_ONE, obj); obj = intPool.borrowObject(KEY_ONE); intPool.returnObject(KEY_ONE, obj); obj = intPool.borrowObject(KEY_ONE); intPool.returnObject(KEY_ONE, obj); // borrow, return, borrow, return // FIFO 3,4,5,^,6,7,0,1,2 // LIFO 7,6,^,5,4,3,2,1,0 // In either case, pointer should be at 6 intPool.evict(); // LIFO - 16, 17, 20 // FIFO - 16, 17, 10 intPool.evict(); // LIFO - 21, 22, 23 // FIFO - 11, 12, 20 intPool.evict(); // LIFO - 24, 25, 26 // FIFO - 21, 22, 23 intPool.evict(); // LIFO - 27, 10, 11 // FIFO - 24, 25, 26 for (int i = 0; i < 8; i++) { final VisitTracker<Integer> tracker = intPool.borrowObject(KEY_ONE); if ((lifo && tracker.getId() > 1) || (!lifo && tracker.getId() > 2)) { assertEquals( 1, tracker.getValidateCount(),"Instance " + tracker.getId() + " visited wrong number of times."); } else { assertEquals( 2, tracker.getValidateCount(),"Instance " + tracker.getId() + " visited wrong number of times."); } } } // Randomly generate some pools with random numTests // and make sure evictor cycles through elements appropriately final int[] smallPrimes = { 2, 3, 5, 7 }; final Random random = new Random(); random.setSeed(System.currentTimeMillis()); for (int i = 0; i < smallPrimes.length; i++) { for (int j = 0; j < 5; j++) {// Try the tests a few times // Can't use clear as some objects are still active so create // a new pool trackerFactory = new VisitTrackerFactory<>(); try (GenericKeyedObjectPool<Integer, VisitTracker<Integer>, RuntimeException> intPool = new GenericKeyedObjectPool<>( trackerFactory)) { intPool.setMaxIdlePerKey(-1); intPool.setMaxTotalPerKey(-1); intPool.setNumTestsPerEvictionRun(smallPrimes[i]); intPool.setMinEvictableIdleTime(Duration.ofMillis(-1)); intPool.setTestWhileIdle(true); intPool.setLifo(lifo); intPool.setTestOnReturn(false); intPool.setTestOnBorrow(false); final int zeroLength = 10 + random.nextInt(20); for (int k = 0; k < zeroLength; k++) { intPool.addObject(KEY_ZERO); } final int oneLength = 10 + random.nextInt(20); for (int k = 0; k < oneLength; k++) { intPool.addObject(KEY_ONE); } final int twoLength = 10 + random.nextInt(20); for (int k = 0; k < twoLength; k++) { intPool.addObject(KEY_TWO); } // Choose a random number of evictor runs final int runs = 10 + random.nextInt(50); for (int k = 0; k < runs; k++) { intPool.evict(); } // Total instances in pool final int totalInstances = zeroLength + oneLength + twoLength; // Number of times evictor should have cycled through pools final int cycleCount = (runs * intPool.getNumTestsPerEvictionRun()) / totalInstances; // Look at elements and make sure they are visited cycleCount // or cycleCount + 1 times VisitTracker<Integer> tracker = null; int visitCount = 0; for (int k = 0; k < zeroLength; k++) { tracker = intPool.borrowObject(KEY_ZERO); visitCount = tracker.getValidateCount(); if (visitCount < cycleCount || visitCount > cycleCount + 1) { fail(formatSettings("ZERO", "runs", runs, "lifo", lifo, "i", i, "j", j, "k", k, "visitCount", visitCount, "cycleCount", cycleCount, "totalInstances", totalInstances, zeroLength, oneLength, twoLength)); } } for (int k = 0; k < oneLength; k++) { tracker = intPool.borrowObject(KEY_ONE); visitCount = tracker.getValidateCount(); if (visitCount < cycleCount || visitCount > cycleCount + 1) { fail(formatSettings("ONE", "runs", runs, "lifo", lifo, "i", i, "j", j, "k", k, "visitCount", visitCount, "cycleCount", cycleCount, "totalInstances", totalInstances, zeroLength, oneLength, twoLength)); } } final int[] visits = new int[twoLength]; for (int k = 0; k < twoLength; k++) { tracker = intPool.borrowObject(KEY_TWO); visitCount = tracker.getValidateCount(); visits[k] = visitCount; if (visitCount < cycleCount || visitCount > cycleCount + 1) { final StringBuilder sb = new StringBuilder("Visits:"); for (int l = 0; l <= k; l++) { sb.append(visits[l]).append(' '); } fail(formatSettings("TWO " + sb.toString(), "runs", runs, "lifo", lifo, "i", i, "j", j, "k", k, "visitCount", visitCount, "cycleCount", cycleCount, "totalInstances", totalInstances, zeroLength, oneLength, twoLength)); } } } } } } private String formatSettings(final String title, final String s, final int i, final String s0, final boolean b0, final String s1, final int i1, final String s2, final int i2, final String s3, final int i3, final String s4, final int i4, final String s5, final int i5, final String s6, final int i6, final int zeroLength, final int oneLength, final int twoLength){ final StringBuilder sb = new StringBuilder(80); sb.append(title).append(' '); sb.append(s).append('=').append(i).append(' '); sb.append(s0).append('=').append(b0).append(' '); sb.append(s1).append('=').append(i1).append(' '); sb.append(s2).append('=').append(i2).append(' '); sb.append(s3).append('=').append(i3).append(' '); sb.append(s4).append('=').append(i4).append(' '); sb.append(s5).append('=').append(i5).append(' '); sb.append(s6).append('=').append(i6).append(' '); sb.append("Lengths=").append(zeroLength).append(',').append(oneLength).append(',').append(twoLength).append(' '); return sb.toString(); } private String getExceptionTrace(final Throwable t){ final StringWriter sw = new StringWriter(); t.printStackTrace(new PrintWriter(sw)); return sw.toString(); } @Override protected Object getNthObject(final Object key, final int n) { return String.valueOf(key) + String.valueOf(n); } @Override protected boolean isFifo() { return false; } @Override protected boolean isLifo() { return true; } @SuppressWarnings("unchecked") @Override protected <E extends Exception> KeyedObjectPool<Object, Object, E> makeEmptyPool(final int minCapacity) { final KeyedPooledObjectFactory<Object, Object, RuntimeException> perKeyFactory = new SimplePerKeyFactory(); final GenericKeyedObjectPool<Object, Object, RuntimeException> perKeyPool = new GenericKeyedObjectPool<>(perKeyFactory); perKeyPool.setMaxTotalPerKey(minCapacity); perKeyPool.setMaxIdlePerKey(minCapacity); return (KeyedObjectPool<Object, Object, E>) perKeyPool; } @Override protected <E extends Exception> KeyedObjectPool<Object, Object, E> makeEmptyPool(final KeyedPooledObjectFactory<Object, Object, E> fac) { return new GenericKeyedObjectPool<>(fac); } @Override protected Object makeKey(final int n) { return String.valueOf(n); } /** * Kicks off {@code numThreads} test threads, each of which will go * through {@code iterations} borrow-return cycles with random delay * times &lt;= delay in between. * * @param <T> Type of object in pool * @param numThreads Number of test threads * @param iterations Number of iterations for each thread * @param delay Maximum delay between iterations * @param gkopPool The keyed object pool to use */ public <T, E extends Exception> void runTestThreads(final int numThreads, final int iterations, final int delay, final GenericKeyedObjectPool<String, T, E> gkopPool) { final ArrayList<TestThread<T, E>> threads = new ArrayList<>(); for (int i = 0; i < numThreads; i++) { final TestThread<T, E> testThread = new TestThread<>(gkopPool, iterations, delay); threads.add(testThread); final Thread t = new Thread(testThread); t.start(); } for (final TestThread<T, E> testThread : threads) { while (!(testThread.complete())) { Waiter.sleepQuietly(500L); } if (testThread.failed()) { fail("Thread failed: " + threads.indexOf(testThread) + "\n" + getExceptionTrace(testThread.exception)); } } } @BeforeEach public void setUp() { simpleFactory = new SimpleFactory<>(); gkoPool = new GenericKeyedObjectPool<>(simpleFactory); } @AfterEach public void tearDownJmx() throws Exception { super.tearDown(); final ObjectName jmxName = gkoPool.getJmxName(); final String poolName = Objects.toString(jmxName, null); gkoPool.clear(); gkoPool.close(); gkoPool = null; simpleFactory = null; final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); final Set<ObjectName> result = mbs.queryNames(new ObjectName( "org.apache.commoms.pool2:type=GenericKeyedObjectPool,*"), null); // There should be no registered pools at this point final int registeredPoolCount = result.size(); final StringBuilder msg = new StringBuilder("Current pool is: "); msg.append(poolName); msg.append(" Still open pools are: "); for (final ObjectName name : result) { // Clean these up ready for the next test msg.append(name.toString()); msg.append(" created via\n"); msg.append(mbs.getAttribute(name, "CreationStackTrace")); msg.append('\n'); mbs.unregisterMBean(name); } assertEquals( 0, registeredPoolCount, msg.toString()); } @Test public void testAppendStats() { assertFalse(gkoPool.getMessageStatistics()); assertEquals("foo", (gkoPool.appendStats("foo"))); try (final GenericKeyedObjectPool<?, ?, Exception> pool = new GenericKeyedObjectPool<>(new SimpleFactory<>())) { pool.setMessagesStatistics(true); assertNotEquals("foo", (pool.appendStats("foo"))); pool.setMessagesStatistics(false); assertEquals("foo", (pool.appendStats("foo"))); } } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testBlockedKeyDoesNotBlockPool() throws Exception { gkoPool.setBlockWhenExhausted(true); gkoPool.setMaxWaitMillis(5000); gkoPool.setMaxTotalPerKey(1); gkoPool.setMaxTotal(-1); gkoPool.borrowObject("one"); final long startMillis = System.currentTimeMillis(); // Needs to be in a separate thread as this will block final Runnable simple = new SimpleTestThread<>(gkoPool, "one"); (new Thread(simple)).start(); // This should be almost instant. If it isn't it means this thread got // stuck behind the thread created above which is bad. // Give other thread a chance to start Thread.sleep(1000); gkoPool.borrowObject("two"); final long endMillis = System.currentTimeMillis(); // If it fails it will be more than 4000ms (5000 less the 1000 sleep) // If it passes it should be almost instant // Use 3000ms as the threshold - should avoid timing issues on most // (all? platforms) assertTrue((endMillis - startMillis) < 4000, "Elapsed time: " + (endMillis - startMillis) + " should be less than 4000"); } /* * Note: This test relies on timing for correct execution. There *should* be * enough margin for this to work correctly on most (all?) systems but be * aware of this if you see a failure of this test. */ @SuppressWarnings({ "rawtypes" }) @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testBorrowObjectFairness() throws Exception { final int numThreads = 40; final int maxTotal = 40; final GenericKeyedObjectPoolConfig<String> config = new GenericKeyedObjectPoolConfig<>(); config.setMaxTotalPerKey(maxTotal); config.setFairness(true); config.setLifo(false); config.setMaxIdlePerKey(maxTotal); gkoPool = new GenericKeyedObjectPool<>(simpleFactory, config); // Exhaust the pool final String[] objects = new String[maxTotal]; for (int i = 0; i < maxTotal; i++) { objects[i] = gkoPool.borrowObject("0"); } // Start and park threads waiting to borrow objects final TestThread[] threads = new TestThread[numThreads]; for(int i=0;i<numThreads;i++) { threads[i] = new TestThread<>(gkoPool, 1, 0, 2000, false, "0" + String.valueOf(i % maxTotal), "0"); final Thread t = new Thread(threads[i]); t.start(); // Short delay to ensure threads start in correct order try { Thread.sleep(10); } catch (final InterruptedException e) { fail(e.toString()); } } // Return objects, other threads should get served in order for (int i = 0; i < maxTotal; i++) { gkoPool.returnObject("0", objects[i]); } // Wait for threads to finish for (int i = 0; i < numThreads; i++) { while (!(threads[i]).complete()) { Waiter.sleepQuietly(500L); } if (threads[i].failed()) { fail("Thread " + i + " failed: " + threads[i].exception.toString()); } } } /** * POOL-192 * Verify that clear(key) does not leak capacity. * * @throws Exception May occur in some failure modes */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testClear() throws Exception { gkoPool.setMaxTotal(2); gkoPool.setMaxTotalPerKey(2); gkoPool.setBlockWhenExhausted(false); gkoPool.addObject("one"); gkoPool.addObject("one"); assertEquals(2, gkoPool.getNumIdle()); gkoPool.clear("one"); assertEquals(0, gkoPool.getNumIdle()); assertEquals(0, gkoPool.getNumIdle("one")); final String obj1 = gkoPool.borrowObject("one"); final String obj2 = gkoPool.borrowObject("one"); gkoPool.returnObject("one", obj1); gkoPool.returnObject("one", obj2); gkoPool.clear(); assertEquals(0, gkoPool.getNumIdle()); assertEquals(0, gkoPool.getNumIdle("one")); gkoPool.borrowObject("one"); gkoPool.borrowObject("one"); gkoPool.close(); } /** * Test to make sure that clearOldest does not destroy instances that have been checked out. * * @throws Exception May occur in some failure modes */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testClearOldest() throws Exception { // Make destroy have some latency so clearOldest takes some time final WaiterFactory<String> waiterFactory = new WaiterFactory<>(0, 20, 0, 0, 0, 0, 50, 5, 0); try (final GenericKeyedObjectPool<String, Waiter, RuntimeException> waiterPool = new GenericKeyedObjectPool<>(waiterFactory)) { waiterPool.setMaxTotalPerKey(5); waiterPool.setMaxTotal(50); waiterPool.setLifo(false); // Load the pool with idle instances - 5 each for 10 keys for (int i = 0; i < 10; i++) { final String key = Integer.toString(i); for (int j = 0; j < 5; j++) { waiterPool.addObject(key); } // Make sure order is maintained Thread.sleep(20); } // Now set up a race - one thread wants a new instance, triggering clearOldest // Other goes after an element on death row // See if we end up with dead man walking final SimpleTestThread<Waiter, RuntimeException> t2 = new SimpleTestThread<>(waiterPool, "51"); final Thread thread2 = new Thread(t2); thread2.start(); // Triggers clearOldest, killing all of the 0's and the 2 oldest 1's Thread.sleep(50); // Wait for clearOldest to kick off, but not long enough to reach the 1's final Waiter waiter = waiterPool.borrowObject("1"); Thread.sleep(200); // Wait for execution to happen waiterPool.returnObject("1", waiter); // Will throw IllegalStateException if dead } } /** * POOL-391 Verify that when clear(key) is called with reuseCapacity true, * capacity freed is reused and allocated to most loaded pools. * * @throws Exception May occur in some failure modes */ @Test public void testClearReuseCapacity() throws Exception { gkoPool.setMaxTotalPerKey(6); gkoPool.setMaxTotal(6); gkoPool.setMaxWait(Duration.ofSeconds(5)); // Create one thread to wait on "one", two on "two", three on "three" final ArrayList<Thread> testThreads = new ArrayList<>(); testThreads.add(new Thread(new SimpleTestThread<>(gkoPool, "one"))); testThreads.add(new Thread(new SimpleTestThread<>(gkoPool, "two"))); testThreads.add(new Thread(new SimpleTestThread<>(gkoPool, "two"))); testThreads.add(new Thread(new SimpleTestThread<>(gkoPool, "three"))); testThreads.add(new Thread(new SimpleTestThread<>(gkoPool, "three"))); testThreads.add(new Thread(new SimpleTestThread<>(gkoPool, "three"))); // Borrow two each from "four", "five", "six" - using all capacity final String four = gkoPool.borrowObject("four"); final String four2 = gkoPool.borrowObject("four"); final String five = gkoPool.borrowObject("five"); final String five2 = gkoPool.borrowObject("five"); final String six = gkoPool.borrowObject("six"); final String six2 = gkoPool.borrowObject("six"); Thread.sleep(100); // Launch the waiters - all will be blocked waiting for (Thread t : testThreads) { t.start(); } Thread.sleep(100); // Return and clear the fours - at least one "three" should get served // Other should be a two or a three (three was most loaded) gkoPool.returnObject("four", four); gkoPool.returnObject("four", four2); gkoPool.clear("four"); Thread.sleep(20); assertTrue(!testThreads.get(3).isAlive() || !testThreads.get(4).isAlive() || !testThreads.get(5).isAlive()); // Now clear the fives gkoPool.returnObject("five", five); gkoPool.returnObject("five", five2); gkoPool.clear("five"); Thread.sleep(20); // Clear the sixes gkoPool.returnObject("six", six); gkoPool.returnObject("six", six2); gkoPool.clear("six"); Thread.sleep(20); for (Thread t : testThreads) { assertFalse(t.isAlive()); } } /** * POOL-391 Adapted from code in the JIRA ticket. * * @throws Exception May occur in some failure modes */ @Test @Timeout(value = 2000, unit = TimeUnit.MILLISECONDS) public void testClearUnblocksWaiters() { final GenericKeyedObjectPoolConfig<Integer> config = new GenericKeyedObjectPoolConfig<>(); config.setMaxTotalPerKey(1); config.setMinIdlePerKey(0); config.setMaxIdlePerKey(-1); config.setMaxTotal(-1); config.setMaxWait(Duration.ofMillis(5)); GenericKeyedObjectPool<Integer, Integer, InterruptedException> testPool = new GenericKeyedObjectPool<>( new KeyedPooledObjectFactory<Integer, Integer, InterruptedException>() { @Override public void activateObject(Integer key, PooledObject<Integer> p) { // do nothing } @Override public void destroyObject(Integer key, PooledObject<Integer> p) throws InterruptedException { Thread.sleep(500); } @Override public PooledObject<Integer> makeObject(Integer key) { return new DefaultPooledObject<>(10); } @Override public void passivateObject(Integer key, PooledObject<Integer> p) { // do nothing } @Override public boolean validateObject(Integer key, PooledObject<Integer> p) { return true; } }, config); final int borrowKey = 10; Thread t = new Thread(() -> { try { while (true) { Integer integer = testPool.borrowObject(borrowKey); testPool.returnObject(borrowKey, integer); Thread.sleep(10); } } catch (Exception e) { fail(); } }); Thread t2 = new Thread(() -> { try { while (true) { testPool.clear(borrowKey); Thread.sleep(10); } } catch (Exception e) { fail(); } }); t.start(); t2.start(); } // POOL-259 @Test public void testClientWaitStats() throws Exception { final SimpleFactory<String> factory = new SimpleFactory<>(); // Give makeObject a little latency factory.setMakeLatency(200); try (final GenericKeyedObjectPool<String, String, Exception> pool = new GenericKeyedObjectPool<>(factory, new GenericKeyedObjectPoolConfig<>())) { final String s = pool.borrowObject("one"); // First borrow waits on create, so wait time should be at least 200 ms // Allow 100ms error in clock times assertTrue(pool.getMaxBorrowWaitTimeMillis() >= 100); assertTrue(pool.getMeanBorrowWaitTimeMillis() >= 100); pool.returnObject("one", s); pool.borrowObject("one"); // Second borrow does not have to wait on create, average should be about 100 assertTrue(pool.getMaxBorrowWaitTimeMillis() > 100); assertTrue(pool.getMeanBorrowWaitTimeMillis() < 200); assertTrue(pool.getMeanBorrowWaitTimeMillis() > 20); } } /** * POOL-231 - verify that concurrent invalidates of the same object do not * corrupt pool destroyCount. * * @throws Exception May occur in some failure modes */ @Test public void testConcurrentInvalidate() throws Exception { // Get allObjects and idleObjects loaded with some instances final int nObjects = 1000; final String key = "one"; gkoPool.setMaxTotal(nObjects); gkoPool.setMaxTotalPerKey(nObjects); gkoPool.setMaxIdlePerKey(nObjects); final String [] obj = new String[nObjects]; for (int i = 0; i < nObjects; i++) { obj[i] = gkoPool.borrowObject(key); } for (int i = 0; i < nObjects; i++) { if (i % 2 == 0) { gkoPool.returnObject(key, obj[i]); } } final int nThreads = 20; final int nIterations = 60; final InvalidateThread[] threads = new InvalidateThread[nThreads]; // Randomly generated list of distinct invalidation targets final ArrayList<Integer> targets = new ArrayList<>(); final Random random = new Random(); for (int j = 0; j < nIterations; j++) { // Get a random invalidation target Integer targ = Integer.valueOf(random.nextInt(nObjects)); while (targets.contains(targ)) { targ = Integer.valueOf(random.nextInt(nObjects)); } targets.add(targ); // Launch nThreads threads all trying to invalidate the target for (int i = 0; i < nThreads; i++) { threads[i] = new InvalidateThread(gkoPool, key, obj[targ.intValue()]); } for (int i = 0; i < nThreads; i++) { new Thread(threads[i]).start(); } boolean done = false; while (!done) { done = true; for (int i = 0; i < nThreads; i++) { done = done && threads[i].complete(); } Thread.sleep(100); } } assertEquals(nIterations, gkoPool.getDestroyedCount()); } @Test public void testConstructorNullFactory() { // add dummy assert (won't be invoked because of IAE) to avoid "unused" warning assertThrows(IllegalArgumentException.class, () -> new GenericKeyedObjectPool<>(null)); } @SuppressWarnings("deprecation") @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testConstructors() { // Make constructor arguments all different from defaults final int maxTotalPerKey = 1; final int minIdle = 2; final Duration maxWaitDuration = Duration.ofMillis(3); final long maxWaitMillis = maxWaitDuration.toMillis(); final int maxIdle = 4; final int maxTotal = 5; final long minEvictableIdleTimeMillis = 6; final int numTestsPerEvictionRun = 7; final boolean testOnBorrow = true; final boolean testOnReturn = true; final boolean testWhileIdle = true; final long timeBetweenEvictionRunsMillis = 8; final boolean blockWhenExhausted = false; final boolean lifo = false; final KeyedPooledObjectFactory<Object, Object, RuntimeException> dummyFactory = new DummyFactory(); try (GenericKeyedObjectPool<Object, Object, RuntimeException> objPool = new GenericKeyedObjectPool<>(dummyFactory)) { assertEquals(GenericKeyedObjectPoolConfig.DEFAULT_MAX_TOTAL_PER_KEY, objPool.getMaxTotalPerKey()); assertEquals(GenericKeyedObjectPoolConfig.DEFAULT_MAX_IDLE_PER_KEY, objPool.getMaxIdlePerKey()); assertEquals(BaseObjectPoolConfig.DEFAULT_MAX_WAIT_MILLIS, objPool.getMaxWaitMillis()); assertEquals(GenericKeyedObjectPoolConfig.DEFAULT_MIN_IDLE_PER_KEY, objPool.getMinIdlePerKey()); assertEquals(GenericKeyedObjectPoolConfig.DEFAULT_MAX_TOTAL, objPool.getMaxTotal()); // assertEquals(BaseObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, objPool.getMinEvictableIdleTimeMillis()); assertEquals(BaseObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_TIME, objPool.getMinEvictableIdleTime()); assertEquals(BaseObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_TIME, objPool.getMinEvictableIdleDuration()); // assertEquals(BaseObjectPoolConfig.DEFAULT_NUM_TESTS_PER_EVICTION_RUN, objPool.getNumTestsPerEvictionRun()); assertEquals(Boolean.valueOf(BaseObjectPoolConfig.DEFAULT_TEST_ON_BORROW), Boolean.valueOf(objPool.getTestOnBorrow())); assertEquals(Boolean.valueOf(BaseObjectPoolConfig.DEFAULT_TEST_ON_RETURN), Boolean.valueOf(objPool.getTestOnReturn())); assertEquals(Boolean.valueOf(BaseObjectPoolConfig.DEFAULT_TEST_WHILE_IDLE), Boolean.valueOf(objPool.getTestWhileIdle())); // assertEquals(BaseObjectPoolConfig.DEFAULT_TIME_BETWEEN_EVICTION_RUNS, objPool.getDurationBetweenEvictionRuns()); assertEquals(BaseObjectPoolConfig.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, objPool.getTimeBetweenEvictionRunsMillis()); assertEquals(BaseObjectPoolConfig.DEFAULT_TIME_BETWEEN_EVICTION_RUNS, objPool.getTimeBetweenEvictionRuns()); // assertEquals(Boolean.valueOf(BaseObjectPoolConfig.DEFAULT_BLOCK_WHEN_EXHAUSTED), Boolean.valueOf(objPool.getBlockWhenExhausted())); assertEquals(Boolean.valueOf(BaseObjectPoolConfig.DEFAULT_LIFO), Boolean.valueOf(objPool.getLifo())); } final GenericKeyedObjectPoolConfig<Object> config = new GenericKeyedObjectPoolConfig<>(); config.setLifo(lifo); config.setMaxTotalPerKey(maxTotalPerKey); config.setMaxIdlePerKey(maxIdle); config.setMinIdlePerKey(minIdle); config.setMaxTotal(maxTotal); config.setMaxWait(maxWaitDuration); config.setMinEvictableIdleTime(Duration.ofMillis(minEvictableIdleTimeMillis)); config.setNumTestsPerEvictionRun(numTestsPerEvictionRun); config.setTestOnBorrow(testOnBorrow); config.setTestOnReturn(testOnReturn); config.setTestWhileIdle(testWhileIdle); config.setTimeBetweenEvictionRuns(Duration.ofMillis(timeBetweenEvictionRunsMillis)); config.setBlockWhenExhausted(blockWhenExhausted); try (GenericKeyedObjectPool<Object, Object, RuntimeException> objPool = new GenericKeyedObjectPool<>(dummyFactory, config)) { assertEquals(maxTotalPerKey, objPool.getMaxTotalPerKey()); assertEquals(maxIdle, objPool.getMaxIdlePerKey()); assertEquals(maxWaitDuration, objPool.getMaxWaitDuration()); assertEquals(maxWaitMillis, objPool.getMaxWaitMillis()); assertEquals(minIdle, objPool.getMinIdlePerKey()); assertEquals(maxTotal, objPool.getMaxTotal()); assertEquals(minEvictableIdleTimeMillis, objPool.getMinEvictableIdleDuration().toMillis()); assertEquals(minEvictableIdleTimeMillis, objPool.getMinEvictableIdleTimeMillis()); assertEquals(minEvictableIdleTimeMillis, objPool.getMinEvictableIdleTime().toMillis()); assertEquals(numTestsPerEvictionRun, objPool.getNumTestsPerEvictionRun()); assertEquals(Boolean.valueOf(testOnBorrow), Boolean.valueOf(objPool.getTestOnBorrow())); assertEquals(Boolean.valueOf(testOnReturn), Boolean.valueOf(objPool.getTestOnReturn())); assertEquals(Boolean.valueOf(testWhileIdle), Boolean.valueOf(objPool.getTestWhileIdle())); assertEquals(timeBetweenEvictionRunsMillis, objPool.getDurationBetweenEvictionRuns().toMillis()); assertEquals(timeBetweenEvictionRunsMillis, objPool.getTimeBetweenEvictionRunsMillis()); assertEquals(timeBetweenEvictionRunsMillis, objPool.getTimeBetweenEvictionRuns().toMillis()); assertEquals(Boolean.valueOf(blockWhenExhausted), Boolean.valueOf(objPool.getBlockWhenExhausted())); assertEquals(Boolean.valueOf(lifo), Boolean.valueOf(objPool.getLifo())); } } /** * JIRA: POOL-270 - make sure constructor correctly sets run * frequency of evictor timer. */ @Test public void testContructorEvictionConfig() throws Exception { final GenericKeyedObjectPoolConfig<String> config = new GenericKeyedObjectPoolConfig<>(); config.setTimeBetweenEvictionRuns(Duration.ofMillis(500)); config.setMinEvictableIdleTime(Duration.ofMillis(50)); config.setNumTestsPerEvictionRun(5); try (final GenericKeyedObjectPool<String, String, Exception> p = new GenericKeyedObjectPool<>(simpleFactory, config)) { for (int i = 0; i < 5; i++) { p.addObject("one"); } Waiter.sleepQuietly(100); assertEquals(5, p.getNumIdle("one")); Waiter.sleepQuietly(500); assertEquals(0, p.getNumIdle("one")); } } /** * Verifies that when a factory's makeObject produces instances that are not * discernible by equals, the pool can handle them. * * JIRA: POOL-283 */ @Test public void testEqualsIndiscernible() throws Exception { final HashSetFactory factory = new HashSetFactory(); try (final GenericKeyedObjectPool<String, HashSet<String>, RuntimeException> pool = new GenericKeyedObjectPool<>(factory, new GenericKeyedObjectPoolConfig<>())) { final HashSet<String> s1 = pool.borrowObject("a"); final HashSet<String> s2 = pool.borrowObject("a"); pool.returnObject("a", s1); pool.returnObject("a", s2); } } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testEviction() throws Exception { gkoPool.setMaxIdlePerKey(500); gkoPool.setMaxTotalPerKey(500); gkoPool.setNumTestsPerEvictionRun(100); gkoPool.setMinEvictableIdleTime(Duration.ofMillis(250)); gkoPool.setTimeBetweenEvictionRuns(Duration.ofMillis(500)); final String[] active = new String[500]; for(int i=0;i<500;i++) { active[i] = gkoPool.borrowObject(""); } for(int i=0;i<500;i++) { gkoPool.returnObject("",active[i]); } Waiter.sleepQuietly(1000L); assertTrue(gkoPool.getNumIdle("") < 500, "Should be less than 500 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertTrue(gkoPool.getNumIdle("") < 400, "Should be less than 400 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertTrue(gkoPool.getNumIdle("") < 300,"Should be less than 300 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertTrue(gkoPool.getNumIdle("") < 200, "Should be less than 200 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertTrue(gkoPool.getNumIdle("") < 100 , "Should be less than 100 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertEquals(0,gkoPool.getNumIdle(""),"Should be zero idle, found " + gkoPool.getNumIdle("")); for(int i=0;i<500;i++) { active[i] = gkoPool.borrowObject(""); } for(int i=0;i<500;i++) { gkoPool.returnObject("",active[i]); } Waiter.sleepQuietly(1000L); assertTrue(gkoPool.getNumIdle("") < 500,"Should be less than 500 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertTrue(gkoPool.getNumIdle("") < 400,"Should be less than 400 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertTrue(gkoPool.getNumIdle("") < 300,"Should be less than 300 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertTrue(gkoPool.getNumIdle("") < 200,"Should be less than 200 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertTrue(gkoPool.getNumIdle("") < 100,"Should be less than 100 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertEquals(0,gkoPool.getNumIdle(""),"Should be zero idle, found " + gkoPool.getNumIdle("")); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testEviction2() throws Exception { gkoPool.setMaxIdlePerKey(500); gkoPool.setMaxTotalPerKey(500); gkoPool.setNumTestsPerEvictionRun(100); gkoPool.setMinEvictableIdleTime(Duration.ofMillis(500)); gkoPool.setTimeBetweenEvictionRuns(Duration.ofMillis(500)); final String[] active = new String[500]; final String[] active2 = new String[500]; for (int i = 0; i < 500; i++) { active[i] = gkoPool.borrowObject(""); active2[i] = gkoPool.borrowObject("2"); } for (int i = 0; i < 500; i++) { gkoPool.returnObject("", active[i]); gkoPool.returnObject("2", active2[i]); } Waiter.sleepQuietly(1100L); assertTrue(gkoPool.getNumIdle() < 1000, "Should be less than 1000 idle, found " + gkoPool.getNumIdle()); final long sleepMillisPart2 = 600L; Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 900, "Should be less than 900 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 800, "Should be less than 800 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 700, "Should be less than 700 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 600, "Should be less than 600 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 500, "Should be less than 500 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 400, "Should be less than 400 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 300, "Should be less than 300 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 200, "Should be less than 200 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 100, "Should be less than 100 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertEquals(0, gkoPool.getNumIdle(), "Should be zero idle, found " + gkoPool.getNumIdle()); } /** * Test to make sure evictor visits least recently used objects first, * regardless of FIFO/LIFO * * JIRA: POOL-86 * * @throws Exception May occur in some failure modes */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testEvictionOrder() throws Exception { checkEvictionOrder(false); checkEvictionOrder(true); } // POOL-326 @Test public void testEvictorClearOldestRace() throws Exception { gkoPool.setMinEvictableIdleTime(Duration.ofMillis(100)); gkoPool.setNumTestsPerEvictionRun(1); // Introduce latency between when evictor starts looking at an instance and when // it decides to destroy it gkoPool.setEvictionPolicy(new SlowEvictionPolicy<>(1000)); // Borrow an instance final String val = gkoPool.borrowObject("foo"); // Add another idle one gkoPool.addObject("foo"); // Sleep long enough so idle one is eligible for eviction Thread.sleep(1000); // Start evictor and race with clearOldest gkoPool.setTimeBetweenEvictionRuns(Duration.ofMillis(10)); // Wait for evictor to start Thread.sleep(100); gkoPool.clearOldest(); // Wait for slow evictor to complete Thread.sleep(1500); // See if we get NPE on return (POOL-326) gkoPool.returnObject("foo", val); } /** * Verifies that the evictor visits objects in expected order * and frequency. * * @throws Exception May occur in some failure modes */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testEvictorVisiting() throws Exception { checkEvictorVisiting(true); checkEvictorVisiting(false); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testExceptionInValidationDuringEviction() throws Exception { gkoPool.setMaxIdlePerKey(1); gkoPool.setMinEvictableIdleTime(Duration.ZERO); gkoPool.setTestWhileIdle(true); final String obj = gkoPool.borrowObject("one"); gkoPool.returnObject("one", obj); simpleFactory.setThrowExceptionOnValidate(true); assertThrows(RuntimeException.class, gkoPool::evict); assertEquals(0, gkoPool.getNumActive()); assertEquals(0, gkoPool.getNumIdle()); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testExceptionOnActivateDuringBorrow() throws Exception { final String obj1 = gkoPool.borrowObject("one"); final String obj2 = gkoPool.borrowObject("one"); gkoPool.returnObject("one", obj1); gkoPool.returnObject("one", obj2); simpleFactory.setThrowExceptionOnActivate(true); simpleFactory.setEvenValid(false); // Activation will now throw every other time // First attempt throws, but loop continues and second succeeds final String obj = gkoPool.borrowObject("one"); assertEquals(1, gkoPool.getNumActive("one")); assertEquals(0, gkoPool.getNumIdle("one")); assertEquals(1, gkoPool.getNumActive()); assertEquals(0, gkoPool.getNumIdle()); gkoPool.returnObject("one", obj); simpleFactory.setValid(false); // Validation will now fail on activation when borrowObject returns // an idle instance, and then when attempting to create a new instance assertThrows(NoSuchElementException.class, () -> gkoPool.borrowObject("one")); assertEquals(0, gkoPool.getNumActive("one")); assertEquals(0, gkoPool.getNumIdle("one")); assertEquals(0, gkoPool.getNumActive()); assertEquals(0, gkoPool.getNumIdle()); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testExceptionOnDestroyDuringBorrow() throws Exception { simpleFactory.setThrowExceptionOnDestroy(true); simpleFactory.setValidationEnabled(true); gkoPool.setTestOnBorrow(true); gkoPool.borrowObject("one"); simpleFactory.setValid(false); // Make validation fail on next borrow attempt assertThrows(NoSuchElementException.class, () -> gkoPool.borrowObject("one")); assertEquals(1, gkoPool.getNumActive("one")); assertEquals(0, gkoPool.getNumIdle("one")); assertEquals(1, gkoPool.getNumActive()); assertEquals(0, gkoPool.getNumIdle()); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testExceptionOnDestroyDuringReturn() throws Exception { simpleFactory.setThrowExceptionOnDestroy(true); simpleFactory.setValidationEnabled(true); gkoPool.setTestOnReturn(true); final String obj1 = gkoPool.borrowObject("one"); gkoPool.borrowObject("one"); simpleFactory.setValid(false); // Make validation fail gkoPool.returnObject("one", obj1); assertEquals(1, gkoPool.getNumActive("one")); assertEquals(0, gkoPool.getNumIdle("one")); assertEquals(1, gkoPool.getNumActive()); assertEquals(0, gkoPool.getNumIdle()); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testExceptionOnPassivateDuringReturn() throws Exception { final String obj = gkoPool.borrowObject("one"); simpleFactory.setThrowExceptionOnPassivate(true); gkoPool.returnObject("one", obj); assertEquals(0,gkoPool.getNumIdle()); gkoPool.close(); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testFIFO() throws Exception { gkoPool.setLifo(false); final String key = "key"; gkoPool.addObject(key); // "key0" gkoPool.addObject(key); // "key1" gkoPool.addObject(key); // "key2" assertEquals( "key0", gkoPool.borrowObject(key),"Oldest"); assertEquals( "key1", gkoPool.borrowObject(key),"Middle"); assertEquals( "key2", gkoPool.borrowObject(key),"Youngest"); final String s = gkoPool.borrowObject(key); assertEquals( "key3", s,"new-3"); gkoPool.returnObject(key, s); assertEquals( s, gkoPool.borrowObject(key),"returned"); assertEquals( "key4", gkoPool.borrowObject(key),"new-4"); } @Test @Timeout(value = 60, unit = TimeUnit.SECONDS) public void testGetKeys() throws Exception { gkoPool.addObject("one"); assertEquals(1, gkoPool.getKeys().size()); gkoPool.addObject("two"); assertEquals(2, gkoPool.getKeys().size()); gkoPool.clear("one"); assertEquals(1, gkoPool.getKeys().size()); assertEquals("two", gkoPool.getKeys().get(0)); gkoPool.clear(); } @Test public void testGetStatsString() { assertNotNull((gkoPool.getStatsString())); } /** * Verify that threads waiting on a depleted pool get served when a checked out object is * invalidated. * * JIRA: POOL-240 * * @throws Exception May occur in some failure modes */ @Test public void testInvalidateFreesCapacity() throws Exception { final SimpleFactory<String> factory = new SimpleFactory<>(); try (final GenericKeyedObjectPool<String, String, Exception> pool = new GenericKeyedObjectPool<>(factory)) { pool.setMaxTotalPerKey(2); pool.setMaxWaitMillis(500); // Borrow an instance and hold if for 5 seconds final WaitingTestThread<Exception> thread1 = new WaitingTestThread<>(pool, "one", 5000); thread1.start(); // Borrow another instance final String obj = pool.borrowObject("one"); // Launch another thread - will block, but fail in 500 ms final WaitingTestThread<Exception> thread2 = new WaitingTestThread<>(pool, "one", 100); thread2.start(); // Invalidate the object borrowed by this thread - should allow thread2 to create Thread.sleep(20); pool.invalidateObject("one", obj); Thread.sleep(600); // Wait for thread2 to timeout if (thread2.thrown != null) { fail(thread2.thrown.toString()); } } } @Test public void testInvalidateFreesCapacityForOtherKeys() throws Exception { gkoPool.setMaxTotal(1); gkoPool.setMaxWait(Duration.ofMillis(500)); Thread borrower = new Thread(new SimpleTestThread<>(gkoPool, "two")); String obj = gkoPool.borrowObject("one"); borrower.start(); // Will block Thread.sleep(100); // Make sure borrower has started gkoPool.invalidateObject("one", obj); // Should free capacity to serve the other key Thread.sleep(20); // Should have been served by now assertFalse(borrower.isAlive()); } @Test public void testInvalidateMissingKey() throws Exception { assertThrows(IllegalStateException.class, () -> gkoPool.invalidateObject("UnknownKey", "Ignored")); } @ParameterizedTest @EnumSource(DestroyMode.class) public void testInvalidateMissingKeyForDestroyMode(final DestroyMode destroyMode) throws Exception { assertThrows(IllegalStateException.class, () -> gkoPool.invalidateObject("UnknownKey", "Ignored", destroyMode)); } /** * Verify that threads blocked waiting on a depleted pool get served when a checked out instance * is invalidated. * * JIRA: POOL-240 * * @throws Exception May occur in some failure modes */ @Test public void testInvalidateWaiting() throws Exception { final GenericKeyedObjectPoolConfig<Object> config = new GenericKeyedObjectPoolConfig<>(); config.setMaxTotal(2); config.setBlockWhenExhausted(true); config.setMinIdlePerKey(0); config.setMaxWait(Duration.ofMillis(-1)); config.setNumTestsPerEvictionRun(Integer.MAX_VALUE); // always test all idle objects config.setTestOnBorrow(true); config.setTestOnReturn(false); config.setTestWhileIdle(true); config.setTimeBetweenEvictionRuns(Duration.ofMillis(-1)); try (final GenericKeyedObjectPool<Integer, Object, RuntimeException> pool = new GenericKeyedObjectPool<>(new ObjectFactory(), config)) { // Allocate both objects with this thread pool.borrowObject(Integer.valueOf(1)); // object1 final Object object2 = pool.borrowObject(Integer.valueOf(1)); // Cause a thread to block waiting for an object final ExecutorService executorService = Executors.newSingleThreadExecutor(new DaemonThreadFactory()); final Semaphore signal = new Semaphore(0); final Future<Exception> result = executorService.submit(() -> { try { signal.release(); final Object object3 = pool.borrowObject(Integer.valueOf(1)); pool.returnObject(Integer.valueOf(1), object3); signal.release(); } catch (final Exception e1) { return e1; } catch (final Throwable e2) { return new Exception(e2); } return null; }); // Wait for the thread to start assertTrue(signal.tryAcquire(5, TimeUnit.SECONDS)); // Attempt to ensure that test thread is blocked waiting for an object Thread.sleep(500); pool.invalidateObject(Integer.valueOf(1), object2); assertTrue(signal.tryAcquire(2, TimeUnit.SECONDS),"Call to invalidateObject did not unblock pool waiters."); if (result.get() != null) { throw new AssertionError(result.get()); } } } /** * Ensure the pool is registered. */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testJmxRegistration() { final ObjectName oname = gkoPool.getJmxName(); final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); final Set<ObjectName> result = mbs.queryNames(oname, null); assertEquals(1, result.size()); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testLIFO() throws Exception { gkoPool.setLifo(true); final String key = "key"; gkoPool.addObject(key); // "key0" gkoPool.addObject(key); // "key1" gkoPool.addObject(key); // "key2" assertEquals( "key2", gkoPool.borrowObject(key),"Youngest"); assertEquals( "key1", gkoPool.borrowObject(key),"Middle"); assertEquals( "key0", gkoPool.borrowObject(key),"Oldest"); final String s = gkoPool.borrowObject(key); assertEquals( "key3", s,"new-3"); gkoPool.returnObject(key, s); assertEquals( s, gkoPool.borrowObject(key),"returned"); assertEquals( "key4", gkoPool.borrowObject(key),"new-4"); } /** * Verifies that threads that get parked waiting for keys not in use * when the pool is at maxTotal eventually get served. * * @throws Exception May occur in some failure modes */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testLivenessPerKey() throws Exception { gkoPool.setMaxIdlePerKey(3); gkoPool.setMaxTotal(3); gkoPool.setMaxTotalPerKey(3); gkoPool.setMaxWaitMillis(3000); // Really a timeout for the test // Check out and briefly hold 3 "1"s final WaitingTestThread<Exception> t1 = new WaitingTestThread<>(gkoPool, "1", 100); final WaitingTestThread<Exception> t2 = new WaitingTestThread<>(gkoPool, "1", 100); final WaitingTestThread<Exception> t3 = new WaitingTestThread<>(gkoPool, "1", 100); t1.start(); t2.start(); t3.start(); // Try to get a "2" while all capacity is in use. // Thread will park waiting on empty queue. Verify it gets served. gkoPool.borrowObject("2"); } /** * Verify that factory exceptions creating objects do not corrupt per key create count. * * JIRA: POOL-243 * * @throws Exception May occur in some failure modes */ @Test public void testMakeObjectException() throws Exception { final SimpleFactory<String> factory = new SimpleFactory<>(); try (final GenericKeyedObjectPool<String, String, Exception> pool = new GenericKeyedObjectPool<>(factory)) { pool.setMaxTotalPerKey(1); pool.setBlockWhenExhausted(false); factory.exceptionOnCreate = true; assertThrows(Exception.class, () -> pool.borrowObject("One")); factory.exceptionOnCreate = false; pool.borrowObject("One"); } } /** * Test case for POOL-180. */ @Test @Timeout(value = 200000, unit = TimeUnit.MILLISECONDS) public void testMaxActivePerKeyExceeded() { final WaiterFactory<String> waiterFactory = new WaiterFactory<>(0, 20, 0, 0, 0, 0, 8, 5, 0); // TODO Fix this. Can't use local pool since runTestThreads uses the // protected pool field try (final GenericKeyedObjectPool<String, Waiter, RuntimeException> waiterPool = new GenericKeyedObjectPool<>(waiterFactory)) { waiterPool.setMaxTotalPerKey(5); waiterPool.setMaxTotal(8); waiterPool.setTestOnBorrow(true); waiterPool.setMaxIdlePerKey(5); waiterPool.setMaxWaitMillis(-1); runTestThreads(20, 300, 250, waiterPool); } } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMaxIdle() throws Exception { gkoPool.setMaxTotalPerKey(100); gkoPool.setMaxIdlePerKey(8); final String[] active = new String[100]; for(int i=0;i<100;i++) { active[i] = gkoPool.borrowObject(""); } assertEquals(100,gkoPool.getNumActive("")); assertEquals(0,gkoPool.getNumIdle("")); for(int i=0;i<100;i++) { gkoPool.returnObject("",active[i]); assertEquals(99 - i,gkoPool.getNumActive("")); assertEquals((i < 8 ? i+1 : 8),gkoPool.getNumIdle("")); } for(int i=0;i<100;i++) { active[i] = gkoPool.borrowObject("a"); } assertEquals(100,gkoPool.getNumActive("a")); assertEquals(0,gkoPool.getNumIdle("a")); for(int i=0;i<100;i++) { gkoPool.returnObject("a",active[i]); assertEquals(99 - i,gkoPool.getNumActive("a")); assertEquals((i < 8 ? i+1 : 8),gkoPool.getNumIdle("a")); } // total number of idle instances is twice maxIdle assertEquals(16, gkoPool.getNumIdle()); // Each pool is at the sup assertEquals(8, gkoPool.getNumIdle("")); assertEquals(8, gkoPool.getNumIdle("a")); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMaxTotal() throws Exception { gkoPool.setMaxTotalPerKey(2); gkoPool.setMaxTotal(3); gkoPool.setBlockWhenExhausted(false); final String o1 = gkoPool.borrowObject("a"); assertNotNull(o1); final String o2 = gkoPool.borrowObject("a"); assertNotNull(o2); final String o3 = gkoPool.borrowObject("b"); assertNotNull(o3); assertThrows(NoSuchElementException.class, () -> gkoPool.borrowObject("c")); assertEquals(0, gkoPool.getNumIdle()); gkoPool.returnObject("b", o3); assertEquals(1, gkoPool.getNumIdle()); assertEquals(1, gkoPool.getNumIdle("b")); final Object o4 = gkoPool.borrowObject("b"); assertNotNull(o4); assertEquals(0, gkoPool.getNumIdle()); assertEquals(0, gkoPool.getNumIdle("b")); gkoPool.setMaxTotal(4); final Object o5 = gkoPool.borrowObject("b"); assertNotNull(o5); assertEquals(2, gkoPool.getNumActive("a")); assertEquals(2, gkoPool.getNumActive("b")); assertEquals(gkoPool.getMaxTotal(), gkoPool.getNumActive("b") + gkoPool.getNumActive("b")); assertEquals(gkoPool.getNumActive(), gkoPool.getMaxTotal()); } /** * Verifies that maxTotal is not exceeded when factory destroyObject * has high latency, testOnReturn is set and there is high incidence of * validation failures. */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMaxTotalInvariant() { final int maxTotal = 15; simpleFactory.setEvenValid(false); // Every other validation fails simpleFactory.setDestroyLatency(100); // Destroy takes 100 ms simpleFactory.setMaxTotalPerKey(maxTotal); // (makes - destroys) bound simpleFactory.setValidationEnabled(true); gkoPool.setMaxTotal(maxTotal); gkoPool.setMaxIdlePerKey(-1); gkoPool.setTestOnReturn(true); gkoPool.setMaxWaitMillis(10000L); runTestThreads(5, 10, 50, gkoPool); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMaxTotalLRU() throws Exception { gkoPool.setMaxTotalPerKey(2); gkoPool.setMaxTotal(3); final String o1 = gkoPool.borrowObject("a"); assertNotNull(o1); gkoPool.returnObject("a", o1); Thread.sleep(25); final String o2 = gkoPool.borrowObject("b"); assertNotNull(o2); gkoPool.returnObject("b", o2); Thread.sleep(25); final String o3 = gkoPool.borrowObject("c"); assertNotNull(o3); gkoPool.returnObject("c", o3); Thread.sleep(25); final String o4 = gkoPool.borrowObject("a"); assertNotNull(o4); gkoPool.returnObject("a", o4); Thread.sleep(25); assertSame(o1, o4); // this should cause b to be bumped out of the pool final String o5 = gkoPool.borrowObject("d"); assertNotNull(o5); gkoPool.returnObject("d", o5); Thread.sleep(25); // now re-request b, we should get a different object because it should // have been expelled from pool (was oldest because a was requested after b) final String o6 = gkoPool.borrowObject("b"); assertNotNull(o6); gkoPool.returnObject("b", o6); assertNotSame(o1, o6); assertNotSame(o2, o6); // second a is still in there final String o7 = gkoPool.borrowObject("a"); assertNotNull(o7); gkoPool.returnObject("a", o7); assertSame(o4, o7); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMaxTotalPerKey() throws Exception { gkoPool.setMaxTotalPerKey(3); gkoPool.setBlockWhenExhausted(false); gkoPool.borrowObject(""); gkoPool.borrowObject(""); gkoPool.borrowObject(""); assertThrows(NoSuchElementException.class, () -> gkoPool.borrowObject("")); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMaxTotalPerKeyZero() { gkoPool.setMaxTotalPerKey(0); gkoPool.setBlockWhenExhausted(false); assertThrows(NoSuchElementException.class, () -> gkoPool.borrowObject("a")); } /** * Verifies that if a borrow of a new key is blocked because maxTotal has * been reached, that borrow continues once another object is returned. * * JIRA: POOL-310 */ @Test public void testMaxTotalWithThreads() throws Exception { gkoPool.setMaxTotalPerKey(2); gkoPool.setMaxTotal(1); final int holdTime = 2000; final TestThread<String, Exception> testA = new TestThread<>(gkoPool, 1, 0, holdTime, false, null, "a"); final TestThread<String, Exception> testB = new TestThread<>(gkoPool, 1, 0, holdTime, false, null, "b"); final Thread threadA = new Thread(testA); final Thread threadB = new Thread(testB); threadA.start(); threadB.start(); Thread.sleep(holdTime * 2); // Both threads should be complete now. boolean threadRunning = true; int count = 0; while (threadRunning && count < 15) { threadRunning = threadA.isAlive(); threadRunning = threadB.isAlive(); Thread.sleep(200); count++; } assertFalse(threadA.isAlive()); assertFalse(threadB.isAlive()); assertFalse(testA.failed); assertFalse(testB.failed); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMaxTotalZero() { gkoPool.setMaxTotal(0); gkoPool.setBlockWhenExhausted(false); assertThrows(NoSuchElementException.class, () -> gkoPool.borrowObject("a")); } /* * Test multi-threaded pool access. * Multiple keys, multiple threads, but maxActive only allows half the threads to succeed. * * This test was prompted by Continuum build failures in the Commons DBCP test case: * TestSharedPoolDataSource.testMultipleThreads2() * Let's see if the this fails on Continuum too! */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMaxWaitMultiThreaded() throws Exception { final long maxWait = 500; // wait for connection final long holdTime = 4 * maxWait; // how long to hold connection final int keyCount = 4; // number of different keys final int threadsPerKey = 5; // number of threads to grab the key initially gkoPool.setBlockWhenExhausted(true); gkoPool.setMaxWaitMillis(maxWait); gkoPool.setMaxTotalPerKey(threadsPerKey); // Create enough threads so half the threads will have to wait final WaitingTestThread<Exception>[] wtt = new WaitingTestThread[keyCount * threadsPerKey * 2]; for(int i=0; i < wtt.length; i++){ wtt[i] = new WaitingTestThread(gkoPool,Integer.toString(i % keyCount),holdTime); } final long originMillis = System.currentTimeMillis() - 1000; for (final WaitingTestThread<Exception> element : wtt) { element.start(); } int failed = 0; for (final WaitingTestThread<Exception> element : wtt) { element.join(); if (element.thrown != null){ failed++; } } if (DISPLAY_THREAD_DETAILS || wtt.length/2 != failed){ System.out.println( "MaxWait: " + maxWait + " HoldTime: " + holdTime + " KeyCount: " + keyCount + " MaxActive: " + threadsPerKey + " Threads: " + wtt.length + " Failed: " + failed ); for (final WaitingTestThread<Exception> wt : wtt) { System.out.println( "Preborrow: " + (wt.preBorrowMillis - originMillis) + " Postborrow: " + (wt.postBorrowMillis != 0 ? wt.postBorrowMillis - originMillis : -1) + " BorrowTime: " + (wt.postBorrowMillis != 0 ? wt.postBorrowMillis - wt.preBorrowMillis : -1) + " PostReturn: " + (wt.postReturnMillis != 0 ? wt.postReturnMillis - originMillis : -1) + " Ended: " + (wt.endedMillis - originMillis) + " Key: " + (wt.key) + " ObjId: " + wt.objectId ); } } assertEquals(wtt.length/2,failed,"Expected half the threads to fail"); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMinIdle() throws Exception { gkoPool.setMaxIdlePerKey(500); gkoPool.setMinIdlePerKey(5); gkoPool.setMaxTotalPerKey(10); gkoPool.setNumTestsPerEvictionRun(0); gkoPool.setMinEvictableIdleTime(Duration.ofMillis(50)); gkoPool.setTimeBetweenEvictionRuns(Duration.ofMillis(100)); gkoPool.setTestWhileIdle(true); // Generate a random key final String key = "A"; gkoPool.preparePool(key); Waiter.sleepQuietly(150L); assertEquals(5, gkoPool.getNumIdle(), "Should be 5 idle, found " + gkoPool.getNumIdle()); final String[] active = new String[5]; active[0] = gkoPool.borrowObject(key); Waiter.sleepQuietly(150L); assertEquals(5, gkoPool.getNumIdle(), "Should be 5 idle, found " + gkoPool.getNumIdle()); for (int i = 1; i < 5; i++) { active[i] = gkoPool.borrowObject(key); } Waiter.sleepQuietly(150L); assertEquals(5, gkoPool.getNumIdle(), "Should be 5 idle, found " + gkoPool.getNumIdle()); for (int i = 0; i < 5; i++) { gkoPool.returnObject(key, active[i]); } Waiter.sleepQuietly(150L); assertEquals(10, gkoPool.getNumIdle(), "Should be 10 idle, found " + gkoPool.getNumIdle()); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMinIdleMaxTotalPerKey() throws Exception { gkoPool.setMaxIdlePerKey(500); gkoPool.setMinIdlePerKey(5); gkoPool.setMaxTotalPerKey(10); gkoPool.setNumTestsPerEvictionRun(0); gkoPool.setMinEvictableIdleTime(Duration.ofMillis(50)); gkoPool.setTimeBetweenEvictionRuns(Duration.ofMillis(100)); gkoPool.setTestWhileIdle(true); final String key = "A"; gkoPool.preparePool(key); assertEquals(5, gkoPool.getNumIdle(), "Should be 5 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(150L); assertEquals(5, gkoPool.getNumIdle(), "Should be 5 idle, found " + gkoPool.getNumIdle()); final String[] active = new String[10]; Waiter.sleepQuietly(150L); assertEquals(5, gkoPool.getNumIdle(), "Should be 5 idle, found " + gkoPool.getNumIdle()); for(int i=0 ; i<5 ; i++) { active[i] = gkoPool.borrowObject(key); } Waiter.sleepQuietly(150L); assertEquals(5, gkoPool.getNumIdle(), "Should be 5 idle, found " + gkoPool.getNumIdle()); for(int i=0 ; i<5 ; i++) { gkoPool.returnObject(key, active[i]); } Waiter.sleepQuietly(150L); assertEquals(10, gkoPool.getNumIdle(), "Should be 10 idle, found " + gkoPool.getNumIdle()); for(int i=0 ; i<10 ; i++) { active[i] = gkoPool.borrowObject(key); } Waiter.sleepQuietly(150L); assertEquals(0, gkoPool.getNumIdle(), "Should be 0 idle, found " + gkoPool.getNumIdle()); for(int i=0 ; i<10 ; i++) { gkoPool.returnObject(key, active[i]); } Waiter.sleepQuietly(150L); assertEquals(10, gkoPool.getNumIdle(), "Should be 10 idle, found " + gkoPool.getNumIdle()); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMinIdleNoPreparePool() throws Exception { gkoPool.setMaxIdlePerKey(500); gkoPool.setMinIdlePerKey(5); gkoPool.setMaxTotalPerKey(10); gkoPool.setNumTestsPerEvictionRun(0); gkoPool.setMinEvictableIdleTime(Duration.ofMillis(50)); gkoPool.setTimeBetweenEvictionRuns(Duration.ofMillis(100)); gkoPool.setTestWhileIdle(true); //Generate a random key final String key = "A"; Waiter.sleepQuietly(150L); assertEquals(0, gkoPool.getNumIdle(), "Should be 0 idle, found " + gkoPool.getNumIdle()); final Object active = gkoPool.borrowObject(key); assertNotNull(active); Waiter.sleepQuietly(150L); assertEquals(5, gkoPool.getNumIdle(), "Should be 5 idle, found " + gkoPool.getNumIdle()); } /** * Verifies that returning an object twice (without borrow in between) causes ISE * but does not re-validate or re-passivate the instance. * * JIRA: POOL-285 */ @Test public void testMultipleReturn() throws Exception { final WaiterFactory<String> factory = new WaiterFactory<>(0, 0, 0, 0, 0, 0); try (final GenericKeyedObjectPool<String, Waiter, RuntimeException> pool = new GenericKeyedObjectPool<>(factory)) { pool.setTestOnReturn(true); final Waiter waiter = pool.borrowObject("a"); pool.returnObject("a", waiter); assertEquals(1, waiter.getValidationCount()); assertEquals(1, waiter.getPassivationCount()); try { pool.returnObject("a", waiter); fail("Expecting IllegalStateException from multiple return"); } catch (final IllegalStateException ex) { // Exception is expected, now check no repeat validation/passivation assertEquals(1, waiter.getValidationCount()); assertEquals(1, waiter.getPassivationCount()); } } } /** * Verifies that when a borrowed object is mutated in a way that does not * preserve equality and hashcode, the pool can recognized it on return. * * JIRA: POOL-284 */ @Test public void testMutable() throws Exception { final HashSetFactory factory = new HashSetFactory(); try (final GenericKeyedObjectPool<String, HashSet<String>, RuntimeException> pool = new GenericKeyedObjectPool<>(factory, new GenericKeyedObjectPoolConfig<>())) { final HashSet<String> s1 = pool.borrowObject("a"); final HashSet<String> s2 = pool.borrowObject("a"); s1.add("One"); s2.add("One"); pool.returnObject("a", s1); pool.returnObject("a", s2); } } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testNegativeMaxTotalPerKey() throws Exception { gkoPool.setMaxTotalPerKey(-1); gkoPool.setBlockWhenExhausted(false); final String obj = gkoPool.borrowObject(""); assertEquals("0",obj); gkoPool.returnObject("",obj); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testNumActiveNumIdle2() throws Exception { assertEquals(0,gkoPool.getNumActive()); assertEquals(0,gkoPool.getNumIdle()); assertEquals(0,gkoPool.getNumActive("A")); assertEquals(0,gkoPool.getNumIdle("A")); assertEquals(0,gkoPool.getNumActive("B")); assertEquals(0,gkoPool.getNumIdle("B")); final String objA0 = gkoPool.borrowObject("A"); final String objB0 = gkoPool.borrowObject("B"); assertEquals(2,gkoPool.getNumActive()); assertEquals(0,gkoPool.getNumIdle()); assertEquals(1,gkoPool.getNumActive("A")); assertEquals(0,gkoPool.getNumIdle("A")); assertEquals(1,gkoPool.getNumActive("B")); assertEquals(0,gkoPool.getNumIdle("B")); final String objA1 = gkoPool.borrowObject("A"); final String objB1 = gkoPool.borrowObject("B"); assertEquals(4,gkoPool.getNumActive()); assertEquals(0,gkoPool.getNumIdle()); assertEquals(2,gkoPool.getNumActive("A")); assertEquals(0,gkoPool.getNumIdle("A")); assertEquals(2,gkoPool.getNumActive("B")); assertEquals(0,gkoPool.getNumIdle("B")); gkoPool.returnObject("A",objA0); gkoPool.returnObject("B",objB0); assertEquals(2,gkoPool.getNumActive()); assertEquals(2,gkoPool.getNumIdle()); assertEquals(1,gkoPool.getNumActive("A")); assertEquals(1,gkoPool.getNumIdle("A")); assertEquals(1,gkoPool.getNumActive("B")); assertEquals(1,gkoPool.getNumIdle("B")); gkoPool.returnObject("A",objA1); gkoPool.returnObject("B",objB1); assertEquals(0,gkoPool.getNumActive()); assertEquals(4,gkoPool.getNumIdle()); assertEquals(0,gkoPool.getNumActive("A")); assertEquals(2,gkoPool.getNumIdle("A")); assertEquals(0,gkoPool.getNumActive("B")); assertEquals(2,gkoPool.getNumIdle("B")); } @Test public void testReturnObjectThrowsIllegalStateException() { try (final GenericKeyedObjectPool<String, String, Exception> pool = new GenericKeyedObjectPool<>(new SimpleFactory<>())) { assertThrows(IllegalStateException.class, () -> pool.returnObject("Foo", "Bar")); } } @Test public void testReturnObjectWithBlockWhenExhausted() throws Exception { gkoPool.setBlockWhenExhausted(true); gkoPool.setMaxTotal(1); // Test return object with no take waiters String obj = gkoPool.borrowObject("0"); gkoPool.returnObject("0", obj); // Test return object with a take waiter final TestThread<String, Exception> testA = new TestThread<>(gkoPool, 1, 0, 500, false, null, "0"); final TestThread<String, Exception> testB = new TestThread<>(gkoPool, 1, 0, 0, false, null, "1"); final Thread threadA = new Thread(testA); final Thread threadB = new Thread(testB); threadA.start(); threadB.start(); threadA.join(); threadB.join(); } @Test public void testReturnObjectWithoutBlockWhenExhausted() throws Exception { gkoPool.setBlockWhenExhausted(false); // Test return object with no take waiters String obj = gkoPool.borrowObject("0"); gkoPool.returnObject("0", obj); } /** * JIRA: POOL-287 * * Verify that when an attempt is made to borrow an instance from the pool * while the evictor is visiting it, there is no capacity leak. * * Test creates the scenario described in POOL-287. */ @Test public void testReturnToHead() throws Exception { final SimpleFactory<String> factory = new SimpleFactory<>(); factory.setValidateLatency(100); factory.setValid(true); // Validation always succeeds try (final GenericKeyedObjectPool<String, String, Exception> pool = new GenericKeyedObjectPool<>(factory)) { pool.setMaxWaitMillis(1000); pool.setTestWhileIdle(true); pool.setMaxTotalPerKey(2); pool.setNumTestsPerEvictionRun(1); pool.setTimeBetweenEvictionRuns(Duration.ofMillis(500)); // Load pool with two objects pool.addObject("one"); // call this o1 pool.addObject("one"); // call this o2 // Default is LIFO, so "one" pool is now [o2, o1] in offer order. // Evictor will visit in oldest-to-youngest order, so o1 then o2 Thread.sleep(800); // Wait for first eviction run to complete // At this point, one eviction run should have completed, visiting o1 // and eviction cursor should be pointed at o2, which is the next offered instance Thread.sleep(250); // Wait for evictor to start final String o1 = pool.borrowObject("one"); // o2 is under eviction, so this will return o1 final String o2 = pool.borrowObject("one"); // Once validation completes, o2 should be offered pool.returnObject("one", o1); pool.returnObject("one", o2); } } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testSettersAndGetters() { { gkoPool.setMaxTotalPerKey(123); assertEquals(123, gkoPool.getMaxTotalPerKey()); } { gkoPool.setMaxIdlePerKey(12); assertEquals(12, gkoPool.getMaxIdlePerKey()); } { gkoPool.setMaxWaitMillis(1234L); assertEquals(1234L, gkoPool.getMaxWaitMillis()); } { gkoPool.setMinEvictableIdleTimeMillis(12345L); assertEquals(12345L, gkoPool.getMinEvictableIdleTimeMillis()); } { gkoPool.setMinEvictableIdleTime(Duration.ofMillis(12345L)); assertEquals(12345L, gkoPool.getMinEvictableIdleTime().toMillis()); } { gkoPool.setMinEvictableIdleTime(Duration.ofMillis(12345L)); assertEquals(12345L, gkoPool.getMinEvictableIdleDuration().toMillis()); } { gkoPool.setNumTestsPerEvictionRun(11); assertEquals(11, gkoPool.getNumTestsPerEvictionRun()); } { gkoPool.setTestOnBorrow(true); assertTrue(gkoPool.getTestOnBorrow()); gkoPool.setTestOnBorrow(false); assertFalse(gkoPool.getTestOnBorrow()); } { gkoPool.setTestOnReturn(true); assertTrue(gkoPool.getTestOnReturn()); gkoPool.setTestOnReturn(false); assertFalse(gkoPool.getTestOnReturn()); } { gkoPool.setTestWhileIdle(true); assertTrue(gkoPool.getTestWhileIdle()); gkoPool.setTestWhileIdle(false); assertFalse(gkoPool.getTestWhileIdle()); } { gkoPool.setTimeBetweenEvictionRunsMillis(11235L); assertEquals(11235L, gkoPool.getDurationBetweenEvictionRuns().toMillis()); assertEquals(11235L, gkoPool.getTimeBetweenEvictionRuns().toMillis()); assertEquals(11235L, gkoPool.getTimeBetweenEvictionRunsMillis()); } { gkoPool.setTimeBetweenEvictionRuns(Duration.ofMillis(11235L)); assertEquals(11235L, gkoPool.getDurationBetweenEvictionRuns().toMillis()); assertEquals(11235L, gkoPool.getTimeBetweenEvictionRuns().toMillis()); assertEquals(11235L, gkoPool.getTimeBetweenEvictionRunsMillis()); } { gkoPool.setBlockWhenExhausted(true); assertTrue(gkoPool.getBlockWhenExhausted()); gkoPool.setBlockWhenExhausted(false); assertFalse(gkoPool.getBlockWhenExhausted()); } } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testThreaded1() { gkoPool.setMaxTotalPerKey(15); gkoPool.setMaxIdlePerKey(15); gkoPool.setMaxWaitMillis(1000L); runTestThreads(20, 100, 50, gkoPool); } // Pool-361 @Test public void testValidateOnCreate() throws Exception { gkoPool.setTestOnCreate(true); simpleFactory.setValidationEnabled(true); gkoPool.addObject("one"); assertEquals(1, simpleFactory.validateCounter); } @Test public void testValidateOnCreateFailure() throws Exception { gkoPool.setTestOnCreate(true); gkoPool.setTestOnBorrow(false); gkoPool.setMaxTotal(2); simpleFactory.setValidationEnabled(true); simpleFactory.setValid(false); // Make sure failed validations do not leak capacity gkoPool.addObject("one"); gkoPool.addObject("one"); assertEquals(0, gkoPool.getNumIdle()); assertEquals(0, gkoPool.getNumActive()); simpleFactory.setValid(true); final String obj = gkoPool.borrowObject("one"); assertNotNull(obj); gkoPool.addObject("one"); // Should have one idle, one out now assertEquals(1, gkoPool.getNumIdle()); assertEquals(1, gkoPool.getNumActive()); } /** * Verify that threads waiting on a depleted pool get served when a returning object fails * validation. * * JIRA: POOL-240 * * @throws Exception May occur in some failure modes */ @Test public void testValidationFailureOnReturnFreesCapacity() throws Exception { final SimpleFactory<String> factory = new SimpleFactory<>(); factory.setValid(false); // Validate will always fail factory.setValidationEnabled(true); try (final GenericKeyedObjectPool<String, String, Exception> pool = new GenericKeyedObjectPool<>(factory)) { pool.setMaxTotalPerKey(2); pool.setMaxWaitMillis(1500); pool.setTestOnReturn(true); pool.setTestOnBorrow(false); // Borrow an instance and hold if for 5 seconds final WaitingTestThread<Exception> thread1 = new WaitingTestThread<>(pool, "one", 5000); thread1.start(); // Borrow another instance and return it after 500 ms (validation will fail) final WaitingTestThread<Exception> thread2 = new WaitingTestThread<>(pool, "one", 500); thread2.start(); Thread.sleep(50); // Try to borrow an object final String obj = pool.borrowObject("one"); pool.returnObject("one", obj); } } // POOL-276 @Test public void testValidationOnCreateOnly() throws Exception { simpleFactory.enableValidation = true; gkoPool.setMaxTotal(1); gkoPool.setTestOnCreate(true); gkoPool.setTestOnBorrow(false); gkoPool.setTestOnReturn(false); gkoPool.setTestWhileIdle(false); final String o1 = gkoPool.borrowObject("KEY"); assertEquals("KEY0", o1); final Timer t = new Timer(); t.schedule( new TimerTask() { @Override public void run() { gkoPool.returnObject("KEY", o1); } }, 3000); final String o2 = gkoPool.borrowObject("KEY"); assertEquals("KEY0", o2); assertEquals(1, simpleFactory.validateCounter); } /** * POOL-189 * * @throws Exception May occur in some failure modes */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testWhenExhaustedBlockClosePool() throws Exception { gkoPool.setMaxTotalPerKey(1); gkoPool.setBlockWhenExhausted(true); gkoPool.setMaxWaitMillis(-1); final String obj1 = gkoPool.borrowObject("a"); // Make sure an object was obtained assertNotNull(obj1); // Create a separate thread to try and borrow another object final WaitingTestThread<Exception> wtt = new WaitingTestThread<>(gkoPool, "a", 200); wtt.start(); // Give wtt time to start Thread.sleep(200); // close the pool (Bug POOL-189) gkoPool.close(); // Give interrupt time to take effect Thread.sleep(200); // Check thread was interrupted assertTrue(wtt.thrown instanceof InterruptedException); } }
Format block
src/test/java/org/apache/commons/pool2/impl/TestGenericKeyedObjectPool.java
Format block
Java
apache-2.0
8af531865a5697c1dcebe64ae27d19ddca22c791
0
stalep/aesh,jfdenise/aesh,felipewmartins/aesh,aslakknutsen/aesh,gastaldi/aesh,brmeyer/aesh,ryanemerson/aesh,jerr/aesh,aeshell/aesh,1and1/aesh
/* * Copyright 2012 Red Hat, Inc. and/or its affiliates. * * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package org.jboss.jreadline.console.operator; import junit.framework.TestCase; import org.jboss.jreadline.console.ConsoleOperation; import java.util.List; /** * @author <a href="mailto:stale.pedersen@jboss.org">Ståle W. Pedersen</a> */ public class ControlOperatorParserTest extends TestCase { public ControlOperatorParserTest(String name) { super(name); } public void testRedirectionOperation() { assertEquals(new ConsoleOperation(ControlOperator.NONE, "ls foo.txt"), ControlOperatorParser.findAllControlOperators("ls foo.txt").get(0)); assertEquals(new ConsoleOperation(ControlOperator.OVERWRITE_OUT, "ls . "), ControlOperatorParser.findAllControlOperators("ls . > foo.txt").get(0)); assertEquals(new ConsoleOperation(ControlOperator.NONE, " foo.txt"), ControlOperatorParser.findAllControlOperators("ls . > foo.txt").get(1)); assertEquals(new ConsoleOperation(ControlOperator.OVERWRITE_OUT, "bas "), ControlOperatorParser.findAllControlOperators("bas > foo.txt 2>&1 ").get(0)); assertEquals(new ConsoleOperation(ControlOperator.OVERWRITE_OUT_AND_ERR, " foo.txt "), ControlOperatorParser.findAllControlOperators("bas > foo.txt 2>&1 ").get(1)); List<ConsoleOperation> ops = ControlOperatorParser.findAllControlOperators("bas | foo.txt 2>&1 foo"); assertEquals(new ConsoleOperation(ControlOperator.PIPE, "bas "), ops.get(0)); assertEquals(new ConsoleOperation(ControlOperator.OVERWRITE_OUT_AND_ERR, " foo.txt "), ops.get(1)); assertEquals(new ConsoleOperation(ControlOperator.NONE, " foo"), ops.get(2)); ops = ControlOperatorParser.findAllControlOperators("bas | foo"); assertEquals(new ConsoleOperation(ControlOperator.PIPE, "bas "), ops.get(0)); assertEquals(new ConsoleOperation(ControlOperator.NONE, " foo"), ops.get(1)); ops = ControlOperatorParser.findAllControlOperators("bas 2> foo"); assertEquals(new ConsoleOperation(ControlOperator.OVERWRITE_ERR, "bas "), ops.get(0)); assertEquals(new ConsoleOperation(ControlOperator.NONE, " foo"), ops.get(1)); ops = ControlOperatorParser.findAllControlOperators("bas < foo"); assertEquals(new ConsoleOperation(ControlOperator.OVERWRITE_IN, "bas "), ops.get(0)); assertEquals(new ConsoleOperation(ControlOperator.NONE, " foo"), ops.get(1)); ops = ControlOperatorParser.findAllControlOperators("bas > foo > foo2"); assertEquals(new ConsoleOperation(ControlOperator.OVERWRITE_OUT, "bas "), ops.get(0)); assertEquals(new ConsoleOperation(ControlOperator.OVERWRITE_OUT, " foo "), ops.get(1)); assertEquals(new ConsoleOperation(ControlOperator.NONE, " foo2"), ops.get(2)); ops = ControlOperatorParser.findAllControlOperators("bas > foo; foo2"); assertEquals(new ConsoleOperation(ControlOperator.OVERWRITE_OUT, "bas "), ops.get(0)); assertEquals(new ConsoleOperation(ControlOperator.END, " foo"), ops.get(1)); assertEquals(new ConsoleOperation(ControlOperator.NONE, " foo2"), ops.get(2)); ops = ControlOperatorParser.findAllControlOperators("bas & foo; foo2 && foo3; bar"); assertEquals(new ConsoleOperation(ControlOperator.AMP, "bas "), ops.get(0)); assertEquals(new ConsoleOperation(ControlOperator.END, " foo"), ops.get(1)); assertEquals(new ConsoleOperation(ControlOperator.AND, " foo2 "), ops.get(2)); assertEquals(new ConsoleOperation(ControlOperator.END, " foo3"), ops.get(3)); assertEquals(new ConsoleOperation(ControlOperator.NONE, " bar"), ops.get(4)); //TODO: must fix this! //assertEquals(new ConsoleOperation(ControlOperator.NONE, "ls \\<foo.txt\\>"), // ControlOperatorParser.findAllControlOperators("ls \\<foo.txt\\>").get(0)); } public void testFindLastRedirectionBeforeCursor() { assertEquals(0, ControlOperatorParser.findLastRedirectionPositionBeforeCursor(" foo", 5)); assertEquals(2, ControlOperatorParser.findLastRedirectionPositionBeforeCursor(" > foo", 5)); assertEquals(4, ControlOperatorParser.findLastRedirectionPositionBeforeCursor("ls > bah > foo", 6)); assertEquals(10, ControlOperatorParser.findLastRedirectionPositionBeforeCursor("ls > bah > foo", 12)); assertEquals(13, ControlOperatorParser.findLastRedirectionPositionBeforeCursor("ls > bah 2>&1 foo", 15)); } }
src/test/java/org/jboss/jreadline/console/operator/ControlOperatorParserTest.java
/* * Copyright 2012 Red Hat, Inc. and/or its affiliates. * * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package org.jboss.jreadline.console.operator; import junit.framework.TestCase; import org.jboss.jreadline.console.ConsoleOperation; import java.util.List; /** * @author <a href="mailto:stale.pedersen@jboss.org">Ståle W. Pedersen</a> */ public class ControlOperatorParserTest extends TestCase { public ControlOperatorParserTest(String name) { super(name); } public void testRedirectionOperation() { assertEquals(new ConsoleOperation(ControlOperator.NONE, "ls foo.txt"), ControlOperatorParser.findAllControlOperators("ls foo.txt").get(0)); assertEquals(new ConsoleOperation(ControlOperator.OVERWRITE_OUT, "ls . "), ControlOperatorParser.findAllControlOperators("ls . > foo.txt").get(0)); assertEquals(new ConsoleOperation(ControlOperator.NONE, " foo.txt"), ControlOperatorParser.findAllControlOperators("ls . > foo.txt").get(1)); assertEquals(new ConsoleOperation(ControlOperator.OVERWRITE_OUT, "bas "), ControlOperatorParser.findAllControlOperators("bas > foo.txt 2>&1 ").get(0)); assertEquals(new ConsoleOperation(ControlOperator.OVERWRITE_OUT_AND_ERR, " foo.txt "), ControlOperatorParser.findAllControlOperators("bas > foo.txt 2>&1 ").get(1)); List<ConsoleOperation> ops = ControlOperatorParser.findAllControlOperators("bas | foo.txt 2>&1 foo"); assertEquals(new ConsoleOperation(ControlOperator.PIPE, "bas "), ops.get(0)); assertEquals(new ConsoleOperation(ControlOperator.OVERWRITE_OUT_AND_ERR, " foo.txt "), ops.get(1)); assertEquals(new ConsoleOperation(ControlOperator.NONE, " foo"), ops.get(2)); ops = ControlOperatorParser.findAllControlOperators("bas | foo"); assertEquals(new ConsoleOperation(ControlOperator.PIPE, "bas "), ops.get(0)); assertEquals(new ConsoleOperation(ControlOperator.NONE, " foo"), ops.get(1)); ops = ControlOperatorParser.findAllControlOperators("bas 2> foo"); assertEquals(new ConsoleOperation(ControlOperator.OVERWRITE_ERR, "bas "), ops.get(0)); assertEquals(new ConsoleOperation(ControlOperator.NONE, " foo"), ops.get(1)); ops = ControlOperatorParser.findAllControlOperators("bas < foo"); assertEquals(new ConsoleOperation(ControlOperator.OVERWRITE_IN, "bas "), ops.get(0)); assertEquals(new ConsoleOperation(ControlOperator.NONE, " foo"), ops.get(1)); ops = ControlOperatorParser.findAllControlOperators("bas > foo > foo2"); assertEquals(new ConsoleOperation(ControlOperator.OVERWRITE_OUT, "bas "), ops.get(0)); assertEquals(new ConsoleOperation(ControlOperator.OVERWRITE_OUT, " foo "), ops.get(1)); assertEquals(new ConsoleOperation(ControlOperator.NONE, " foo2"), ops.get(2)); ops = ControlOperatorParser.findAllControlOperators("bas > foo; foo2"); assertEquals(new ConsoleOperation(ControlOperator.OVERWRITE_OUT, "bas "), ops.get(0)); assertEquals(new ConsoleOperation(ControlOperator.END, " foo"), ops.get(1)); assertEquals(new ConsoleOperation(ControlOperator.NONE, " foo2"), ops.get(2)); ops = ControlOperatorParser.findAllControlOperators("bas & foo; foo2 && foo3; bar"); assertEquals(new ConsoleOperation(ControlOperator.AMP, "bas "), ops.get(0)); assertEquals(new ConsoleOperation(ControlOperator.END, " foo"), ops.get(1)); assertEquals(new ConsoleOperation(ControlOperator.AND, " foo2 "), ops.get(2)); assertEquals(new ConsoleOperation(ControlOperator.END, " foo3"), ops.get(3)); assertEquals(new ConsoleOperation(ControlOperator.NONE, " bar"), ops.get(4)); } public void testFindLastRedirectionBeforeCursor() { assertEquals(0, ControlOperatorParser.findLastRedirectionPositionBeforeCursor(" foo", 5)); assertEquals(2, ControlOperatorParser.findLastRedirectionPositionBeforeCursor(" > foo", 5)); assertEquals(4, ControlOperatorParser.findLastRedirectionPositionBeforeCursor("ls > bah > foo", 6)); assertEquals(10, ControlOperatorParser.findLastRedirectionPositionBeforeCursor("ls > bah > foo", 12)); assertEquals(13, ControlOperatorParser.findLastRedirectionPositionBeforeCursor("ls > bah 2>&1 foo", 15)); } }
added todo, must fix this
src/test/java/org/jboss/jreadline/console/operator/ControlOperatorParserTest.java
added todo, must fix this
Java
apache-2.0
87b86e9cf28d1703decdb52a1a59b93ff0c71a27
0
veraPDF/veraPDF-pdfbox,BezrukovM/veraPDF-pdfbox,veraPDF/veraPDF-pdfbox,BezrukovM/veraPDF-pdfbox,ZhenyaM/veraPDF-pdfbox,ZhenyaM/veraPDF-pdfbox
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pdfbox.pdfparser; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Queue; import java.util.Set; import java.util.TreeMap; import java.util.Vector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.cos.COSBase; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSDocument; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.cos.COSNull; import org.apache.pdfbox.cos.COSNumber; import org.apache.pdfbox.cos.COSObject; import org.apache.pdfbox.cos.COSObjectKey; import org.apache.pdfbox.cos.COSStream; import org.apache.pdfbox.io.IOUtils; import org.apache.pdfbox.pdfparser.XrefTrailerResolver.XRefType; import org.apache.pdfbox.pdmodel.encryption.SecurityHandler; import static org.apache.pdfbox.util.Charsets.ISO_8859_1; /** * PDF-Parser which first reads startxref and xref tables in order to know valid objects and parse only these objects. * * First {@link PDFParser#parse()} or {@link FDFParser#parse()} must be called before page objects * can be retrieved, e.g. {@link PDFParser#getPDDocument()}. * * This class is a much enhanced version of <code>QuickParser</code> presented in <a * href="https://issues.apache.org/jira/browse/PDFBOX-1104">PDFBOX-1104</a> by Jeremy Villalobos. */ public class COSParser extends BaseParser { private static final String PDF_HEADER = "%PDF-"; private static final String FDF_HEADER = "%FDF-"; private static final String PDF_DEFAULT_VERSION = "1.4"; private static final String FDF_DEFAULT_VERSION = "1.0"; private static final char[] XREF_TABLE = new char[] { 'x', 'r', 'e', 'f' }; private static final char[] XREF_STREAM = new char[] { '/', 'X', 'R', 'e', 'f' }; private static final char[] STARTXREF = new char[] { 's','t','a','r','t','x','r','e','f' }; private static final long MINIMUM_SEARCH_OFFSET = 6; private static final int X = 'x'; /** * Only parse the PDF file minimally allowing access to basic information. */ public static final String SYSPROP_PARSEMINIMAL = "org.apache.pdfbox.pdfparser.nonSequentialPDFParser.parseMinimal"; /** * The range within the %%EOF marker will be searched. * Useful if there are additional characters after %%EOF within the PDF. */ public static final String SYSPROP_EOFLOOKUPRANGE = "org.apache.pdfbox.pdfparser.nonSequentialPDFParser.eofLookupRange"; /** * How many trailing bytes to read for EOF marker. */ private static final int DEFAULT_TRAIL_BYTECOUNT = 2048; /** * EOF-marker. */ protected static final char[] EOF_MARKER = new char[] { '%', '%', 'E', 'O', 'F' }; /** * obj-marker. */ protected static final char[] OBJ_MARKER = new char[] { 'o', 'b', 'j' }; private long trailerOffset; /** * file length. */ protected long fileLen; /** * is parser using auto healing capacity ? */ private boolean isLenient = true; protected boolean initialParseDone = false; /** * Contains all found objects of a brute force search. */ private Map<COSObjectKey, Long> bfSearchCOSObjectKeyOffsets = null; private List<Long> bfSearchXRefTablesOffsets = null; private List<Long> bfSearchXRefStreamsOffsets = null; /** * The security handler. */ protected SecurityHandler securityHandler = null; /** * how many trailing bytes to read for EOF marker. */ private int readTrailBytes = DEFAULT_TRAIL_BYTECOUNT; private static final Log LOG = LogFactory.getLog(COSParser.class); /** * Collects all Xref/trailer objects and resolves them into single * object using startxref reference. */ protected XrefTrailerResolver xrefTrailerResolver = new XrefTrailerResolver(); /** * The prefix for the temp file being used. */ public static final String TMP_FILE_PREFIX = "tmpPDF"; /** * Default constructor. */ public COSParser() { } /** * Constructor. * * @param input inputStream of the pdf to be read * @throws IOException if something went wrong */ public COSParser(InputStream input) throws IOException { super(input); } /** * Sets how many trailing bytes of PDF file are searched for EOF marker and 'startxref' marker. If not set we use * default value {@link #DEFAULT_TRAIL_BYTECOUNT}. * * <p>We check that new value is at least 16. However for practical use cases this value should not be lower than * 1000; even 2000 was found to not be enough in some cases where some trailing garbage like HTML snippets followed * the EOF marker.</p> * * <p> * In case system property {@link #SYSPROP_EOFLOOKUPRANGE} is defined this value will be set on initialization but * can be overwritten later. * </p> * * @param byteCount number of trailing bytes */ public void setEOFLookupRange(int byteCount) { if (byteCount > 15) { readTrailBytes = byteCount; } } /** * Parses cross reference tables. * * @param startXRefOffset start offset of the first table * @return the trailer dictionary * @throws IOException if something went wrong */ protected COSDictionary parseXref(long startXRefOffset) throws IOException { pdfSource.seek(startXRefOffset); long startXrefOffset = Math.max(0, parseStartXref()); // check the startxref offset long fixedOffset = checkXRefOffset(startXrefOffset); if (fixedOffset > -1) { startXrefOffset = fixedOffset; } document.setStartXref(startXrefOffset); long prev = startXrefOffset; // ---- parse whole chain of xref tables/object streams using PREV reference while (prev > 0) { // seek to xref table pdfSource.seek(prev); // skip white spaces skipSpaces(); // -- parse xref if (pdfSource.peek() == X) { // xref table and trailer // use existing parser to parse xref table parseXrefTable(prev); // parse the last trailer. trailerOffset = pdfSource.getOffset(); // PDFBOX-1739 skip extra xref entries in RegisSTAR documents while (isLenient && pdfSource.peek() != 't') { if (pdfSource.getOffset() == trailerOffset) { // warn only the first time LOG.warn("Expected trailer object at position " + trailerOffset + ", keep trying"); } readLine(); } if (!parseTrailer()) { throw new IOException("Expected trailer object at position: " + pdfSource.getOffset()); } COSDictionary trailer = xrefTrailerResolver.getCurrentTrailer(); // check for a XRef stream, it may contain some object ids of compressed objects if(trailer.containsKey(COSName.XREF_STM)) { int streamOffset = trailer.getInt(COSName.XREF_STM); // check the xref stream reference fixedOffset = checkXRefStreamOffset(streamOffset, false); if (fixedOffset > -1 && fixedOffset != streamOffset) { streamOffset = (int)fixedOffset; trailer.setInt(COSName.XREF_STM, streamOffset); } if (streamOffset > 0) { pdfSource.seek(streamOffset); skipSpaces(); parseXrefObjStream(prev, false); } else { if(isLenient) { LOG.error("Skipped XRef stream due to a corrupt offset:"+streamOffset); } else { throw new IOException("Skipped XRef stream due to a corrupt offset:"+streamOffset); } } } prev = trailer.getInt(COSName.PREV); if (prev > 0) { // check the xref table reference fixedOffset = checkXRefOffset(prev); if (fixedOffset > -1 && fixedOffset != prev) { prev = fixedOffset; trailer.setLong(COSName.PREV, prev); } } } else { // parse xref stream prev = parseXrefObjStream(prev, true); if (prev > 0) { // check the xref table reference fixedOffset = checkXRefOffset(prev); if (fixedOffset > -1 && fixedOffset != prev) { prev = fixedOffset; COSDictionary trailer = xrefTrailerResolver.getCurrentTrailer(); trailer.setLong(COSName.PREV, prev); } } } } // ---- build valid xrefs out of the xref chain xrefTrailerResolver.setStartxref(startXrefOffset); COSDictionary trailer = xrefTrailerResolver.getTrailer(); document.setTrailer(trailer); document.setIsXRefStream(XRefType.STREAM == xrefTrailerResolver.getXrefType()); // check the offsets of all referenced objects checkXrefOffsets(); // copy xref table document.addXRefTable(xrefTrailerResolver.getXrefTable()); return trailer; } /** * Parses an xref object stream starting with indirect object id. * * @return value of PREV item in dictionary or <code>-1</code> if no such item exists */ private long parseXrefObjStream(long objByteOffset, boolean isStandalone) throws IOException { // ---- parse indirect object head readObjectNumber(); readGenerationNumber(); readExpectedString(OBJ_MARKER, true); COSDictionary dict = parseCOSDictionary(); COSStream xrefStream = parseCOSStream(dict); parseXrefStream(xrefStream, (int) objByteOffset, isStandalone); xrefStream.close(); return dict.getLong(COSName.PREV); } /** * Looks for and parses startxref. We first look for last '%%EOF' marker (within last * {@link #DEFAULT_TRAIL_BYTECOUNT} bytes (or range set via {@link #setEOFLookupRange(int)}) and go back to find * <code>startxref</code>. * * @return the offset of StartXref * @throws IOException If something went wrong. */ protected final long getStartxrefOffset() throws IOException { byte[] buf; long skipBytes; // read trailing bytes into buffer try { final int trailByteCount = (fileLen < readTrailBytes) ? (int) fileLen : readTrailBytes; buf = new byte[trailByteCount]; skipBytes = fileLen - trailByteCount; pdfSource.seek(skipBytes); int off = 0; int readBytes; while (off < trailByteCount) { readBytes = pdfSource.read(buf, off, trailByteCount - off); // in order to not get stuck in a loop we check readBytes (this should never happen) if (readBytes < 1) { throw new IOException( "No more bytes to read for trailing buffer, but expected: " + (trailByteCount - off)); } off += readBytes; } } finally { pdfSource.seek(0); } // find last '%%EOF' int bufOff = lastIndexOf(EOF_MARKER, buf, buf.length); if (bufOff < 0) { document.setEofComplyPDFA(false); if (isLenient) { // in lenient mode the '%%EOF' isn't needed bufOff = buf.length; LOG.debug("Missing end of file marker '" + new String(EOF_MARKER) + "'"); } else { throw new IOException("Missing end of file marker '" + new String(EOF_MARKER) + "'"); } } else if (buf.length - bufOff > 6 || (buf.length - bufOff == 6 && buf[buf.length - 1] != 0x0A && buf[buf.length - 1] != 0x0D)) { document.setEofComplyPDFA(false); } // find last startxref preceding EOF marker bufOff = lastIndexOf(STARTXREF, buf, bufOff); long startXRefOffset = skipBytes + bufOff; if (bufOff < 0) { if (isLenient) { LOG.debug("Can't find offset for startxref"); return -1; } else { throw new IOException("Missing 'startxref' marker."); } } return startXRefOffset; } /** * Searches last appearance of pattern within buffer. Lookup before _lastOff and goes back until 0. * * @param pattern pattern to search for * @param buf buffer to search pattern in * @param endOff offset (exclusive) where lookup starts at * * @return start offset of pattern within buffer or <code>-1</code> if pattern could not be found */ protected int lastIndexOf(final char[] pattern, final byte[] buf, final int endOff) { final int lastPatternChOff = pattern.length - 1; int bufOff = endOff; int patOff = lastPatternChOff; char lookupCh = pattern[patOff]; while (--bufOff >= 0) { if (buf[bufOff] == lookupCh) { if (--patOff < 0) { // whole pattern matched return bufOff; } // matched current char, advance to preceding one lookupCh = pattern[patOff]; } else if (patOff < lastPatternChOff) { // no char match but already matched some chars; reset patOff = lastPatternChOff; lookupCh = pattern[patOff]; } } return -1; } /** * Return true if parser is lenient. Meaning auto healing capacity of the parser are used. * * @return true if parser is lenient */ public boolean isLenient() { return isLenient; } /** * Change the parser leniency flag. * * This method can only be called before the parsing of the file. * * @param lenient try to handle malformed PDFs. * */ public void setLenient(boolean lenient) { if (initialParseDone) { throw new IllegalArgumentException("Cannot change leniency after parsing"); } this.isLenient = lenient; } /** * Creates a unique object id using object number and object generation * number. (requires object number &lt; 2^31)) */ private long getObjectId(final COSObject obj) { return obj.getObjectNumber() << 32 | obj.getGenerationNumber(); } /** * Adds all from newObjects to toBeParsedList if it is not an COSObject or * we didn't add this COSObject already (checked via addedObjects). */ private void addNewToList(final Queue<COSBase> toBeParsedList, final Collection<COSBase> newObjects, final Set<Long> addedObjects) { for (COSBase newObject : newObjects) { addNewToList(toBeParsedList, newObject, addedObjects); } } /** * Adds newObject to toBeParsedList if it is not an COSObject or we didn't * add this COSObject already (checked via addedObjects). */ private void addNewToList(final Queue<COSBase> toBeParsedList, final COSBase newObject, final Set<Long> addedObjects) { if (newObject instanceof COSObject) { final long objId = getObjectId((COSObject) newObject); if (!addedObjects.add(objId)) { return; } } toBeParsedList.add(newObject); } /** * Will parse every object necessary to load a single page from the pdf document. We try our * best to order objects according to offset in file before reading to minimize seek operations. * * @param dict the COSObject from the parent pages. * @param excludeObjects dictionary object reference entries with these names will not be parsed * * @throws IOException if something went wrong */ protected void parseDictObjects(COSDictionary dict, COSName... excludeObjects) throws IOException { // ---- create queue for objects waiting for further parsing final Queue<COSBase> toBeParsedList = new LinkedList<COSBase>(); // offset ordered object map final TreeMap<Long, List<COSObject>> objToBeParsed = new TreeMap<Long, List<COSObject>>(); // in case of compressed objects offset points to stmObj final Set<Long> parsedObjects = new HashSet<Long>(); final Set<Long> addedObjects = new HashSet<Long>(); addExcludedToList(excludeObjects, dict, parsedObjects); addNewToList(toBeParsedList, dict.getValues(), addedObjects); // ---- go through objects to be parsed while (!(toBeParsedList.isEmpty() && objToBeParsed.isEmpty())) { // -- first get all COSObject from other kind of objects and // put them in objToBeParsed; afterwards toBeParsedList is empty COSBase baseObj; while ((baseObj = toBeParsedList.poll()) != null) { if (baseObj instanceof COSDictionary) { addNewToList(toBeParsedList, ((COSDictionary) baseObj).getValues(), addedObjects); } else if (baseObj instanceof COSArray) { final Iterator<COSBase> arrIter = ((COSArray) baseObj).iterator(); while (arrIter.hasNext()) { addNewToList(toBeParsedList, arrIter.next(), addedObjects); } } else if (baseObj instanceof COSObject) { COSObject obj = (COSObject) baseObj; long objId = getObjectId(obj); COSObjectKey objKey = new COSObjectKey(obj.getObjectNumber(), obj.getGenerationNumber()); if (!parsedObjects.contains(objId)) { Long fileOffset = xrefTrailerResolver.getXrefTable().get(objKey); // it is allowed that object references point to null, // thus we have to test if (fileOffset != null && fileOffset != 0) { if (fileOffset > 0) { objToBeParsed.put(fileOffset, Collections.singletonList(obj)); } else { // negative offset means we have a compressed // object within object stream; // get offset of object stream fileOffset = xrefTrailerResolver.getXrefTable().get( new COSObjectKey((int)-fileOffset, 0)); if ((fileOffset == null) || (fileOffset <= 0)) { throw new IOException( "Invalid object stream xref object reference for key '" + objKey + "': " + fileOffset); } List<COSObject> stmObjects = objToBeParsed.get(fileOffset); if (stmObjects == null) { stmObjects = new ArrayList<COSObject>(); objToBeParsed.put(fileOffset, stmObjects); } stmObjects.add(obj); } } else { // NULL object COSObject pdfObject = document.getObjectFromPool(objKey); pdfObject.setObject(COSNull.NULL); } } } } // ---- read first COSObject with smallest offset // resulting object will be added to toBeParsedList if (objToBeParsed.isEmpty()) { break; } for (COSObject obj : objToBeParsed.remove(objToBeParsed.firstKey())) { COSBase parsedObj = parseObjectDynamically(obj, false); obj.setObject(parsedObj); addNewToList(toBeParsedList, parsedObj, addedObjects); parsedObjects.add(getObjectId(obj)); } } } // add objects not to be parsed to list of already parsed objects private void addExcludedToList(COSName[] excludeObjects, COSDictionary dict, final Set<Long> parsedObjects) { if (excludeObjects != null) { for (COSName objName : excludeObjects) { COSBase baseObj = dict.getItem(objName); if (baseObj instanceof COSObject) { parsedObjects.add(getObjectId((COSObject) baseObj)); } } } } /** * This will parse the next object from the stream and add it to the local state. * * @param obj object to be parsed (we only take object number and generation number for lookup start offset) * @param requireExistingNotCompressedObj if <code>true</code> object to be parsed must not be contained within * compressed stream * @return the parsed object (which is also added to document object) * * @throws IOException If an IO error occurs. */ protected final COSBase parseObjectDynamically(COSObject obj, boolean requireExistingNotCompressedObj) throws IOException { return parseObjectDynamically(obj.getObjectNumber(), obj.getGenerationNumber(), requireExistingNotCompressedObj); } /** * This will parse the next object from the stream and add it to the local state. * It's reduced to parsing an indirect object. * * @param objNr object number of object to be parsed * @param objGenNr object generation number of object to be parsed * @param requireExistingNotCompressedObj if <code>true</code> the object to be parsed must be defined in xref * (comment: null objects may be missing from xref) and it must not be a compressed object within object stream * (this is used to circumvent being stuck in a loop in a malicious PDF) * * @return the parsed object (which is also added to document object) * * @throws IOException If an IO error occurs. */ protected COSBase parseObjectDynamically(long objNr, int objGenNr, boolean requireExistingNotCompressedObj) throws IOException { // ---- create object key and get object (container) from pool final COSObjectKey objKey = new COSObjectKey(objNr, objGenNr); final COSObject pdfObject = document.getObjectFromPool(objKey); if (pdfObject.getObject() == null) { // not previously parsed // ---- read offset or object stream object number from xref table Long offsetOrObjstmObNr = xrefTrailerResolver.getXrefTable().get(objKey); // sanity test to circumvent loops with broken documents if (requireExistingNotCompressedObj && ((offsetOrObjstmObNr == null) || (offsetOrObjstmObNr <= 0))) { throw new IOException("Object must be defined and must not be compressed object: " + objKey.getNumber() + ":" + objKey.getGeneration()); } if (offsetOrObjstmObNr == null) { // not defined object -> NULL object (Spec. 1.7, chap. 3.2.9) pdfObject.setObject(COSNull.NULL); } else if (offsetOrObjstmObNr > 0) { // offset of indirect object in file parseFileObject(offsetOrObjstmObNr, objKey, objNr, objGenNr, pdfObject); } else { // xref value is object nr of object stream containing object to be parsed // since our object was not found it means object stream was not parsed so far parseObjectStream((int) -offsetOrObjstmObNr); } } return pdfObject.getObject(); } private void parseFileObject(Long offsetOrObjstmObNr, final COSObjectKey objKey, long objNr, int objGenNr, final COSObject pdfObject) throws IOException { // ---- go to object start pdfSource.seek(offsetOrObjstmObNr - 1); if (!isEOL(pdfSource.read())) { pdfObject.setHeaderOfObjectComplyPDFA(false); } // ---- we must have an indirect object final long readObjNr = readObjectNumber(); if ((pdfSource.read() != 32) || skipSpaces() > 0) { pdfObject.setHeaderFormatComplyPDFA(false); } final int readObjGen = readGenerationNumber(); if ((pdfSource.read() != 32) || skipSpaces() > 0) { pdfObject.setHeaderFormatComplyPDFA(false); } readExpectedString(OBJ_MARKER, true); // ---- consistency check if ((readObjNr != objKey.getNumber()) || (readObjGen != objKey.getGeneration())) { throw new IOException("XREF for " + objKey.getNumber() + ":" + objKey.getGeneration() + " points to wrong object: " + readObjNr + ":" + readObjGen); } if (!isEOL()) { pdfObject.setHeaderOfObjectComplyPDFA(false); } COSBase pb = parseDirObject(); skipSpaces(); pdfSource.seek(pdfSource.getOffset() - 1); int whiteSpace = pdfSource.read(); String endObjectKey = readString(); if (endObjectKey.equals(STREAM_STRING)) { pdfSource.unread(endObjectKey.getBytes(ISO_8859_1)); pdfSource.unread(' '); if (pb instanceof COSDictionary) { COSStream stream = parseCOSStream((COSDictionary) pb); if (securityHandler != null) { securityHandler.decryptStream(stream, objNr, objGenNr); } pb = stream; } else { // this is not legal // the combination of a dict and the stream/endstream // forms a complete stream object throw new IOException("Stream not preceded by dictionary (offset: " + offsetOrObjstmObNr + ")."); } skipSpaces(); pdfSource.seek(pdfSource.getOffset() - 1); whiteSpace = pdfSource.read(); endObjectKey = readLineWithoutSkip(); // we have case with a second 'endstream' before endobj if (!endObjectKey.startsWith(ENDOBJ_STRING) && endObjectKey.startsWith(ENDSTREAM_STRING)) { endObjectKey = endObjectKey.substring(9).trim(); if (endObjectKey.length() == 0) { // no other characters in extra endstream line // read next line whiteSpace = pdfSource.read(); skipSpaces(); endObjectKey = readLineWithoutSkip(); } } } else if (securityHandler != null) { securityHandler.decrypt(pb, objNr, objGenNr); } if (!isEOL(whiteSpace)) { pdfObject.setEndOfObjectComplyPDFA(false); } pdfObject.setObject(pb); if (!endObjectKey.startsWith(ENDOBJ_STRING)) { if (isLenient) { LOG.warn("Object (" + readObjNr + ":" + readObjGen + ") at offset " + offsetOrObjstmObNr + " does not end with 'endobj' but with '" + endObjectKey + "'"); } else { throw new IOException("Object (" + readObjNr + ":" + readObjGen + ") at offset " + offsetOrObjstmObNr + " does not end with 'endobj' but with '" + endObjectKey + "'"); } } whiteSpace = pdfSource.read(); if (!isEOL(whiteSpace)) { pdfObject.setEndOfObjectComplyPDFA(false); pdfSource.unread(whiteSpace); } } private void parseObjectStream(int objstmObjNr) throws IOException { final COSBase objstmBaseObj = parseObjectDynamically(objstmObjNr, 0, true); if (objstmBaseObj instanceof COSStream) { // parse object stream PDFObjectStreamParser parser = new PDFObjectStreamParser((COSStream) objstmBaseObj, document); parser.parse(); parser.close(); // get set of object numbers referenced for this object stream final Set<Long> refObjNrs = xrefTrailerResolver.getContainedObjectNumbers(objstmObjNr); // register all objects which are referenced to be contained in object stream for (COSObject next : parser.getObjects()) { COSObjectKey stmObjKey = new COSObjectKey(next); if (refObjNrs.contains(stmObjKey.getNumber())) { COSObject stmObj = document.getObjectFromPool(stmObjKey); stmObj.setObject(next.getObject()); } } } } private boolean inGetLength = false; /** * Returns length value referred to or defined in given object. */ private COSNumber getLength(final COSBase lengthBaseObj) throws IOException { if (lengthBaseObj == null) { return null; } if (inGetLength) { throw new IOException("Loop while reading length from " + lengthBaseObj); } COSNumber retVal = null; try { inGetLength = true; // maybe length was given directly if (lengthBaseObj instanceof COSNumber) { retVal = (COSNumber) lengthBaseObj; } // length in referenced object else if (lengthBaseObj instanceof COSObject) { COSObject lengthObj = (COSObject) lengthBaseObj; if (lengthObj.getObject() == null) { // not read so far, keep current stream position final long curFileOffset = pdfSource.getOffset(); parseObjectDynamically(lengthObj, true); // reset current stream position pdfSource.seek(curFileOffset); if (lengthObj.getObject() == null) { throw new IOException("Length object content was not read."); } } if (!(lengthObj.getObject() instanceof COSNumber)) { throw new IOException("Wrong type of referenced length object " + lengthObj + ": " + lengthObj.getObject().getClass().getSimpleName()); } retVal = (COSNumber) lengthObj.getObject(); } else { throw new IOException("Wrong type of length object: " + lengthBaseObj.getClass().getSimpleName()); } } finally { inGetLength = false; } return retVal; } private static final int STREAMCOPYBUFLEN = 8192; private final byte[] streamCopyBuf = new byte[STREAMCOPYBUFLEN]; /** * This will read a COSStream from the input stream using length attribute within dictionary. If * length attribute is a indirect reference it is first resolved to get the stream length. This * means we copy stream data without testing for 'endstream' or 'endobj' and thus it is no * problem if these keywords occur within stream. We require 'endstream' to be found after * stream data is read. * * @param dic dictionary that goes with this stream. * * @return parsed pdf stream. * * @throws IOException if an error occurred reading the stream, like problems with reading * length attribute, stream does not end with 'endstream' after data read, stream too short etc. */ protected COSStream parseCOSStream(COSDictionary dic) throws IOException { final COSStream stream = document.createCOSStream(dic); OutputStream out = null; try { // read 'stream'; this was already tested in parseObjectsDynamically() readString(); checkStreamSpacings(stream); stream.setOriginLength(pdfSource.getOffset()); skipWhiteSpaces(); /* * This needs to be dic.getItem because when we are parsing, the underlying object might still be null. */ COSNumber streamLengthObj = getLength(dic.getItem(COSName.LENGTH)); if (streamLengthObj == null) { if (isLenient) { LOG.warn("The stream doesn't provide any stream length, using fallback readUntilEnd, at offset " + pdfSource.getOffset()); } else { throw new IOException("Missing length for stream."); } } // get output stream to copy data to if (streamLengthObj != null && validateStreamLength(streamLengthObj.longValue())) { out = stream.createFilteredStream(streamLengthObj); readValidStream(out, streamLengthObj); } else { out = stream.createFilteredStream(); readUntilEndStream(new EndstreamOutputStream(out)); } checkEndStreamSpacings(stream); String endStream = readString(); if (endStream.equals("endobj") && isLenient) { LOG.warn("stream ends with 'endobj' instead of 'endstream' at offset " + pdfSource.getOffset()); stream.setEndStreamSpacingsComplyPDFA(false); // avoid follow-up warning about missing endobj pdfSource.unread(ENDOBJ); } else if (endStream.length() > 9 && isLenient && endStream.substring(0,9).equals(ENDSTREAM_STRING)) { LOG.warn("stream ends with '" + endStream + "' instead of 'endstream' at offset " + pdfSource.getOffset()); stream.setEndStreamSpacingsComplyPDFA(false); // unread the "extra" bytes pdfSource.unread(endStream.substring(9).getBytes(ISO_8859_1)); } else if (!endStream.equals(ENDSTREAM_STRING)) { throw new IOException( "Error reading stream, expected='endstream' actual='" + endStream + "' at offset " + pdfSource.getOffset()); } } finally { if (out != null) { out.close(); } } return stream; } private void checkStreamSpacings(COSStream stream) throws IOException { int whiteSpace = pdfSource.read(); if (whiteSpace == 13) { whiteSpace = pdfSource.read(); if (whiteSpace != 10) { stream.setStreamSpacingsComplyPDFA(false); pdfSource.unread(whiteSpace); } } else if (whiteSpace != 10) { LOG.warn("Stream at " + pdfSource.getOffset() + " offset has no EOL marker."); stream.setStreamSpacingsComplyPDFA(false); pdfSource.unread(whiteSpace); } } private void checkEndStreamSpacings(COSStream stream) throws IOException { byte eolCount = 0; skipSpaces(); pdfSource.seek(pdfSource.getOffset() - 2); int firstSymbol = pdfSource.read(); int secondSymbol = pdfSource.read(); if (secondSymbol == 10) { if (firstSymbol == 13) { eolCount = 2; } else { eolCount = 1; } } else if (secondSymbol == 13) { eolCount = 1; } else { LOG.warn("End of stream at " + pdfSource.getOffset() + " offset has no contain EOL marker."); stream.setEndStreamSpacingsComplyPDFA(false); } stream.setOriginLength(pdfSource.getOffset() - stream.getOriginLength() - eolCount); } private void readValidStream(OutputStream out, COSNumber streamLengthObj) throws IOException { long remainBytes = streamLengthObj.longValue(); while (remainBytes > 0) { final int chunk = (remainBytes > STREAMCOPYBUFLEN) ? STREAMCOPYBUFLEN : (int) remainBytes; final int readBytes = pdfSource.read(streamCopyBuf, 0, chunk); if (readBytes <= 0) { // shouldn't happen, the stream length has already been validated throw new IOException("read error at offset " + pdfSource.getOffset() + ": expected " + chunk + " bytes, but read() returns " + readBytes); } out.write(streamCopyBuf, 0, readBytes); remainBytes -= readBytes; } } private boolean validateStreamLength(long streamLength) throws IOException { boolean streamLengthIsValid = true; long originOffset = pdfSource.getOffset(); long expectedEndOfStream = originOffset + streamLength; if (expectedEndOfStream > fileLen) { streamLengthIsValid = false; LOG.error("The end of the stream is out of range, using workaround to read the stream, " + "found " + originOffset + " but expected " + expectedEndOfStream); } else { pdfSource.seek(expectedEndOfStream); skipSpaces(); if (!isString(ENDSTREAM)) { streamLengthIsValid = false; LOG.error("The end of the stream doesn't point to the correct offset, using workaround to read the stream, " + "found " + originOffset + " but expected " + expectedEndOfStream); } pdfSource.seek(originOffset); } return streamLengthIsValid; } /** * Check if the cross reference table/stream can be found at the current offset. * * @param startXRefOffset * @return the revised offset * @throws IOException */ private long checkXRefOffset(long startXRefOffset) throws IOException { // repair mode isn't available in non-lenient mode if (!isLenient) { return startXRefOffset; } pdfSource.seek(startXRefOffset); if (pdfSource.peek() == X && isString(XREF_TABLE)) { return startXRefOffset; } if (startXRefOffset > 0) { long fixedOffset = checkXRefStreamOffset(startXRefOffset, true); if (fixedOffset > -1) { return fixedOffset; } } // try to find a fixed offset return calculateXRefFixedOffset(startXRefOffset, false); } /** * Check if the cross reference stream can be found at the current offset. * * @param startXRefOffset the expected start offset of the XRef stream * @param checkOnly check only but don't repair the offset if set to true * @return the revised offset * @throws IOException if something went wrong */ private long checkXRefStreamOffset(long startXRefOffset, boolean checkOnly) throws IOException { // repair mode isn't available in non-lenient mode if (!isLenient || startXRefOffset == 0) { return startXRefOffset; } // seek to offset-1 pdfSource.seek(startXRefOffset-1); int nextValue = pdfSource.read(); // the first character has to be a whitespace, and then a digit if (isWhitespace(nextValue) && isDigit()) { try { // it's a XRef stream readObjectNumber(); readGenerationNumber(); readExpectedString(OBJ_MARKER, true); pdfSource.seek(startXRefOffset); return startXRefOffset; } catch (IOException exception) { // there wasn't an object of a xref stream // try to repair the offset pdfSource.seek(startXRefOffset); } } // try to find a fixed offset return checkOnly ? -1 : calculateXRefFixedOffset(startXRefOffset, true); } /** * Try to find a fixed offset for the given xref table/stream. * * @param objectOffset the given offset where to look at * @param streamsOnly search for xref streams only * @return the fixed offset * * @throws IOException if something went wrong */ private long calculateXRefFixedOffset(long objectOffset, boolean streamsOnly) throws IOException { if (objectOffset < 0) { LOG.error("Invalid object offset " + objectOffset + " when searching for a xref table/stream"); return 0; } // start a brute force search for all xref tables and try to find the offset we are looking for long newOffset = bfSearchForXRef(objectOffset, streamsOnly); if (newOffset > -1) { LOG.debug("Fixed reference for xref table/stream " + objectOffset + " -> " + newOffset); return newOffset; } LOG.error("Can't find the object axref table/stream at offset " + objectOffset); return 0; } /** * Check the XRef table by dereferencing all objects and fixing the offset if necessary. * * @throws IOException if something went wrong. */ private void checkXrefOffsets() throws IOException { // repair mode isn't available in non-lenient mode if (!isLenient) { return; } Map<COSObjectKey, Long> xrefOffset = xrefTrailerResolver.getXrefTable(); if (xrefOffset != null) { boolean bruteForceSearch = false; for (Entry<COSObjectKey, Long> objectEntry : xrefOffset.entrySet()) { COSObjectKey objectKey = objectEntry.getKey(); Long objectOffset = objectEntry.getValue(); // a negative offset number represents a object number itself // see type 2 entry in xref stream if (objectOffset != null && objectOffset >= 0 && !checkObjectKeys(objectKey, objectOffset)) { LOG.debug("Stop checking xref offsets as at least one couldn't be dereferenced"); bruteForceSearch = true; break; } } if (bruteForceSearch) { bfSearchForObjects(); if (bfSearchCOSObjectKeyOffsets != null && !bfSearchCOSObjectKeyOffsets.isEmpty()) { LOG.debug("Replaced read xref table with the results of a brute force search"); xrefOffset.putAll(bfSearchCOSObjectKeyOffsets); } } } } /** * Check if the given object can be found at the given offset. * * @param objectKey the object we are looking for * @param offset the offset where to look * @return returns true if the given object can be dereferenced at the given offset * @throws IOException if something went wrong */ private boolean checkObjectKeys(COSObjectKey objectKey, long offset) throws IOException { // there can't be any object at the very beginning of a pdf if (offset < MINIMUM_SEARCH_OFFSET) { return false; } long objectNr = objectKey.getNumber(); int objectGen = objectKey.getGeneration(); long originOffset = pdfSource.getOffset(); pdfSource.seek(offset); String objectString = createObjectString(objectNr, objectGen); try { if (isString(objectString.getBytes(ISO_8859_1))) { // everything is ok, return origin object key pdfSource.seek(originOffset); return true; } } catch (IOException exception) { // Swallow the exception, obviously there isn't any valid object number } finally { pdfSource.seek(originOffset); } // no valid object number found return false; } /** * Create a string for the given object id. * * @param objectID the object id * @param genID the generation id * @return the generated string */ private String createObjectString(long objectID, int genID) { return Long.toString(objectID) + " " + Integer.toString(genID) + " obj"; } /** * Brute force search for every object in the pdf. * * @throws IOException if something went wrong */ private void bfSearchForObjects() throws IOException { if (bfSearchCOSObjectKeyOffsets == null) { bfSearchCOSObjectKeyOffsets = new HashMap<COSObjectKey, Long>(); long originOffset = pdfSource.getOffset(); long currentOffset = MINIMUM_SEARCH_OFFSET; String objString = " obj"; char[] string = objString.toCharArray(); do { pdfSource.seek(currentOffset); if (isString(string)) { long tempOffset = currentOffset - 1; pdfSource.seek(tempOffset); int genID = pdfSource.peek(); // is the next char a digit? if (isDigit(genID)) { genID -= 48; tempOffset--; pdfSource.seek(tempOffset); if (isSpace()) { while (tempOffset > MINIMUM_SEARCH_OFFSET && isSpace()) { pdfSource.seek(--tempOffset); } int length = 0; while (tempOffset > MINIMUM_SEARCH_OFFSET && isDigit()) { pdfSource.seek(--tempOffset); length++; } if (length > 0) { pdfSource.read(); byte[] objIDBytes = pdfSource.readFully(length); String objIdString = new String(objIDBytes, 0, objIDBytes.length, ISO_8859_1); Long objectID; try { objectID = Long.valueOf(objIdString); } catch (NumberFormatException exception) { objectID = null; } if (objectID != null) { bfSearchCOSObjectKeyOffsets.put(new COSObjectKey(objectID, genID), tempOffset+1); } } } } } currentOffset++; } while (!pdfSource.isEOF()); // reestablish origin position pdfSource.seek(originOffset); } } /** * Search for the offset of the given xref table/stream among those found by a brute force search. * * @param streamsOnly search for xref streams only * @return the offset of the xref entry * @throws IOException if something went wrong */ private long bfSearchForXRef(long xrefOffset, boolean streamsOnly) throws IOException { long newOffset = -1; long newOffsetTable = -1; long newOffsetStream = -1; if (!streamsOnly) { bfSearchForXRefTables(); } bfSearchForXRefStreams(); if (!streamsOnly && bfSearchXRefTablesOffsets != null) { // TODO to be optimized, this won't work in every case newOffsetTable = searchNearestValue(bfSearchXRefTablesOffsets, xrefOffset); } if (bfSearchXRefStreamsOffsets != null) { // TODO to be optimized, this won't work in every case newOffsetStream = searchNearestValue(bfSearchXRefStreamsOffsets, xrefOffset); } // choose the nearest value if (newOffsetTable > -1 && newOffsetStream > -1) { long differenceTable = xrefOffset - newOffsetTable; long differenceStream = xrefOffset - newOffsetStream; if (Math.abs(differenceTable) > Math.abs(differenceStream)) { newOffset = differenceStream; bfSearchXRefStreamsOffsets.remove(newOffsetStream); } else { newOffset = differenceTable; bfSearchXRefTablesOffsets.remove(newOffsetTable); } } else if (newOffsetTable > -1) { newOffset = newOffsetTable; bfSearchXRefTablesOffsets.remove(newOffsetTable); } else if (newOffsetStream > -1) { newOffset = newOffsetStream; bfSearchXRefStreamsOffsets.remove(newOffsetStream); } return newOffset; } private long searchNearestValue(List<Long> values, long offset) { long newValue = -1; long currentDifference = -1; int currentOffsetIndex = -1; int numberOfOffsets = values.size(); // find the nearest value for (int i = 0; i < numberOfOffsets; i++) { long newDifference = offset - values.get(i); // find the nearest offset if (currentDifference == -1 || (Math.abs(currentDifference) > Math.abs(newDifference))) { currentDifference = newDifference; currentOffsetIndex = i; } } if (currentOffsetIndex > -1) { newValue = values.get(currentOffsetIndex); } return newValue; } /** * Brute force search for all xref entries (tables). * * @throws IOException if something went wrong */ private void bfSearchForXRefTables() throws IOException { if (bfSearchXRefTablesOffsets == null) { // a pdf may contain more than one xref entry bfSearchXRefTablesOffsets = new Vector<Long>(); long originOffset = pdfSource.getOffset(); pdfSource.seek(MINIMUM_SEARCH_OFFSET); // search for xref tables while (!pdfSource.isEOF()) { if (isString(XREF_TABLE)) { long newOffset = pdfSource.getOffset(); pdfSource.seek(newOffset - 1); // ensure that we don't read "startxref" instead of "xref" if (isWhitespace()) { bfSearchXRefTablesOffsets.add(newOffset); } pdfSource.seek(newOffset + 4); } pdfSource.read(); } pdfSource.seek(originOffset); } } /** * Brute force search for all /XRef entries (streams). * * @throws IOException if something went wrong */ private void bfSearchForXRefStreams() throws IOException { if (bfSearchXRefStreamsOffsets == null) { // a pdf may contain more than one /XRef entry bfSearchXRefStreamsOffsets = new Vector<Long>(); long originOffset = pdfSource.getOffset(); pdfSource.seek(MINIMUM_SEARCH_OFFSET); // search for XRef streams String objString = " obj"; char[] string = objString.toCharArray(); while (!pdfSource.isEOF()) { if (isString(XREF_STREAM)) { // search backwards for the beginning of the stream long newOffset = -1; long xrefOffset = pdfSource.getOffset(); boolean objFound = false; for (int i = 1; i < 30 && !objFound; i++) { long currentOffset = xrefOffset - (i * 10); if (currentOffset > 0) { pdfSource.seek(currentOffset); for (int j = 0; j < 10; j++) { if (isString(string)) { long tempOffset = currentOffset - 1; pdfSource.seek(tempOffset); int genID = pdfSource.peek(); // is the next char a digit? if (isDigit(genID)) { genID -= 48; tempOffset--; pdfSource.seek(tempOffset); if (isSpace()) { int length = 0; pdfSource.seek(--tempOffset); while (tempOffset > MINIMUM_SEARCH_OFFSET && isDigit()) { pdfSource.seek(--tempOffset); length++; } if (length > 0) { pdfSource.read(); newOffset = pdfSource.getOffset(); } } } LOG.debug("Fixed reference for xref stream " + xrefOffset + " -> " + newOffset); objFound = true; break; } else { currentOffset++; pdfSource.read(); } } } } if (newOffset > -1) { bfSearchXRefStreamsOffsets.add(newOffset); } pdfSource.seek(xrefOffset + 5); } pdfSource.read(); } pdfSource.seek(originOffset); } } /** * Rebuild the trailer dictionary if startxref can't be found. * * @return the rebuild trailer dictionary * * @throws IOException if something went wrong */ protected final COSDictionary rebuildTrailer() throws IOException { COSDictionary trailer = null; bfSearchForObjects(); if (bfSearchCOSObjectKeyOffsets != null) { xrefTrailerResolver.nextXrefObj( 0, XRefType.TABLE ); for (COSObjectKey objectKey : bfSearchCOSObjectKeyOffsets.keySet()) { xrefTrailerResolver.setXRef(objectKey, bfSearchCOSObjectKeyOffsets.get(objectKey)); } xrefTrailerResolver.setStartxref(0); trailer = xrefTrailerResolver.getTrailer(); getDocument().setTrailer(trailer); // search for the different parts of the trailer dictionary for(COSObjectKey key : bfSearchCOSObjectKeyOffsets.keySet()) { Long offset = bfSearchCOSObjectKeyOffsets.get(key); pdfSource.seek(offset); readObjectNumber(); readGenerationNumber(); readExpectedString(OBJ_MARKER, true); try { COSDictionary dictionary = parseCOSDictionary(); if (dictionary != null) { // document catalog if (COSName.CATALOG.equals(dictionary.getCOSName(COSName.TYPE))) { trailer.setItem(COSName.ROOT, document.getObjectFromPool(key)); } // info dictionary else if (dictionary.containsKey(COSName.TITLE) || dictionary.containsKey(COSName.AUTHOR) || dictionary.containsKey(COSName.SUBJECT) || dictionary.containsKey(COSName.KEYWORDS) || dictionary.containsKey(COSName.CREATOR) || dictionary.containsKey(COSName.PRODUCER) || dictionary.containsKey(COSName.CREATION_DATE)) { trailer.setItem(COSName.INFO, document.getObjectFromPool(key)); } // TODO encryption dictionary } } catch(IOException exception) { LOG.debug("Skipped object "+key+", either it's corrupt or not a dictionary"); } } } return trailer; } /** * This will parse the startxref section from the stream. * The startxref value is ignored. * * @return the startxref value or -1 on parsing error * @throws IOException If an IO error occurs. */ private long parseStartXref() throws IOException { long startXref = -1; if (isString(STARTXREF)) { readString(); skipSpaces(); // This integer is the byte offset of the first object referenced by the xref or xref stream startXref = readLong(); } return startXref; } /** * Checks if the given string can be found at the current offset. * * @param string the bytes of the string to look for * @return true if the bytes are in place, false if not * @throws IOException if something went wrong */ private boolean isString(byte[] string) throws IOException { boolean bytesMatching = false; if (pdfSource.peek() == string[0]) { int length = string.length; byte[] bytesRead = new byte[length]; int numberOfBytes = pdfSource.read(bytesRead, 0, length); while (numberOfBytes < length) { int readMore = pdfSource.read(bytesRead, numberOfBytes, length - numberOfBytes); if (readMore < 0) { break; } numberOfBytes += readMore; } if (Arrays.equals(string, bytesRead)) { bytesMatching = true; } pdfSource.unread(bytesRead, 0, numberOfBytes); } return bytesMatching; } /** * Checks if the given string can be found at the current offset. * * @param string the bytes of the string to look for * @return true if the bytes are in place, false if not * @throws IOException if something went wrong */ private boolean isString(char[] string) throws IOException { boolean bytesMatching = true; long originOffset = pdfSource.getOffset(); for (char c : string) { if (pdfSource.read() != c) { bytesMatching = false; } } pdfSource.seek(originOffset); return bytesMatching; } /** * This will parse the trailer from the stream and add it to the state. * * @return false on parsing error * @throws IOException If an IO error occurs. */ private boolean parseTrailer() throws IOException { if(pdfSource.peek() != 't') { return false; } //read "trailer" long currentOffset = pdfSource.getOffset(); String nextLine = readLine(); if( !nextLine.trim().equals( "trailer" ) ) { // in some cases the EOL is missing and the trailer immediately // continues with "<<" or with a blank character // even if this does not comply with PDF reference we want to support as many PDFs as possible // Acrobat reader can also deal with this. if (nextLine.startsWith("trailer")) { // we can't just unread a portion of the read data as we don't know if the EOL consist of 1 or 2 bytes int len = "trailer".length(); // jump back right after "trailer" pdfSource.seek(currentOffset + len); } else { return false; } } // in some cases the EOL is missing and the trailer continues with " <<" // even if this does not comply with PDF reference we want to support as many PDFs as possible // Acrobat reader can also deal with this. skipSpaces(); COSDictionary parsedTrailer = parseCOSDictionary(); xrefTrailerResolver.setTrailer( parsedTrailer ); skipSpaces(); return true; } /** * Parse the header of a pdf. * * @return true if a PDF header was found * @throws IOException if something went wrong */ protected boolean parsePDFHeader() throws IOException { return parseHeader(PDF_HEADER, PDF_DEFAULT_VERSION); } /** * Parse the header of a fdf. * * @return true if a FDF header was found * @throws IOException if something went wrong */ protected boolean parseFDFHeader() throws IOException { return parseHeader(FDF_HEADER, FDF_DEFAULT_VERSION); } private boolean parseHeader(String headerMarker, String defaultVersion) throws IOException { // read first line String header = readLine(); // some pdf-documents are broken and the pdf-version is in one of the following lines if (!header.contains(headerMarker)) { if (header.contains(headerMarker.substring(1))) { document.setNonValidHeader(true); } header = readLine(); while (!header.contains(headerMarker) && !header.contains(headerMarker.substring(1))) { // if a line starts with a digit, it has to be the first one with data in it if ((header.length() > 0) && (Character.isDigit(header.charAt(0)))) { break; } header = readLine(); } } else if (header.charAt(0) != '%') { document.setNonValidHeader(true); } // nothing found if (!header.contains(headerMarker)) { pdfSource.seek(0); return false; } //sometimes there is some garbage in the header before the header //actually starts, so lets try to find the header first. int headerStart = header.indexOf( headerMarker ); // greater than zero because if it is zero then there is no point of trimming if ( headerStart > 0 ) { //trim off any leading characters header = header.substring( headerStart, header.length() ); } // This is used if there is garbage after the header on the same line if (header.startsWith(headerMarker) && !header.matches(headerMarker + "\\d.\\d")) { if (header.length() < headerMarker.length() + 3) { // No version number at all, set to 1.4 as default header = headerMarker + defaultVersion; LOG.debug("No version found, set to " + defaultVersion + " as default."); } else { String headerGarbage = header.substring(headerMarker.length() + 3, header.length()) + "\n"; header = header.substring(0, headerMarker.length() + 3); pdfSource.unread(headerGarbage.getBytes(ISO_8859_1)); } } float headerVersion = -1; try { String[] headerParts = header.split("-"); if (headerParts.length == 2) { headerVersion = Float.parseFloat(headerParts[1]); } } catch (NumberFormatException exception) { LOG.debug("Can't parse the header version.", exception); } if (headerVersion < 0) { throw new IOException( "Error getting header version: " + header); } document.setVersion(headerVersion); checkComment(); // rewind pdfSource.seek(0); return true; } /** check second line of pdf header */ private void checkComment() throws IOException { String comment = readLine(); if (comment.charAt(0) != '%') { document.setNonValidCommentStart(true); } Integer pos = comment.indexOf('%') > -1 ? comment.indexOf('%') + 1 : 0; if (comment.substring(pos).trim().length() < 4) { document.setNonValidCommentLength(true); } Integer repetition = Math.min(4, comment.substring(pos).length()); for (int i = 0; i < repetition; i++, pos++) { if ((int)comment.charAt(pos) < 128) { document.setNonValidCommentContent(true); break; } } } /** * This will parse the xref table from the stream and add it to the state * The XrefTable contents are ignored. * @param startByteOffset the offset to start at * @return false on parsing error * @throws IOException If an IO error occurs. */ protected boolean parseXrefTable(long startByteOffset) throws IOException { if(pdfSource.peek() != 'x') { return false; } String xref = readString(); if( !xref.trim().equals( "xref" ) ) { return false; } // check for trailer after xref String str = readString(); byte[] b = str.getBytes(ISO_8859_1); pdfSource.unread(b, 0, b.length); // signal start of new XRef xrefTrailerResolver.nextXrefObj( startByteOffset, XRefType.TABLE ); if (str.startsWith("trailer")) { LOG.warn("skipping empty xref table"); return false; } // Xref tables can have multiple sections. Each starts with a starting object id and a count. while(true) { // first obj id long currObjID = readObjectNumber(); // the number of objects in the xref table long count = readLong(); skipSpaces(); for(int i = 0; i < count; i++) { if(pdfSource.isEOF() || isEndOfName((char)pdfSource.peek())) { break; } if(pdfSource.peek() == 't') { break; } //Ignore table contents String currentLine = readLine(); String[] splitString = currentLine.split("\\s"); if (splitString.length < 3) { LOG.warn("invalid xref line: " + currentLine); break; } /* This supports the corrupt table as reported in * PDFBOX-474 (XXXX XXX XX n) */ if(splitString[splitString.length-1].equals("n")) { try { int currOffset = Integer.parseInt(splitString[0]); int currGenID = Integer.parseInt(splitString[1]); COSObjectKey objKey = new COSObjectKey(currObjID, currGenID); xrefTrailerResolver.setXRef(objKey, currOffset); } catch(NumberFormatException e) { throw new IOException(e); } } else if(!splitString[2].equals("f")) { throw new IOException("Corrupt XRefTable Entry - ObjID:" + currObjID); } currObjID++; skipSpaces(); } skipSpaces(); if (!isDigit()) { break; } } return true; } /** * Fills XRefTrailerResolver with data of given stream. * Stream must be of type XRef. * @param stream the stream to be read * @param objByteOffset the offset to start at * @param isStandalone should be set to true if the stream is not part of a hybrid xref table * @throws IOException if there is an error parsing the stream */ private void parseXrefStream(COSStream stream, long objByteOffset, boolean isStandalone) throws IOException { // the cross reference stream of a hybrid xref table will be added to the existing one // and we must not override the offset and the trailer if ( isStandalone ) { xrefTrailerResolver.nextXrefObj( objByteOffset, XRefType.STREAM ); xrefTrailerResolver.setTrailer(stream); } PDFXrefStreamParser parser = new PDFXrefStreamParser( stream, document, xrefTrailerResolver ); parser.parse(); parser.close(); } /** * This will get the document that was parsed. parse() must be called before this is called. * When you are done with this document you must call close() on it to release * resources. * * @return The document that was parsed. * * @throws IOException If there is an error getting the document. */ public COSDocument getDocument() throws IOException { if( document == null ) { throw new IOException( "You must call parse() before calling getDocument()" ); } return document; } /** * Create a temporary file with the input stream. The caller must take care * to delete this file at end of the parse method. * * @param input * @return the temporary file * @throws IOException If something went wrong. */ File createTmpFile(InputStream input) throws IOException { FileOutputStream fos = null; try { File tmpFile = File.createTempFile(TMP_FILE_PREFIX, ".pdf"); fos = new FileOutputStream(tmpFile); IOUtils.copy(input, fos); return tmpFile; } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(fos); } } /** * Parse the values of the trailer dictionary and return the root object. * * @param trailer The trailer dictionary. * @return The parsed root object. * @throws IOException If an IO error occurs or if the root object is * missing in the trailer dictionary. */ protected COSBase parseTrailerValuesDynamically(COSDictionary trailer) throws IOException { // PDFBOX-1557 - ensure that all COSObject are loaded in the trailer // PDFBOX-1606 - after securityHandler has been instantiated for (COSBase trailerEntry : trailer.getValues()) { if (trailerEntry instanceof COSObject) { COSObject tmpObj = (COSObject) trailerEntry; parseObjectDynamically(tmpObj, false); } } // parse catalog or root object COSObject root = (COSObject) trailer.getItem(COSName.ROOT); if (root == null) { throw new IOException("Missing root object specification in trailer."); } return parseObjectDynamically(root, false); } /** * @return last trailer in current document */ public COSDictionary getLastTrailer() { return xrefTrailerResolver.getLastTrailer(); } }
pdfbox/src/main/java/org/apache/pdfbox/pdfparser/COSParser.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pdfbox.pdfparser; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Queue; import java.util.Set; import java.util.TreeMap; import java.util.Vector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.cos.COSBase; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSDocument; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.cos.COSNull; import org.apache.pdfbox.cos.COSNumber; import org.apache.pdfbox.cos.COSObject; import org.apache.pdfbox.cos.COSObjectKey; import org.apache.pdfbox.cos.COSStream; import org.apache.pdfbox.io.IOUtils; import org.apache.pdfbox.pdfparser.XrefTrailerResolver.XRefType; import org.apache.pdfbox.pdmodel.encryption.SecurityHandler; import static org.apache.pdfbox.util.Charsets.ISO_8859_1; /** * PDF-Parser which first reads startxref and xref tables in order to know valid objects and parse only these objects. * * First {@link PDFParser#parse()} or {@link FDFParser#parse()} must be called before page objects * can be retrieved, e.g. {@link PDFParser#getPDDocument()}. * * This class is a much enhanced version of <code>QuickParser</code> presented in <a * href="https://issues.apache.org/jira/browse/PDFBOX-1104">PDFBOX-1104</a> by Jeremy Villalobos. */ public class COSParser extends BaseParser { private static final String PDF_HEADER = "%PDF-"; private static final String FDF_HEADER = "%FDF-"; private static final String PDF_DEFAULT_VERSION = "1.4"; private static final String FDF_DEFAULT_VERSION = "1.0"; private static final char[] XREF_TABLE = new char[] { 'x', 'r', 'e', 'f' }; private static final char[] XREF_STREAM = new char[] { '/', 'X', 'R', 'e', 'f' }; private static final char[] STARTXREF = new char[] { 's','t','a','r','t','x','r','e','f' }; private static final long MINIMUM_SEARCH_OFFSET = 6; private static final int X = 'x'; /** * Only parse the PDF file minimally allowing access to basic information. */ public static final String SYSPROP_PARSEMINIMAL = "org.apache.pdfbox.pdfparser.nonSequentialPDFParser.parseMinimal"; /** * The range within the %%EOF marker will be searched. * Useful if there are additional characters after %%EOF within the PDF. */ public static final String SYSPROP_EOFLOOKUPRANGE = "org.apache.pdfbox.pdfparser.nonSequentialPDFParser.eofLookupRange"; /** * How many trailing bytes to read for EOF marker. */ private static final int DEFAULT_TRAIL_BYTECOUNT = 2048; /** * EOF-marker. */ protected static final char[] EOF_MARKER = new char[] { '%', '%', 'E', 'O', 'F' }; /** * obj-marker. */ protected static final char[] OBJ_MARKER = new char[] { 'o', 'b', 'j' }; private long trailerOffset; /** * file length. */ protected long fileLen; /** * is parser using auto healing capacity ? */ private boolean isLenient = true; protected boolean initialParseDone = false; /** * Contains all found objects of a brute force search. */ private Map<COSObjectKey, Long> bfSearchCOSObjectKeyOffsets = null; private List<Long> bfSearchXRefTablesOffsets = null; private List<Long> bfSearchXRefStreamsOffsets = null; /** * The security handler. */ protected SecurityHandler securityHandler = null; /** * how many trailing bytes to read for EOF marker. */ private int readTrailBytes = DEFAULT_TRAIL_BYTECOUNT; private static final Log LOG = LogFactory.getLog(COSParser.class); /** * Collects all Xref/trailer objects and resolves them into single * object using startxref reference. */ protected XrefTrailerResolver xrefTrailerResolver = new XrefTrailerResolver(); /** * The prefix for the temp file being used. */ public static final String TMP_FILE_PREFIX = "tmpPDF"; /** * Default constructor. */ public COSParser() { } /** * Constructor. * * @param input inputStream of the pdf to be read * @throws IOException if something went wrong */ public COSParser(InputStream input) throws IOException { super(input); } /** * Sets how many trailing bytes of PDF file are searched for EOF marker and 'startxref' marker. If not set we use * default value {@link #DEFAULT_TRAIL_BYTECOUNT}. * * <p>We check that new value is at least 16. However for practical use cases this value should not be lower than * 1000; even 2000 was found to not be enough in some cases where some trailing garbage like HTML snippets followed * the EOF marker.</p> * * <p> * In case system property {@link #SYSPROP_EOFLOOKUPRANGE} is defined this value will be set on initialization but * can be overwritten later. * </p> * * @param byteCount number of trailing bytes */ public void setEOFLookupRange(int byteCount) { if (byteCount > 15) { readTrailBytes = byteCount; } } /** * Parses cross reference tables. * * @param startXRefOffset start offset of the first table * @return the trailer dictionary * @throws IOException if something went wrong */ protected COSDictionary parseXref(long startXRefOffset) throws IOException { pdfSource.seek(startXRefOffset); long startXrefOffset = Math.max(0, parseStartXref()); // check the startxref offset long fixedOffset = checkXRefOffset(startXrefOffset); if (fixedOffset > -1) { startXrefOffset = fixedOffset; } document.setStartXref(startXrefOffset); long prev = startXrefOffset; // ---- parse whole chain of xref tables/object streams using PREV reference while (prev > 0) { // seek to xref table pdfSource.seek(prev); // skip white spaces skipSpaces(); // -- parse xref if (pdfSource.peek() == X) { // xref table and trailer // use existing parser to parse xref table parseXrefTable(prev); // parse the last trailer. trailerOffset = pdfSource.getOffset(); // PDFBOX-1739 skip extra xref entries in RegisSTAR documents while (isLenient && pdfSource.peek() != 't') { if (pdfSource.getOffset() == trailerOffset) { // warn only the first time LOG.warn("Expected trailer object at position " + trailerOffset + ", keep trying"); } readLine(); } if (!parseTrailer()) { throw new IOException("Expected trailer object at position: " + pdfSource.getOffset()); } COSDictionary trailer = xrefTrailerResolver.getCurrentTrailer(); // check for a XRef stream, it may contain some object ids of compressed objects if(trailer.containsKey(COSName.XREF_STM)) { int streamOffset = trailer.getInt(COSName.XREF_STM); // check the xref stream reference fixedOffset = checkXRefStreamOffset(streamOffset, false); if (fixedOffset > -1 && fixedOffset != streamOffset) { streamOffset = (int)fixedOffset; trailer.setInt(COSName.XREF_STM, streamOffset); } if (streamOffset > 0) { pdfSource.seek(streamOffset); skipSpaces(); parseXrefObjStream(prev, false); } else { if(isLenient) { LOG.error("Skipped XRef stream due to a corrupt offset:"+streamOffset); } else { throw new IOException("Skipped XRef stream due to a corrupt offset:"+streamOffset); } } } prev = trailer.getInt(COSName.PREV); if (prev > 0) { // check the xref table reference fixedOffset = checkXRefOffset(prev); if (fixedOffset > -1 && fixedOffset != prev) { prev = fixedOffset; trailer.setLong(COSName.PREV, prev); } } } else { // parse xref stream prev = parseXrefObjStream(prev, true); if (prev > 0) { // check the xref table reference fixedOffset = checkXRefOffset(prev); if (fixedOffset > -1 && fixedOffset != prev) { prev = fixedOffset; COSDictionary trailer = xrefTrailerResolver.getCurrentTrailer(); trailer.setLong(COSName.PREV, prev); } } } } // ---- build valid xrefs out of the xref chain xrefTrailerResolver.setStartxref(startXrefOffset); COSDictionary trailer = xrefTrailerResolver.getTrailer(); document.setTrailer(trailer); document.setIsXRefStream(XRefType.STREAM == xrefTrailerResolver.getXrefType()); // check the offsets of all referenced objects checkXrefOffsets(); // copy xref table document.addXRefTable(xrefTrailerResolver.getXrefTable()); return trailer; } /** * Parses an xref object stream starting with indirect object id. * * @return value of PREV item in dictionary or <code>-1</code> if no such item exists */ private long parseXrefObjStream(long objByteOffset, boolean isStandalone) throws IOException { // ---- parse indirect object head readObjectNumber(); readGenerationNumber(); readExpectedString(OBJ_MARKER, true); COSDictionary dict = parseCOSDictionary(); COSStream xrefStream = parseCOSStream(dict); parseXrefStream(xrefStream, (int) objByteOffset, isStandalone); xrefStream.close(); return dict.getLong(COSName.PREV); } /** * Looks for and parses startxref. We first look for last '%%EOF' marker (within last * {@link #DEFAULT_TRAIL_BYTECOUNT} bytes (or range set via {@link #setEOFLookupRange(int)}) and go back to find * <code>startxref</code>. * * @return the offset of StartXref * @throws IOException If something went wrong. */ protected final long getStartxrefOffset() throws IOException { byte[] buf; long skipBytes; // read trailing bytes into buffer try { final int trailByteCount = (fileLen < readTrailBytes) ? (int) fileLen : readTrailBytes; buf = new byte[trailByteCount]; skipBytes = fileLen - trailByteCount; pdfSource.seek(skipBytes); int off = 0; int readBytes; while (off < trailByteCount) { readBytes = pdfSource.read(buf, off, trailByteCount - off); // in order to not get stuck in a loop we check readBytes (this should never happen) if (readBytes < 1) { throw new IOException( "No more bytes to read for trailing buffer, but expected: " + (trailByteCount - off)); } off += readBytes; } } finally { pdfSource.seek(0); } // find last '%%EOF' int bufOff = lastIndexOf(EOF_MARKER, buf, buf.length); if (bufOff < 0) { document.setEofComplyPDFA(false); if (isLenient) { // in lenient mode the '%%EOF' isn't needed bufOff = buf.length; LOG.debug("Missing end of file marker '" + new String(EOF_MARKER) + "'"); } else { throw new IOException("Missing end of file marker '" + new String(EOF_MARKER) + "'"); } } else if (buf.length - bufOff > 6 || (buf.length - bufOff == 6 && buf[buf.length - 1] != '\r' && buf[buf.length - 1] != '\n')) { document.setEofComplyPDFA(false); } // find last startxref preceding EOF marker bufOff = lastIndexOf(STARTXREF, buf, bufOff); long startXRefOffset = skipBytes + bufOff; if (bufOff < 0) { if (isLenient) { LOG.debug("Can't find offset for startxref"); return -1; } else { throw new IOException("Missing 'startxref' marker."); } } return startXRefOffset; } /** * Searches last appearance of pattern within buffer. Lookup before _lastOff and goes back until 0. * * @param pattern pattern to search for * @param buf buffer to search pattern in * @param endOff offset (exclusive) where lookup starts at * * @return start offset of pattern within buffer or <code>-1</code> if pattern could not be found */ protected int lastIndexOf(final char[] pattern, final byte[] buf, final int endOff) { final int lastPatternChOff = pattern.length - 1; int bufOff = endOff; int patOff = lastPatternChOff; char lookupCh = pattern[patOff]; while (--bufOff >= 0) { if (buf[bufOff] == lookupCh) { if (--patOff < 0) { // whole pattern matched return bufOff; } // matched current char, advance to preceding one lookupCh = pattern[patOff]; } else if (patOff < lastPatternChOff) { // no char match but already matched some chars; reset patOff = lastPatternChOff; lookupCh = pattern[patOff]; } } return -1; } /** * Return true if parser is lenient. Meaning auto healing capacity of the parser are used. * * @return true if parser is lenient */ public boolean isLenient() { return isLenient; } /** * Change the parser leniency flag. * * This method can only be called before the parsing of the file. * * @param lenient try to handle malformed PDFs. * */ public void setLenient(boolean lenient) { if (initialParseDone) { throw new IllegalArgumentException("Cannot change leniency after parsing"); } this.isLenient = lenient; } /** * Creates a unique object id using object number and object generation * number. (requires object number &lt; 2^31)) */ private long getObjectId(final COSObject obj) { return obj.getObjectNumber() << 32 | obj.getGenerationNumber(); } /** * Adds all from newObjects to toBeParsedList if it is not an COSObject or * we didn't add this COSObject already (checked via addedObjects). */ private void addNewToList(final Queue<COSBase> toBeParsedList, final Collection<COSBase> newObjects, final Set<Long> addedObjects) { for (COSBase newObject : newObjects) { addNewToList(toBeParsedList, newObject, addedObjects); } } /** * Adds newObject to toBeParsedList if it is not an COSObject or we didn't * add this COSObject already (checked via addedObjects). */ private void addNewToList(final Queue<COSBase> toBeParsedList, final COSBase newObject, final Set<Long> addedObjects) { if (newObject instanceof COSObject) { final long objId = getObjectId((COSObject) newObject); if (!addedObjects.add(objId)) { return; } } toBeParsedList.add(newObject); } /** * Will parse every object necessary to load a single page from the pdf document. We try our * best to order objects according to offset in file before reading to minimize seek operations. * * @param dict the COSObject from the parent pages. * @param excludeObjects dictionary object reference entries with these names will not be parsed * * @throws IOException if something went wrong */ protected void parseDictObjects(COSDictionary dict, COSName... excludeObjects) throws IOException { // ---- create queue for objects waiting for further parsing final Queue<COSBase> toBeParsedList = new LinkedList<COSBase>(); // offset ordered object map final TreeMap<Long, List<COSObject>> objToBeParsed = new TreeMap<Long, List<COSObject>>(); // in case of compressed objects offset points to stmObj final Set<Long> parsedObjects = new HashSet<Long>(); final Set<Long> addedObjects = new HashSet<Long>(); addExcludedToList(excludeObjects, dict, parsedObjects); addNewToList(toBeParsedList, dict.getValues(), addedObjects); // ---- go through objects to be parsed while (!(toBeParsedList.isEmpty() && objToBeParsed.isEmpty())) { // -- first get all COSObject from other kind of objects and // put them in objToBeParsed; afterwards toBeParsedList is empty COSBase baseObj; while ((baseObj = toBeParsedList.poll()) != null) { if (baseObj instanceof COSDictionary) { addNewToList(toBeParsedList, ((COSDictionary) baseObj).getValues(), addedObjects); } else if (baseObj instanceof COSArray) { final Iterator<COSBase> arrIter = ((COSArray) baseObj).iterator(); while (arrIter.hasNext()) { addNewToList(toBeParsedList, arrIter.next(), addedObjects); } } else if (baseObj instanceof COSObject) { COSObject obj = (COSObject) baseObj; long objId = getObjectId(obj); COSObjectKey objKey = new COSObjectKey(obj.getObjectNumber(), obj.getGenerationNumber()); if (!parsedObjects.contains(objId)) { Long fileOffset = xrefTrailerResolver.getXrefTable().get(objKey); // it is allowed that object references point to null, // thus we have to test if (fileOffset != null && fileOffset != 0) { if (fileOffset > 0) { objToBeParsed.put(fileOffset, Collections.singletonList(obj)); } else { // negative offset means we have a compressed // object within object stream; // get offset of object stream fileOffset = xrefTrailerResolver.getXrefTable().get( new COSObjectKey((int)-fileOffset, 0)); if ((fileOffset == null) || (fileOffset <= 0)) { throw new IOException( "Invalid object stream xref object reference for key '" + objKey + "': " + fileOffset); } List<COSObject> stmObjects = objToBeParsed.get(fileOffset); if (stmObjects == null) { stmObjects = new ArrayList<COSObject>(); objToBeParsed.put(fileOffset, stmObjects); } stmObjects.add(obj); } } else { // NULL object COSObject pdfObject = document.getObjectFromPool(objKey); pdfObject.setObject(COSNull.NULL); } } } } // ---- read first COSObject with smallest offset // resulting object will be added to toBeParsedList if (objToBeParsed.isEmpty()) { break; } for (COSObject obj : objToBeParsed.remove(objToBeParsed.firstKey())) { COSBase parsedObj = parseObjectDynamically(obj, false); obj.setObject(parsedObj); addNewToList(toBeParsedList, parsedObj, addedObjects); parsedObjects.add(getObjectId(obj)); } } } // add objects not to be parsed to list of already parsed objects private void addExcludedToList(COSName[] excludeObjects, COSDictionary dict, final Set<Long> parsedObjects) { if (excludeObjects != null) { for (COSName objName : excludeObjects) { COSBase baseObj = dict.getItem(objName); if (baseObj instanceof COSObject) { parsedObjects.add(getObjectId((COSObject) baseObj)); } } } } /** * This will parse the next object from the stream and add it to the local state. * * @param obj object to be parsed (we only take object number and generation number for lookup start offset) * @param requireExistingNotCompressedObj if <code>true</code> object to be parsed must not be contained within * compressed stream * @return the parsed object (which is also added to document object) * * @throws IOException If an IO error occurs. */ protected final COSBase parseObjectDynamically(COSObject obj, boolean requireExistingNotCompressedObj) throws IOException { return parseObjectDynamically(obj.getObjectNumber(), obj.getGenerationNumber(), requireExistingNotCompressedObj); } /** * This will parse the next object from the stream and add it to the local state. * It's reduced to parsing an indirect object. * * @param objNr object number of object to be parsed * @param objGenNr object generation number of object to be parsed * @param requireExistingNotCompressedObj if <code>true</code> the object to be parsed must be defined in xref * (comment: null objects may be missing from xref) and it must not be a compressed object within object stream * (this is used to circumvent being stuck in a loop in a malicious PDF) * * @return the parsed object (which is also added to document object) * * @throws IOException If an IO error occurs. */ protected COSBase parseObjectDynamically(long objNr, int objGenNr, boolean requireExistingNotCompressedObj) throws IOException { // ---- create object key and get object (container) from pool final COSObjectKey objKey = new COSObjectKey(objNr, objGenNr); final COSObject pdfObject = document.getObjectFromPool(objKey); if (pdfObject.getObject() == null) { // not previously parsed // ---- read offset or object stream object number from xref table Long offsetOrObjstmObNr = xrefTrailerResolver.getXrefTable().get(objKey); // sanity test to circumvent loops with broken documents if (requireExistingNotCompressedObj && ((offsetOrObjstmObNr == null) || (offsetOrObjstmObNr <= 0))) { throw new IOException("Object must be defined and must not be compressed object: " + objKey.getNumber() + ":" + objKey.getGeneration()); } if (offsetOrObjstmObNr == null) { // not defined object -> NULL object (Spec. 1.7, chap. 3.2.9) pdfObject.setObject(COSNull.NULL); } else if (offsetOrObjstmObNr > 0) { // offset of indirect object in file parseFileObject(offsetOrObjstmObNr, objKey, objNr, objGenNr, pdfObject); } else { // xref value is object nr of object stream containing object to be parsed // since our object was not found it means object stream was not parsed so far parseObjectStream((int) -offsetOrObjstmObNr); } } return pdfObject.getObject(); } private void parseFileObject(Long offsetOrObjstmObNr, final COSObjectKey objKey, long objNr, int objGenNr, final COSObject pdfObject) throws IOException { // ---- go to object start pdfSource.seek(offsetOrObjstmObNr - 1); if (!isEOL(pdfSource.read())) { pdfObject.setHeaderOfObjectComplyPDFA(false); } // ---- we must have an indirect object final long readObjNr = readObjectNumber(); if ((pdfSource.read() != 32) || skipSpaces() > 0) { pdfObject.setHeaderFormatComplyPDFA(false); } final int readObjGen = readGenerationNumber(); if ((pdfSource.read() != 32) || skipSpaces() > 0) { pdfObject.setHeaderFormatComplyPDFA(false); } readExpectedString(OBJ_MARKER, true); // ---- consistency check if ((readObjNr != objKey.getNumber()) || (readObjGen != objKey.getGeneration())) { throw new IOException("XREF for " + objKey.getNumber() + ":" + objKey.getGeneration() + " points to wrong object: " + readObjNr + ":" + readObjGen); } if (!isEOL()) { pdfObject.setHeaderOfObjectComplyPDFA(false); } COSBase pb = parseDirObject(); skipSpaces(); pdfSource.seek(pdfSource.getOffset() - 1); int whiteSpace = pdfSource.read(); String endObjectKey = readString(); if (endObjectKey.equals(STREAM_STRING)) { pdfSource.unread(endObjectKey.getBytes(ISO_8859_1)); pdfSource.unread(' '); if (pb instanceof COSDictionary) { COSStream stream = parseCOSStream((COSDictionary) pb); if (securityHandler != null) { securityHandler.decryptStream(stream, objNr, objGenNr); } pb = stream; } else { // this is not legal // the combination of a dict and the stream/endstream // forms a complete stream object throw new IOException("Stream not preceded by dictionary (offset: " + offsetOrObjstmObNr + ")."); } skipSpaces(); pdfSource.seek(pdfSource.getOffset() - 1); whiteSpace = pdfSource.read(); endObjectKey = readLineWithoutSkip(); // we have case with a second 'endstream' before endobj if (!endObjectKey.startsWith(ENDOBJ_STRING) && endObjectKey.startsWith(ENDSTREAM_STRING)) { endObjectKey = endObjectKey.substring(9).trim(); if (endObjectKey.length() == 0) { // no other characters in extra endstream line // read next line whiteSpace = pdfSource.read(); skipSpaces(); endObjectKey = readLineWithoutSkip(); } } } else if (securityHandler != null) { securityHandler.decrypt(pb, objNr, objGenNr); } if (!isEOL(whiteSpace)) { pdfObject.setEndOfObjectComplyPDFA(false); } pdfObject.setObject(pb); if (!endObjectKey.startsWith(ENDOBJ_STRING)) { if (isLenient) { LOG.warn("Object (" + readObjNr + ":" + readObjGen + ") at offset " + offsetOrObjstmObNr + " does not end with 'endobj' but with '" + endObjectKey + "'"); } else { throw new IOException("Object (" + readObjNr + ":" + readObjGen + ") at offset " + offsetOrObjstmObNr + " does not end with 'endobj' but with '" + endObjectKey + "'"); } } whiteSpace = pdfSource.read(); if (!isEOL(whiteSpace)) { pdfObject.setEndOfObjectComplyPDFA(false); pdfSource.unread(whiteSpace); } } private void parseObjectStream(int objstmObjNr) throws IOException { final COSBase objstmBaseObj = parseObjectDynamically(objstmObjNr, 0, true); if (objstmBaseObj instanceof COSStream) { // parse object stream PDFObjectStreamParser parser = new PDFObjectStreamParser((COSStream) objstmBaseObj, document); parser.parse(); parser.close(); // get set of object numbers referenced for this object stream final Set<Long> refObjNrs = xrefTrailerResolver.getContainedObjectNumbers(objstmObjNr); // register all objects which are referenced to be contained in object stream for (COSObject next : parser.getObjects()) { COSObjectKey stmObjKey = new COSObjectKey(next); if (refObjNrs.contains(stmObjKey.getNumber())) { COSObject stmObj = document.getObjectFromPool(stmObjKey); stmObj.setObject(next.getObject()); } } } } private boolean inGetLength = false; /** * Returns length value referred to or defined in given object. */ private COSNumber getLength(final COSBase lengthBaseObj) throws IOException { if (lengthBaseObj == null) { return null; } if (inGetLength) { throw new IOException("Loop while reading length from " + lengthBaseObj); } COSNumber retVal = null; try { inGetLength = true; // maybe length was given directly if (lengthBaseObj instanceof COSNumber) { retVal = (COSNumber) lengthBaseObj; } // length in referenced object else if (lengthBaseObj instanceof COSObject) { COSObject lengthObj = (COSObject) lengthBaseObj; if (lengthObj.getObject() == null) { // not read so far, keep current stream position final long curFileOffset = pdfSource.getOffset(); parseObjectDynamically(lengthObj, true); // reset current stream position pdfSource.seek(curFileOffset); if (lengthObj.getObject() == null) { throw new IOException("Length object content was not read."); } } if (!(lengthObj.getObject() instanceof COSNumber)) { throw new IOException("Wrong type of referenced length object " + lengthObj + ": " + lengthObj.getObject().getClass().getSimpleName()); } retVal = (COSNumber) lengthObj.getObject(); } else { throw new IOException("Wrong type of length object: " + lengthBaseObj.getClass().getSimpleName()); } } finally { inGetLength = false; } return retVal; } private static final int STREAMCOPYBUFLEN = 8192; private final byte[] streamCopyBuf = new byte[STREAMCOPYBUFLEN]; /** * This will read a COSStream from the input stream using length attribute within dictionary. If * length attribute is a indirect reference it is first resolved to get the stream length. This * means we copy stream data without testing for 'endstream' or 'endobj' and thus it is no * problem if these keywords occur within stream. We require 'endstream' to be found after * stream data is read. * * @param dic dictionary that goes with this stream. * * @return parsed pdf stream. * * @throws IOException if an error occurred reading the stream, like problems with reading * length attribute, stream does not end with 'endstream' after data read, stream too short etc. */ protected COSStream parseCOSStream(COSDictionary dic) throws IOException { final COSStream stream = document.createCOSStream(dic); OutputStream out = null; try { // read 'stream'; this was already tested in parseObjectsDynamically() readString(); checkStreamSpacings(stream); stream.setOriginLength(pdfSource.getOffset()); skipWhiteSpaces(); /* * This needs to be dic.getItem because when we are parsing, the underlying object might still be null. */ COSNumber streamLengthObj = getLength(dic.getItem(COSName.LENGTH)); if (streamLengthObj == null) { if (isLenient) { LOG.warn("The stream doesn't provide any stream length, using fallback readUntilEnd, at offset " + pdfSource.getOffset()); } else { throw new IOException("Missing length for stream."); } } // get output stream to copy data to if (streamLengthObj != null && validateStreamLength(streamLengthObj.longValue())) { out = stream.createFilteredStream(streamLengthObj); readValidStream(out, streamLengthObj); } else { out = stream.createFilteredStream(); readUntilEndStream(new EndstreamOutputStream(out)); } checkEndStreamSpacings(stream); String endStream = readString(); if (endStream.equals("endobj") && isLenient) { LOG.warn("stream ends with 'endobj' instead of 'endstream' at offset " + pdfSource.getOffset()); stream.setEndStreamSpacingsComplyPDFA(false); // avoid follow-up warning about missing endobj pdfSource.unread(ENDOBJ); } else if (endStream.length() > 9 && isLenient && endStream.substring(0,9).equals(ENDSTREAM_STRING)) { LOG.warn("stream ends with '" + endStream + "' instead of 'endstream' at offset " + pdfSource.getOffset()); stream.setEndStreamSpacingsComplyPDFA(false); // unread the "extra" bytes pdfSource.unread(endStream.substring(9).getBytes(ISO_8859_1)); } else if (!endStream.equals(ENDSTREAM_STRING)) { throw new IOException( "Error reading stream, expected='endstream' actual='" + endStream + "' at offset " + pdfSource.getOffset()); } } finally { if (out != null) { out.close(); } } return stream; } private void checkStreamSpacings(COSStream stream) throws IOException { int whiteSpace = pdfSource.read(); if (whiteSpace == 13) { whiteSpace = pdfSource.read(); if (whiteSpace != 10) { stream.setStreamSpacingsComplyPDFA(false); pdfSource.unread(whiteSpace); } } else if (whiteSpace != 10) { LOG.warn("Stream at " + pdfSource.getOffset() + " offset has no EOL marker."); stream.setStreamSpacingsComplyPDFA(false); pdfSource.unread(whiteSpace); } } private void checkEndStreamSpacings(COSStream stream) throws IOException { byte eolCount = 0; skipSpaces(); pdfSource.seek(pdfSource.getOffset() - 2); int firstSymbol = pdfSource.read(); int secondSymbol = pdfSource.read(); if (secondSymbol == 10) { if (firstSymbol == 13) { eolCount = 2; } else { eolCount = 1; } } else if (secondSymbol == 13) { eolCount = 1; } else { LOG.warn("End of stream at " + pdfSource.getOffset() + " offset has no contain EOL marker."); stream.setEndStreamSpacingsComplyPDFA(false); } stream.setOriginLength(pdfSource.getOffset() - stream.getOriginLength() - eolCount); } private void readValidStream(OutputStream out, COSNumber streamLengthObj) throws IOException { long remainBytes = streamLengthObj.longValue(); while (remainBytes > 0) { final int chunk = (remainBytes > STREAMCOPYBUFLEN) ? STREAMCOPYBUFLEN : (int) remainBytes; final int readBytes = pdfSource.read(streamCopyBuf, 0, chunk); if (readBytes <= 0) { // shouldn't happen, the stream length has already been validated throw new IOException("read error at offset " + pdfSource.getOffset() + ": expected " + chunk + " bytes, but read() returns " + readBytes); } out.write(streamCopyBuf, 0, readBytes); remainBytes -= readBytes; } } private boolean validateStreamLength(long streamLength) throws IOException { boolean streamLengthIsValid = true; long originOffset = pdfSource.getOffset(); long expectedEndOfStream = originOffset + streamLength; if (expectedEndOfStream > fileLen) { streamLengthIsValid = false; LOG.error("The end of the stream is out of range, using workaround to read the stream, " + "found " + originOffset + " but expected " + expectedEndOfStream); } else { pdfSource.seek(expectedEndOfStream); skipSpaces(); if (!isString(ENDSTREAM)) { streamLengthIsValid = false; LOG.error("The end of the stream doesn't point to the correct offset, using workaround to read the stream, " + "found " + originOffset + " but expected " + expectedEndOfStream); } pdfSource.seek(originOffset); } return streamLengthIsValid; } /** * Check if the cross reference table/stream can be found at the current offset. * * @param startXRefOffset * @return the revised offset * @throws IOException */ private long checkXRefOffset(long startXRefOffset) throws IOException { // repair mode isn't available in non-lenient mode if (!isLenient) { return startXRefOffset; } pdfSource.seek(startXRefOffset); if (pdfSource.peek() == X && isString(XREF_TABLE)) { return startXRefOffset; } if (startXRefOffset > 0) { long fixedOffset = checkXRefStreamOffset(startXRefOffset, true); if (fixedOffset > -1) { return fixedOffset; } } // try to find a fixed offset return calculateXRefFixedOffset(startXRefOffset, false); } /** * Check if the cross reference stream can be found at the current offset. * * @param startXRefOffset the expected start offset of the XRef stream * @param checkOnly check only but don't repair the offset if set to true * @return the revised offset * @throws IOException if something went wrong */ private long checkXRefStreamOffset(long startXRefOffset, boolean checkOnly) throws IOException { // repair mode isn't available in non-lenient mode if (!isLenient || startXRefOffset == 0) { return startXRefOffset; } // seek to offset-1 pdfSource.seek(startXRefOffset-1); int nextValue = pdfSource.read(); // the first character has to be a whitespace, and then a digit if (isWhitespace(nextValue) && isDigit()) { try { // it's a XRef stream readObjectNumber(); readGenerationNumber(); readExpectedString(OBJ_MARKER, true); pdfSource.seek(startXRefOffset); return startXRefOffset; } catch (IOException exception) { // there wasn't an object of a xref stream // try to repair the offset pdfSource.seek(startXRefOffset); } } // try to find a fixed offset return checkOnly ? -1 : calculateXRefFixedOffset(startXRefOffset, true); } /** * Try to find a fixed offset for the given xref table/stream. * * @param objectOffset the given offset where to look at * @param streamsOnly search for xref streams only * @return the fixed offset * * @throws IOException if something went wrong */ private long calculateXRefFixedOffset(long objectOffset, boolean streamsOnly) throws IOException { if (objectOffset < 0) { LOG.error("Invalid object offset " + objectOffset + " when searching for a xref table/stream"); return 0; } // start a brute force search for all xref tables and try to find the offset we are looking for long newOffset = bfSearchForXRef(objectOffset, streamsOnly); if (newOffset > -1) { LOG.debug("Fixed reference for xref table/stream " + objectOffset + " -> " + newOffset); return newOffset; } LOG.error("Can't find the object axref table/stream at offset " + objectOffset); return 0; } /** * Check the XRef table by dereferencing all objects and fixing the offset if necessary. * * @throws IOException if something went wrong. */ private void checkXrefOffsets() throws IOException { // repair mode isn't available in non-lenient mode if (!isLenient) { return; } Map<COSObjectKey, Long> xrefOffset = xrefTrailerResolver.getXrefTable(); if (xrefOffset != null) { boolean bruteForceSearch = false; for (Entry<COSObjectKey, Long> objectEntry : xrefOffset.entrySet()) { COSObjectKey objectKey = objectEntry.getKey(); Long objectOffset = objectEntry.getValue(); // a negative offset number represents a object number itself // see type 2 entry in xref stream if (objectOffset != null && objectOffset >= 0 && !checkObjectKeys(objectKey, objectOffset)) { LOG.debug("Stop checking xref offsets as at least one couldn't be dereferenced"); bruteForceSearch = true; break; } } if (bruteForceSearch) { bfSearchForObjects(); if (bfSearchCOSObjectKeyOffsets != null && !bfSearchCOSObjectKeyOffsets.isEmpty()) { LOG.debug("Replaced read xref table with the results of a brute force search"); xrefOffset.putAll(bfSearchCOSObjectKeyOffsets); } } } } /** * Check if the given object can be found at the given offset. * * @param objectKey the object we are looking for * @param offset the offset where to look * @return returns true if the given object can be dereferenced at the given offset * @throws IOException if something went wrong */ private boolean checkObjectKeys(COSObjectKey objectKey, long offset) throws IOException { // there can't be any object at the very beginning of a pdf if (offset < MINIMUM_SEARCH_OFFSET) { return false; } long objectNr = objectKey.getNumber(); int objectGen = objectKey.getGeneration(); long originOffset = pdfSource.getOffset(); pdfSource.seek(offset); String objectString = createObjectString(objectNr, objectGen); try { if (isString(objectString.getBytes(ISO_8859_1))) { // everything is ok, return origin object key pdfSource.seek(originOffset); return true; } } catch (IOException exception) { // Swallow the exception, obviously there isn't any valid object number } finally { pdfSource.seek(originOffset); } // no valid object number found return false; } /** * Create a string for the given object id. * * @param objectID the object id * @param genID the generation id * @return the generated string */ private String createObjectString(long objectID, int genID) { return Long.toString(objectID) + " " + Integer.toString(genID) + " obj"; } /** * Brute force search for every object in the pdf. * * @throws IOException if something went wrong */ private void bfSearchForObjects() throws IOException { if (bfSearchCOSObjectKeyOffsets == null) { bfSearchCOSObjectKeyOffsets = new HashMap<COSObjectKey, Long>(); long originOffset = pdfSource.getOffset(); long currentOffset = MINIMUM_SEARCH_OFFSET; String objString = " obj"; char[] string = objString.toCharArray(); do { pdfSource.seek(currentOffset); if (isString(string)) { long tempOffset = currentOffset - 1; pdfSource.seek(tempOffset); int genID = pdfSource.peek(); // is the next char a digit? if (isDigit(genID)) { genID -= 48; tempOffset--; pdfSource.seek(tempOffset); if (isSpace()) { while (tempOffset > MINIMUM_SEARCH_OFFSET && isSpace()) { pdfSource.seek(--tempOffset); } int length = 0; while (tempOffset > MINIMUM_SEARCH_OFFSET && isDigit()) { pdfSource.seek(--tempOffset); length++; } if (length > 0) { pdfSource.read(); byte[] objIDBytes = pdfSource.readFully(length); String objIdString = new String(objIDBytes, 0, objIDBytes.length, ISO_8859_1); Long objectID; try { objectID = Long.valueOf(objIdString); } catch (NumberFormatException exception) { objectID = null; } if (objectID != null) { bfSearchCOSObjectKeyOffsets.put(new COSObjectKey(objectID, genID), tempOffset+1); } } } } } currentOffset++; } while (!pdfSource.isEOF()); // reestablish origin position pdfSource.seek(originOffset); } } /** * Search for the offset of the given xref table/stream among those found by a brute force search. * * @param streamsOnly search for xref streams only * @return the offset of the xref entry * @throws IOException if something went wrong */ private long bfSearchForXRef(long xrefOffset, boolean streamsOnly) throws IOException { long newOffset = -1; long newOffsetTable = -1; long newOffsetStream = -1; if (!streamsOnly) { bfSearchForXRefTables(); } bfSearchForXRefStreams(); if (!streamsOnly && bfSearchXRefTablesOffsets != null) { // TODO to be optimized, this won't work in every case newOffsetTable = searchNearestValue(bfSearchXRefTablesOffsets, xrefOffset); } if (bfSearchXRefStreamsOffsets != null) { // TODO to be optimized, this won't work in every case newOffsetStream = searchNearestValue(bfSearchXRefStreamsOffsets, xrefOffset); } // choose the nearest value if (newOffsetTable > -1 && newOffsetStream > -1) { long differenceTable = xrefOffset - newOffsetTable; long differenceStream = xrefOffset - newOffsetStream; if (Math.abs(differenceTable) > Math.abs(differenceStream)) { newOffset = differenceStream; bfSearchXRefStreamsOffsets.remove(newOffsetStream); } else { newOffset = differenceTable; bfSearchXRefTablesOffsets.remove(newOffsetTable); } } else if (newOffsetTable > -1) { newOffset = newOffsetTable; bfSearchXRefTablesOffsets.remove(newOffsetTable); } else if (newOffsetStream > -1) { newOffset = newOffsetStream; bfSearchXRefStreamsOffsets.remove(newOffsetStream); } return newOffset; } private long searchNearestValue(List<Long> values, long offset) { long newValue = -1; long currentDifference = -1; int currentOffsetIndex = -1; int numberOfOffsets = values.size(); // find the nearest value for (int i = 0; i < numberOfOffsets; i++) { long newDifference = offset - values.get(i); // find the nearest offset if (currentDifference == -1 || (Math.abs(currentDifference) > Math.abs(newDifference))) { currentDifference = newDifference; currentOffsetIndex = i; } } if (currentOffsetIndex > -1) { newValue = values.get(currentOffsetIndex); } return newValue; } /** * Brute force search for all xref entries (tables). * * @throws IOException if something went wrong */ private void bfSearchForXRefTables() throws IOException { if (bfSearchXRefTablesOffsets == null) { // a pdf may contain more than one xref entry bfSearchXRefTablesOffsets = new Vector<Long>(); long originOffset = pdfSource.getOffset(); pdfSource.seek(MINIMUM_SEARCH_OFFSET); // search for xref tables while (!pdfSource.isEOF()) { if (isString(XREF_TABLE)) { long newOffset = pdfSource.getOffset(); pdfSource.seek(newOffset - 1); // ensure that we don't read "startxref" instead of "xref" if (isWhitespace()) { bfSearchXRefTablesOffsets.add(newOffset); } pdfSource.seek(newOffset + 4); } pdfSource.read(); } pdfSource.seek(originOffset); } } /** * Brute force search for all /XRef entries (streams). * * @throws IOException if something went wrong */ private void bfSearchForXRefStreams() throws IOException { if (bfSearchXRefStreamsOffsets == null) { // a pdf may contain more than one /XRef entry bfSearchXRefStreamsOffsets = new Vector<Long>(); long originOffset = pdfSource.getOffset(); pdfSource.seek(MINIMUM_SEARCH_OFFSET); // search for XRef streams String objString = " obj"; char[] string = objString.toCharArray(); while (!pdfSource.isEOF()) { if (isString(XREF_STREAM)) { // search backwards for the beginning of the stream long newOffset = -1; long xrefOffset = pdfSource.getOffset(); boolean objFound = false; for (int i = 1; i < 30 && !objFound; i++) { long currentOffset = xrefOffset - (i * 10); if (currentOffset > 0) { pdfSource.seek(currentOffset); for (int j = 0; j < 10; j++) { if (isString(string)) { long tempOffset = currentOffset - 1; pdfSource.seek(tempOffset); int genID = pdfSource.peek(); // is the next char a digit? if (isDigit(genID)) { genID -= 48; tempOffset--; pdfSource.seek(tempOffset); if (isSpace()) { int length = 0; pdfSource.seek(--tempOffset); while (tempOffset > MINIMUM_SEARCH_OFFSET && isDigit()) { pdfSource.seek(--tempOffset); length++; } if (length > 0) { pdfSource.read(); newOffset = pdfSource.getOffset(); } } } LOG.debug("Fixed reference for xref stream " + xrefOffset + " -> " + newOffset); objFound = true; break; } else { currentOffset++; pdfSource.read(); } } } } if (newOffset > -1) { bfSearchXRefStreamsOffsets.add(newOffset); } pdfSource.seek(xrefOffset + 5); } pdfSource.read(); } pdfSource.seek(originOffset); } } /** * Rebuild the trailer dictionary if startxref can't be found. * * @return the rebuild trailer dictionary * * @throws IOException if something went wrong */ protected final COSDictionary rebuildTrailer() throws IOException { COSDictionary trailer = null; bfSearchForObjects(); if (bfSearchCOSObjectKeyOffsets != null) { xrefTrailerResolver.nextXrefObj( 0, XRefType.TABLE ); for (COSObjectKey objectKey : bfSearchCOSObjectKeyOffsets.keySet()) { xrefTrailerResolver.setXRef(objectKey, bfSearchCOSObjectKeyOffsets.get(objectKey)); } xrefTrailerResolver.setStartxref(0); trailer = xrefTrailerResolver.getTrailer(); getDocument().setTrailer(trailer); // search for the different parts of the trailer dictionary for(COSObjectKey key : bfSearchCOSObjectKeyOffsets.keySet()) { Long offset = bfSearchCOSObjectKeyOffsets.get(key); pdfSource.seek(offset); readObjectNumber(); readGenerationNumber(); readExpectedString(OBJ_MARKER, true); try { COSDictionary dictionary = parseCOSDictionary(); if (dictionary != null) { // document catalog if (COSName.CATALOG.equals(dictionary.getCOSName(COSName.TYPE))) { trailer.setItem(COSName.ROOT, document.getObjectFromPool(key)); } // info dictionary else if (dictionary.containsKey(COSName.TITLE) || dictionary.containsKey(COSName.AUTHOR) || dictionary.containsKey(COSName.SUBJECT) || dictionary.containsKey(COSName.KEYWORDS) || dictionary.containsKey(COSName.CREATOR) || dictionary.containsKey(COSName.PRODUCER) || dictionary.containsKey(COSName.CREATION_DATE)) { trailer.setItem(COSName.INFO, document.getObjectFromPool(key)); } // TODO encryption dictionary } } catch(IOException exception) { LOG.debug("Skipped object "+key+", either it's corrupt or not a dictionary"); } } } return trailer; } /** * This will parse the startxref section from the stream. * The startxref value is ignored. * * @return the startxref value or -1 on parsing error * @throws IOException If an IO error occurs. */ private long parseStartXref() throws IOException { long startXref = -1; if (isString(STARTXREF)) { readString(); skipSpaces(); // This integer is the byte offset of the first object referenced by the xref or xref stream startXref = readLong(); } return startXref; } /** * Checks if the given string can be found at the current offset. * * @param string the bytes of the string to look for * @return true if the bytes are in place, false if not * @throws IOException if something went wrong */ private boolean isString(byte[] string) throws IOException { boolean bytesMatching = false; if (pdfSource.peek() == string[0]) { int length = string.length; byte[] bytesRead = new byte[length]; int numberOfBytes = pdfSource.read(bytesRead, 0, length); while (numberOfBytes < length) { int readMore = pdfSource.read(bytesRead, numberOfBytes, length - numberOfBytes); if (readMore < 0) { break; } numberOfBytes += readMore; } if (Arrays.equals(string, bytesRead)) { bytesMatching = true; } pdfSource.unread(bytesRead, 0, numberOfBytes); } return bytesMatching; } /** * Checks if the given string can be found at the current offset. * * @param string the bytes of the string to look for * @return true if the bytes are in place, false if not * @throws IOException if something went wrong */ private boolean isString(char[] string) throws IOException { boolean bytesMatching = true; long originOffset = pdfSource.getOffset(); for (char c : string) { if (pdfSource.read() != c) { bytesMatching = false; } } pdfSource.seek(originOffset); return bytesMatching; } /** * This will parse the trailer from the stream and add it to the state. * * @return false on parsing error * @throws IOException If an IO error occurs. */ private boolean parseTrailer() throws IOException { if(pdfSource.peek() != 't') { return false; } //read "trailer" long currentOffset = pdfSource.getOffset(); String nextLine = readLine(); if( !nextLine.trim().equals( "trailer" ) ) { // in some cases the EOL is missing and the trailer immediately // continues with "<<" or with a blank character // even if this does not comply with PDF reference we want to support as many PDFs as possible // Acrobat reader can also deal with this. if (nextLine.startsWith("trailer")) { // we can't just unread a portion of the read data as we don't know if the EOL consist of 1 or 2 bytes int len = "trailer".length(); // jump back right after "trailer" pdfSource.seek(currentOffset + len); } else { return false; } } // in some cases the EOL is missing and the trailer continues with " <<" // even if this does not comply with PDF reference we want to support as many PDFs as possible // Acrobat reader can also deal with this. skipSpaces(); COSDictionary parsedTrailer = parseCOSDictionary(); xrefTrailerResolver.setTrailer( parsedTrailer ); skipSpaces(); return true; } /** * Parse the header of a pdf. * * @return true if a PDF header was found * @throws IOException if something went wrong */ protected boolean parsePDFHeader() throws IOException { return parseHeader(PDF_HEADER, PDF_DEFAULT_VERSION); } /** * Parse the header of a fdf. * * @return true if a FDF header was found * @throws IOException if something went wrong */ protected boolean parseFDFHeader() throws IOException { return parseHeader(FDF_HEADER, FDF_DEFAULT_VERSION); } private boolean parseHeader(String headerMarker, String defaultVersion) throws IOException { // read first line String header = readLine(); // some pdf-documents are broken and the pdf-version is in one of the following lines if (!header.contains(headerMarker)) { if (header.contains(headerMarker.substring(1))) { document.setNonValidHeader(true); } header = readLine(); while (!header.contains(headerMarker) && !header.contains(headerMarker.substring(1))) { // if a line starts with a digit, it has to be the first one with data in it if ((header.length() > 0) && (Character.isDigit(header.charAt(0)))) { break; } header = readLine(); } } else if (header.charAt(0) != '%') { document.setNonValidHeader(true); } // nothing found if (!header.contains(headerMarker)) { pdfSource.seek(0); return false; } //sometimes there is some garbage in the header before the header //actually starts, so lets try to find the header first. int headerStart = header.indexOf( headerMarker ); // greater than zero because if it is zero then there is no point of trimming if ( headerStart > 0 ) { //trim off any leading characters header = header.substring( headerStart, header.length() ); } // This is used if there is garbage after the header on the same line if (header.startsWith(headerMarker) && !header.matches(headerMarker + "\\d.\\d")) { if (header.length() < headerMarker.length() + 3) { // No version number at all, set to 1.4 as default header = headerMarker + defaultVersion; LOG.debug("No version found, set to " + defaultVersion + " as default."); } else { String headerGarbage = header.substring(headerMarker.length() + 3, header.length()) + "\n"; header = header.substring(0, headerMarker.length() + 3); pdfSource.unread(headerGarbage.getBytes(ISO_8859_1)); } } float headerVersion = -1; try { String[] headerParts = header.split("-"); if (headerParts.length == 2) { headerVersion = Float.parseFloat(headerParts[1]); } } catch (NumberFormatException exception) { LOG.debug("Can't parse the header version.", exception); } if (headerVersion < 0) { throw new IOException( "Error getting header version: " + header); } document.setVersion(headerVersion); checkComment(); // rewind pdfSource.seek(0); return true; } /** check second line of pdf header */ private void checkComment() throws IOException { String comment = readLine(); if (comment.charAt(0) != '%') { document.setNonValidCommentStart(true); } Integer pos = comment.indexOf('%') > -1 ? comment.indexOf('%') + 1 : 0; if (comment.substring(pos).trim().length() < 4) { document.setNonValidCommentLength(true); } Integer repetition = Math.min(4, comment.substring(pos).length()); for (int i = 0; i < repetition; i++, pos++) { if ((int)comment.charAt(pos) < 128) { document.setNonValidCommentContent(true); break; } } } /** * This will parse the xref table from the stream and add it to the state * The XrefTable contents are ignored. * @param startByteOffset the offset to start at * @return false on parsing error * @throws IOException If an IO error occurs. */ protected boolean parseXrefTable(long startByteOffset) throws IOException { if(pdfSource.peek() != 'x') { return false; } String xref = readString(); if( !xref.trim().equals( "xref" ) ) { return false; } // check for trailer after xref String str = readString(); byte[] b = str.getBytes(ISO_8859_1); pdfSource.unread(b, 0, b.length); // signal start of new XRef xrefTrailerResolver.nextXrefObj( startByteOffset, XRefType.TABLE ); if (str.startsWith("trailer")) { LOG.warn("skipping empty xref table"); return false; } // Xref tables can have multiple sections. Each starts with a starting object id and a count. while(true) { // first obj id long currObjID = readObjectNumber(); // the number of objects in the xref table long count = readLong(); skipSpaces(); for(int i = 0; i < count; i++) { if(pdfSource.isEOF() || isEndOfName((char)pdfSource.peek())) { break; } if(pdfSource.peek() == 't') { break; } //Ignore table contents String currentLine = readLine(); String[] splitString = currentLine.split("\\s"); if (splitString.length < 3) { LOG.warn("invalid xref line: " + currentLine); break; } /* This supports the corrupt table as reported in * PDFBOX-474 (XXXX XXX XX n) */ if(splitString[splitString.length-1].equals("n")) { try { int currOffset = Integer.parseInt(splitString[0]); int currGenID = Integer.parseInt(splitString[1]); COSObjectKey objKey = new COSObjectKey(currObjID, currGenID); xrefTrailerResolver.setXRef(objKey, currOffset); } catch(NumberFormatException e) { throw new IOException(e); } } else if(!splitString[2].equals("f")) { throw new IOException("Corrupt XRefTable Entry - ObjID:" + currObjID); } currObjID++; skipSpaces(); } skipSpaces(); if (!isDigit()) { break; } } return true; } /** * Fills XRefTrailerResolver with data of given stream. * Stream must be of type XRef. * @param stream the stream to be read * @param objByteOffset the offset to start at * @param isStandalone should be set to true if the stream is not part of a hybrid xref table * @throws IOException if there is an error parsing the stream */ private void parseXrefStream(COSStream stream, long objByteOffset, boolean isStandalone) throws IOException { // the cross reference stream of a hybrid xref table will be added to the existing one // and we must not override the offset and the trailer if ( isStandalone ) { xrefTrailerResolver.nextXrefObj( objByteOffset, XRefType.STREAM ); xrefTrailerResolver.setTrailer(stream); } PDFXrefStreamParser parser = new PDFXrefStreamParser( stream, document, xrefTrailerResolver ); parser.parse(); parser.close(); } /** * This will get the document that was parsed. parse() must be called before this is called. * When you are done with this document you must call close() on it to release * resources. * * @return The document that was parsed. * * @throws IOException If there is an error getting the document. */ public COSDocument getDocument() throws IOException { if( document == null ) { throw new IOException( "You must call parse() before calling getDocument()" ); } return document; } /** * Create a temporary file with the input stream. The caller must take care * to delete this file at end of the parse method. * * @param input * @return the temporary file * @throws IOException If something went wrong. */ File createTmpFile(InputStream input) throws IOException { FileOutputStream fos = null; try { File tmpFile = File.createTempFile(TMP_FILE_PREFIX, ".pdf"); fos = new FileOutputStream(tmpFile); IOUtils.copy(input, fos); return tmpFile; } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(fos); } } /** * Parse the values of the trailer dictionary and return the root object. * * @param trailer The trailer dictionary. * @return The parsed root object. * @throws IOException If an IO error occurs or if the root object is * missing in the trailer dictionary. */ protected COSBase parseTrailerValuesDynamically(COSDictionary trailer) throws IOException { // PDFBOX-1557 - ensure that all COSObject are loaded in the trailer // PDFBOX-1606 - after securityHandler has been instantiated for (COSBase trailerEntry : trailer.getValues()) { if (trailerEntry instanceof COSObject) { COSObject tmpObj = (COSObject) trailerEntry; parseObjectDynamically(tmpObj, false); } } // parse catalog or root object COSObject root = (COSObject) trailer.getItem(COSName.ROOT); if (root == null) { throw new IOException("Missing root object specification in trailer."); } return parseObjectDynamically(root, false); } /** * @return last trailer in current document */ public COSDictionary getLastTrailer() { return xrefTrailerResolver.getLastTrailer(); } }
Change char to byte
pdfbox/src/main/java/org/apache/pdfbox/pdfparser/COSParser.java
Change char to byte
Java
bsd-3-clause
8cd5894f55997da5e3b51febe2764d0d43c3410d
0
jMonkeyEngine/jmonkeyengine,jMonkeyEngine/jmonkeyengine,jMonkeyEngine/jmonkeyengine,zzuegg/jmonkeyengine,jMonkeyEngine/jmonkeyengine,zzuegg/jmonkeyengine,zzuegg/jmonkeyengine,zzuegg/jmonkeyengine
/* * Copyright (c) 2009-2018 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package jme3test.terrain; import com.jme3.app.SimpleApplication; import com.jme3.font.BitmapText; import com.jme3.input.KeyInput; import com.jme3.input.controls.ActionListener; import com.jme3.input.controls.KeyTrigger; import com.jme3.light.AmbientLight; import com.jme3.light.DirectionalLight; import com.jme3.material.Material; import com.jme3.math.ColorRGBA; import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.jme3.scene.Geometry; import com.jme3.scene.Node; import com.jme3.scene.shape.Sphere; import com.jme3.terrain.ProgressMonitor; import com.jme3.terrain.Terrain; import com.jme3.terrain.geomipmap.MultiTerrainLodControl; import com.jme3.terrain.geomipmap.NeighbourFinder; import com.jme3.terrain.geomipmap.TerrainQuad; import com.jme3.terrain.geomipmap.lodcalc.DistanceLodCalculator; import com.jme3.texture.Texture; import com.jme3.texture.Texture.WrapMode; import java.util.List; /** * Demonstrates the NeighbourFinder interface for TerrainQuads, * allowing you to tile terrains together without having to use * TerrainGrid. It also introduces the MultiTerrainLodControl that * will seam the edges of all the terrains supplied. * * @author sploreg */ public class TerrainTestTile extends SimpleApplication { private TiledTerrain terrain; Material matTerrain; Material matWire; boolean wireframe = false; boolean triPlanar = false; boolean wardiso = false; boolean minnaert = false; protected BitmapText hintText; private float grassScale = 256; public static void main(String[] args) { TerrainTestTile app = new TerrainTestTile(); app.start(); } @Override public void simpleInitApp() { loadHintText(); setupKeys(); // WIREFRAME material matWire = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); matWire.getAdditionalRenderState().setWireframe(true); matWire.setColor("Color", ColorRGBA.Green); terrain = new TiledTerrain(); rootNode.attachChild(terrain); DirectionalLight light = new DirectionalLight(); light.setDirection((new Vector3f(-0.5f, -1f, -0.5f)).normalize()); rootNode.addLight(light); AmbientLight ambLight = new AmbientLight(); ambLight.setColor(new ColorRGBA(1f, 1f, 0.8f, 0.2f)); rootNode.addLight(ambLight); cam.setLocation(new Vector3f(0, 256, 0)); cam.lookAtDirection(new Vector3f(0, -1, -1).normalizeLocal(), Vector3f.UNIT_Y); Sphere s = new Sphere(12, 12, 3); Geometry g = new Geometry("marker"); g.setMesh(s); Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); mat.setColor("Color", ColorRGBA.Red); g.setMaterial(mat); g.setLocalTranslation(0, -100, 0); rootNode.attachChild(g); Geometry g2 = new Geometry("marker"); g2.setMesh(s); mat.setColor("Color", ColorRGBA.Red); g2.setMaterial(mat); g2.setLocalTranslation(10, -100, 0); rootNode.attachChild(g2); Geometry g3 = new Geometry("marker"); g3.setMesh(s); mat.setColor("Color", ColorRGBA.Red); g3.setMaterial(mat); g3.setLocalTranslation(0, -100, 10); rootNode.attachChild(g3); } public void loadHintText() { hintText = new BitmapText(guiFont, false); hintText.setLocalTranslation(0, getCamera().getHeight(), 0); hintText.setText("Press T to toggle wireframe"); guiNode.attachChild(hintText); } private void setupKeys() { flyCam.setMoveSpeed(100); inputManager.addMapping("wireframe", new KeyTrigger(KeyInput.KEY_T)); inputManager.addListener(actionListener, "wireframe"); } private ActionListener actionListener = new ActionListener() { public void onAction(String name, boolean pressed, float tpf) { if (name.equals("wireframe") && !pressed) { wireframe = !wireframe; if (wireframe) { terrain.setMaterial(matWire); } else { terrain.setMaterial(matTerrain); } } } }; /** * A sample class (node in this case) that demonstrates * the use of NeighbourFinder. * It just links up the left,right,top,bottom TerrainQuads * so LOD can work. * It does not implement many of the Terrain interface's methods, * you will want to do that for your own implementations. */ private class TiledTerrain extends Node implements Terrain, NeighbourFinder { private TerrainQuad terrain1; private TerrainQuad terrain2; private TerrainQuad terrain3; private TerrainQuad terrain4; TiledTerrain() { // TERRAIN TEXTURE material matTerrain = new Material(assetManager, "Common/MatDefs/Terrain/TerrainLighting.j3md"); matTerrain.setBoolean("useTriPlanarMapping", false); matTerrain.setBoolean("WardIso", true); matTerrain.setFloat("Shininess", 0); // GRASS texture Texture grass = assetManager.loadTexture("Textures/Terrain/splat/grass.jpg"); grass.setWrap(WrapMode.Repeat); matTerrain.setTexture("DiffuseMap", grass); matTerrain.setFloat("DiffuseMap_0_scale", grassScale); // CREATE THE TERRAIN terrain1 = new TerrainQuad("terrain 1", 65, 513, null); terrain1.setMaterial(matTerrain); terrain1.setLocalTranslation(-256, -100, -256); terrain1.setLocalScale(1f, 1f, 1f); this.attachChild(terrain1); terrain2 = new TerrainQuad("terrain 2", 65, 513, null); terrain2.setMaterial(matTerrain); terrain2.setLocalTranslation(-256, -100, 256); terrain2.setLocalScale(1f, 1f, 1f); this.attachChild(terrain2); terrain3 = new TerrainQuad("terrain 3", 65, 513, null); terrain3.setMaterial(matTerrain); terrain3.setLocalTranslation(256, -100, -256); terrain3.setLocalScale(1f, 1f, 1f); this.attachChild(terrain3); terrain4 = new TerrainQuad("terrain 4", 65, 513, null); terrain4.setMaterial(matTerrain); terrain4.setLocalTranslation(256, -100, 256); terrain4.setLocalScale(1f, 1f, 1f); this.attachChild(terrain4); terrain1.setNeighbourFinder(this); terrain2.setNeighbourFinder(this); terrain3.setNeighbourFinder(this); terrain4.setNeighbourFinder(this); MultiTerrainLodControl lodControl = new MultiTerrainLodControl(getCamera()); lodControl.setLodCalculator( new DistanceLodCalculator(65, 2.7f) ); // patch size, and a multiplier lodControl.addTerrain(terrain1); lodControl.addTerrain(terrain2); lodControl.addTerrain(terrain3);// order of these seems to matter lodControl.addTerrain(terrain4); this.addControl(lodControl); } /** * 1 3 * 2 4 */ public TerrainQuad getRightQuad(TerrainQuad center) { //System.out.println("lookup neighbour"); if (center == terrain1) return terrain3; if (center == terrain2) return terrain4; return null; } /** * 1 3 * 2 4 */ public TerrainQuad getLeftQuad(TerrainQuad center) { //System.out.println("lookup neighbour"); if (center == terrain3) return terrain1; if (center == terrain4) return terrain2; return null; } /** * 1 3 * 2 4 */ public TerrainQuad getTopQuad(TerrainQuad center) { //System.out.println("lookup neighbour"); if (center == terrain2) return terrain1; if (center == terrain4) return terrain3; return null; } /** * 1 3 * 2 4 */ public TerrainQuad getDownQuad(TerrainQuad center) { //System.out.println("lookup neighbour"); if (center == terrain1) return terrain2; if (center == terrain3) return terrain4; return null; } public float getHeight(Vector2f xz) { // you will have to offset the coordinate for each terrain, to center on it throw new UnsupportedOperationException("Not supported yet."); } public Vector3f getNormal(Vector2f xz) { // you will have to offset the coordinate for each terrain, to center on it throw new UnsupportedOperationException("Not supported yet."); } public float getHeightmapHeight(Vector2f xz) { // you will have to offset the coordinate for each terrain, to center on it throw new UnsupportedOperationException("Not supported yet."); } public void setHeight(Vector2f xzCoordinate, float height) { // you will have to offset the coordinate for each terrain, to center on it throw new UnsupportedOperationException("Not supported yet."); } public void setHeight(List<Vector2f> xz, List<Float> height) { // you will have to offset the coordinate for each terrain, to center on it throw new UnsupportedOperationException("Not supported yet."); } public void adjustHeight(Vector2f xzCoordinate, float delta) { // you will have to offset the coordinate for each terrain, to center on it throw new UnsupportedOperationException("Not supported yet."); } public void adjustHeight(List<Vector2f> xz, List<Float> height) { // you will have to offset the coordinate for each terrain, to center on it throw new UnsupportedOperationException("Not supported yet."); } public float[] getHeightMap() { throw new UnsupportedOperationException("Not supported yet."); } public int getMaxLod() { throw new UnsupportedOperationException("Not supported yet."); } public void setLocked(boolean locked) { throw new UnsupportedOperationException("Not supported yet."); } public void generateEntropy(ProgressMonitor monitor) { throw new UnsupportedOperationException("Not supported yet."); } public Material getMaterial() { throw new UnsupportedOperationException("Not supported yet."); } public Material getMaterial(Vector3f worldLocation) { throw new UnsupportedOperationException("Not supported yet."); } public int getTerrainSize() { throw new UnsupportedOperationException("Not supported yet."); } public int getNumMajorSubdivisions() { throw new UnsupportedOperationException("Not supported yet."); } } }
jme3-examples/src/main/java/jme3test/terrain/TerrainTestTile.java
/* * Copyright (c) 2009-2012 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package jme3test.terrain; import com.jme3.app.SimpleApplication; import com.jme3.font.BitmapText; import com.jme3.input.KeyInput; import com.jme3.input.controls.ActionListener; import com.jme3.input.controls.KeyTrigger; import com.jme3.light.AmbientLight; import com.jme3.light.DirectionalLight; import com.jme3.material.Material; import com.jme3.math.ColorRGBA; import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.jme3.scene.Geometry; import com.jme3.scene.Node; import com.jme3.scene.shape.Sphere; import com.jme3.terrain.ProgressMonitor; import com.jme3.terrain.Terrain; import com.jme3.terrain.geomipmap.MultiTerrainLodControl; import com.jme3.terrain.geomipmap.NeighbourFinder; import com.jme3.terrain.geomipmap.TerrainQuad; import com.jme3.terrain.geomipmap.lodcalc.DistanceLodCalculator; import com.jme3.texture.Texture; import com.jme3.texture.Texture.WrapMode; import java.util.List; /** * Demonstrates the NeighbourFinder interface for TerrainQuads, * allowing you to tile terrains together without having to use * TerrainGrid. It also introduces the MultiTerrainLodControl that * will seam the edges of all the terrains supplied. * * @author sploreg */ public class TerrainTestTile extends SimpleApplication { private TiledTerrain terrain; Material matTerrain; Material matWire; boolean wireframe = true; boolean triPlanar = false; boolean wardiso = false; boolean minnaert = false; protected BitmapText hintText; private float grassScale = 256; public static void main(String[] args) { TerrainTestTile app = new TerrainTestTile(); app.start(); } @Override public void simpleInitApp() { loadHintText(); setupKeys(); // WIREFRAME material matWire = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); matWire.getAdditionalRenderState().setWireframe(true); matWire.setColor("Color", ColorRGBA.Green); terrain = new TiledTerrain(); rootNode.attachChild(terrain); DirectionalLight light = new DirectionalLight(); light.setDirection((new Vector3f(-0.5f, -1f, -0.5f)).normalize()); rootNode.addLight(light); AmbientLight ambLight = new AmbientLight(); ambLight.setColor(new ColorRGBA(1f, 1f, 0.8f, 0.2f)); rootNode.addLight(ambLight); cam.setLocation(new Vector3f(0, 256, 0)); cam.lookAtDirection(new Vector3f(0, -1, -1).normalizeLocal(), Vector3f.UNIT_Y); Sphere s = new Sphere(12, 12, 3); Geometry g = new Geometry("marker"); g.setMesh(s); Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); mat.setColor("Color", ColorRGBA.Red); g.setMaterial(mat); g.setLocalTranslation(0, -100, 0); rootNode.attachChild(g); Geometry g2 = new Geometry("marker"); g2.setMesh(s); mat.setColor("Color", ColorRGBA.Red); g2.setMaterial(mat); g2.setLocalTranslation(10, -100, 0); rootNode.attachChild(g2); Geometry g3 = new Geometry("marker"); g3.setMesh(s); mat.setColor("Color", ColorRGBA.Red); g3.setMaterial(mat); g3.setLocalTranslation(0, -100, 10); rootNode.attachChild(g3); } public void loadHintText() { hintText = new BitmapText(guiFont, false); hintText.setLocalTranslation(0, getCamera().getHeight(), 0); hintText.setText("Hit 'T' to toggle wireframe"); guiNode.attachChild(hintText); } private void setupKeys() { flyCam.setMoveSpeed(100); inputManager.addMapping("wireframe", new KeyTrigger(KeyInput.KEY_T)); inputManager.addListener(actionListener, "wireframe"); } private ActionListener actionListener = new ActionListener() { public void onAction(String name, boolean pressed, float tpf) { if (name.equals("wireframe") && !pressed) { wireframe = !wireframe; if (!wireframe) { terrain.setMaterial(matWire); } else { terrain.setMaterial(matTerrain); } } } }; /** * A sample class (node in this case) that demonstrates * the use of NeighbourFinder. * It just links up the left,right,top,bottom TerrainQuads * so LOD can work. * It does not implement many of the Terrain interface's methods, * you will want to do that for your own implementations. */ private class TiledTerrain extends Node implements Terrain, NeighbourFinder { private TerrainQuad terrain1; private TerrainQuad terrain2; private TerrainQuad terrain3; private TerrainQuad terrain4; TiledTerrain() { // TERRAIN TEXTURE material matTerrain = new Material(assetManager, "Common/MatDefs/Terrain/TerrainLighting.j3md"); matTerrain.setBoolean("useTriPlanarMapping", false); matTerrain.setBoolean("WardIso", true); matTerrain.setFloat("Shininess", 0); // GRASS texture Texture grass = assetManager.loadTexture("Textures/Terrain/splat/grass.jpg"); grass.setWrap(WrapMode.Repeat); matTerrain.setTexture("DiffuseMap", grass); matTerrain.setFloat("DiffuseMap_0_scale", grassScale); // CREATE THE TERRAIN terrain1 = new TerrainQuad("terrain 1", 65, 513, null); terrain1.setMaterial(matTerrain); terrain1.setLocalTranslation(-256, -100, -256); terrain1.setLocalScale(1f, 1f, 1f); this.attachChild(terrain1); terrain2 = new TerrainQuad("terrain 2", 65, 513, null); terrain2.setMaterial(matTerrain); terrain2.setLocalTranslation(-256, -100, 256); terrain2.setLocalScale(1f, 1f, 1f); this.attachChild(terrain2); terrain3 = new TerrainQuad("terrain 3", 65, 513, null); terrain3.setMaterial(matTerrain); terrain3.setLocalTranslation(256, -100, -256); terrain3.setLocalScale(1f, 1f, 1f); this.attachChild(terrain3); terrain4 = new TerrainQuad("terrain 4", 65, 513, null); terrain4.setMaterial(matTerrain); terrain4.setLocalTranslation(256, -100, 256); terrain4.setLocalScale(1f, 1f, 1f); this.attachChild(terrain4); terrain1.setNeighbourFinder(this); terrain2.setNeighbourFinder(this); terrain3.setNeighbourFinder(this); terrain4.setNeighbourFinder(this); MultiTerrainLodControl lodControl = new MultiTerrainLodControl(getCamera()); lodControl.setLodCalculator( new DistanceLodCalculator(65, 2.7f) ); // patch size, and a multiplier lodControl.addTerrain(terrain1); lodControl.addTerrain(terrain2); lodControl.addTerrain(terrain3);// order of these seems to matter lodControl.addTerrain(terrain4); this.addControl(lodControl); } /** * 1 3 * 2 4 */ public TerrainQuad getRightQuad(TerrainQuad center) { //System.out.println("lookup neighbour"); if (center == terrain1) return terrain3; if (center == terrain2) return terrain4; return null; } /** * 1 3 * 2 4 */ public TerrainQuad getLeftQuad(TerrainQuad center) { //System.out.println("lookup neighbour"); if (center == terrain3) return terrain1; if (center == terrain4) return terrain2; return null; } /** * 1 3 * 2 4 */ public TerrainQuad getTopQuad(TerrainQuad center) { //System.out.println("lookup neighbour"); if (center == terrain2) return terrain1; if (center == terrain4) return terrain3; return null; } /** * 1 3 * 2 4 */ public TerrainQuad getDownQuad(TerrainQuad center) { //System.out.println("lookup neighbour"); if (center == terrain1) return terrain2; if (center == terrain3) return terrain4; return null; } public float getHeight(Vector2f xz) { // you will have to offset the coordinate for each terrain, to center on it throw new UnsupportedOperationException("Not supported yet."); } public Vector3f getNormal(Vector2f xz) { // you will have to offset the coordinate for each terrain, to center on it throw new UnsupportedOperationException("Not supported yet."); } public float getHeightmapHeight(Vector2f xz) { // you will have to offset the coordinate for each terrain, to center on it throw new UnsupportedOperationException("Not supported yet."); } public void setHeight(Vector2f xzCoordinate, float height) { // you will have to offset the coordinate for each terrain, to center on it throw new UnsupportedOperationException("Not supported yet."); } public void setHeight(List<Vector2f> xz, List<Float> height) { // you will have to offset the coordinate for each terrain, to center on it throw new UnsupportedOperationException("Not supported yet."); } public void adjustHeight(Vector2f xzCoordinate, float delta) { // you will have to offset the coordinate for each terrain, to center on it throw new UnsupportedOperationException("Not supported yet."); } public void adjustHeight(List<Vector2f> xz, List<Float> height) { // you will have to offset the coordinate for each terrain, to center on it throw new UnsupportedOperationException("Not supported yet."); } public float[] getHeightMap() { throw new UnsupportedOperationException("Not supported yet."); } public int getMaxLod() { throw new UnsupportedOperationException("Not supported yet."); } public void setLocked(boolean locked) { throw new UnsupportedOperationException("Not supported yet."); } public void generateEntropy(ProgressMonitor monitor) { throw new UnsupportedOperationException("Not supported yet."); } public Material getMaterial() { throw new UnsupportedOperationException("Not supported yet."); } public Material getMaterial(Vector3f worldLocation) { throw new UnsupportedOperationException("Not supported yet."); } public int getTerrainSize() { throw new UnsupportedOperationException("Not supported yet."); } public int getNumMajorSubdivisions() { throw new UnsupportedOperationException("Not supported yet."); } } }
TerrainTestTile: T key had to be pressed 2x before effect (see PR #827)
jme3-examples/src/main/java/jme3test/terrain/TerrainTestTile.java
TerrainTestTile: T key had to be pressed 2x before effect (see PR #827)
Java
bsd-3-clause
514e592d810bdfee88c10b10369a907c6dbcdded
0
wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy
/* * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.nodes; import com.oracle.graal.api.meta.*; import com.oracle.graal.graph.*; import com.oracle.graal.graph.spi.*; import com.oracle.graal.nodes.calc.*; import com.oracle.graal.nodes.extended.*; import com.oracle.graal.nodes.spi.*; import com.oracle.graal.nodes.type.*; /** * A node that changes the stamp of its input based on some condition being true. */ @NodeInfo(nameTemplate = "GuardingPi(!={p#negated}) {p#reason/s}") public class GuardingPiNode extends FixedWithNextNode implements Lowerable, GuardingNode, Canonicalizable, ValueProxy { @Input private ValueNode object; @Input private LogicNode condition; private final DeoptimizationReason reason; private final DeoptimizationAction action; private boolean negated; public ValueNode object() { return object; } public LogicNode condition() { return condition; } /** * Constructor for {@link #guardingNonNull(Object)} node intrinsic. */ private GuardingPiNode(ValueNode object) { this(object, object.graph().unique(new IsNullNode(object)), true, DeoptimizationReason.NullCheckException, DeoptimizationAction.None, object.stamp().join(StampFactory.objectNonNull())); } /** * Creates a guarding pi node. * * @param object the object whose type is refined if this guard succeeds * @param condition the condition to test * @param negateCondition the guard succeeds if {@code condition != negateCondition} * @param stamp the refined type of the object if the guard succeeds */ public GuardingPiNode(ValueNode object, ValueNode condition, boolean negateCondition, DeoptimizationReason reason, DeoptimizationAction action, Stamp stamp) { super(stamp); assert stamp != null; this.object = object; this.condition = (LogicNode) condition; this.reason = reason; this.action = action; this.negated = negateCondition; } @Override public void lower(LoweringTool tool) { GuardingNode guard = tool.createGuard(condition, reason, action, negated); ValueAnchorNode anchor = graph().add(new ValueAnchorNode((ValueNode) guard)); PiNode pi = graph().unique(new PiNode(object, stamp(), (ValueNode) guard)); replaceAtUsages(pi); graph().replaceFixedWithFixed(this, anchor); } @Override public boolean inferStamp() { return updateStamp(stamp().join(object().stamp())); } @Override public Node canonical(CanonicalizerTool tool) { if (stamp() == StampFactory.illegal(object.kind())) { // The guard always fails return graph().add(new DeoptimizeNode(action, reason)); } if (condition instanceof LogicConstantNode) { LogicConstantNode c = (LogicConstantNode) condition; if (c.getValue() == negated) { // The guard always fails return graph().add(new DeoptimizeNode(action, reason)); } if (c.getValue() != negated && stamp().equals(object().stamp())) { return object; } } return this; } @NodeIntrinsic public static <T> T guardingNonNull(T object) { if (object == null) { throw new NullPointerException(); } return object; } @NodeIntrinsic public static native Object guardingPi(Object object, LogicNode condition, @ConstantNodeParameter boolean negateCondition, @ConstantNodeParameter DeoptimizationReason reason, @ConstantNodeParameter DeoptimizationAction action, @ConstantNodeParameter Stamp stamp); @Override public ValueNode getOriginalValue() { return object; } }
graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/GuardingPiNode.java
/* * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.nodes; import com.oracle.graal.api.meta.*; import com.oracle.graal.graph.*; import com.oracle.graal.graph.spi.*; import com.oracle.graal.nodes.calc.*; import com.oracle.graal.nodes.extended.*; import com.oracle.graal.nodes.spi.*; import com.oracle.graal.nodes.type.*; /** * A node that changes the stamp of its input based on some condition being true. */ @NodeInfo(nameTemplate = "GuardingPi(!={p#negated}) {p#reason/s}") public class GuardingPiNode extends FixedWithNextNode implements Lowerable, GuardingNode, Canonicalizable, ValueProxy { @Input private ValueNode object; @Input private LogicNode condition; private final DeoptimizationReason reason; private final DeoptimizationAction action; private boolean negated; public ValueNode object() { return object; } public LogicNode condition() { return condition; } /** * Constructor for {@link #guardingNonNull(Object)} node intrinsic. */ private GuardingPiNode(ValueNode object) { this(object, object.graph().unique(new IsNullNode(object)), true, DeoptimizationReason.NullCheckException, DeoptimizationAction.None, object.stamp().join(StampFactory.objectNonNull())); } /** * Creates a guarding pi node. * * @param object the object whose type is refined if this guard succeeds * @param condition the condition to test * @param negateCondition the guard succeeds if {@code condition != negateCondition} * @param stamp the refined type of the object if the guard succeeds */ public GuardingPiNode(ValueNode object, ValueNode condition, boolean negateCondition, DeoptimizationReason reason, DeoptimizationAction action, Stamp stamp) { super(stamp); assert stamp != null; this.object = object; this.condition = (LogicNode) condition; this.reason = reason; this.action = action; this.negated = negateCondition; } @Override public void lower(LoweringTool tool) { if (graph().getGuardsStage() == StructuredGraph.GuardsStage.FIXED_DEOPTS) { throw new GraalInternalError("Cannot create guards in after-guard lowering"); } GuardingNode guard = tool.createGuard(condition, reason, action, negated); ValueAnchorNode anchor = graph().add(new ValueAnchorNode((ValueNode) guard)); PiNode pi = graph().unique(new PiNode(object, stamp(), (ValueNode) guard)); replaceAtUsages(pi); graph().replaceFixedWithFixed(this, anchor); } @Override public boolean inferStamp() { return updateStamp(stamp().join(object().stamp())); } @Override public Node canonical(CanonicalizerTool tool) { if (stamp() == StampFactory.illegal(object.kind())) { // The guard always fails return graph().add(new DeoptimizeNode(action, reason)); } if (condition instanceof LogicConstantNode) { LogicConstantNode c = (LogicConstantNode) condition; if (c.getValue() == negated) { // The guard always fails return graph().add(new DeoptimizeNode(action, reason)); } if (c.getValue() != negated && stamp().equals(object().stamp())) { return object; } } return this; } @NodeIntrinsic public static <T> T guardingNonNull(T object) { if (object == null) { throw new NullPointerException(); } return object; } @NodeIntrinsic public static native Object guardingPi(Object object, LogicNode condition, @ConstantNodeParameter boolean negateCondition, @ConstantNodeParameter DeoptimizationReason reason, @ConstantNodeParameter DeoptimizationAction action, @ConstantNodeParameter Stamp stamp); @Override public ValueNode getOriginalValue() { return object; } }
Remove reduduant guards stage check in GuardingPiNode.lower
graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/GuardingPiNode.java
Remove reduduant guards stage check in GuardingPiNode.lower
Java
mit
57b41324b5231d815608e7790a4ec952b81c36db
0
MarkEWaite/git-client-plugin,MarkEWaite/git-client-plugin,MarkEWaite/git-client-plugin
src/test/java/org/jenkinsci/plugins/gitclient/RemotingTest.java
package org.jenkinsci.plugins.gitclient; import static org.junit.Assert.*; import hudson.FilePath; import hudson.model.Computer; import hudson.model.StreamBuildListener; import hudson.remoting.Callable; import hudson.remoting.VirtualChannel; import hudson.slaves.DumbSlave; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.Repository; import org.junit.ClassRule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.jvnet.hudson.test.JenkinsRule; import java.io.IOException; import org.jenkinsci.remoting.RoleChecker; /** * @author Kohsuke Kawaguchi */ public class RemotingTest { @ClassRule public static JenkinsRule j = new JenkinsRule(); @ClassRule public static TemporaryFolder tempFolder = new TemporaryFolder(); /** * Makes sure {@link GitClient} is remotable. */ @Test public void testRemotability() throws Exception { DumbSlave agent = j.createSlave(); GitClient jgit = new JGitAPIImpl(tempFolder.getRoot(), StreamBuildListener.fromStdout()); Computer c = agent.toComputer(); c.connect(false).get(); VirtualChannel channel = c.getChannel(); channel.call(new Work(jgit)); channel.close(); } private static class Work implements Callable<Void, IOException> { private static final long serialVersionUID = 1L; private final GitClient git; private Work(GitClient git) { this.git = git; } @Override public Void call() throws IOException { try { git.init(); git.getWorkTree().child("foo").touch(0); git.add("foo"); PersonIdent alice = new PersonIdent("alice", "alice@jenkins-ci.org"); git.setAuthor(alice); git.setCommitter(alice); git.commit("committing changes"); FilePath ws = git.withRepository(new RepositoryCallableImpl()); assertEquals(ws, git.getWorkTree()); return null; } catch (InterruptedException e) { throw new Error(e); } } @Override public void checkRoles(RoleChecker rc) throws SecurityException { throw new UnsupportedOperationException("unexpected call to checkRoles in private static Work class"); } } private static class RepositoryCallableImpl implements RepositoryCallback<FilePath> { private static final long serialVersionUID = 1L; @Override public FilePath invoke(Repository repo, VirtualChannel channel) { assertNotNull(repo); return new FilePath(repo.getWorkTree()); } } }
Delete `RemotingTest`
src/test/java/org/jenkinsci/plugins/gitclient/RemotingTest.java
Delete `RemotingTest`
Java
mit
96da27331d0bfe3ee1b187df5274b8fba9f69042
0
RichardWarburton/honest-profiler,nitsanw/honest-profiler,jvm-profiling-tools/honest-profiler,RichardWarburton/honest-profiler,nitsanw/honest-profiler,RichardWarburton/honest-profiler,jvm-profiling-tools/honest-profiler,nitsanw/honest-profiler,RichardWarburton/honest-profiler,RichardWarburton/honest-profiler,nitsanw/honest-profiler,RichardWarburton/honest-profiler,jvm-profiling-tools/honest-profiler,nitsanw/honest-profiler,jvm-profiling-tools/honest-profiler,nitsanw/honest-profiler
/** * Copyright (c) 2014 Richard Warburton (richard.warburton@gmail.com) * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **/ package com.insightfullogic.honest_profiler.ports.javafx.controller; import static com.insightfullogic.honest_profiler.ports.javafx.model.filter.FilterType.STRING; import static com.insightfullogic.honest_profiler.ports.javafx.util.DialogUtil.FILTER; import static com.insightfullogic.honest_profiler.ports.javafx.util.DialogUtil.showExportDialog; import static com.insightfullogic.honest_profiler.ports.javafx.util.FxUtil.refreshTable; import static com.insightfullogic.honest_profiler.ports.javafx.util.StyleUtil.doubleDiffStyler; import static com.insightfullogic.honest_profiler.ports.javafx.util.StyleUtil.intDiffStyler; import static com.insightfullogic.honest_profiler.ports.javafx.util.report.ReportUtil.writeFlatProfileDiffCsv; import static com.insightfullogic.honest_profiler.ports.javafx.view.Icon.EXPORT_16; import static com.insightfullogic.honest_profiler.ports.javafx.view.Icon.FUNNEL_16; import static com.insightfullogic.honest_profiler.ports.javafx.view.Icon.FUNNEL_ACTIVE_16; import static com.insightfullogic.honest_profiler.ports.javafx.view.Icon.viewFor; import java.util.function.Function; import com.insightfullogic.honest_profiler.core.filters.ProfileFilter; import com.insightfullogic.honest_profiler.core.profiles.Profile; import com.insightfullogic.honest_profiler.ports.javafx.controller.filter.FilterDialogController; import com.insightfullogic.honest_profiler.ports.javafx.model.ApplicationContext; import com.insightfullogic.honest_profiler.ports.javafx.model.ProfileContext; import com.insightfullogic.honest_profiler.ports.javafx.model.diff.FlatEntryDiff; import com.insightfullogic.honest_profiler.ports.javafx.model.diff.FlatProfileDiff; import com.insightfullogic.honest_profiler.ports.javafx.model.filter.FilterSpecification; import com.insightfullogic.honest_profiler.ports.javafx.util.DialogUtil; import com.insightfullogic.honest_profiler.ports.javafx.util.report.ReportUtil; import com.insightfullogic.honest_profiler.ports.javafx.view.cell.CountTableCell; import com.insightfullogic.honest_profiler.ports.javafx.view.cell.MethodNameTableCell; import com.insightfullogic.honest_profiler.ports.javafx.view.cell.PercentageTableCell; import javafx.beans.property.ObjectProperty; import javafx.beans.property.ReadOnlyIntegerWrapper; import javafx.beans.property.ReadOnlyStringWrapper; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TableColumn; import javafx.scene.control.TableColumn.CellDataFeatures; import javafx.scene.control.TableView; import javafx.scene.control.Tooltip; import javafx.scene.control.cell.PropertyValueFactory; import javafx.util.Callback; public class FlatDiffViewController extends AbstractController { @FXML private Button filterButton; @FXML private Button exportButton; @FXML private Label baseSourceLabel; @FXML private Label newSourceLabel; @FXML private TableView<FlatEntryDiff> diffTable; @FXML private TableColumn<FlatEntryDiff, String> method; @FXML private TableColumn<FlatEntryDiff, Number> baseSelfTime; @FXML private TableColumn<FlatEntryDiff, Number> newSelfTime; @FXML private TableColumn<FlatEntryDiff, Number> selfTimeDiff; @FXML private TableColumn<FlatEntryDiff, Number> baseTotalTime; @FXML private TableColumn<FlatEntryDiff, Number> newTotalTime; @FXML private TableColumn<FlatEntryDiff, Number> totalTimeDiff; @FXML private TableColumn<FlatEntryDiff, Number> baseSelfCount; @FXML private TableColumn<FlatEntryDiff, Number> newSelfCount; @FXML private TableColumn<FlatEntryDiff, Number> selfCountDiff; @FXML private TableColumn<FlatEntryDiff, Number> baseTotalCount; @FXML private TableColumn<FlatEntryDiff, Number> newTotalCount; @FXML private TableColumn<FlatEntryDiff, Number> totalCountDiff; @FXML private TableColumn<FlatEntryDiff, Number> baseTraceCount; @FXML private TableColumn<FlatEntryDiff, Number> newTraceCount; @FXML private TableColumn<FlatEntryDiff, Number> traceCountDiff; private ProfileContext baseProfileContext; private ProfileContext newProfileContext; private FilterDialogController filterDialogController; private ObjectProperty<FilterSpecification> filterSpec; private FlatProfileDiff diff; private ProfileFilter currentFilter; @FXML private void initialize() { info(filterButton, "Specify filters restricting the visible entries"); info(exportButton, "Export the visible entries to a CSV file"); diff = new FlatProfileDiff(diffTable.getItems()); currentFilter = new ProfileFilter(); filterDialogController = (FilterDialogController) DialogUtil .<FilterSpecification>createDialog(FILTER, "Specify Filters", false); filterDialogController.addAllowedFilterTypes(STRING); exportButton.setGraphic(viewFor(EXPORT_16)); exportButton.setTooltip(new Tooltip("Export the current view to a file")); exportButton.setOnAction(event -> showExportDialog( exportButton.getScene().getWindow(), "flat_diff_profile.csv", out -> writeFlatProfileDiffCsv(out, diff, ReportUtil.Mode.CSV) )); filterSpec = new SimpleObjectProperty<>(null); filterSpec.addListener((property, oldValue, newValue) -> { filterButton.setGraphic( newValue == null || !newValue.isFiltering() ? viewFor(FUNNEL_16) : viewFor(FUNNEL_ACTIVE_16)); currentFilter = new ProfileFilter(newValue.getFilters()); diff.clear(); updateDiff(baseProfileContext.getProfile(), true); updateDiff(newProfileContext.getProfile(), false); }); filterButton.setGraphic(viewFor(FUNNEL_16)); filterButton.setOnAction( event -> filterSpec.set(filterDialogController.showAndWait().get())); method .setCellValueFactory(data -> new ReadOnlyStringWrapper(data.getValue().getFullName())); method.setCellFactory(col -> new MethodNameTableCell<FlatEntryDiff>()); configureTimeShareColumn(baseSelfTime, "baseSelfTimeShare", null); configureTimeShareColumn(newSelfTime, "newSelfTimeShare", null); configureTimeShareColumn(baseTotalTime, "baseTotalTimeShare", null); configureTimeShareColumn(newTotalTime, "newTotalTimeShare", null); configureTimeShareColumn(selfTimeDiff, "pctSelfChange", doubleDiffStyler); configureTimeShareColumn(totalTimeDiff, "pctTotalChange", doubleDiffStyler); configureCountColumn(baseSelfCount, "baseSelfCount", null); configureCountColumn(newSelfCount, "newSelfCount", null); configureCountColumn(baseTotalCount, "baseTotalCount", null); configureCountColumn(newTotalCount, "newTotalCount", null); configureCountColumn(baseTraceCount, "baseTraceCount", null); configureCountColumn(newTraceCount, "newTraceCount", null); configureCountDiffColumn( selfCountDiff, data -> new ReadOnlyIntegerWrapper( data.getValue().getNewSelfCount() - data.getValue().getBaseSelfCount()), intDiffStyler); configureCountDiffColumn( totalCountDiff, data -> new ReadOnlyIntegerWrapper( data.getValue().getNewTotalCount() - data.getValue().getBaseTotalCount()), intDiffStyler); configureCountDiffColumn( traceCountDiff, data -> new ReadOnlyIntegerWrapper( data.getValue().getNewTraceCount() - data.getValue().getBaseTraceCount()), intDiffStyler); } @Override public void setApplicationContext(ApplicationContext applicationContext) { super.setApplicationContext(applicationContext); filterDialogController.setApplicationContext(appCtx()); } public void setProfileContexts(ProfileContext baseContext, ProfileContext newContext) { baseProfileContext = baseContext; newProfileContext = newContext; baseSourceLabel.setText(baseContext.getName()); newSourceLabel.setText(newContext.getName()); updateDiff(baseContext.getProfile(), true); updateDiff(newContext.getProfile(), false); baseProfileContext.profileProperty() .addListener((property, oldValue, newValue) -> updateDiff(newValue, true)); newProfileContext.profileProperty() .addListener((property, oldValue, newValue) -> updateDiff(newValue, false)); } private void updateDiff(Profile profile, boolean base) { Profile copy = profile.copy(); currentFilter.accept(copy); if (base) { diff.updateBase(copy.getFlatByMethodProfile()); } else { diff.updateNew(copy.getFlatByMethodProfile()); } refreshTable(diffTable); } private void configureTimeShareColumn(TableColumn<FlatEntryDiff, Number> column, String propertyName, Function<Number, String> styler) { column.setCellValueFactory(new PropertyValueFactory<>(propertyName)); column.setCellFactory(col -> new PercentageTableCell<FlatEntryDiff>(styler)); } private void configureCountColumn(TableColumn<FlatEntryDiff, Number> column, String propertyName, Function<Number, String> styler) { column.setCellValueFactory(new PropertyValueFactory<>(propertyName)); column.setCellFactory(col -> new CountTableCell<FlatEntryDiff>(styler)); } private void configureCountDiffColumn(TableColumn<FlatEntryDiff, Number> column, Callback<CellDataFeatures<FlatEntryDiff, Number>, ObservableValue<Number>> callback, Function<Number, String> styler) { column.setCellValueFactory(callback); column.setCellFactory(col -> new CountTableCell<FlatEntryDiff>(styler)); } }
src/main/java/com/insightfullogic/honest_profiler/ports/javafx/controller/FlatDiffViewController.java
/** * Copyright (c) 2014 Richard Warburton (richard.warburton@gmail.com) * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **/ package com.insightfullogic.honest_profiler.ports.javafx.controller; import static com.insightfullogic.honest_profiler.ports.javafx.model.filter.FilterType.STRING; import static com.insightfullogic.honest_profiler.ports.javafx.model.filter.FilterType.TIME_SHARE; import static com.insightfullogic.honest_profiler.ports.javafx.util.DialogUtil.FILTER; import static com.insightfullogic.honest_profiler.ports.javafx.util.DialogUtil.showExportDialog; import static com.insightfullogic.honest_profiler.ports.javafx.util.FxUtil.refreshTable; import static com.insightfullogic.honest_profiler.ports.javafx.util.StyleUtil.doubleDiffStyler; import static com.insightfullogic.honest_profiler.ports.javafx.util.StyleUtil.intDiffStyler; import static com.insightfullogic.honest_profiler.ports.javafx.util.report.ReportUtil.writeFlatProfileDiffCsv; import static com.insightfullogic.honest_profiler.ports.javafx.view.Icon.EXPORT_16; import static com.insightfullogic.honest_profiler.ports.javafx.view.Icon.FUNNEL_16; import static com.insightfullogic.honest_profiler.ports.javafx.view.Icon.FUNNEL_ACTIVE_16; import static com.insightfullogic.honest_profiler.ports.javafx.view.Icon.viewFor; import java.util.function.Function; import com.insightfullogic.honest_profiler.core.filters.ProfileFilter; import com.insightfullogic.honest_profiler.core.profiles.Profile; import com.insightfullogic.honest_profiler.ports.javafx.controller.filter.FilterDialogController; import com.insightfullogic.honest_profiler.ports.javafx.model.ApplicationContext; import com.insightfullogic.honest_profiler.ports.javafx.model.ProfileContext; import com.insightfullogic.honest_profiler.ports.javafx.model.diff.FlatEntryDiff; import com.insightfullogic.honest_profiler.ports.javafx.model.diff.FlatProfileDiff; import com.insightfullogic.honest_profiler.ports.javafx.model.filter.FilterSpecification; import com.insightfullogic.honest_profiler.ports.javafx.util.DialogUtil; import com.insightfullogic.honest_profiler.ports.javafx.util.report.ReportUtil; import com.insightfullogic.honest_profiler.ports.javafx.view.cell.CountTableCell; import com.insightfullogic.honest_profiler.ports.javafx.view.cell.MethodNameTableCell; import com.insightfullogic.honest_profiler.ports.javafx.view.cell.PercentageTableCell; import javafx.beans.property.ObjectProperty; import javafx.beans.property.ReadOnlyIntegerWrapper; import javafx.beans.property.ReadOnlyStringWrapper; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TableColumn; import javafx.scene.control.TableColumn.CellDataFeatures; import javafx.scene.control.TableView; import javafx.scene.control.Tooltip; import javafx.scene.control.cell.PropertyValueFactory; import javafx.util.Callback; public class FlatDiffViewController extends AbstractController { @FXML private Button filterButton; @FXML private Button exportButton; @FXML private Label baseSourceLabel; @FXML private Label newSourceLabel; @FXML private TableView<FlatEntryDiff> diffTable; @FXML private TableColumn<FlatEntryDiff, String> method; @FXML private TableColumn<FlatEntryDiff, Number> baseSelfTime; @FXML private TableColumn<FlatEntryDiff, Number> newSelfTime; @FXML private TableColumn<FlatEntryDiff, Number> selfTimeDiff; @FXML private TableColumn<FlatEntryDiff, Number> baseTotalTime; @FXML private TableColumn<FlatEntryDiff, Number> newTotalTime; @FXML private TableColumn<FlatEntryDiff, Number> totalTimeDiff; @FXML private TableColumn<FlatEntryDiff, Number> baseSelfCount; @FXML private TableColumn<FlatEntryDiff, Number> newSelfCount; @FXML private TableColumn<FlatEntryDiff, Number> selfCountDiff; @FXML private TableColumn<FlatEntryDiff, Number> baseTotalCount; @FXML private TableColumn<FlatEntryDiff, Number> newTotalCount; @FXML private TableColumn<FlatEntryDiff, Number> totalCountDiff; @FXML private TableColumn<FlatEntryDiff, Number> baseTraceCount; @FXML private TableColumn<FlatEntryDiff, Number> newTraceCount; @FXML private TableColumn<FlatEntryDiff, Number> traceCountDiff; private ProfileContext baseProfileContext; private ProfileContext newProfileContext; private FilterDialogController filterDialogController; private ObjectProperty<FilterSpecification> filterSpec; private FlatProfileDiff diff; private ProfileFilter currentFilter; @FXML private void initialize() { info(filterButton, "Specify filters restricting the visible entries"); info(exportButton, "Export the visible entries to a CSV file"); diff = new FlatProfileDiff(diffTable.getItems()); currentFilter = new ProfileFilter(); filterDialogController = (FilterDialogController) DialogUtil .<FilterSpecification>createDialog(FILTER, "Specify Filters", false); filterDialogController.addAllowedFilterTypes(STRING, TIME_SHARE); exportButton.setGraphic(viewFor(EXPORT_16)); exportButton.setTooltip(new Tooltip("Export the current view to a file")); exportButton.setOnAction(event -> showExportDialog( exportButton.getScene().getWindow(), "flat_diff_profile.csv", out -> writeFlatProfileDiffCsv(out, diff, ReportUtil.Mode.CSV) )); filterSpec = new SimpleObjectProperty<>(null); filterSpec.addListener((property, oldValue, newValue) -> { filterButton.setGraphic( newValue == null || !newValue.isFiltering() ? viewFor(FUNNEL_16) : viewFor(FUNNEL_ACTIVE_16)); currentFilter = new ProfileFilter(newValue.getFilters()); diff.clear(); updateDiff(baseProfileContext.getProfile(), true); updateDiff(newProfileContext.getProfile(), false); }); filterButton.setGraphic(viewFor(FUNNEL_16)); filterButton.setOnAction( event -> filterSpec.set(filterDialogController.showAndWait().get())); method .setCellValueFactory(data -> new ReadOnlyStringWrapper(data.getValue().getFullName())); method.setCellFactory(col -> new MethodNameTableCell<FlatEntryDiff>()); configureTimeShareColumn(baseSelfTime, "baseSelfTimeShare", null); configureTimeShareColumn(newSelfTime, "newSelfTimeShare", null); configureTimeShareColumn(baseTotalTime, "baseTotalTimeShare", null); configureTimeShareColumn(newTotalTime, "newTotalTimeShare", null); configureTimeShareColumn(selfTimeDiff, "pctSelfChange", doubleDiffStyler); configureTimeShareColumn(totalTimeDiff, "pctTotalChange", doubleDiffStyler); configureCountColumn(baseSelfCount, "baseSelfCount", null); configureCountColumn(newSelfCount, "newSelfCount", null); configureCountColumn(baseTotalCount, "baseTotalCount", null); configureCountColumn(newTotalCount, "newTotalCount", null); configureCountColumn(baseTraceCount, "baseTraceCount", null); configureCountColumn(newTraceCount, "newTraceCount", null); configureCountDiffColumn( selfCountDiff, data -> new ReadOnlyIntegerWrapper( data.getValue().getNewSelfCount() - data.getValue().getBaseSelfCount()), intDiffStyler); configureCountDiffColumn( totalCountDiff, data -> new ReadOnlyIntegerWrapper( data.getValue().getNewTotalCount() - data.getValue().getBaseTotalCount()), intDiffStyler); configureCountDiffColumn( traceCountDiff, data -> new ReadOnlyIntegerWrapper( data.getValue().getNewTraceCount() - data.getValue().getBaseTraceCount()), intDiffStyler); } @Override public void setApplicationContext(ApplicationContext applicationContext) { super.setApplicationContext(applicationContext); filterDialogController.setApplicationContext(appCtx()); } public void setProfileContexts(ProfileContext baseContext, ProfileContext newContext) { baseProfileContext = baseContext; newProfileContext = newContext; baseSourceLabel.setText(baseContext.getName()); newSourceLabel.setText(newContext.getName()); updateDiff(baseContext.getProfile(), true); updateDiff(newContext.getProfile(), false); baseProfileContext.profileProperty() .addListener((property, oldValue, newValue) -> updateDiff(newValue, true)); newProfileContext.profileProperty() .addListener((property, oldValue, newValue) -> updateDiff(newValue, false)); } private void updateDiff(Profile profile, boolean base) { Profile copy = profile.copy(); currentFilter.accept(copy); if (base) { diff.updateBase(copy.getFlatByFrameProfile()); } else { diff.updateNew(copy.getFlatByFrameProfile()); } refreshTable(diffTable); } private void configureTimeShareColumn(TableColumn<FlatEntryDiff, Number> column, String propertyName, Function<Number, String> styler) { column.setCellValueFactory(new PropertyValueFactory<>(propertyName)); column.setCellFactory(col -> new PercentageTableCell<FlatEntryDiff>(styler)); } private void configureCountColumn(TableColumn<FlatEntryDiff, Number> column, String propertyName, Function<Number, String> styler) { column.setCellValueFactory(new PropertyValueFactory<>(propertyName)); column.setCellFactory(col -> new CountTableCell<FlatEntryDiff>(styler)); } private void configureCountDiffColumn(TableColumn<FlatEntryDiff, Number> column, Callback<CellDataFeatures<FlatEntryDiff, Number>, ObservableValue<Number>> callback, Function<Number, String> styler) { column.setCellValueFactory(callback); column.setCellFactory(col -> new CountTableCell<FlatEntryDiff>(styler)); } }
Fixed and restricted Diff View filtering Allowing only String filter for now. For other filters, the filtering paradigm must be reworked to be a bit more general.
src/main/java/com/insightfullogic/honest_profiler/ports/javafx/controller/FlatDiffViewController.java
Fixed and restricted Diff View filtering
Java
mit
bf7737e9535a8571ea2680a4aa897a1f4b1756d5
0
Cuhey3/my-orchestrator,Cuhey3/my-orchestrator,Cuhey3/my-orchestrator
package com.heroku.myapp.myorchestrator.consumers.snapshot.seiyu; import com.heroku.myapp.commons.config.enumerate.Kind; import com.heroku.myapp.commons.consumers.SnapshotQueueConsumer; import com.heroku.myapp.commons.util.actions.MasterUtil; import com.heroku.myapp.commons.util.content.DocumentUtil; import com.heroku.myapp.commons.util.content.MapList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.apache.camel.Exchange; import org.bson.Document; import org.springframework.stereotype.Component; @Component public class SnapshotSoundDirectorStatisticsConsumer extends SnapshotQueueConsumer { @Override protected Optional<Document> doSnapshot(Exchange exchange) { MasterUtil util = new MasterUtil(exchange); Set<String> ignore = new HashSet<>(Arrays.asList(new String[]{"藤原啓治", "井上和彦 (声優)", "千葉繁", "宮村優子 (声優)", "津久井教生", "山田陽", "幾原邦彦", "板垣伸", "水島努", "高松信司", "稲垣隆行", "佐藤順一", "三ツ矢雄二","塩屋翼"})); MapList list = util.mapList(Kind.pages_mutual_sound_director).filteredList((map) -> { List<String> director = (List<String>) map.get("director"); return !director.stream().allMatch((d) -> ignore.contains(d)); }); int size = list.size(); List<Map<String, Object>> result = list.stream().flatMap((map) -> { List<String> director = (List<String>) map.get("director"); String title = (String) map.get("title"); return director.stream().map((name) -> { Map<String, String> part = new LinkedHashMap<>(); part.put("key", name); part.put("title", title); return part; }); }).collect(Collectors.groupingBy((part) -> part.get("key"))) .entrySet().stream() .filter((entry) -> !ignore.contains(entry.getKey())) .map((entry) -> { String director = entry.getKey(); Set<String> titles = entry.getValue().stream().map((m) -> m.get("title")) .collect(Collectors.toSet()); Map<String, Object> resultMap = new LinkedHashMap<>(); resultMap.put("director", director); resultMap.put("count", titles.size()); resultMap.put("percentage", titles.size() * 100d / size); return resultMap; }).sorted((Map<String, Object> o1, Map<String, Object> o2) -> { double d1 = (double) o1.get("percentage"); double d2 = (double) o2.get("percentage"); if (d1 == d2) { return 0; } else if (d1 > d2) { return -1; } else { return 1; } }).collect(Collectors.toList()); return new DocumentUtil(result).nullable(); } }
src/main/java/com/heroku/myapp/myorchestrator/consumers/snapshot/seiyu/SnapshotSoundDirectorStatisticsConsumer.java
package com.heroku.myapp.myorchestrator.consumers.snapshot.seiyu; import com.heroku.myapp.commons.config.enumerate.Kind; import com.heroku.myapp.commons.consumers.SnapshotQueueConsumer; import com.heroku.myapp.commons.util.actions.MasterUtil; import com.heroku.myapp.commons.util.content.DocumentUtil; import com.heroku.myapp.commons.util.content.MapList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.apache.camel.Exchange; import org.bson.Document; import org.springframework.stereotype.Component; @Component public class SnapshotSoundDirectorStatisticsConsumer extends SnapshotQueueConsumer { @Override protected Optional<Document> doSnapshot(Exchange exchange) { MasterUtil util = new MasterUtil(exchange); Set<String> ignore = new HashSet<>(Arrays.asList(new String[]{"藤原啓治", "井上和彦 (声優)","千葉繁","宮村優子 (声優)"})); MapList list = util.mapList(Kind.pages_mutual_sound_director).filteredList((map) -> { List<String> director = (List<String>) map.get("director"); return !director.stream().allMatch((d) -> ignore.contains(d)); }); int size = list.size(); List<Map<String, Object>> result = list.stream().flatMap((map) -> { List<String> director = (List<String>) map.get("director"); String title = (String) map.get("title"); return director.stream().map((name) -> { Map<String, String> part = new LinkedHashMap<>(); part.put("key", name); part.put("title", title); return part; }); }).collect(Collectors.groupingBy((part) -> part.get("key"))) .entrySet().stream() .filter((entry) -> !ignore.contains(entry.getKey())) .map((entry) -> { String director = entry.getKey(); Set<String> titles = entry.getValue().stream().map((m) -> m.get("title")) .collect(Collectors.toSet()); Map<String, Object> resultMap = new LinkedHashMap<>(); resultMap.put("director", director); resultMap.put("count", titles.size()); resultMap.put("percentage", titles.size() * 100d / size); return resultMap; }).sorted((Map<String, Object> o1, Map<String, Object> o2) -> { double d1 = (double) o1.get("percentage"); double d2 = (double) o2.get("percentage"); if (d1 == d2) { return 0; } else if (d1 > d2) { return -1; } else { return 1; } }).collect(Collectors.toList()); return new DocumentUtil(result).nullable(); } }
modify SnapshotSoundDirectorStatisticsConsumer logic
src/main/java/com/heroku/myapp/myorchestrator/consumers/snapshot/seiyu/SnapshotSoundDirectorStatisticsConsumer.java
modify SnapshotSoundDirectorStatisticsConsumer logic
Java
mit
e7bbd3eb14182891ac680ff8874abe816fea4719
0
AlmasB/FXGL,AlmasB/FXGL,AlmasB/FXGL,AlmasB/FXGL
/* * The MIT License (MIT) * * FXGL - JavaFX Game Library * * Copyright (c) 2015 AlmasB (almaslvl@gmail.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.almasb.fxgl; import java.awt.image.BufferedImage; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import javax.imageio.ImageIO; import com.almasb.fxgl.TimerAction.TimerType; import com.almasb.fxgl.asset.AssetManager; import com.almasb.fxgl.effect.ParticleManager; import com.almasb.fxgl.entity.CombinedEntity; import com.almasb.fxgl.entity.Entity; import com.almasb.fxgl.entity.EntityType; import com.almasb.fxgl.entity.FXGLEvent; import com.almasb.fxgl.event.InputManager; import com.almasb.fxgl.event.QTEManager; import com.almasb.fxgl.physics.PhysicsEntity; import com.almasb.fxgl.physics.PhysicsManager; import javafx.animation.AnimationTimer; import javafx.application.Application; import javafx.application.Platform; import javafx.beans.property.BooleanProperty; import javafx.embed.swing.SwingFXUtils; import javafx.geometry.Point2D; import javafx.geometry.Rectangle2D; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.input.KeyEvent; import javafx.scene.layout.Pane; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; /** * To use FXGL extend this class and implement necessary methods * * @author Almas Baimagambetov (AlmasB) (almaslvl@gmail.com) * @version 1.0 * */ public abstract class GameApplication extends Application { static { Thread.setDefaultUncaughtExceptionHandler((thread, error) -> { FXGLLogger.getLogger("FXGL.DefaultErrorHandler").severe("Unhandled Exception"); FXGLLogger.getLogger("FXGL.DefaultErrorHandler").severe(FXGLLogger.errorTraceAsString(error)); FXGLLogger.getLogger("FXGL.DefaultErrorHandler").severe("Closing due to Unhandled Exception"); FXGLLogger.close(); System.exit(0); }); FXGLLogger.init(Level.ALL); Version.print(); } /** * The logger */ protected static final Logger log = FXGLLogger.getLogger("FXGL.GameApplication"); /** * A second in nanoseconds */ public static final long SECOND = 1000000000; /** * Time per single frame in nanoseconds */ public static final long TIME_PER_FRAME = SECOND / 60; /** * A minute in nanoseconds */ public static final long MINUTE = 60 * SECOND; /** * Settings for this game instance */ private GameSettings settings = new GameSettings(); /* * All scenegraph roots */ /** * The root for entities (game objects) */ private Pane gameRoot = new Pane(); /** * The overlay root above {@link #gameRoot}. Contains UI elements, native JavaFX nodes. * May also contain entities as Entity is a subclass of Parent. * uiRoot isn't affected by viewport movement. */ private Pane uiRoot = new Pane(); /** * THE root of the {@link #mainScene}. Contains {@link #gameRoot} and {@link #uiRoot} in this order. */ private Pane root = new Pane(gameRoot, uiRoot); /** * The root of the {@link #mainMenuScene} */ private Pane mainMenuRoot = new Pane(); /** * Reference to game scene */ protected Scene mainScene = new Scene(root); /** * Reference to game window */ protected Stage mainStage; /** * Scene for main menu */ private Scene mainMenuScene = new Scene(mainMenuRoot); /** * These are current width and height of the scene * NOT the window */ private double currentWidth, currentHeight; private List<Entity> tmpAddList = new ArrayList<>(); private List<Entity> tmpRemoveList = new ArrayList<>(); /** * The main loop timer */ private AnimationTimer timer = new AnimationTimer() { @Override public void handle(long internalTime) { processUpdate(internalTime); } }; /** * List for all timer based actions */ private List<TimerAction> timerActions = new ArrayList<>(); /* * Various managers that handle different aspects of the application */ protected final InputManager inputManager = new InputManager(this); /** * Used for loading various assets */ protected final AssetManager assetManager = AssetManager.INSTANCE; protected final PhysicsManager physicsManager = new PhysicsManager(this); protected final ParticleManager particleManager = new ParticleManager(this); protected final QTEManager qteManager = new QTEManager(this); protected final SaveLoadManager saveLoadManager = new SaveLoadManager(); /** * Default random number generator */ protected final Random random = new Random(); /** * Current time for this tick in nanoseconds. Also time elapsed * from the start of game. This time does not change while the game is paused */ protected long now = 0; /** * Current tick. It is also number of ticks since start of game */ protected long tick = 0; /** * These are used to approximate FPS value */ private FPSCounter fpsCounter = new FPSCounter(); private FPSCounter fpsPerformanceCounter = new FPSCounter(); /** * Used as delta from internal JavaFX timestamp to calculate render FPS */ private long fpsTime = 0; /** * Average render FPS */ protected int fps = 0; /** * Average performance FPS */ protected int fpsPerformance = 0; /** * Initialize game settings * * @param settings */ protected abstract void initSettings(GameSettings settings); /** * Override to use your custom intro video * * @return */ protected Intro initIntroVideo() { return new FXGLIntro(getWidth(), getHeight()); } /** * Initialize game assets, such as Texture, AudioClip, Music * * @throws Exception */ protected abstract void initAssets() throws Exception; /** * Initialize game objects */ protected abstract void initGame(); /** * Initiliaze collision handlers, physics properties */ protected abstract void initPhysics(); /** * Initiliaze UI objects */ protected abstract void initUI(); /** * Initiliaze input, i.e. * bind key presses / key typed, bind mouse */ protected abstract void initInput(); /** * Main loop update phase, most of game logic and clean up * * @param now */ protected abstract void onUpdate(); /** * Default implementation does nothing * * Override to add your own cleanup */ protected void onExit() { } /** * Override this method to initialize custom * main menu * * If you do override it make sure to call {@link #startGame()} * to start the game * * @param mainMenuRoot */ protected void initMainMenu(Pane mainMenuRoot) { } /** * This is called AFTER all init methods complete * and BEFORE the main loop starts * * It is safe to use any protected fields at this stage */ protected void postInit() { } /** * Set preferred sizes to roots and set * stage properties */ private void applySettings() { currentWidth = settings.getWidth(); currentHeight = settings.getHeight(); mainStage.setTitle(settings.getTitle() + " " + settings.getVersion()); mainStage.setResizable(false); mainMenuRoot.setPrefSize(settings.getWidth(), settings.getHeight()); root.setPrefSize(settings.getWidth(), settings.getHeight()); // ensure the window frame is just right for the scene size mainStage.setScene(mainScene); mainStage.sizeToScene(); } /** * Ensure managers are of legal state and ready */ private void initManagers() { inputManager.init(mainScene); qteManager.init(); mainScene.addEventHandler(KeyEvent.KEY_RELEASED, qteManager::keyReleasedHandler); } /** * Opens and shows the actual window. Configures what parts of scenes * need to be shown and in which * order based on the subclass implementation of certain init methods */ private void configureAndShowStage() { boolean menuEnabled = mainMenuRoot.getChildren().size() > 0; mainStage.setScene(menuEnabled ? mainMenuScene : mainScene); mainStage.setOnCloseRequest(event -> exit()); mainStage.show(); if (settings.isIntroEnabled()) { Intro intro = initIntroVideo(); if (intro == null) intro = new FXGLIntro(getWidth(), getHeight()); intro.onFinished = () -> { if (menuEnabled) mainMenuScene.setRoot(mainMenuRoot); else { mainScene.setRoot(root); timer.start(); } }; if (menuEnabled) mainMenuScene.setRoot(intro); else mainScene.setRoot(intro); intro.startIntro(); } else { if (!menuEnabled) timer.start(); } } @Override public void start(Stage primaryStage) throws Exception { log.finer("start()"); // capture the reference to primaryStage so we can access it mainStage = primaryStage; initSettings(settings); applySettings(); initManagers(); try { initAssets(); initMainMenu(mainMenuRoot); initGame(); initPhysics(); initUI(); initInput(); postInit(); } catch (Exception e) { log.severe("Exception occurred during initialization: " + e.getMessage()); Arrays.asList(e.getStackTrace()) .stream() .map(StackTraceElement::toString) .filter(s -> !s.contains("Unknown Source") && !s.contains("Native Method")) .map(s -> "Cause: " + s) .forEachOrdered(log::severe); exit(); } configureAndShowStage(); } /** * This is the internal FXGL update tick, * executed 60 times a second ~ every 0.166 (6) seconds * * @param internalTime - The timestamp of the current frame given in nanoseconds (from JavaFX) */ private void processUpdate(long internalTime) { long startNanos = System.nanoTime(); long realFPS = internalTime - fpsTime; fpsTime = internalTime; timerActions.forEach(action -> action.update(now)); timerActions.removeIf(TimerAction::isExpired); inputManager.onUpdate(now); physicsManager.onUpdate(now); onUpdate(); gameRoot.getChildren().addAll(tmpAddList); tmpAddList.clear(); gameRoot.getChildren().removeAll(tmpRemoveList); tmpRemoveList.stream() .filter(e -> e instanceof PhysicsEntity) .map(e -> (PhysicsEntity)e) .forEach(physicsManager::destroyBody); tmpRemoveList.forEach(entity -> entity.onClean()); tmpRemoveList.clear(); gameRoot.getChildren().stream().map(node -> (Entity)node).forEach(entity -> entity.onUpdate(now)); fpsPerformance = Math.round(fpsPerformanceCounter.count(SECOND / (System.nanoTime() - startNanos))); fps = Math.round(fpsCounter.count(SECOND / realFPS)); tick++; now += TIME_PER_FRAME; } /** * Sets viewport origin. Use it for camera movement * * Do NOT use if the viewport was bound * * @param x * @param y */ public void setViewportOrigin(int x, int y) { gameRoot.setLayoutX(-x); gameRoot.setLayoutY(-y); } /** * Note: viewport origin, like anything in a scene, has top-left origin point * * @return viewport origin */ public Point2D getViewportOrigin() { return new Point2D(-gameRoot.getLayoutX(), -gameRoot.getLayoutY()); } /** * Binds the viewport origin so that it follows the given entity * distX and distY represent bound distance between entity and viewport origin * * <pre> * Example: * * bindViewportOrigin(player, (int) (getWidth() / 2), (int) (getHeight() / 2)); * * the code above centers the camera on player * For most platformers / side scrollers use: * * bindViewportOriginX(player, (int) (getWidth() / 2)); * * </pre> * * @param entity * @param distX * @param distY */ protected void bindViewportOrigin(Entity entity, int distX, int distY) { gameRoot.layoutXProperty().bind(entity.translateXProperty().negate().add(distX)); gameRoot.layoutYProperty().bind(entity.translateYProperty().negate().add(distY)); } /** * Binds the viewport origin so that it follows the given entity * distX represent bound distance in X axis between entity and viewport origin * * @param entity * @param distX */ protected void bindViewportOriginX(Entity entity, int distX) { gameRoot.layoutXProperty().bind(entity.translateXProperty().negate().add(distX)); } /** * Binds the viewport origin so that it follows the given entity * distY represent bound distance in Y axis between entity and viewport origin * * @param entity * @param distY */ protected void bindViewportOriginY(Entity entity, int distY) { gameRoot.layoutYProperty().bind(entity.translateYProperty().negate().add(distY)); } /** * * @return a list of ALL entities currently registered in the application */ public List<Entity> getAllEntities() { return gameRoot.getChildren().stream() .map(node -> (Entity)node) .collect(Collectors.toList()); } /** * Returns a list of entities whose type matches given * arguments * * @param type * @param types * @return */ public List<Entity> getEntities(EntityType type, EntityType... types) { List<String> list = Arrays.asList(types).stream() .map(EntityType::getUniqueType) .collect(Collectors.toList()); list.add(type.getUniqueType()); return gameRoot.getChildren().stream() .map(node -> (Entity)node) .filter(entity -> list.contains(entity.getTypeAsString())) .collect(Collectors.toList()); } /** * Returns a list of entities whose type matches given arguments and * which are partially or entirely * in the specified rectangular selection * * @param selection Rectangle2D that describes the selection box * @param type * @param types * @return */ public List<Entity> getEntitiesInRange(Rectangle2D selection, EntityType type, EntityType... types) { Entity boundsEntity = Entity.noType(); boundsEntity.setPosition(selection.getMinX(), selection.getMinY()); boundsEntity.setGraphics(new Rectangle(selection.getWidth(), selection.getHeight())); return getEntities(type, types).stream() .filter(entity -> entity.getBoundsInParent().intersects(boundsEntity.getBoundsInParent())) .collect(Collectors.toList()); } /** * Add an entity/entities to the scenegraph * * This is safe to be called from any thread * * @param entities */ public void addEntities(Entity... entities) { for (Entity e : entities) { if (e instanceof CombinedEntity) { tmpAddList.addAll(e.getChildrenUnmodifiable() .stream().map(node -> (Entity)node) .collect(Collectors.toList())); } else if (e instanceof PhysicsEntity) { physicsManager.createBody((PhysicsEntity) e); tmpAddList.add(e); } else tmpAddList.add(e); } } /** * Remove an entity from the scenegraph * * This is safe to be called from any thread * * @param entity */ public void removeEntity(Entity entity) { tmpRemoveList.add(entity); } /** * Equivalent to uiRoot.getChildren().addAll() * * @param n * @param nodes */ public void addUINodes(Node n, Node... nodes) { uiRoot.getChildren().add(n); uiRoot.getChildren().addAll(nodes); } /** * Equivalent to uiRoot.getChildren().remove() * * @param n */ public void removeUINode(Node n) { uiRoot.getChildren().remove(n); } /** * Call this to manually start the game when you * override {@link #initMainMenu(Pane)} */ protected void startGame() { mainStage.setScene(mainScene); timer.start(); } /** * Pauses the main loop execution */ public void pause() { timer.stop(); } /** * Resumes the main loop execution */ public void resume() { timer.start(); } /** * Pauses the game and opens main menu * Does nothing if main menu was not initialized */ protected void openMainMenu() { if (mainMenuRoot.getChildren().size() == 0) return; timer.stop(); // we are changing our scene so it is intuitive that // all input gets cleared inputManager.clearAllInput(); mainStage.setScene(mainMenuScene); } /** * This method will be automatically called when main window is closed * This method will shutdown the threads and close the logger * * You can call this method when you want to quit the application manually * from the game */ protected final void exit() { log.finer("Closing Normally"); onExit(); FXGLLogger.close(); Platform.exit(); } /** * The Runnable action will be scheduled to run at given interval. * The action will run for the first time after given interval. * * Note: the scheduled action will not run while the game is paused * * @param action the action * @param interval time in nanoseconds */ public void runAtInterval(Runnable action, double interval) { timerActions.add(new TimerAction(now, interval, action, TimerType.INDEFINITE)); } /** * The Runnable action will be scheduled for execution iff * whileCondition is initially true. If that's the case * then the Runnable action will be scheduled to run at given interval. * The action will run for the first time after given interval * * The action will be removed from schedule when whileCondition becomes {@code false}. * * Note: the scheduled action will not run while the game is paused * * @param action * @param interval * @param whileCondition */ public void runAtIntervalWhile(Runnable action, double interval, BooleanProperty whileCondition) { if (!whileCondition.get()) { return; } TimerAction act = new TimerAction(now, interval, action, TimerType.INDEFINITE); timerActions.add(act); whileCondition.addListener((obs, old, newValue) -> { if (!newValue.booleanValue()) act.expire(); }); } /** * The Runnable action will be executed once after given delay * * Note: the scheduled action will not run while the game is paused * * @param action * @param delay */ public void runOnceAfter(Runnable action, double delay) { timerActions.add(new TimerAction(now, delay, action, TimerType.ONCE)); } /** * Fires an FXGL event on all entities whose type * matches given arguments * * @param event * @param type * @param types */ public void fireFXGLEvent(FXGLEvent event, EntityType type, EntityType... types) { getEntities(type, types).forEach(e -> e.fireFXGLEvent(event)); } /** * Fires an FXGL event on all entities registered in the application * * @param event */ public void fireFXGLEvent(FXGLEvent event) { getAllEntities().forEach(e -> e.fireFXGLEvent(event)); } /** * Saves a screenshot of the current main scene into a ".png" file * * @return true if the screenshot was saved successfully, false otherwise */ protected boolean saveScreenshot() { Image fxImage = mainScene.snapshot(null); BufferedImage img = SwingFXUtils.fromFXImage(fxImage, null); String fileName = "./" + settings.getTitle() + settings.getVersion() + LocalDateTime.now() + ".png"; fileName = fileName.replace(":", "_"); try (OutputStream os = Files.newOutputStream(Paths.get(fileName))) { return ImageIO.write(img, "png", os); } catch (Exception e) { log.finer("Exception occurred during saveScreenshot() - " + e.getMessage()); } return false; } /** * * @return width of the main scene */ public double getWidth() { return currentWidth; } /** * * @return height of the main scene */ public double getHeight() { return currentHeight; } /** * * @return current tick since the start of game */ public long getTick() { return tick; } /** * * @return current time since start of game in nanoseconds */ public long getNow() { return now; } }
src/com/almasb/fxgl/GameApplication.java
/* * The MIT License (MIT) * * FXGL - JavaFX Game Library * * Copyright (c) 2015 AlmasB (almaslvl@gmail.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.almasb.fxgl; import java.awt.image.BufferedImage; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import javax.imageio.ImageIO; import com.almasb.fxgl.TimerAction.TimerType; import com.almasb.fxgl.asset.AssetManager; import com.almasb.fxgl.effect.ParticleManager; import com.almasb.fxgl.entity.CombinedEntity; import com.almasb.fxgl.entity.Entity; import com.almasb.fxgl.entity.EntityType; import com.almasb.fxgl.entity.FXGLEvent; import com.almasb.fxgl.event.InputManager; import com.almasb.fxgl.event.QTEManager; import com.almasb.fxgl.physics.PhysicsEntity; import com.almasb.fxgl.physics.PhysicsManager; import javafx.animation.AnimationTimer; import javafx.application.Application; import javafx.application.Platform; import javafx.beans.property.BooleanProperty; import javafx.embed.swing.SwingFXUtils; import javafx.geometry.Point2D; import javafx.geometry.Rectangle2D; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.input.KeyEvent; import javafx.scene.layout.Pane; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; /** * To use FXGL extend this class and implement necessary methods * * @author Almas Baimagambetov (AlmasB) (almaslvl@gmail.com) * @version 1.0 * */ public abstract class GameApplication extends Application { static { Thread.setDefaultUncaughtExceptionHandler((thread, error) -> { FXGLLogger.getLogger("FXGL.DefaultErrorHandler").severe("Unhandled Exception"); FXGLLogger.getLogger("FXGL.DefaultErrorHandler").severe(FXGLLogger.errorTraceAsString(error)); FXGLLogger.getLogger("FXGL.DefaultErrorHandler").severe("Closing due to Unhandled Exception"); FXGLLogger.close(); System.exit(0); }); FXGLLogger.init(Level.ALL); Version.print(); } /** * The logger */ protected static final Logger log = FXGLLogger.getLogger("FXGL.GameApplication"); /** * A second in nanoseconds */ public static final long SECOND = 1000000000; /** * Time per single frame in nanoseconds */ public static final long TIME_PER_FRAME = SECOND / 60; /** * A minute in nanoseconds */ public static final long MINUTE = 60 * SECOND; /** * Settings for this game instance */ private GameSettings settings = new GameSettings(); /* * All scenegraph roots */ /** * The root for entities (game objects) */ private Pane gameRoot = new Pane(); /** * The overlay root above {@link #gameRoot}. Contains UI elements, native JavaFX nodes. * May also contain entities as Entity is a subclass of Parent. * uiRoot isn't affected by viewport movement. */ private Pane uiRoot = new Pane(); /** * THE root of the {@link #mainScene}. Contains {@link #gameRoot} and {@link #uiRoot} in this order. */ private Pane root = new Pane(gameRoot, uiRoot); /** * The root of the {@link #mainMenuScene} */ private Pane mainMenuRoot = new Pane(); /** * Reference to game scene */ protected Scene mainScene = new Scene(root); /** * Reference to game window */ protected Stage mainStage; /** * Scene for main menu */ private Scene mainMenuScene = new Scene(mainMenuRoot); /** * These are current width and height of the scene * NOT the window */ private double currentWidth, currentHeight; private List<Entity> tmpAddList = new ArrayList<>(); private List<Entity> tmpRemoveList = new ArrayList<>(); /** * The main loop timer */ private AnimationTimer timer = new AnimationTimer() { @Override public void handle(long internalTime) { processUpdate(internalTime); } }; /** * List for all timer based actions */ private List<TimerAction> timerActions = new ArrayList<>(); /* * Various managers that handle different aspects of the application */ protected final InputManager inputManager = new InputManager(this); /** * Used for loading various assets */ protected final AssetManager assetManager = AssetManager.INSTANCE; protected final PhysicsManager physicsManager = new PhysicsManager(this); protected final ParticleManager particleManager = new ParticleManager(this); protected final QTEManager qteManager = new QTEManager(this); protected final SaveLoadManager saveLoadManager = new SaveLoadManager(); /** * Default random number generator */ protected final Random random = new Random(); /** * Current time for this tick in nanoseconds. Also time elapsed * from the start of game. This time does not change while the game is paused */ protected long now = 0; /** * Current tick. It is also number of ticks since start of game */ protected long tick = 0; /** * These are used to approximate FPS value */ private FPSCounter fpsCounter = new FPSCounter(); private FPSCounter fpsPerformanceCounter = new FPSCounter(); /** * Used as delta from internal JavaFX timestamp to calculate render FPS */ private long fpsTime = 0; /** * Average render FPS */ protected int fps = 0; /** * Average performance FPS */ protected int fpsPerformance = 0; /** * Initialize game settings * * @param settings */ protected abstract void initSettings(GameSettings settings); /** * Override to use your custom intro video * * @return */ protected Intro initIntroVideo() { return new FXGLIntro(getWidth(), getHeight()); } /** * Initialize game assets, such as Texture, AudioClip, Music * * @throws Exception */ protected abstract void initAssets() throws Exception; /** * Initialize game objects */ protected abstract void initGame(); /** * Initiliaze collision handlers, physics properties */ protected abstract void initPhysics(); /** * Initiliaze UI objects */ protected abstract void initUI(); /** * Initiliaze input, i.e. * bind key presses / key typed, bind mouse */ protected abstract void initInput(); /** * Main loop update phase, most of game logic and clean up * * @param now */ protected abstract void onUpdate(); /** * Default implementation does nothing * * Override to add your own cleanup */ protected void onExit() { } /** * Override this method to initialize custom * main menu * * If you do override it make sure to call {@link #startGame()} * to start the game * * @param mainMenuRoot */ protected void initMainMenu(Pane mainMenuRoot) { } /** * This is called AFTER all init methods complete * and BEFORE the main loop starts * * It is safe to use any protected fields at this stage */ protected void postInit() { } /** * Set preferred sizes to roots and set * stage properties */ private void applySettings() { currentWidth = settings.getWidth(); currentHeight = settings.getHeight(); mainStage.setTitle(settings.getTitle() + " " + settings.getVersion()); mainStage.setResizable(false); mainMenuRoot.setPrefSize(settings.getWidth(), settings.getHeight()); root.setPrefSize(settings.getWidth(), settings.getHeight()); // ensure the window frame is just right for the scene size mainStage.setScene(mainScene); mainStage.sizeToScene(); } /** * Ensure managers are of legal state and ready */ private void initManagers() { inputManager.init(mainScene); qteManager.init(); mainScene.addEventHandler(KeyEvent.KEY_RELEASED, qteManager::keyReleasedHandler); } /** * Opens and shows the actual window. Configures what parts of scenes * need to be shown and in which * order based on the subclass implementation of certain init methods */ private void configureAndShowStage() { boolean menuEnabled = mainMenuRoot.getChildren().size() > 0; mainStage.setScene(menuEnabled ? mainMenuScene : mainScene); mainStage.setOnCloseRequest(event -> exit()); mainStage.show(); if (settings.isIntroEnabled()) { Intro intro = initIntroVideo(); if (intro == null) intro = new FXGLIntro(getWidth(), getHeight()); intro.onFinished = () -> { if (menuEnabled) mainMenuScene.setRoot(mainMenuRoot); else { mainScene.setRoot(root); timer.start(); } }; if (menuEnabled) mainMenuScene.setRoot(intro); else mainScene.setRoot(intro); intro.startIntro(); } else { if (!menuEnabled) timer.start(); } } @Override public void start(Stage primaryStage) throws Exception { log.finer("start()"); // capture the reference to primaryStage so we can access it mainStage = primaryStage; initSettings(settings); applySettings(); initManagers(); try { initAssets(); initMainMenu(mainMenuRoot); initGame(); initPhysics(); initUI(); initInput(); postInit(); } catch (Exception e) { log.severe("Exception occurred during initialization: " + e.getMessage()); StackTraceElement[] trace = e.getStackTrace(); Arrays.asList(trace) .stream() .map(StackTraceElement::toString) .filter(s -> !s.contains("Unknown Source") && !s.contains("Native Method")) .map(s -> "Cause: " + s) .forEachOrdered(log::severe); exit(); } configureAndShowStage(); } /** * This is the internal FXGL update tick, * executed 60 times a second ~ every 0.166 (6) seconds * * @param internalTime - The timestamp of the current frame given in nanoseconds (from JavaFX) */ private void processUpdate(long internalTime) { long startNanos = System.nanoTime(); long realFPS = internalTime - fpsTime; fpsTime = internalTime; timerActions.forEach(action -> action.update(now)); timerActions.removeIf(TimerAction::isExpired); inputManager.onUpdate(now); physicsManager.onUpdate(now); onUpdate(); gameRoot.getChildren().addAll(tmpAddList); tmpAddList.clear(); gameRoot.getChildren().removeAll(tmpRemoveList); tmpRemoveList.stream() .filter(e -> e instanceof PhysicsEntity) .map(e -> (PhysicsEntity)e) .forEach(physicsManager::destroyBody); tmpRemoveList.forEach(entity -> entity.onClean()); tmpRemoveList.clear(); gameRoot.getChildren().stream().map(node -> (Entity)node).forEach(entity -> entity.onUpdate(now)); fpsPerformance = Math.round(fpsPerformanceCounter.count(SECOND / (System.nanoTime() - startNanos))); fps = Math.round(fpsCounter.count(SECOND / realFPS)); tick++; now += TIME_PER_FRAME; } /** * Sets viewport origin. Use it for camera movement * * Do NOT use if the viewport was bound * * @param x * @param y */ public void setViewportOrigin(int x, int y) { gameRoot.setLayoutX(-x); gameRoot.setLayoutY(-y); } /** * Note: viewport origin, like anything in a scene, has top-left origin point * * @return viewport origin */ public Point2D getViewportOrigin() { return new Point2D(-gameRoot.getLayoutX(), -gameRoot.getLayoutY()); } /** * Binds the viewport origin so that it follows the given entity * distX and distY represent bound distance between entity and viewport origin * * <pre> * Example: * * bindViewportOrigin(player, (int) (getWidth() / 2), (int) (getHeight() / 2)); * * the code above centers the camera on player * For most platformers / side scrollers use: * * bindViewportOriginX(player, (int) (getWidth() / 2)); * * </pre> * * @param entity * @param distX * @param distY */ protected void bindViewportOrigin(Entity entity, int distX, int distY) { gameRoot.layoutXProperty().bind(entity.translateXProperty().negate().add(distX)); gameRoot.layoutYProperty().bind(entity.translateYProperty().negate().add(distY)); } /** * Binds the viewport origin so that it follows the given entity * distX represent bound distance in X axis between entity and viewport origin * * @param entity * @param distX */ protected void bindViewportOriginX(Entity entity, int distX) { gameRoot.layoutXProperty().bind(entity.translateXProperty().negate().add(distX)); } /** * Binds the viewport origin so that it follows the given entity * distY represent bound distance in Y axis between entity and viewport origin * * @param entity * @param distY */ protected void bindViewportOriginY(Entity entity, int distY) { gameRoot.layoutYProperty().bind(entity.translateYProperty().negate().add(distY)); } /** * * @return a list of ALL entities currently registered in the application */ public List<Entity> getAllEntities() { return gameRoot.getChildren().stream() .map(node -> (Entity)node) .collect(Collectors.toList()); } /** * Returns a list of entities whose type matches given * arguments * * @param type * @param types * @return */ public List<Entity> getEntities(EntityType type, EntityType... types) { List<String> list = Arrays.asList(types).stream() .map(EntityType::getUniqueType) .collect(Collectors.toList()); list.add(type.getUniqueType()); return gameRoot.getChildren().stream() .map(node -> (Entity)node) .filter(entity -> list.contains(entity.getTypeAsString())) .collect(Collectors.toList()); } /** * Returns a list of entities whose type matches given arguments and * which are partially or entirely * in the specified rectangular selection * * @param selection Rectangle2D that describes the selection box * @param type * @param types * @return */ public List<Entity> getEntitiesInRange(Rectangle2D selection, EntityType type, EntityType... types) { Entity boundsEntity = Entity.noType(); boundsEntity.setPosition(selection.getMinX(), selection.getMinY()); boundsEntity.setGraphics(new Rectangle(selection.getWidth(), selection.getHeight())); return getEntities(type, types).stream() .filter(entity -> entity.getBoundsInParent().intersects(boundsEntity.getBoundsInParent())) .collect(Collectors.toList()); } /** * Add an entity/entities to the scenegraph * * This is safe to be called from any thread * * @param entities */ public void addEntities(Entity... entities) { for (Entity e : entities) { if (e instanceof CombinedEntity) { tmpAddList.addAll(e.getChildrenUnmodifiable() .stream().map(node -> (Entity)node) .collect(Collectors.toList())); } else if (e instanceof PhysicsEntity) { physicsManager.createBody((PhysicsEntity) e); tmpAddList.add(e); } else tmpAddList.add(e); } } /** * Remove an entity from the scenegraph * * This is safe to be called from any thread * * @param entity */ public void removeEntity(Entity entity) { tmpRemoveList.add(entity); } /** * Equivalent to uiRoot.getChildren().addAll() * * @param n * @param nodes */ public void addUINodes(Node n, Node... nodes) { uiRoot.getChildren().add(n); uiRoot.getChildren().addAll(nodes); } /** * Equivalent to uiRoot.getChildren().remove() * * @param n */ public void removeUINode(Node n) { uiRoot.getChildren().remove(n); } /** * Call this to manually start the game when you * override {@link #initMainMenu(Pane)} */ protected void startGame() { mainStage.setScene(mainScene); timer.start(); } /** * Pauses the main loop execution */ public void pause() { timer.stop(); } /** * Resumes the main loop execution */ public void resume() { timer.start(); } /** * Pauses the game and opens main menu * Does nothing if main menu was not initialized */ protected void openMainMenu() { if (mainMenuRoot.getChildren().size() == 0) return; timer.stop(); // we are changing our scene so it is intuitive that // all input gets cleared inputManager.clearAllInput(); mainStage.setScene(mainMenuScene); } /** * This method will be automatically called when main window is closed * This method will shutdown the threads and close the logger * * You can call this method when you want to quit the application manually * from the game */ protected final void exit() { log.finer("Closing Normally"); onExit(); FXGLLogger.close(); Platform.exit(); } /** * The Runnable action will be scheduled to run at given interval. * The action will run for the first time after given interval. * * Note: the scheduled action will not run while the game is paused * * @param action the action * @param interval time in nanoseconds */ public void runAtInterval(Runnable action, double interval) { timerActions.add(new TimerAction(now, interval, action, TimerType.INDEFINITE)); } /** * The Runnable action will be scheduled for execution iff * whileCondition is initially true. If that's the case * then the Runnable action will be scheduled to run at given interval. * The action will run for the first time after given interval * * The action will be removed from schedule when whileCondition becomes {@code false}. * * Note: the scheduled action will not run while the game is paused * * @param action * @param interval * @param whileCondition */ public void runAtIntervalWhile(Runnable action, double interval, BooleanProperty whileCondition) { if (!whileCondition.get()) { return; } TimerAction act = new TimerAction(now, interval, action, TimerType.INDEFINITE); timerActions.add(act); whileCondition.addListener((obs, old, newValue) -> { if (!newValue.booleanValue()) act.expire(); }); } /** * The Runnable action will be executed once after given delay * * Note: the scheduled action will not run while the game is paused * * @param action * @param delay */ public void runOnceAfter(Runnable action, double delay) { timerActions.add(new TimerAction(now, delay, action, TimerType.ONCE)); } /** * Fires an FXGL event on all entities whose type * matches given arguments * * @param event * @param type * @param types */ public void fireFXGLEvent(FXGLEvent event, EntityType type, EntityType... types) { getEntities(type, types).forEach(e -> e.fireFXGLEvent(event)); } /** * Fires an FXGL event on all entities registered in the application * * @param event */ public void fireFXGLEvent(FXGLEvent event) { getAllEntities().forEach(e -> e.fireFXGLEvent(event)); } /** * Saves a screenshot of the current main scene into a ".png" file * * @return true if the screenshot was saved successfully, false otherwise */ protected boolean saveScreenshot() { Image fxImage = mainScene.snapshot(null); BufferedImage img = SwingFXUtils.fromFXImage(fxImage, null); String fileName = "./" + settings.getTitle() + settings.getVersion() + LocalDateTime.now() + ".png"; fileName = fileName.replace(":", "_"); try (OutputStream os = Files.newOutputStream(Paths.get(fileName))) { return ImageIO.write(img, "png", os); } catch (Exception e) { log.finer("Exception occurred during saveScreenshot() - " + e.getMessage()); } return false; } /** * * @return width of the main scene */ public double getWidth() { return currentWidth; } /** * * @return height of the main scene */ public double getHeight() { return currentHeight; } /** * * @return current tick since the start of game */ public long getTick() { return tick; } /** * * @return current time since start of game in nanoseconds */ public long getNow() { return now; } }
no need to create a reference for trace
src/com/almasb/fxgl/GameApplication.java
no need to create a reference for trace
Java
mit
f91fb0c06339b488cb1609d737e497905a419385
0
EDACC/edacc_gui,EDACC/edacc_gui,EDACC/edacc_gui,EDACC/edacc_gui,EDACC/edacc_gui
/* * EDACCGridSettingsView.java * * Created on Nov 26, 2009, 7:54:46 PM */ package edacc; import edacc.model.DBEmptyException; import edacc.model.DBVersionException; import edacc.model.DBVersionUnknownException; import edacc.model.DatabaseConnector; import edacc.model.NoConnectionToDBException; import edacc.model.TaskRunnable; import edacc.model.Tasks; import java.awt.event.KeyEvent; import java.io.IOException; import java.sql.SQLException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import org.jdesktop.application.ApplicationContext; /** * * @author Daniel D. */ public class EDACCDatabaseSettingsView extends javax.swing.JDialog { private final String connection_settings_filename = "connection_details.xml"; /** Creates new form EDACCGridSettingsView */ public EDACCDatabaseSettingsView(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); //btnConnect.requestFocus(); getRootPane().setDefaultButton(btnConnect); try { loadDatabaseSettings(null); reloadSessionNames(); txtSessionName.setText(""); } catch (IOException ex) { Logger.getLogger(EDACCDatabaseSettingsView.class.getName()).log(Level.SEVERE, null, ex); } } private void loadDatabaseSettings(String sessionName) throws IOException { String ext = ""; if (sessionName != null) { ext = "[" + sessionName + "]"; } ApplicationContext ctxt = EDACCApp.getApplication().getContext(); Map<String, String> map = (Map<String, String>) ctxt.getLocalStorage().load(connection_settings_filename); if (map != null) { if (map.containsKey("hostname" + ext)) { this.txtHostname.setText(map.get("hostname" + ext)); } if (map.containsKey("database" + ext)) { this.txtDatabase.setText(map.get("database" + ext)); } if (map.containsKey("port" + ext)) { this.txtPort.setText(map.get("port" + ext)); } if (map.containsKey("username" + ext)) { this.txtUsername.setText(map.get("username" + ext)); } if (map.containsKey("max_connections" + ext)) { this.txtMaxConnections.setText(map.get("max_connections" + ext)); } if (map.containsKey("secured_connection" + ext)) { this.chkUseSSL.setSelected(map.get("secured_connection" + ext).equalsIgnoreCase("true")); } if (map.containsKey("use_compression" + ext)) { this.chkCompress.setSelected(map.get("use_compression" + ext).equalsIgnoreCase("true")); } if (map.containsKey("save_password" + ext)) { this.chkSavePassword.setSelected(map.get("save_password" + ext).equalsIgnoreCase("true")); } if (this.chkSavePassword.isSelected() && map.containsKey("password" + ext)) { this.txtPassword.setText(map.get("password" + ext)); } } txtSessionName.setText(sessionName); } private void saveDatabaseSettings(String sessionName) throws IOException { String ext = ""; if (sessionName != null) { ext = "[" + sessionName + "]"; } ApplicationContext ctxt = EDACCApp.getApplication().getContext(); Map<String, String> map = (Map<String, String>) ctxt.getLocalStorage().load(connection_settings_filename); if (map == null) { map = new HashMap<String, String>(); } map.put("hostname" + ext, txtHostname.getText()); map.put("database" + ext, txtDatabase.getText()); map.put("port" + ext, txtPort.getText()); map.put("username" + ext, txtUsername.getText()); map.put("max_connections" + ext, txtMaxConnections.getText()); map.put("secured_connection" + ext, chkUseSSL.isSelected() ? "true" : "false"); map.put("use_compression" + ext, chkCompress.isSelected() ? "true" : "false"); map.put("save_password" + ext, chkSavePassword.isSelected() ? "true" : "false"); if (chkSavePassword.isSelected()) { map.put("password" + ext, txtPassword.getText()); } else { map.put("password" + ext, ""); } ctxt.getLocalStorage().save(map, connection_settings_filename); } private void removeSavedDatabaseSession(String sessionName) throws IOException { String ext = ""; if (sessionName != null) { ext = "[" + sessionName + "]"; } ApplicationContext ctxt = EDACCApp.getApplication().getContext(); Map<String, String> map = (Map<String, String>) ctxt.getLocalStorage().load(connection_settings_filename); if (map == null) { return; } map.remove("hostname" + ext); map.remove("database" + ext); map.remove("port" + ext); map.remove("username" + ext); map.remove("max_connections" + ext); map.remove("secured_connection" + ext); map.remove("use_compression" + ext); map.remove("save_password" + ext); map.remove("password" + ext); ctxt.getLocalStorage().save(map, connection_settings_filename); } private void reloadSessionNames() throws IOException { ApplicationContext ctxt = EDACCApp.getApplication().getContext(); Map<String, String> map = (Map<String, String>) ctxt.getLocalStorage().load(connection_settings_filename); if (map == null) { map = new HashMap<String, String>(); } List<String> sessions = new LinkedList<String>(); for (String key : map.keySet()) { if (key.startsWith("hostname") && key.length() >= 10) { String name = key.substring(9, key.length()-1); sessions.add(name); } } Collections.sort(sessions); listSavedSessions.setListData(sessions.toArray()); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { btnConnect = new javax.swing.JButton(); btnCancel = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); txtPassword = new javax.swing.JPasswordField(); lblPort = new javax.swing.JLabel(); lblHostname = new javax.swing.JLabel(); txtHostname = new javax.swing.JTextField(); lblDatabase = new javax.swing.JLabel(); txtDatabase = new javax.swing.JTextField(); lblUsername = new javax.swing.JLabel(); txtUsername = new javax.swing.JTextField(); txtPort = new javax.swing.JTextField(); lblPassword = new javax.swing.JLabel(); chkUseSSL = new javax.swing.JCheckBox(); lblPassword1 = new javax.swing.JLabel(); chkCompress = new javax.swing.JCheckBox(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); txtMaxConnections = new javax.swing.JTextField(); chkSavePassword = new javax.swing.JCheckBox(); btnSaveSession = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); txtSessionName = new javax.swing.JTextField(); jPanel2 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); listSavedSessions = new javax.swing.JList(); btnLoadSession = new javax.swing.JButton(); btnRemoveSession = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(edacc.EDACCApp.class).getContext().getResourceMap(EDACCDatabaseSettingsView.class); setTitle(resourceMap.getString("Form.title")); // NOI18N setIconImage(null); setMinimumSize(new java.awt.Dimension(400, 220)); setName("Form"); // NOI18N setResizable(false); btnConnect.setText(resourceMap.getString("btnConnect.text")); // NOI18N btnConnect.setToolTipText(resourceMap.getString("btnConnect.toolTipText")); // NOI18N btnConnect.setName("btnConnect"); // NOI18N btnConnect.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnConnectActionPerformed(evt); } }); btnConnect.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { btnConnectKeyPressed(evt); } }); btnCancel.setText(resourceMap.getString("btnCancel.text")); // NOI18N btnCancel.setToolTipText(resourceMap.getString("btnCancel.toolTipText")); // NOI18N btnCancel.setName("btnCancel"); // NOI18N btnCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCancelActionPerformed(evt); } }); btnCancel.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { btnCancelKeyPressed(evt); } }); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel1.border.title"))); // NOI18N jPanel1.setName("jPanel1"); // NOI18N txtPassword.setText(resourceMap.getString("txtPassword.text")); // NOI18N txtPassword.setToolTipText(resourceMap.getString("txtPassword.toolTipText")); // NOI18N txtPassword.setName("txtPassword"); // NOI18N txtPassword.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtPasswordKeyPressed(evt); } }); lblPort.setLabelFor(txtPort); lblPort.setText(resourceMap.getString("lblPort.text")); // NOI18N lblPort.setMaximumSize(new java.awt.Dimension(100, 17)); lblPort.setMinimumSize(new java.awt.Dimension(100, 17)); lblPort.setName("lblPort"); // NOI18N lblPort.setPreferredSize(new java.awt.Dimension(100, 17)); lblHostname.setLabelFor(txtHostname); lblHostname.setText(resourceMap.getString("lblHostname.text")); // NOI18N lblHostname.setMaximumSize(new java.awt.Dimension(100, 17)); lblHostname.setMinimumSize(new java.awt.Dimension(100, 17)); lblHostname.setName("lblHostname"); // NOI18N lblHostname.setPreferredSize(new java.awt.Dimension(100, 17)); txtHostname.setText(resourceMap.getString("txtHostname.text")); // NOI18N txtHostname.setToolTipText(resourceMap.getString("txtHostname.toolTipText")); // NOI18N txtHostname.setName("txtHostname"); // NOI18N txtHostname.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtHostnameKeyPressed(evt); } }); lblDatabase.setLabelFor(txtDatabase); lblDatabase.setText(resourceMap.getString("lblDatabase.text")); // NOI18N lblDatabase.setName("lblDatabase"); // NOI18N lblDatabase.setPreferredSize(new java.awt.Dimension(100, 17)); txtDatabase.setText(resourceMap.getString("txtDatabase.text")); // NOI18N txtDatabase.setToolTipText(resourceMap.getString("txtDatabase.toolTipText")); // NOI18N txtDatabase.setName("txtDatabase"); // NOI18N txtDatabase.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtDatabaseKeyPressed(evt); } }); lblUsername.setLabelFor(txtUsername); lblUsername.setText(resourceMap.getString("lblUsername.text")); // NOI18N lblUsername.setName("lblUsername"); // NOI18N lblUsername.setPreferredSize(new java.awt.Dimension(100, 17)); txtUsername.setText(resourceMap.getString("txtUsername.text")); // NOI18N txtUsername.setToolTipText(resourceMap.getString("txtUsername.toolTipText")); // NOI18N txtUsername.setName("txtUsername"); // NOI18N txtUsername.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtUsernameKeyPressed(evt); } }); txtPort.setText(resourceMap.getString("txtPort.text")); // NOI18N txtPort.setToolTipText(resourceMap.getString("txtPort.toolTipText")); // NOI18N txtPort.setName("txtPort"); // NOI18N txtPort.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtPortKeyPressed(evt); } }); lblPassword.setLabelFor(txtPassword); lblPassword.setText(resourceMap.getString("lblPassword.text")); // NOI18N lblPassword.setName("lblPassword"); // NOI18N lblPassword.setPreferredSize(new java.awt.Dimension(100, 17)); chkUseSSL.setText(resourceMap.getString("chkUseSSL.text")); // NOI18N chkUseSSL.setName("chkUseSSL"); // NOI18N lblPassword1.setLabelFor(txtPassword); lblPassword1.setText(resourceMap.getString("lblPassword1.text")); // NOI18N lblPassword1.setName("lblPassword1"); // NOI18N lblPassword1.setPreferredSize(new java.awt.Dimension(100, 17)); chkCompress.setText(resourceMap.getString("chkCompress.text")); // NOI18N chkCompress.setName("chkCompress"); // NOI18N jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N jLabel1.setName("jLabel1"); // NOI18N jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N jLabel2.setName("jLabel2"); // NOI18N txtMaxConnections.setText(resourceMap.getString("txtMaxConnections.text")); // NOI18N txtMaxConnections.setName("txtMaxConnections"); // NOI18N txtMaxConnections.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtMaxConnectionsKeyPressed(evt); } }); chkSavePassword.setText(resourceMap.getString("chkSavePassword.text")); // NOI18N chkSavePassword.setName("chkSavePassword"); // NOI18N btnSaveSession.setText(resourceMap.getString("btnSaveSession.text")); // NOI18N btnSaveSession.setName("btnSaveSession"); // NOI18N btnSaveSession.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSaveSessionActionPerformed(evt); } }); jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N jLabel3.setName("jLabel3"); // NOI18N txtSessionName.setText(resourceMap.getString("txtSessionName.text")); // NOI18N txtSessionName.setName("txtSessionName"); // NOI18N javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblHostname, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE) .addComponent(lblDatabase, 0, 0, Short.MAX_VALUE) .addComponent(lblUsername, 0, 0, Short.MAX_VALUE) .addComponent(lblPassword, 0, 0, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel2) .addGap(26, 26, 26)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(lblPassword1, 0, 0, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1) .addGap(61, 61, 61))) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3) .addGap(42, 42, 42))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(txtSessionName) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnSaveSession, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(chkSavePassword) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(txtHostname, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(32, 32, 32) .addComponent(lblPort, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE) .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(txtUsername) .addComponent(txtPassword) .addComponent(txtDatabase, javax.swing.GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE) .addComponent(chkCompress) .addComponent(chkUseSSL) .addComponent(txtMaxConnections)))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(lblHostname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtHostname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblPort, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(lblDatabase, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtDatabase, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(lblUsername, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(6, 6, 6) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(lblPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(chkSavePassword) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(txtMaxConnections, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblPassword1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(chkUseSSL)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(chkCompress)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnSaveSession) .addComponent(jLabel3) .addComponent(txtSessionName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {lblDatabase, lblHostname, lblPassword, lblUsername}); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel2.border.title"))); // NOI18N jPanel2.setName("jPanel2"); // NOI18N jScrollPane1.setName("jScrollPane1"); // NOI18N listSavedSessions.setName("listSavedSessions"); // NOI18N listSavedSessions.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { listSavedSessionsMouseClicked(evt); } }); jScrollPane1.setViewportView(listSavedSessions); btnLoadSession.setText(resourceMap.getString("btnLoadSession.text")); // NOI18N btnLoadSession.setName("btnLoadSession"); // NOI18N btnLoadSession.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnLoadSessionActionPerformed(evt); } }); btnRemoveSession.setText(resourceMap.getString("btnRemoveSession.text")); // NOI18N btnRemoveSession.setName("btnRemoveSession"); // NOI18N btnRemoveSession.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRemoveSessionActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(88, Short.MAX_VALUE) .addComponent(btnRemoveSession) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnLoadSession, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 240, Short.MAX_VALUE) ); jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnLoadSession, btnRemoveSession}); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 219, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnLoadSession) .addComponent(btnRemoveSession))) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 575, Short.MAX_VALUE) .addComponent(btnConnect, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 271, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnCancel) .addComponent(btnConnect)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed this.setVisible(false); this.dispose(); }//GEN-LAST:event_btnCancelActionPerformed private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConnectActionPerformed Tasks.startTask(new TaskRunnable() { @Override public void run(Tasks task) { try { try { saveDatabaseSettings(null); } catch (IOException ex) { // couldn't save connection settings, doesn't really matter Logger.getLogger(EDACCDatabaseSettingsView.class.getName()).log(Level.SEVERE, null, ex); } DatabaseConnector.getInstance().connect(txtHostname.getText(), Integer.parseInt(txtPort.getText()), txtUsername.getText(), txtDatabase.getText(), txtPassword.getText(), chkUseSSL.isSelected(), chkCompress.isSelected(), Integer.parseInt(txtMaxConnections.getText())); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { EDACCDatabaseSettingsView.this.setVisible(false); } }); } catch (ClassNotFoundException e) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JOptionPane.showMessageDialog(EDACCDatabaseSettingsView.this, "Couldn't find the MySQL jdbc driver Connector-J. Make sure it's in your Java class path", "Database driver not found", JOptionPane.ERROR_MESSAGE); } }); } catch (final SQLException e) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JOptionPane.showMessageDialog(EDACCDatabaseSettingsView.this, "Couldn't connect to the database: \n\n" + e.getMessage(), "Connection error", JOptionPane.ERROR_MESSAGE); } }); } catch (final DBVersionException e) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { handleDBVersionException(e); } }); } catch (final DBVersionUnknownException e) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { handleDBVersionException(e); } }); } catch (final DBEmptyException e) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { handleDBVersionException(e); } }); } } }); }//GEN-LAST:event_btnConnectActionPerformed private void handleDBVersionException(Exception ex) { if (ex instanceof DBEmptyException) { if (JOptionPane.showConfirmDialog(this, "It seems that there are no tables in the database. Do you want to create them?", "Warning!", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION) { Tasks.startTask(new TaskRunnable() { @Override public void run(Tasks task) { try { DatabaseConnector.getInstance().createDBSchema(task); } catch (NoConnectionToDBException ex1) { JOptionPane.showMessageDialog(Tasks.getTaskView(), "Couldn't generate the EDACC tables: No connection to database. Please connect to a database first.", "Error!", JOptionPane.ERROR_MESSAGE); DatabaseConnector.getInstance().disconnect(); } catch (SQLException ex) { JOptionPane.showMessageDialog(Tasks.getTaskView(), "An error occured while trying to generate the EDACC tables: " + ex.getMessage(), "Error!", JOptionPane.ERROR_MESSAGE); DatabaseConnector.getInstance().disconnect(); } catch (IOException ex) { JOptionPane.showMessageDialog(Tasks.getTaskView(), "An error occured while trying to generate the EDACC tables: " + ex.getMessage(), "Error!", JOptionPane.ERROR_MESSAGE); DatabaseConnector.getInstance().disconnect(); } } }); } else { DatabaseConnector.getInstance().disconnect(); } return; } boolean updateModel = false; if (ex instanceof DBVersionUnknownException) { int userinput = JOptionPane.showConfirmDialog(this, "The version of the database model is unknown. If you created the database\ntables with EDACC 0.2 or EDACC 0.3, you can update the database model\nnow to version " + ((DBVersionUnknownException) ex).localVersion + ".\nDo you want to update the database model?", "Unknown Database Model Version", JOptionPane.YES_NO_OPTION); if (userinput == 0) { // update model updateModel = true; } else { // don't update model } } else if (ex instanceof DBVersionException) { int currentVersion = ((DBVersionException) ex).currentVersion; int localVersion = ((DBVersionException) ex).localVersion; if (currentVersion > localVersion) { JOptionPane.showMessageDialog(this, "The version of the database model is too new. Please update you EDACC application.", "Error", JOptionPane.ERROR_MESSAGE); } else { int userinput = JOptionPane.showConfirmDialog(this, "The version of the database model is " + currentVersion + " which is older\nthan the database model version supported by this application.\nDo you want to update the database model?", "Database Model Version", JOptionPane.YES_NO_OPTION); if (userinput == 0) { // update model updateModel = true; } else { // don't update model } } } if (!updateModel) { DatabaseConnector.getInstance().disconnect(); } else { Tasks.startTask(new TaskRunnable() { @Override public void run(Tasks task) { try { DatabaseConnector.getInstance().updateDBModel(task); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { EDACCDatabaseSettingsView.this.setVisible(false); } }); } catch (final Exception ex1) { DatabaseConnector.getInstance().disconnect(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JOptionPane.showMessageDialog(EDACCDatabaseSettingsView.this, "Error while updating database model:\n\n" + ex1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } }); } } }); } } private void txtHostnameKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtHostnameKeyPressed // if (evt.getKeyCode() == KeyEvent.VK_TAB) { // txtHostname.select(0, 0); // txtPort.requestFocus(); // txtPort.selectAll(); // } if (evt.getKeyCode() == KeyEvent.VK_ENTER) // connect to DB { evt.consume(); btnConnectActionPerformed(null); } }//GEN-LAST:event_txtHostnameKeyPressed private void txtPortKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPortKeyPressed // if (evt.getKeyCode() == KeyEvent.VK_TAB) { // txtPort.select(0, 0); // txtDatabase.requestFocus(); // txtDatabase.selectAll(); // } if (evt.getKeyCode() == KeyEvent.VK_ENTER) // connect to DB { evt.consume(); btnConnectActionPerformed(null); } }//GEN-LAST:event_txtPortKeyPressed private void txtDatabaseKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDatabaseKeyPressed // if (evt.getKeyCode() == KeyEvent.VK_TAB) { // txtDatabase.select(0, 0); // txtUsername.requestFocus(); // txtUsername.selectAll(); // } if (evt.getKeyCode() == KeyEvent.VK_ENTER) // connect to DB { evt.consume(); btnConnectActionPerformed(null); } }//GEN-LAST:event_txtDatabaseKeyPressed private void txtUsernameKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtUsernameKeyPressed // if (evt.getKeyCode() == KeyEvent.VK_TAB) { // txtUsername.select(0, 0); // txtPassword.requestFocus(); // txtPassword.selectAll(); // } if (evt.getKeyCode() == KeyEvent.VK_ENTER) // connect to DB { evt.consume(); btnConnectActionPerformed(null); } }//GEN-LAST:event_txtUsernameKeyPressed private void txtPasswordKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPasswordKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) // connect to DB { evt.consume(); btnConnectActionPerformed(null); } }//GEN-LAST:event_txtPasswordKeyPressed private void btnConnectKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnConnectKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) // connect to DB { evt.consume(); btnConnectActionPerformed(null); } }//GEN-LAST:event_btnConnectKeyPressed private void btnCancelKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnCancelKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) // connect to DB { evt.consume(); btnCancelActionPerformed(null); } }//GEN-LAST:event_btnCancelKeyPressed private void txtMaxConnectionsKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtMaxConnectionsKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) // connect to DB { evt.consume(); btnConnectActionPerformed(null); } }//GEN-LAST:event_txtMaxConnectionsKeyPressed private void listSavedSessionsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listSavedSessionsMouseClicked if (evt.getClickCount() > 1) { btnLoadSessionActionPerformed(null); btnConnectActionPerformed(null); } }//GEN-LAST:event_listSavedSessionsMouseClicked private void btnSaveSessionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveSessionActionPerformed if (!txtSessionName.getText().equals("")) { try { saveDatabaseSettings(txtSessionName.getText()); reloadSessionNames(); } catch (IOException ex) { Logger.getLogger(EDACCDatabaseSettingsView.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_btnSaveSessionActionPerformed private void btnLoadSessionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoadSessionActionPerformed if (listSavedSessions.getSelectedIndex() != -1) { Object sel = listSavedSessions.getModel().getElementAt(listSavedSessions.getSelectedIndex()); if (sel instanceof String) { try { loadDatabaseSettings((String) sel); } catch (IOException ex) { Logger.getLogger(EDACCDatabaseSettingsView.class.getName()).log(Level.SEVERE, null, ex); } } } }//GEN-LAST:event_btnLoadSessionActionPerformed private void btnRemoveSessionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveSessionActionPerformed if (listSavedSessions.getSelectedIndex() != -1) { Object sel = listSavedSessions.getModel().getElementAt(listSavedSessions.getSelectedIndex()); if (sel instanceof String) { try { removeSavedDatabaseSession((String) sel); reloadSessionNames(); } catch (IOException ex) { Logger.getLogger(EDACCDatabaseSettingsView.class.getName()).log(Level.SEVERE, null, ex); } } } }//GEN-LAST:event_btnRemoveSessionActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnCancel; private javax.swing.JButton btnConnect; private javax.swing.JButton btnLoadSession; private javax.swing.JButton btnRemoveSession; private javax.swing.JButton btnSaveSession; private javax.swing.JCheckBox chkCompress; private javax.swing.JCheckBox chkSavePassword; private javax.swing.JCheckBox chkUseSSL; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel lblDatabase; private javax.swing.JLabel lblHostname; private javax.swing.JLabel lblPassword; private javax.swing.JLabel lblPassword1; private javax.swing.JLabel lblPort; private javax.swing.JLabel lblUsername; private javax.swing.JList listSavedSessions; private javax.swing.JTextField txtDatabase; private javax.swing.JTextField txtHostname; private javax.swing.JTextField txtMaxConnections; private javax.swing.JPasswordField txtPassword; private javax.swing.JTextField txtPort; private javax.swing.JTextField txtSessionName; private javax.swing.JTextField txtUsername; // End of variables declaration//GEN-END:variables }
src/edacc/EDACCDatabaseSettingsView.java
/* * EDACCGridSettingsView.java * * Created on Nov 26, 2009, 7:54:46 PM */ package edacc; import edacc.model.DBEmptyException; import edacc.model.DBVersionException; import edacc.model.DBVersionUnknownException; import edacc.model.DatabaseConnector; import edacc.model.NoConnectionToDBException; import edacc.model.TaskRunnable; import edacc.model.Tasks; import java.awt.event.KeyEvent; import java.io.IOException; import java.sql.SQLException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import org.jdesktop.application.ApplicationContext; /** * * @author Daniel D. */ public class EDACCDatabaseSettingsView extends javax.swing.JDialog { private final String connection_settings_filename = "connection_details.xml"; /** Creates new form EDACCGridSettingsView */ public EDACCDatabaseSettingsView(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); //btnConnect.requestFocus(); getRootPane().setDefaultButton(btnConnect); try { loadDatabaseSettings(null); reloadSessionNames(); txtSessionName.setText(""); } catch (IOException ex) { Logger.getLogger(EDACCDatabaseSettingsView.class.getName()).log(Level.SEVERE, null, ex); } } private void loadDatabaseSettings(String sessionName) throws IOException { String ext = ""; if (sessionName != null) { ext = "[" + sessionName + "]"; } ApplicationContext ctxt = EDACCApp.getApplication().getContext(); Map<String, String> map = (Map<String, String>) ctxt.getLocalStorage().load(connection_settings_filename); if (map != null) { if (map.containsKey("hostname" + ext)) { this.txtHostname.setText(map.get("hostname" + ext)); } if (map.containsKey("database" + ext)) { this.txtDatabase.setText(map.get("database" + ext)); } if (map.containsKey("port" + ext)) { this.txtPort.setText(map.get("port")); } if (map.containsKey("username" + ext)) { this.txtUsername.setText(map.get("username" + ext)); } if (map.containsKey("max_connections" + ext)) { this.txtMaxConnections.setText(map.get("max_connections")); } if (map.containsKey("secured_connection" + ext)) { this.chkUseSSL.setSelected(map.get("secured_connection" + ext).equalsIgnoreCase("true")); } if (map.containsKey("use_compression" + ext)) { this.chkCompress.setSelected(map.get("use_compression" + ext).equalsIgnoreCase("true")); } if (map.containsKey("save_password" + ext)) { this.chkSavePassword.setSelected(map.get("save_password" + ext).equalsIgnoreCase("true")); } if (this.chkSavePassword.isSelected() && map.containsKey("password" + ext)) { this.txtPassword.setText(map.get("password" + ext)); } } txtSessionName.setText(sessionName); } private void saveDatabaseSettings(String sessionName) throws IOException { String ext = ""; if (sessionName != null) { ext = "[" + sessionName + "]"; } ApplicationContext ctxt = EDACCApp.getApplication().getContext(); Map<String, String> map = (Map<String, String>) ctxt.getLocalStorage().load(connection_settings_filename); map.put("hostname" + ext, txtHostname.getText()); map.put("database" + ext, txtDatabase.getText()); map.put("port" + ext, txtPort.getText()); map.put("username" + ext, txtUsername.getText()); map.put("max_connections" + ext, txtMaxConnections.getText()); map.put("secured_connection" + ext, chkUseSSL.isSelected() ? "true" : "false"); map.put("use_compression" + ext, chkCompress.isSelected() ? "true" : "false"); map.put("save_password" + ext, chkSavePassword.isSelected() ? "true" : "false"); if (chkSavePassword.isSelected()) { map.put("password" + ext, txtPassword.getText()); } else { map.put("password" + ext, ""); } ctxt.getLocalStorage().save(map, connection_settings_filename); } private void removeSavedDatabaseSession(String sessionName) throws IOException { String ext = ""; if (sessionName != null) { ext = "[" + sessionName + "]"; } ApplicationContext ctxt = EDACCApp.getApplication().getContext(); Map<String, String> map = (Map<String, String>) ctxt.getLocalStorage().load(connection_settings_filename); map.remove("hostname" + ext); map.remove("database" + ext); map.remove("port" + ext); map.remove("username" + ext); map.remove("max_connections" + ext); map.remove("secured_connection" + ext); map.remove("use_compression" + ext); map.remove("save_password" + ext); map.remove("password" + ext); ctxt.getLocalStorage().save(map, connection_settings_filename); } private void reloadSessionNames() throws IOException { ApplicationContext ctxt = EDACCApp.getApplication().getContext(); Map<String, String> map = (Map<String, String>) ctxt.getLocalStorage().load(connection_settings_filename); List<String> sessions = new LinkedList<String>(); for (String key : map.keySet()) { if (key.startsWith("hostname") && key.length() >= 10) { String name = key.substring(9, key.length()-1); sessions.add(name); } } Collections.sort(sessions); listSavedSessions.setListData(sessions.toArray()); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { btnConnect = new javax.swing.JButton(); btnCancel = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); txtPassword = new javax.swing.JPasswordField(); lblPort = new javax.swing.JLabel(); lblHostname = new javax.swing.JLabel(); txtHostname = new javax.swing.JTextField(); lblDatabase = new javax.swing.JLabel(); txtDatabase = new javax.swing.JTextField(); lblUsername = new javax.swing.JLabel(); txtUsername = new javax.swing.JTextField(); txtPort = new javax.swing.JTextField(); lblPassword = new javax.swing.JLabel(); chkUseSSL = new javax.swing.JCheckBox(); lblPassword1 = new javax.swing.JLabel(); chkCompress = new javax.swing.JCheckBox(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); txtMaxConnections = new javax.swing.JTextField(); chkSavePassword = new javax.swing.JCheckBox(); btnSaveSession = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); txtSessionName = new javax.swing.JTextField(); jPanel2 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); listSavedSessions = new javax.swing.JList(); btnLoadSession = new javax.swing.JButton(); btnRemoveSession = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(edacc.EDACCApp.class).getContext().getResourceMap(EDACCDatabaseSettingsView.class); setTitle(resourceMap.getString("Form.title")); // NOI18N setIconImage(null); setMinimumSize(new java.awt.Dimension(400, 220)); setName("Form"); // NOI18N setResizable(false); btnConnect.setText(resourceMap.getString("btnConnect.text")); // NOI18N btnConnect.setToolTipText(resourceMap.getString("btnConnect.toolTipText")); // NOI18N btnConnect.setName("btnConnect"); // NOI18N btnConnect.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnConnectActionPerformed(evt); } }); btnConnect.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { btnConnectKeyPressed(evt); } }); btnCancel.setText(resourceMap.getString("btnCancel.text")); // NOI18N btnCancel.setToolTipText(resourceMap.getString("btnCancel.toolTipText")); // NOI18N btnCancel.setName("btnCancel"); // NOI18N btnCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCancelActionPerformed(evt); } }); btnCancel.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { btnCancelKeyPressed(evt); } }); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel1.border.title"))); // NOI18N jPanel1.setName("jPanel1"); // NOI18N txtPassword.setText(resourceMap.getString("txtPassword.text")); // NOI18N txtPassword.setToolTipText(resourceMap.getString("txtPassword.toolTipText")); // NOI18N txtPassword.setName("txtPassword"); // NOI18N txtPassword.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtPasswordKeyPressed(evt); } }); lblPort.setLabelFor(txtPort); lblPort.setText(resourceMap.getString("lblPort.text")); // NOI18N lblPort.setMaximumSize(new java.awt.Dimension(100, 17)); lblPort.setMinimumSize(new java.awt.Dimension(100, 17)); lblPort.setName("lblPort"); // NOI18N lblPort.setPreferredSize(new java.awt.Dimension(100, 17)); lblHostname.setLabelFor(txtHostname); lblHostname.setText(resourceMap.getString("lblHostname.text")); // NOI18N lblHostname.setMaximumSize(new java.awt.Dimension(100, 17)); lblHostname.setMinimumSize(new java.awt.Dimension(100, 17)); lblHostname.setName("lblHostname"); // NOI18N lblHostname.setPreferredSize(new java.awt.Dimension(100, 17)); txtHostname.setText(resourceMap.getString("txtHostname.text")); // NOI18N txtHostname.setToolTipText(resourceMap.getString("txtHostname.toolTipText")); // NOI18N txtHostname.setName("txtHostname"); // NOI18N txtHostname.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtHostnameKeyPressed(evt); } }); lblDatabase.setLabelFor(txtDatabase); lblDatabase.setText(resourceMap.getString("lblDatabase.text")); // NOI18N lblDatabase.setName("lblDatabase"); // NOI18N lblDatabase.setPreferredSize(new java.awt.Dimension(100, 17)); txtDatabase.setText(resourceMap.getString("txtDatabase.text")); // NOI18N txtDatabase.setToolTipText(resourceMap.getString("txtDatabase.toolTipText")); // NOI18N txtDatabase.setName("txtDatabase"); // NOI18N txtDatabase.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtDatabaseKeyPressed(evt); } }); lblUsername.setLabelFor(txtUsername); lblUsername.setText(resourceMap.getString("lblUsername.text")); // NOI18N lblUsername.setName("lblUsername"); // NOI18N lblUsername.setPreferredSize(new java.awt.Dimension(100, 17)); txtUsername.setText(resourceMap.getString("txtUsername.text")); // NOI18N txtUsername.setToolTipText(resourceMap.getString("txtUsername.toolTipText")); // NOI18N txtUsername.setName("txtUsername"); // NOI18N txtUsername.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtUsernameKeyPressed(evt); } }); txtPort.setText(resourceMap.getString("txtPort.text")); // NOI18N txtPort.setToolTipText(resourceMap.getString("txtPort.toolTipText")); // NOI18N txtPort.setName("txtPort"); // NOI18N txtPort.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtPortKeyPressed(evt); } }); lblPassword.setLabelFor(txtPassword); lblPassword.setText(resourceMap.getString("lblPassword.text")); // NOI18N lblPassword.setName("lblPassword"); // NOI18N lblPassword.setPreferredSize(new java.awt.Dimension(100, 17)); chkUseSSL.setText(resourceMap.getString("chkUseSSL.text")); // NOI18N chkUseSSL.setName("chkUseSSL"); // NOI18N lblPassword1.setLabelFor(txtPassword); lblPassword1.setText(resourceMap.getString("lblPassword1.text")); // NOI18N lblPassword1.setName("lblPassword1"); // NOI18N lblPassword1.setPreferredSize(new java.awt.Dimension(100, 17)); chkCompress.setText(resourceMap.getString("chkCompress.text")); // NOI18N chkCompress.setName("chkCompress"); // NOI18N jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N jLabel1.setName("jLabel1"); // NOI18N jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N jLabel2.setName("jLabel2"); // NOI18N txtMaxConnections.setText(resourceMap.getString("txtMaxConnections.text")); // NOI18N txtMaxConnections.setName("txtMaxConnections"); // NOI18N txtMaxConnections.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtMaxConnectionsKeyPressed(evt); } }); chkSavePassword.setText(resourceMap.getString("chkSavePassword.text")); // NOI18N chkSavePassword.setName("chkSavePassword"); // NOI18N btnSaveSession.setText(resourceMap.getString("btnSaveSession.text")); // NOI18N btnSaveSession.setName("btnSaveSession"); // NOI18N btnSaveSession.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSaveSessionActionPerformed(evt); } }); jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N jLabel3.setName("jLabel3"); // NOI18N txtSessionName.setText(resourceMap.getString("txtSessionName.text")); // NOI18N txtSessionName.setName("txtSessionName"); // NOI18N javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblHostname, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE) .addComponent(lblDatabase, 0, 0, Short.MAX_VALUE) .addComponent(lblUsername, 0, 0, Short.MAX_VALUE) .addComponent(lblPassword, 0, 0, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel2) .addGap(26, 26, 26)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(lblPassword1, 0, 0, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1) .addGap(61, 61, 61))) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3) .addGap(42, 42, 42))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(txtSessionName) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnSaveSession, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(chkSavePassword) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(txtHostname, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(32, 32, 32) .addComponent(lblPort, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE) .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(txtUsername) .addComponent(txtPassword) .addComponent(txtDatabase, javax.swing.GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE) .addComponent(chkCompress) .addComponent(chkUseSSL) .addComponent(txtMaxConnections)))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(lblHostname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtHostname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblPort, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(lblDatabase, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtDatabase, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(lblUsername, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(6, 6, 6) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(lblPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(chkSavePassword) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(txtMaxConnections, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblPassword1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(chkUseSSL)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(chkCompress)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnSaveSession) .addComponent(jLabel3) .addComponent(txtSessionName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {lblDatabase, lblHostname, lblPassword, lblUsername}); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel2.border.title"))); // NOI18N jPanel2.setName("jPanel2"); // NOI18N jScrollPane1.setName("jScrollPane1"); // NOI18N listSavedSessions.setName("listSavedSessions"); // NOI18N listSavedSessions.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { listSavedSessionsMouseClicked(evt); } }); jScrollPane1.setViewportView(listSavedSessions); btnLoadSession.setText(resourceMap.getString("btnLoadSession.text")); // NOI18N btnLoadSession.setName("btnLoadSession"); // NOI18N btnLoadSession.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnLoadSessionActionPerformed(evt); } }); btnRemoveSession.setText(resourceMap.getString("btnRemoveSession.text")); // NOI18N btnRemoveSession.setName("btnRemoveSession"); // NOI18N btnRemoveSession.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRemoveSessionActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(88, Short.MAX_VALUE) .addComponent(btnRemoveSession) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnLoadSession, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 240, Short.MAX_VALUE) ); jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnLoadSession, btnRemoveSession}); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 219, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnLoadSession) .addComponent(btnRemoveSession))) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 575, Short.MAX_VALUE) .addComponent(btnConnect, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 271, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnCancel) .addComponent(btnConnect)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed this.setVisible(false); this.dispose(); }//GEN-LAST:event_btnCancelActionPerformed private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConnectActionPerformed Tasks.startTask(new TaskRunnable() { @Override public void run(Tasks task) { try { try { saveDatabaseSettings(null); } catch (IOException ex) { // couldn't save connection settings, doesn't really matter Logger.getLogger(EDACCDatabaseSettingsView.class.getName()).log(Level.SEVERE, null, ex); } DatabaseConnector.getInstance().connect(txtHostname.getText(), Integer.parseInt(txtPort.getText()), txtUsername.getText(), txtDatabase.getText(), txtPassword.getText(), chkUseSSL.isSelected(), chkCompress.isSelected(), Integer.parseInt(txtMaxConnections.getText())); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { EDACCDatabaseSettingsView.this.setVisible(false); } }); } catch (ClassNotFoundException e) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JOptionPane.showMessageDialog(EDACCDatabaseSettingsView.this, "Couldn't find the MySQL jdbc driver Connector-J. Make sure it's in your Java class path", "Database driver not found", JOptionPane.ERROR_MESSAGE); } }); } catch (final SQLException e) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JOptionPane.showMessageDialog(EDACCDatabaseSettingsView.this, "Couldn't connect to the database: \n\n" + e.getMessage(), "Connection error", JOptionPane.ERROR_MESSAGE); } }); } catch (final DBVersionException e) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { handleDBVersionException(e); } }); } catch (final DBVersionUnknownException e) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { handleDBVersionException(e); } }); } catch (final DBEmptyException e) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { handleDBVersionException(e); } }); } } }); }//GEN-LAST:event_btnConnectActionPerformed private void handleDBVersionException(Exception ex) { if (ex instanceof DBEmptyException) { if (JOptionPane.showConfirmDialog(this, "It seems that there are no tables in the database. Do you want to create them?", "Warning!", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION) { Tasks.startTask(new TaskRunnable() { @Override public void run(Tasks task) { try { DatabaseConnector.getInstance().createDBSchema(task); } catch (NoConnectionToDBException ex1) { JOptionPane.showMessageDialog(Tasks.getTaskView(), "Couldn't generate the EDACC tables: No connection to database. Please connect to a database first.", "Error!", JOptionPane.ERROR_MESSAGE); DatabaseConnector.getInstance().disconnect(); } catch (SQLException ex) { JOptionPane.showMessageDialog(Tasks.getTaskView(), "An error occured while trying to generate the EDACC tables: " + ex.getMessage(), "Error!", JOptionPane.ERROR_MESSAGE); DatabaseConnector.getInstance().disconnect(); } catch (IOException ex) { JOptionPane.showMessageDialog(Tasks.getTaskView(), "An error occured while trying to generate the EDACC tables: " + ex.getMessage(), "Error!", JOptionPane.ERROR_MESSAGE); DatabaseConnector.getInstance().disconnect(); } } }); } else { DatabaseConnector.getInstance().disconnect(); } return; } boolean updateModel = false; if (ex instanceof DBVersionUnknownException) { int userinput = JOptionPane.showConfirmDialog(this, "The version of the database model is unknown. If you created the database\ntables with EDACC 0.2 or EDACC 0.3, you can update the database model\nnow to version " + ((DBVersionUnknownException) ex).localVersion + ".\nDo you want to update the database model?", "Unknown Database Model Version", JOptionPane.YES_NO_OPTION); if (userinput == 0) { // update model updateModel = true; } else { // don't update model } } else if (ex instanceof DBVersionException) { int currentVersion = ((DBVersionException) ex).currentVersion; int localVersion = ((DBVersionException) ex).localVersion; if (currentVersion > localVersion) { JOptionPane.showMessageDialog(this, "The version of the database model is too new. Please update you EDACC application.", "Error", JOptionPane.ERROR_MESSAGE); } else { int userinput = JOptionPane.showConfirmDialog(this, "The version of the database model is " + currentVersion + " which is older\nthan the database model version supported by this application.\nDo you want to update the database model?", "Database Model Version", JOptionPane.YES_NO_OPTION); if (userinput == 0) { // update model updateModel = true; } else { // don't update model } } } if (!updateModel) { DatabaseConnector.getInstance().disconnect(); } else { Tasks.startTask(new TaskRunnable() { @Override public void run(Tasks task) { try { DatabaseConnector.getInstance().updateDBModel(task); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { EDACCDatabaseSettingsView.this.setVisible(false); } }); } catch (final Exception ex1) { DatabaseConnector.getInstance().disconnect(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JOptionPane.showMessageDialog(EDACCDatabaseSettingsView.this, "Error while updating database model:\n\n" + ex1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } }); } } }); } } private void txtHostnameKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtHostnameKeyPressed // if (evt.getKeyCode() == KeyEvent.VK_TAB) { // txtHostname.select(0, 0); // txtPort.requestFocus(); // txtPort.selectAll(); // } if (evt.getKeyCode() == KeyEvent.VK_ENTER) // connect to DB { evt.consume(); btnConnectActionPerformed(null); } }//GEN-LAST:event_txtHostnameKeyPressed private void txtPortKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPortKeyPressed // if (evt.getKeyCode() == KeyEvent.VK_TAB) { // txtPort.select(0, 0); // txtDatabase.requestFocus(); // txtDatabase.selectAll(); // } if (evt.getKeyCode() == KeyEvent.VK_ENTER) // connect to DB { evt.consume(); btnConnectActionPerformed(null); } }//GEN-LAST:event_txtPortKeyPressed private void txtDatabaseKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDatabaseKeyPressed // if (evt.getKeyCode() == KeyEvent.VK_TAB) { // txtDatabase.select(0, 0); // txtUsername.requestFocus(); // txtUsername.selectAll(); // } if (evt.getKeyCode() == KeyEvent.VK_ENTER) // connect to DB { evt.consume(); btnConnectActionPerformed(null); } }//GEN-LAST:event_txtDatabaseKeyPressed private void txtUsernameKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtUsernameKeyPressed // if (evt.getKeyCode() == KeyEvent.VK_TAB) { // txtUsername.select(0, 0); // txtPassword.requestFocus(); // txtPassword.selectAll(); // } if (evt.getKeyCode() == KeyEvent.VK_ENTER) // connect to DB { evt.consume(); btnConnectActionPerformed(null); } }//GEN-LAST:event_txtUsernameKeyPressed private void txtPasswordKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPasswordKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) // connect to DB { evt.consume(); btnConnectActionPerformed(null); } }//GEN-LAST:event_txtPasswordKeyPressed private void btnConnectKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnConnectKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) // connect to DB { evt.consume(); btnConnectActionPerformed(null); } }//GEN-LAST:event_btnConnectKeyPressed private void btnCancelKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnCancelKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) // connect to DB { evt.consume(); btnCancelActionPerformed(null); } }//GEN-LAST:event_btnCancelKeyPressed private void txtMaxConnectionsKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtMaxConnectionsKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) // connect to DB { evt.consume(); btnConnectActionPerformed(null); } }//GEN-LAST:event_txtMaxConnectionsKeyPressed private void listSavedSessionsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listSavedSessionsMouseClicked if (evt.getClickCount() > 1) { btnLoadSessionActionPerformed(null); btnConnectActionPerformed(null); } }//GEN-LAST:event_listSavedSessionsMouseClicked private void btnSaveSessionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveSessionActionPerformed if (!txtSessionName.getText().equals("")) { try { saveDatabaseSettings(txtSessionName.getText()); reloadSessionNames(); } catch (IOException ex) { Logger.getLogger(EDACCDatabaseSettingsView.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_btnSaveSessionActionPerformed private void btnLoadSessionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoadSessionActionPerformed if (listSavedSessions.getSelectedIndex() != -1) { Object sel = listSavedSessions.getModel().getElementAt(listSavedSessions.getSelectedIndex()); if (sel instanceof String) { try { loadDatabaseSettings((String) sel); } catch (IOException ex) { Logger.getLogger(EDACCDatabaseSettingsView.class.getName()).log(Level.SEVERE, null, ex); } } } }//GEN-LAST:event_btnLoadSessionActionPerformed private void btnRemoveSessionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveSessionActionPerformed if (listSavedSessions.getSelectedIndex() != -1) { Object sel = listSavedSessions.getModel().getElementAt(listSavedSessions.getSelectedIndex()); if (sel instanceof String) { try { removeSavedDatabaseSession((String) sel); reloadSessionNames(); } catch (IOException ex) { Logger.getLogger(EDACCDatabaseSettingsView.class.getName()).log(Level.SEVERE, null, ex); } } } }//GEN-LAST:event_btnRemoveSessionActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnCancel; private javax.swing.JButton btnConnect; private javax.swing.JButton btnLoadSession; private javax.swing.JButton btnRemoveSession; private javax.swing.JButton btnSaveSession; private javax.swing.JCheckBox chkCompress; private javax.swing.JCheckBox chkSavePassword; private javax.swing.JCheckBox chkUseSSL; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel lblDatabase; private javax.swing.JLabel lblHostname; private javax.swing.JLabel lblPassword; private javax.swing.JLabel lblPassword1; private javax.swing.JLabel lblPort; private javax.swing.JLabel lblUsername; private javax.swing.JList listSavedSessions; private javax.swing.JTextField txtDatabase; private javax.swing.JTextField txtHostname; private javax.swing.JTextField txtMaxConnections; private javax.swing.JPasswordField txtPassword; private javax.swing.JTextField txtPort; private javax.swing.JTextField txtSessionName; private javax.swing.JTextField txtUsername; // End of variables declaration//GEN-END:variables }
Fix database session dialog
src/edacc/EDACCDatabaseSettingsView.java
Fix database session dialog
Java
mit
104569a715be313848946bdf413ec033849765f0
0
gems-uff/prov-viewer
/* * The MIT License * * Copyright 2017 Kohwalter. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package br.uff.ic.utility.IO; import br.uff.ic.provviewer.VariableNames; import br.uff.ic.utility.graph.ActivityVertex; import br.uff.ic.utility.graph.AgentVertex; import br.uff.ic.utility.GraphAttribute; import br.uff.ic.utility.graph.Edge; import br.uff.ic.utility.graph.EntityVertex; import br.uff.ic.utility.graph.GraphVertex; import br.uff.ic.utility.graph.Vertex; import edu.uci.ics.jung.graph.Graph; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * * @author Kohwalter */ public class UnityReader extends XMLReader { boolean isProvenanceGraph; boolean hackLabelPathAndFile = false; boolean hackSplitFilePath = true; public UnityReader(File fXmlFile) throws URISyntaxException, IOException { super(fXmlFile); } /** * Method to read the file */ @Override public void readFile() { readHeader(); } /** * Method to read the attributes from the graph object (can be either an * edge or a vertex) * * @param element * @param node */ public void readAttribute(Element element, Map<String, GraphAttribute> attributes) { NodeList attributesList = element.getElementsByTagName("attributes"); if (attributesList.getLength() > 0) { Node nNode = attributesList.item(0); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; NodeList aList = eElement.getElementsByTagName("attribute"); boolean hasGraphFile = false; for (int i = 0; i < aList.getLength(); i++) { GraphAttribute att; if (eElement.getElementsByTagName("name").item(i).getTextContent().equalsIgnoreCase("GraphFile")) { hasGraphFile = true; } if (hackSplitFilePath) { if (eElement.getElementsByTagName("name").item(i).getTextContent().equalsIgnoreCase("Path")) { Collection<GraphAttribute> mPath = new ArrayList<>(); String[] paths = eElement.getElementsByTagName("value").item(i).getTextContent().split("/"); int j = 0; for (String s : paths) { mPath.add(new GraphAttribute("Path_#" + j, s)); j++; } for (GraphAttribute ga : mPath) { attributes.put(ga.getName(), ga); } } } if (eElement.getElementsByTagName("min").item(i) != null && eElement.getElementsByTagName("max").item(i) != null && eElement.getElementsByTagName("quantity").item(i) != null) { if (eElement.getElementsByTagName("originalValues").item(i) != null) { Node valuesList; valuesList = eElement.getElementsByTagName("originalValues").item(i); Element e = (Element) valuesList; Collection<String> oValues = new ArrayList<String>(); for (int j = 0; j < Integer.valueOf(eElement.getElementsByTagName("quantity").item(i).getTextContent()); j++) { oValues.add(e.getElementsByTagName("originalValue").item(j).getTextContent()); } att = new GraphAttribute(eElement.getElementsByTagName("name").item(i).getTextContent(), eElement.getElementsByTagName("value").item(i).getTextContent(), eElement.getElementsByTagName("min").item(i).getTextContent(), eElement.getElementsByTagName("max").item(i).getTextContent(), eElement.getElementsByTagName("quantity").item(i).getTextContent(), oValues); } else { att = new GraphAttribute(eElement.getElementsByTagName("name").item(i).getTextContent(), eElement.getElementsByTagName("value").item(i).getTextContent(), eElement.getElementsByTagName("min").item(i).getTextContent(), eElement.getElementsByTagName("max").item(i).getTextContent(), eElement.getElementsByTagName("quantity").item(i).getTextContent()); } } else { att = new GraphAttribute(eElement.getElementsByTagName("name").item(i).getTextContent(), eElement.getElementsByTagName("value").item(i).getTextContent()); } // node.addAttribute(att); attributes.put(att.getName(), att); } if (!hasGraphFile) { GraphAttribute att = new GraphAttribute(VariableNames.GraphFile, file.getName()); // node.addAttribute(att); attributes.put(att.getName(), att); } } } else { GraphAttribute att = new GraphAttribute(VariableNames.GraphFile, file.getName()); // node.addAttribute(att); attributes.put(att.getName(), att); } } /** * Method that reads the file Header and then the vertex and edge lists (Graph) */ public void readHeader() { isProvenanceGraph = true; NodeList nList; nList = doc.getElementsByTagName("edgesRightToLeft"); if (nList != null && nList.getLength() > 0 && !nList.item(0).getTextContent().equalsIgnoreCase("")) { isProvenanceGraph = Boolean.parseBoolean(nList.item(0).getTextContent()); } NodeList vList = doc.getElementsByTagName("vertex"); NodeList eList = doc.getElementsByTagName("edge"); readGraph(vList, eList, nodes, edges); } public void readGraph(NodeList vList, NodeList eList, Map<String, Vertex> vertices, Collection<Edge> edges) { readVertices(vList, vertices); readEdges(eList, edges, vertices); } /** * Method to read a vertex * @param nList * @param vertices */ public void readVertices(NodeList nList, Map<String, Vertex> vertices) { for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String id = eElement.getElementsByTagName("ID").item(0).getTextContent(); String type = eElement.getElementsByTagName("type").item(0).getTextContent(); String label = eElement.getElementsByTagName("label").item(0).getTextContent(); String date = eElement.getElementsByTagName("date").item(0).getTextContent(); Map<String, GraphAttribute> attributes = new HashMap<>(); readAttribute(eElement, attributes); GraphAttribute path = null; GraphAttribute fileName = null; if (hackLabelPathAndFile) { String[] folders = label.split("/"); String filePath = label.replace(folders[folders.length - 1], ""); String fn = folders[folders.length - 1]; path = new GraphAttribute("Path", filePath); fileName = new GraphAttribute("FileName", fn); if (type.equalsIgnoreCase("Entity")) { label = fn; } if (type.equalsIgnoreCase("Activity")) { label = label.split(":")[0]; } } Vertex node; if (type.equalsIgnoreCase("Activity")) { node = new ActivityVertex(id, label, date); } else if (type.equalsIgnoreCase("Entity")) { node = new EntityVertex(id, label, date); } else if (type.equalsIgnoreCase("Agent")) { node = new AgentVertex(id, label, date); } else { node = new GraphVertex(id, label, date); } // readAttribute(eElement, node); if (hackLabelPathAndFile) { if (node instanceof EntityVertex) { node.addAttribute(path); node.addAttribute(fileName); } } node.addAllAttributes(attributes); System.out.println("Reading vertex: " + id); if (node instanceof GraphVertex) { System.out.println("Its a GraphVertex!"); NodeList collapsedVertices = eElement.getElementsByTagName("collapsedvertices"); NodeList collapsedEdged = eElement.getElementsByTagName("collapsededges"); Node cVertexNode = collapsedVertices.item(0); Node cEdgeNode = collapsedEdged.item(0); if (cVertexNode.getNodeType() == Node.ELEMENT_NODE) { Element cVertexElement = (Element) cVertexNode; Element cEdgeElement = (Element) cEdgeNode; // NodeList vList = cVertexElement.getElementsByTagName("collapsedvertex"); // NodeList eList = cEdgeElement.getElementsByTagName("collapsededge"); NodeList vList = cVertexElement.getChildNodes(); NodeList eList = cEdgeElement.getChildNodes(); Map<String, Vertex> cv = new HashMap<>(); Collection<Edge> ce = new ArrayList<>(); readGraph(vList, eList, cv, ce); ((GraphVertex) node).setClusterGraph(ce, cv); } System.out.println("Finished Reading GraphVertex!"); } vertices.put(node.getID(), node); } } } /** * Method to read an edge */ public void readEdges(NodeList nList, Collection<Edge> edges, Map<String, Vertex> vertices) { for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String id = eElement.getElementsByTagName("ID").item(0).getTextContent(); String type = eElement.getElementsByTagName("type").item(0).getTextContent(); String label = eElement.getElementsByTagName("label").item(0).getTextContent(); String value = eElement.getElementsByTagName("value").item(0).getTextContent(); String source = eElement.getElementsByTagName("sourceID").item(0).getTextContent(); String target = eElement.getElementsByTagName("targetID").item(0).getTextContent(); Edge edge; Map<String, GraphAttribute> attributes = new HashMap<>(); readAttribute(eElement, attributes); String newSource = "Null"; String newTarget = "Null"; if (attributes.containsKey(VariableNames.vertexNewSource)) { newSource = attributes.get(VariableNames.vertexNewSource).getValue(); } if (attributes.containsKey(VariableNames.vertexNewTarget)) { newTarget = attributes.get(VariableNames.vertexNewTarget).getValue(); } if ((vertices.containsKey(source) || vertices.containsKey(newSource)) && (vertices.containsKey(target) || vertices.containsKey(newTarget))) { Vertex vs; Vertex vt; vs = findNode(source, vertices); vt = findNode(target, vertices); if (isProvenanceGraph) { edge = new Edge(id, type, label, value, vt, vs); } else { edge = new Edge(id, type, label, value, vs, vt); } edge.addAllAttributes(attributes); edges.add(edge); } else { System.out.println("Not possible!"); System.out.println("ID: " + id); System.out.println("source: " + source); System.out.println("target: " + target); System.out.println("NewSource: " + newSource); System.out.println("NewTarget: " + newTarget); } } } } /** * Method to find the original Vertex * @param ID is the vertex ID we are looking for * @param vertices is the map that contains the vertices with the Key being the vertex's ID * @return the vertex */ private Vertex findNode(String ID, Map<String, Vertex> vertices) { if (vertices.containsKey(ID)) { return vertices.get(ID); } else { for(String ids : vertices.keySet()) { if(ids.contains(ID)) { // It might have. Lets break it down to make sure it has the Source String currentID = ids.replace("[", ""); // Remove the GraphVertex ID brankets currentID = currentID.replace("]", ""); currentID = currentID.replace(" ", ""); // Remove spaces String[] subIDs = currentID.split(","); // Split each ID that composes the GraphVertex for(String i : subIDs) { // Lets check if each individual ID is the original Source if(i.equalsIgnoreCase(ID)) { // If true then the original vertex is inside this GraphVertex GraphVertex v = (GraphVertex) vertices.get(ids); // We got the GraphVertex, now need to explore it return findNode(v.clusterGraph, ID); } } } } } return null; } /** * Method to find the vertex inside a GraphVertex * @param clusterGraph is the GraphVertex's clustergraph * @param ID is the vertex's ID that we are looking for * @return the vertex */ private Vertex findNode(Graph clusterGraph, String ID) { Vertex found = null; for(Object v : clusterGraph.getVertices()) { if(((Vertex)v).getID().equalsIgnoreCase(ID)) return (Vertex) v; else if(v instanceof GraphVertex) found = findNode(((GraphVertex)v).clusterGraph, ID); } return found; } /** * Method that returns * @param id * @return */ public Vertex getNewPointer(String id) { return nodes.get(id); } }
src/main/java/br/uff/ic/utility/IO/UnityReader.java
/* * The MIT License * * Copyright 2017 Kohwalter. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package br.uff.ic.utility.IO; import br.uff.ic.provviewer.VariableNames; import br.uff.ic.utility.graph.ActivityVertex; import br.uff.ic.utility.graph.AgentVertex; import br.uff.ic.utility.GraphAttribute; import br.uff.ic.utility.graph.Edge; import br.uff.ic.utility.graph.EntityVertex; import br.uff.ic.utility.graph.GraphVertex; import br.uff.ic.utility.graph.Vertex; import edu.uci.ics.jung.graph.Graph; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * * @author Kohwalter */ public class UnityReader extends XMLReader { boolean isProvenanceGraph; boolean hackLabelPathAndFile = false; boolean hackSplitFilePath = true; public UnityReader(File fXmlFile) throws URISyntaxException, IOException { super(fXmlFile); } /** * Method to read the file */ @Override public void readFile() { readHeader(); } /** * Method to read the attributes from the graph object (can be either an * edge or a vertex) * * @param element * @param node */ public void readAttribute(Element element, Map<String, GraphAttribute> attributes) { NodeList attributesList = element.getElementsByTagName("attributes"); if (attributesList.getLength() > 0) { Node nNode = attributesList.item(0); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; NodeList aList = eElement.getElementsByTagName("attribute"); boolean hasGraphFile = false; for (int i = 0; i < aList.getLength(); i++) { GraphAttribute att; if (eElement.getElementsByTagName("name").item(i).getTextContent().equalsIgnoreCase("GraphFile")) { hasGraphFile = true; } if (hackSplitFilePath) { if (eElement.getElementsByTagName("name").item(i).getTextContent().equalsIgnoreCase("Path")) { Collection<GraphAttribute> mPath = new ArrayList<>(); String[] paths = eElement.getElementsByTagName("value").item(i).getTextContent().split("/"); int j = 0; for (String s : paths) { mPath.add(new GraphAttribute("Path_#" + j, s)); j++; } for (GraphAttribute ga : mPath) { attributes.put(ga.getName(), ga); } } } if (eElement.getElementsByTagName("min").item(i) != null && eElement.getElementsByTagName("max").item(i) != null && eElement.getElementsByTagName("quantity").item(i) != null) { if (eElement.getElementsByTagName("originalValues").item(i) != null) { Node valuesList; valuesList = eElement.getElementsByTagName("originalValues").item(i); Element e = (Element) valuesList; Collection<String> oValues = new ArrayList<String>(); for (int j = 0; j < Integer.valueOf(eElement.getElementsByTagName("quantity").item(i).getTextContent()); j++) { oValues.add(e.getElementsByTagName("originalValue").item(j).getTextContent()); } att = new GraphAttribute(eElement.getElementsByTagName("name").item(i).getTextContent(), eElement.getElementsByTagName("value").item(i).getTextContent(), eElement.getElementsByTagName("min").item(i).getTextContent(), eElement.getElementsByTagName("max").item(i).getTextContent(), eElement.getElementsByTagName("quantity").item(i).getTextContent(), oValues); } else { att = new GraphAttribute(eElement.getElementsByTagName("name").item(i).getTextContent(), eElement.getElementsByTagName("value").item(i).getTextContent(), eElement.getElementsByTagName("min").item(i).getTextContent(), eElement.getElementsByTagName("max").item(i).getTextContent(), eElement.getElementsByTagName("quantity").item(i).getTextContent()); } } else { att = new GraphAttribute(eElement.getElementsByTagName("name").item(i).getTextContent(), eElement.getElementsByTagName("value").item(i).getTextContent()); } // node.addAttribute(att); attributes.put(att.getName(), att); } if (!hasGraphFile) { GraphAttribute att = new GraphAttribute(VariableNames.GraphFile, file.getName()); // node.addAttribute(att); attributes.put(att.getName(), att); } } } else { GraphAttribute att = new GraphAttribute(VariableNames.GraphFile, file.getName()); // node.addAttribute(att); attributes.put(att.getName(), att); } } /** * Method that reads the file Header and then the vertex and edge lists (Graph) */ public void readHeader() { isProvenanceGraph = true; NodeList nList; nList = doc.getElementsByTagName("edgesRightToLeft"); if (nList != null && nList.getLength() > 0 && !nList.item(0).getTextContent().equalsIgnoreCase("")) { isProvenanceGraph = Boolean.parseBoolean(nList.item(0).getTextContent()); } NodeList vList = doc.getElementsByTagName("vertex"); NodeList eList = doc.getElementsByTagName("edge"); readGraph(vList, eList, nodes, edges); } public void readGraph(NodeList vList, NodeList eList, Map<String, Vertex> vertices, Collection<Edge> edges) { readVertices(vList, vertices); readEdges(eList, edges, vertices); } /** * Method to read a vertex * @param nList * @param vertices */ public void readVertices(NodeList nList, Map<String, Vertex> vertices) { for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String id = eElement.getElementsByTagName("ID").item(0).getTextContent(); String type = eElement.getElementsByTagName("type").item(0).getTextContent(); String label = eElement.getElementsByTagName("label").item(0).getTextContent(); String date = eElement.getElementsByTagName("date").item(0).getTextContent(); Map<String, GraphAttribute> attributes = new HashMap<>(); readAttribute(eElement, attributes); GraphAttribute path = null; GraphAttribute fileName = null; if (hackLabelPathAndFile) { String[] folders = label.split("/"); String filePath = label.replace(folders[folders.length - 1], ""); String fn = folders[folders.length - 1]; path = new GraphAttribute("Path", filePath); fileName = new GraphAttribute("FileName", fn); if (type.equalsIgnoreCase("Entity")) { label = fn; } if (type.equalsIgnoreCase("Activity")) { label = label.split(":")[0]; } } Vertex node; if (type.equalsIgnoreCase("Activity")) { node = new ActivityVertex(id, label, date); } else if (type.equalsIgnoreCase("Entity")) { node = new EntityVertex(id, label, date); } else if (type.equalsIgnoreCase("Agent")) { node = new AgentVertex(id, label, date); } else { node = new GraphVertex(id, label, date); } // readAttribute(eElement, node); if (hackLabelPathAndFile) { if (node instanceof EntityVertex) { node.addAttribute(path); node.addAttribute(fileName); } } node.addAllAttributes(attributes); if (node instanceof GraphVertex) { NodeList collapsedVertices = eElement.getElementsByTagName("collapsedvertices"); NodeList collapsedEdged = eElement.getElementsByTagName("collapsededges"); Node cVertexNode = collapsedVertices.item(0); Node cEdgeNode = collapsedEdged.item(0); if (cVertexNode.getNodeType() == Node.ELEMENT_NODE) { Element cVertexElement = (Element) cVertexNode; Element cEdgeElement = (Element) cEdgeNode; NodeList vList = cVertexElement.getElementsByTagName("collapsedvertex"); NodeList eList = cEdgeElement.getElementsByTagName("collapsededge"); Map<String, Vertex> cv = new HashMap<>(); Collection<Edge> ce = new ArrayList<>(); readGraph(vList, eList, cv, ce); ((GraphVertex) node).setClusterGraph(ce, cv); } } vertices.put(node.getID(), node); } } } /** * Method to read an edge */ public void readEdges(NodeList nList, Collection<Edge> edges, Map<String, Vertex> vertices) { for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String id = eElement.getElementsByTagName("ID").item(0).getTextContent(); String type = eElement.getElementsByTagName("type").item(0).getTextContent(); String label = eElement.getElementsByTagName("label").item(0).getTextContent(); String value = eElement.getElementsByTagName("value").item(0).getTextContent(); String source = eElement.getElementsByTagName("sourceID").item(0).getTextContent(); String target = eElement.getElementsByTagName("targetID").item(0).getTextContent(); Edge edge; Map<String, GraphAttribute> attributes = new HashMap<>(); readAttribute(eElement, attributes); String newSource = "Null"; String newTarget = "Null"; if (attributes.containsKey(VariableNames.vertexNewSource)) { newSource = attributes.get(VariableNames.vertexNewSource).getValue(); } if (attributes.containsKey(VariableNames.vertexNewTarget)) { newTarget = attributes.get(VariableNames.vertexNewTarget).getValue(); } if ((vertices.containsKey(source) || vertices.containsKey(newSource)) && (vertices.containsKey(target) || vertices.containsKey(newTarget))) { Vertex vs; Vertex vt; vs = findNode(source, vertices); vt = findNode(target, vertices); if (isProvenanceGraph) { edge = new Edge(id, type, label, value, vt, vs); } else { edge = new Edge(id, type, label, value, vs, vt); } edge.addAllAttributes(attributes); edges.add(edge); } else { System.out.println("Not possible!"); System.out.println("ID: " + id); System.out.println("source: " + source); System.out.println("target: " + target); System.out.println("NewSource: " + newSource); System.out.println("NewTarget: " + newTarget); } } } } /** * Method to find the original Vertex * @param ID is the vertex ID we are looking for * @param vertices is the map that contains the vertices with the Key being the vertex's ID * @return the vertex */ private Vertex findNode(String ID, Map<String, Vertex> vertices) { if (vertices.containsKey(ID)) { return vertices.get(ID); } else { for(String ids : vertices.keySet()) { if(ids.contains(ID)) { // It might have. Lets break it down to make sure it has the Source String currentID = ids.replace("[", ""); // Remove the GraphVertex ID brankets currentID = currentID.replace("]", ""); currentID = currentID.replace(" ", ""); // Remove spaces String[] subIDs = currentID.split(","); // Split each ID that composes the GraphVertex for(String i : subIDs) { // Lets check if each individual ID is the original Source if(i.equalsIgnoreCase(ID)) { // If true then the original vertex is inside this GraphVertex GraphVertex v = (GraphVertex) vertices.get(ids); // We got the GraphVertex, now need to explore it return findNode(v.clusterGraph, ID); } } } } } return null; } /** * Method to find the vertex inside a GraphVertex * @param clusterGraph is the GraphVertex's clustergraph * @param ID is the vertex's ID that we are looking for * @return the vertex */ private Vertex findNode(Graph clusterGraph, String ID) { Vertex found = null; for(Object v : clusterGraph.getVertices()) { if(((Vertex)v).getID().equalsIgnoreCase(ID)) return (Vertex) v; else if(v instanceof GraphVertex) found = findNode(((GraphVertex)v).clusterGraph, ID); } return found; } /** * Method that returns * @param id * @return */ public Vertex getNewPointer(String id) { return nodes.get(id); } }
Fixed a problem when building the GraphVertex since it was adding all vertices that it had, even those inside another graphvertex
src/main/java/br/uff/ic/utility/IO/UnityReader.java
Fixed a problem when building the GraphVertex since it was adding all vertices that it had, even those inside another graphvertex
Java
mit
5fdcfe520f818f592cd1794ff0d428f86dde818f
0
tomis007/gameboi
/* * Gameboi */ package gameboi; // for testing import java.util.Random; import java.util.Scanner; /** * Z80 Gameboy CPU * * Implementation of a gameboy cpu. Eight registers (a,b,c,d,e,f,h,l), a * stack pointer, program counter * * @author tomis007 */ public class CPU { // registers private final GBRegisters registers; // stack pointer, program counter private int sp; private int pc; //associated memory to use with CPU private final GBMem memory; /** * Constructor for gameboy z80 CPU * * @param memory GBMem object to associate with this cpu */ public CPU(GBMem memory) { pc = 0x100; sp = 0xfffe; this.memory = memory; registers = new GBRegisters(); } /** * Execute the next opcode in memory * * @return clock cycles taken to execute the opcode */ public int ExecuteOpcode() { int opcode = memory.readByte(pc); pc++; int cycles = runInstruction(opcode); if (pc >= 0x293) { // dumpRegisters(); } if (pc == 0x297) { System.out.println("Breakpoint 0x297"); dumpRegisters(); enterDebugMode(); } // if (pc == 0x294) { // System.out.println("Breakpoint 0x294"); // dumpRegisters(); // enterDebugMode(); // } return cycles; } /** * Debug mode for cpu instructions * */ private void enterDebugMode() { Scanner sc = new Scanner(System.in); String input; input = sc.nextLine(); while (!"q".equals(input)) { if ("p".equals(input)) { dumpRegisters(); } else if ("n".equals(input)) { dumpRegisters(); ExecuteOpcode(); } System.out.print("pc: 0x" + Integer.toHexString(pc) + " > "); input = sc.nextLine(); } } /** * Opcode Instructions for the Gameboy Z80 Chip. * * <p> * Runs the instruction associated with the opcode, and returns the * clock cycles taken. * * TODO HALT,STOP, EI,DI!!!!! * @param opcode (required) opcode to execute * @return number of cycles taken to execute */ private int runInstruction(int opcode) { switch (opcode) { case 0x0: return 4; //NOP /*****8 BIT LOADS*****/ // LD nn,n case 0x06: return eightBitLdNnN(GBRegisters.Reg.B); case 0x0e: return eightBitLdNnN(GBRegisters.Reg.C); case 0x16: return eightBitLdNnN(GBRegisters.Reg.D); case 0x1e: return eightBitLdNnN(GBRegisters.Reg.E); case 0x26: return eightBitLdNnN(GBRegisters.Reg.H); case 0x2e: return eightBitLdNnN(GBRegisters.Reg.L); //LD r1,r2 case 0x7f: return eightBitLdR1R2(GBRegisters.Reg.A, GBRegisters.Reg.A); case 0x78: return eightBitLdR1R2(GBRegisters.Reg.A, GBRegisters.Reg.B); case 0x79: return eightBitLdR1R2(GBRegisters.Reg.A, GBRegisters.Reg.C); case 0x7a: return eightBitLdR1R2(GBRegisters.Reg.A, GBRegisters.Reg.D); case 0x7b: return eightBitLdR1R2(GBRegisters.Reg.A, GBRegisters.Reg.E); case 0x7c: return eightBitLdR1R2(GBRegisters.Reg.A, GBRegisters.Reg.H); case 0x7d: return eightBitLdR1R2(GBRegisters.Reg.A, GBRegisters.Reg.L); case 0x7e: return eightBitLdR1R2(GBRegisters.Reg.A, GBRegisters.Reg.HL); case 0x40: return eightBitLdR1R2(GBRegisters.Reg.B, GBRegisters.Reg.B); case 0x41: return eightBitLdR1R2(GBRegisters.Reg.B, GBRegisters.Reg.C); case 0x42: return eightBitLdR1R2(GBRegisters.Reg.B, GBRegisters.Reg.D); case 0x43: return eightBitLdR1R2(GBRegisters.Reg.B, GBRegisters.Reg.E); case 0x44: return eightBitLdR1R2(GBRegisters.Reg.B, GBRegisters.Reg.H); case 0x45: return eightBitLdR1R2(GBRegisters.Reg.B, GBRegisters.Reg.L); case 0x46: return eightBitLdR1R2(GBRegisters.Reg.B, GBRegisters.Reg.HL); case 0x48: return eightBitLdR1R2(GBRegisters.Reg.C, GBRegisters.Reg.B); case 0x49: return eightBitLdR1R2(GBRegisters.Reg.C, GBRegisters.Reg.C); case 0x4a: return eightBitLdR1R2(GBRegisters.Reg.C, GBRegisters.Reg.D); case 0x4b: return eightBitLdR1R2(GBRegisters.Reg.C, GBRegisters.Reg.E); case 0x4c: return eightBitLdR1R2(GBRegisters.Reg.C, GBRegisters.Reg.H); case 0x4d: return eightBitLdR1R2(GBRegisters.Reg.C, GBRegisters.Reg.L); case 0x4e: return eightBitLdR1R2(GBRegisters.Reg.C, GBRegisters.Reg.HL); case 0x50: return eightBitLdR1R2(GBRegisters.Reg.D, GBRegisters.Reg.B); case 0x51: return eightBitLdR1R2(GBRegisters.Reg.D, GBRegisters.Reg.C); case 0x52: return eightBitLdR1R2(GBRegisters.Reg.D, GBRegisters.Reg.D); case 0x53: return eightBitLdR1R2(GBRegisters.Reg.D, GBRegisters.Reg.E); case 0x54: return eightBitLdR1R2(GBRegisters.Reg.D, GBRegisters.Reg.H); case 0x55: return eightBitLdR1R2(GBRegisters.Reg.D, GBRegisters.Reg.L); case 0x56: return eightBitLdR1R2(GBRegisters.Reg.D, GBRegisters.Reg.HL); case 0x58: return eightBitLdR1R2(GBRegisters.Reg.E, GBRegisters.Reg.B); case 0x59: return eightBitLdR1R2(GBRegisters.Reg.E, GBRegisters.Reg.C); case 0x5a: return eightBitLdR1R2(GBRegisters.Reg.E, GBRegisters.Reg.D); case 0x5b: return eightBitLdR1R2(GBRegisters.Reg.E, GBRegisters.Reg.E); case 0x5c: return eightBitLdR1R2(GBRegisters.Reg.E, GBRegisters.Reg.H); case 0x5d: return eightBitLdR1R2(GBRegisters.Reg.E, GBRegisters.Reg.L); case 0x5e: return eightBitLdR1R2(GBRegisters.Reg.E, GBRegisters.Reg.HL); case 0x60: return eightBitLdR1R2(GBRegisters.Reg.H, GBRegisters.Reg.B); case 0x61: return eightBitLdR1R2(GBRegisters.Reg.H, GBRegisters.Reg.C); case 0x62: return eightBitLdR1R2(GBRegisters.Reg.H, GBRegisters.Reg.D); case 0x63: return eightBitLdR1R2(GBRegisters.Reg.H, GBRegisters.Reg.E); case 0x64: return eightBitLdR1R2(GBRegisters.Reg.H, GBRegisters.Reg.H); case 0x65: return eightBitLdR1R2(GBRegisters.Reg.H, GBRegisters.Reg.L); case 0x66: return eightBitLdR1R2(GBRegisters.Reg.H, GBRegisters.Reg.HL); case 0x68: return eightBitLdR1R2(GBRegisters.Reg.L, GBRegisters.Reg.B); case 0x69: return eightBitLdR1R2(GBRegisters.Reg.L, GBRegisters.Reg.C); case 0x6a: return eightBitLdR1R2(GBRegisters.Reg.L, GBRegisters.Reg.D); case 0x6b: return eightBitLdR1R2(GBRegisters.Reg.L, GBRegisters.Reg.E); case 0x6c: return eightBitLdR1R2(GBRegisters.Reg.L, GBRegisters.Reg.H); case 0x6d: return eightBitLdR1R2(GBRegisters.Reg.L, GBRegisters.Reg.L); case 0x6e: return eightBitLdR1R2(GBRegisters.Reg.L, GBRegisters.Reg.HL); case 0x70: return eightBitLdR1R2(GBRegisters.Reg.HL, GBRegisters.Reg.B); case 0x71: return eightBitLdR1R2(GBRegisters.Reg.HL, GBRegisters.Reg.C); case 0x72: return eightBitLdR1R2(GBRegisters.Reg.HL, GBRegisters.Reg.D); case 0x73: return eightBitLdR1R2(GBRegisters.Reg.HL, GBRegisters.Reg.E); case 0x74: return eightBitLdR1R2(GBRegisters.Reg.HL, GBRegisters.Reg.H); case 0x75: return eightBitLdR1R2(GBRegisters.Reg.HL, GBRegisters.Reg.L); // special 8 bit load from memory case 0x36: return eightBitLoadFromMem(); // LD A,n case 0x0a: return eightBitLdAN(GBRegisters.Reg.BC); case 0x1a: return eightBitLdAN(GBRegisters.Reg.DE); case 0xfa: return eightBitALoadMem(true); case 0x3e: return eightBitALoadMem(false); // LD n,A case 0x47: return eightBitLdR1R2(GBRegisters.Reg.B, GBRegisters.Reg.A); case 0x4f: return eightBitLdR1R2(GBRegisters.Reg.C, GBRegisters.Reg.A); case 0x57: return eightBitLdR1R2(GBRegisters.Reg.D, GBRegisters.Reg.A); case 0x5f: return eightBitLdR1R2(GBRegisters.Reg.E, GBRegisters.Reg.A); case 0x67: return eightBitLdR1R2(GBRegisters.Reg.H, GBRegisters.Reg.A); case 0x6f: return eightBitLdR1R2(GBRegisters.Reg.L, GBRegisters.Reg.A); case 0x02: return eightBitLdR1R2(GBRegisters.Reg.BC, GBRegisters.Reg.A); case 0x12: return eightBitLdR1R2(GBRegisters.Reg.DE, GBRegisters.Reg.A); case 0x77: return eightBitLdR1R2(GBRegisters.Reg.HL, GBRegisters.Reg.A); case 0xea: return eightBitLoadToMem(); // LD A, (C) case 0xf2: return eightBitLDfromAC(); case 0xe2: return eightBitLDtoAC(); // LDD A,(HL) case 0x3a: return eightBitLDAHl(); // LDD (HL), A case 0x32: return eightBitStoreHL(); // LDI (HL), A case 0x2a: return eightBitLDIA(); // LDI (HL), A case 0x22: return eightBitLDIHLA(); // LDH (n), A, LDH A,(n) case 0xe0: return eightBitLdhA(true); case 0xf0: return eightBitLdhA(false); /*****16 BIT LOADS*****/ //LD n, nn case 0x01: return sixteenBitLdNNn(GBRegisters.Reg.BC); case 0x11: return sixteenBitLdNNn(GBRegisters.Reg.DE); case 0x21: return sixteenBitLdNNn(GBRegisters.Reg.HL); case 0x31: return sixteenBitLdNNnSP(); //LD SP,HL case 0xf9: return sixteenBitLdSpHl(); case 0xf8: return sixteenBitLdHlSp(); //LD (nn), SP case 0x08: return sixteenBitLdNnSp(); //Push nn to stack case 0xf5: return pushNN(GBRegisters.Reg.AF); case 0xc5: return pushNN(GBRegisters.Reg.BC); case 0xd5: return pushNN(GBRegisters.Reg.DE); case 0xe5: return pushNN(GBRegisters.Reg.HL); //POP nn off stack case 0xf1: return popNN(GBRegisters.Reg.AF); case 0xc1: return popNN(GBRegisters.Reg.BC); case 0xd1: return popNN(GBRegisters.Reg.DE); case 0xe1: return popNN(GBRegisters.Reg.HL); /******8-BIT ALU*****/ //ADD A,n case 0x87: return addAN(GBRegisters.Reg.A, false, false); case 0x80: return addAN(GBRegisters.Reg.B, false, false); case 0x81: return addAN(GBRegisters.Reg.C, false, false); case 0x82: return addAN(GBRegisters.Reg.D, false, false); case 0x83: return addAN(GBRegisters.Reg.E, false, false); case 0x84: return addAN(GBRegisters.Reg.H, false, false); case 0x85: return addAN(GBRegisters.Reg.L, false, false); case 0x86: return addAN(GBRegisters.Reg.HL, false, false); case 0xc6: return addAN(GBRegisters.Reg.A, false, true); //ADC A,n case 0x8f: return addAN(GBRegisters.Reg.A, true, false); case 0x88: return addAN(GBRegisters.Reg.B, true, false); case 0x89: return addAN(GBRegisters.Reg.C, true, false); case 0x8a: return addAN(GBRegisters.Reg.D, true, false); case 0x8b: return addAN(GBRegisters.Reg.E, true, false); case 0x8c: return addAN(GBRegisters.Reg.H, true, false); case 0x8d: return addAN(GBRegisters.Reg.L, true, false); case 0x8e: return addAN(GBRegisters.Reg.HL, true, false); case 0xce: return addAN(GBRegisters.Reg.A, true, true); //SUB n case 0x97: return subAN(GBRegisters.Reg.A, false, false); case 0x90: return subAN(GBRegisters.Reg.B, false, false); case 0x91: return subAN(GBRegisters.Reg.C, false, false); case 0x92: return subAN(GBRegisters.Reg.D, false, false); case 0x93: return subAN(GBRegisters.Reg.E, false, false); case 0x94: return subAN(GBRegisters.Reg.H, false, false); case 0x95: return subAN(GBRegisters.Reg.L, false, false); case 0x96: return subAN(GBRegisters.Reg.HL, false, false); case 0xd6: return subAN(GBRegisters.Reg.A, false, true); //SUBC A,n case 0x9f: return subAN(GBRegisters.Reg.A, true, false); case 0x98: return subAN(GBRegisters.Reg.B, true, false); case 0x99: return subAN(GBRegisters.Reg.C, true, false); case 0x9a: return subAN(GBRegisters.Reg.D, true, false); case 0x9b: return subAN(GBRegisters.Reg.E, true, false); case 0x9c: return subAN(GBRegisters.Reg.H, true, false); case 0x9d: return subAN(GBRegisters.Reg.L, true, false); case 0x9e: return subAN(GBRegisters.Reg.HL, true, false); case 0xde: return subAN(GBRegisters.Reg.A, true, true); //AND N case 0xa7: return andN(GBRegisters.Reg.A, false); case 0xa0: return andN(GBRegisters.Reg.B, false); case 0xa1: return andN(GBRegisters.Reg.C, false); case 0xa2: return andN(GBRegisters.Reg.D, false); case 0xa3: return andN(GBRegisters.Reg.E, false); case 0xa4: return andN(GBRegisters.Reg.H, false); case 0xa5: return andN(GBRegisters.Reg.L, false); case 0xa6: return andN(GBRegisters.Reg.HL, false); case 0xe6: return andN(GBRegisters.Reg.A, true); //OR N case 0xb7: return orN(GBRegisters.Reg.A, false); case 0xb0: return orN(GBRegisters.Reg.B, false); case 0xb1: return orN(GBRegisters.Reg.C, false); case 0xb2: return orN(GBRegisters.Reg.D, false); case 0xb3: return orN(GBRegisters.Reg.E, false); case 0xb4: return orN(GBRegisters.Reg.H, false); case 0xb5: return orN(GBRegisters.Reg.L, false); case 0xb6: return orN(GBRegisters.Reg.HL, false); case 0xf6: return orN(GBRegisters.Reg.A, true); // XOR n case 0xaf: return xorN(GBRegisters.Reg.A, false); case 0xa8: return xorN(GBRegisters.Reg.B, false); case 0xa9: return xorN(GBRegisters.Reg.C, false); case 0xaa: return xorN(GBRegisters.Reg.D, false); case 0xab: return xorN(GBRegisters.Reg.E, false); case 0xac: return xorN(GBRegisters.Reg.H, false); case 0xad: return xorN(GBRegisters.Reg.L, false); case 0xae: return xorN(GBRegisters.Reg.HL, false); case 0xee: return xorN(GBRegisters.Reg.A, true); // CP n case 0xbf: return cpN(GBRegisters.Reg.A, false); case 0xb8: return cpN(GBRegisters.Reg.B, false); case 0xb9: return cpN(GBRegisters.Reg.C, false); case 0xba: return cpN(GBRegisters.Reg.D, false); case 0xbb: return cpN(GBRegisters.Reg.E, false); case 0xbc: return cpN(GBRegisters.Reg.H, false); case 0xbd: return cpN(GBRegisters.Reg.L, false); case 0xbe: return cpN(GBRegisters.Reg.HL, false); case 0xfe: return cpN(GBRegisters.Reg.A, false); // INC n case 0x3c: return incN(GBRegisters.Reg.A); case 0x04: return incN(GBRegisters.Reg.B); case 0x0c: return incN(GBRegisters.Reg.C); case 0x14: return incN(GBRegisters.Reg.D); case 0x1c: return incN(GBRegisters.Reg.E); case 0x24: return incN(GBRegisters.Reg.H); case 0x2c: return incN(GBRegisters.Reg.L); case 0x34: return incN(GBRegisters.Reg.HL); // DEC n case 0x3d: return decN(GBRegisters.Reg.A); case 0x05: return decN(GBRegisters.Reg.B); case 0x0d: return decN(GBRegisters.Reg.C); case 0x15: return decN(GBRegisters.Reg.D); case 0x1d: return decN(GBRegisters.Reg.E); case 0x25: return decN(GBRegisters.Reg.H); case 0x2d: return decN(GBRegisters.Reg.L); case 0x35: return decN(GBRegisters.Reg.HL); //ADD HL,n case 0x09: return sixteenBitAdd(GBRegisters.Reg.BC, false); case 0x19: return sixteenBitAdd(GBRegisters.Reg.DE, false); case 0x29: return sixteenBitAdd(GBRegisters.Reg.HL, false); case 0x39: return sixteenBitAdd(GBRegisters.Reg.BC, true); //ADD SP,n case 0xe8: return addSPN(); //INC nn case 0x03: return incNN(GBRegisters.Reg.BC, false); case 0x13: return incNN(GBRegisters.Reg.DE, false); case 0x23: return incNN(GBRegisters.Reg.HL, false); case 0x33: return incNN(GBRegisters.Reg.BC, true); //DEC nn case 0x0B: return decNN(GBRegisters.Reg.BC, false); case 0x1B: return decNN(GBRegisters.Reg.DE, false); case 0x2B: return decNN(GBRegisters.Reg.HL, false); case 0x3B: return decNN(GBRegisters.Reg.BC, true); // extended case 0xcb: return extendedOpcode(); // DAA, PROBABLY NOT CORRECT case 0x27: return decAdjust(); //CPL case 0x2f: return cplRegA(); //CCF case 0x3f: return ccf(); //SCF case 0x37: return scf(); //Jumps case 0xc3: return jump(); // conditional jump case 0xc2: return jumpC(opcode); case 0xca: return jumpC(opcode); case 0xd2: return jumpC(opcode); case 0xda: return jumpC(opcode); // JP (HL) case 0xe9: return jumpHL(); //JR n case 0x18: return jumpN(); //JR cc, n case 0x20: return jumpCN(opcode); case 0x28: return jumpCN(opcode); case 0x30: return jumpCN(opcode); case 0x38: return jumpCN(opcode); //TODO HALT,STOP, EI,DI case 0x76: case 0x10: case 0xf3: case 0xfb: System.err.println("TODO!!!!"); System.exit(1); //calls case 0xcd: return call(); case 0xc4: return callC(opcode); case 0xcc: return callC(opcode); case 0xd4: return callC(opcode); case 0xdc: return callC(opcode); //restarts case 0xc7: return restart(0x00); case 0xcf: return restart(0x08); case 0xd7: return restart(0x10); case 0xdf: return restart(0x18); case 0xe7: return restart(0x20); case 0xef: return restart(0x28); case 0xf7: return restart(0x30); case 0xff: return restart(0x38); //RETURNs case 0xc9: return ret(); case 0xc0: return retC(opcode); case 0xc8: return retC(opcode); case 0xd0: return retC(opcode); case 0xd8: return retC(opcode); //TODO RETI case 0xd9: System.err.println("Unimplemented RETI"); System.exit(1); //ROTATES AND SHIFTS //RLCA case 0x07: return rlcA(); //RLA case 0x17: return rlA(); //RRCA case 0x0f: return rrcA(); case 0x1f: return rrA(); default: System.err.println("Unimplemented opcode: 0x" + Integer.toHexString(opcode)); System.exit(1); } return 0; } private int extendedOpcode() { int opcode = memory.readByte(pc); pc++; switch(opcode) { //SWAP N case 0x37: return swapN(GBRegisters.Reg.A); case 0x30: return swapN(GBRegisters.Reg.B); case 0x31: return swapN(GBRegisters.Reg.C); case 0x32: return swapN(GBRegisters.Reg.D); case 0x33: return swapN(GBRegisters.Reg.E); case 0x34: return swapN(GBRegisters.Reg.H); case 0x35: return swapN(GBRegisters.Reg.L); case 0x36: return swapN(GBRegisters.Reg.HL); //RLC n case 0x07: return rlcN(GBRegisters.Reg.A); case 0x00: return rlcN(GBRegisters.Reg.B); case 0x01: return rlcN(GBRegisters.Reg.C); case 0x02: return rlcN(GBRegisters.Reg.D); case 0x03: return rlcN(GBRegisters.Reg.E); case 0x04: return rlcN(GBRegisters.Reg.H); case 0x05: return rlcN(GBRegisters.Reg.L); case 0x06: return rlcN(GBRegisters.Reg.HL); //RL n case 0x17: return rlN(GBRegisters.Reg.A); case 0x10: return rlN(GBRegisters.Reg.B); case 0x11: return rlN(GBRegisters.Reg.C); case 0x12: return rlN(GBRegisters.Reg.D); case 0x13: return rlN(GBRegisters.Reg.E); case 0x14: return rlN(GBRegisters.Reg.H); case 0x15: return rlN(GBRegisters.Reg.L); case 0x16: return rlN(GBRegisters.Reg.HL); //RRC n case 0x0f: return rrcN(GBRegisters.Reg.A); case 0x08: return rrcN(GBRegisters.Reg.B); case 0x09: return rrcN(GBRegisters.Reg.C); case 0x0a: return rrcN(GBRegisters.Reg.D); case 0x0b: return rrcN(GBRegisters.Reg.E); case 0x0c: return rrcN(GBRegisters.Reg.H); case 0x0d: return rrcN(GBRegisters.Reg.L); case 0x0e: return rrcN(GBRegisters.Reg.HL); //RR n case 0x1f: return rrN(GBRegisters.Reg.A); case 0x18: return rrN(GBRegisters.Reg.B); case 0x19: return rrN(GBRegisters.Reg.C); case 0x1a: return rrN(GBRegisters.Reg.D); case 0x1b: return rrN(GBRegisters.Reg.E); case 0x1c: return rrN(GBRegisters.Reg.H); case 0x1d: return rrN(GBRegisters.Reg.L); case 0x1e: return rrN(GBRegisters.Reg.HL); //SRA n case 0x2f: return srAL(GBRegisters.Reg.A, false); case 0x28: return srAL(GBRegisters.Reg.B, false); case 0x29: return srAL(GBRegisters.Reg.C, false); case 0x2a: return srAL(GBRegisters.Reg.D, false); case 0x2b: return srAL(GBRegisters.Reg.E, false); case 0x2c: return srAL(GBRegisters.Reg.H, false); case 0x2d: return srAL(GBRegisters.Reg.L, false); case 0x2e: return srAL(GBRegisters.Reg.HL, false); //SRL n case 0x3f: return srAL(GBRegisters.Reg.A, true); case 0x38: return srAL(GBRegisters.Reg.B, true); case 0x39: return srAL(GBRegisters.Reg.C, true); case 0x3a: return srAL(GBRegisters.Reg.D, true); case 0x3b: return srAL(GBRegisters.Reg.E, true); case 0x3c: return srAL(GBRegisters.Reg.H, true); case 0x3d: return srAL(GBRegisters.Reg.L, true); case 0x3e: return srAL(GBRegisters.Reg.HL, true); default: System.err.println("Unimplemented opcode: 0xcb" + Integer.toHexString(opcode)); System.exit(1); } return 0; } /** * LD nn,n. Put value nn into n. * * <p>nn = B,C,D,E,H,L,BC,DE,HL,SP * n = 8 bit immediate value * * @param register (required) register (nn) to load to */ private int eightBitLdNnN(GBRegisters.Reg register) { int data = memory.readByte(pc); pc++; registers.setReg(register, data); return 8; } /** * Testing function for EightBitLdNnN * * Tests the eightBitLdNnN function with random input data * to make sure the function works correctly */ public void testEightBitLdNnN() { // Random rand = new Random(); // for (int i = 0; i < 2000; ++i) { // int data = rand.nextInt(256); // for (int j = 0; j < 200; ++j) { // eightBitLdNnN(GBRegisters.Reg.E, data); // if (registers.getReg(GBRegisters.Reg.E)!= data) { // System.err.println("Error failed register E test"); // } // data = rand.nextInt(256); // eightBitLdNnN(GBRegisters.Reg.B, data); // if (registers.getReg(GBRegisters.Reg.B)!= data) { // System.err.println("Error failed register B test"); // } // data = rand.nextInt(256); // eightBitLdNnN(GBRegisters.Reg.C, data); // if (registers.getReg(GBRegisters.Reg.C) != data) { // System.err.println("Error failed register C test"); // } // data = rand.nextInt(256); // eightBitLdNnN(GBRegisters.Reg.D, data); // if (registers.getReg(GBRegisters.Reg.D) != data) { // System.err.println("Error failed register D test"); // } // data = rand.nextInt(256); // eightBitLdNnN(GBRegisters.Reg.H, data); // if (registers.getReg(GBRegisters.Reg.H) != data) { // System.err.println("Error failed register H test"); // } // data = rand.nextInt(256); // eightBitLdNnN(GBRegisters.Reg.L, data); // if (registers.getReg(GBRegisters.Reg.L) != data) { // System.err.println("Error failed register L test"); // } // } // } // System.out.println("Finished and reported all error messages"); } /** * Put value r2 into r2. * * <p> Use with: r1,r2 = A,B,C,D,E,H,L,(HL) * * @param dest destination register * @param scr source register */ private int eightBitLdR1R2(GBRegisters.Reg dest, GBRegisters.Reg src) { if (src == GBRegisters.Reg.HL) { int data = memory.readByte(registers.getReg(GBRegisters.Reg.HL)); registers.setReg(dest, data); return 8; } else if ((dest == GBRegisters.Reg.HL) || (dest == GBRegisters.Reg.BC) || (dest == GBRegisters.Reg.DE)) { memory.writeByte(registers.getReg(dest), registers.getReg(src)); return 8; } else { registers.setReg(dest, registers.getReg(src)); return 4; } } /** * Special function for opcode 0x36 * * LD (HL), n */ private int eightBitLoadFromMem() { int data = memory.readByte(pc); pc++; memory.writeByte(registers.getReg(GBRegisters.Reg.HL), data); return 12; } /** * Special function for opcode 0xea * */ private int eightBitLoadToMem() { int address = memory.readByte(pc); pc++; address = address | (memory.readByte(pc) << 8); memory.writeByte(address, registers.getReg(GBRegisters.Reg.A)); return 16; } /** * LD A,n * * Put value n into A. For opcodes 0x0a, 0x1a * * * @param src value n */ private int eightBitLdAN(GBRegisters.Reg src) { int data = memory.readByte(registers.getReg(src)); registers.setReg(GBRegisters.Reg.A, data); return 8; } /** * LD A,n (where n is located in rom, or an address in rom) * * For opcodes: 0xfa, 0x3e * * @param isPointer If true, next two bytes are address in memory to load * from. If false, eight bit immediate value is loaded. */ private int eightBitALoadMem(boolean isPointer) { if (isPointer) { int address = memory.readByte(pc); pc++; address = address | (memory.readByte(pc) << 8); pc++; registers.setReg(GBRegisters.Reg.A, memory.readByte(address)); return 16; } else { int data = memory.readByte(pc); pc++; registers.setReg(GBRegisters.Reg.A, data); return 8; } } /** * LD A, (C) * * put value at address $FF00 + register C into A * Same as: LD A, ($FF00 + C) */ private int eightBitLDfromAC() { int data = memory.readByte(registers.getReg(GBRegisters.Reg.C) + 0xff00); registers.setReg(GBRegisters.Reg.A, data); return 8; } /** * LD (C), A * * Put A into address $FF00 + register C * */ private int eightBitLDtoAC() { int address = registers.getReg(GBRegisters.Reg.C); int data = registers.getReg(GBRegisters.Reg.A); memory.writeByte(address + 0xff00, data); return 8; } /** LDD A, (HL) * * Put value at address HL into A, decrement HL * */ private int eightBitLDAHl() { int address = registers.getReg(GBRegisters.Reg.HL); registers.setReg(GBRegisters.Reg.A, memory.readByte(address)); registers.setReg(GBRegisters.Reg.HL, address - 1); return 8; } /** * LDD (HL), A * Put A into memory address HL, Decrement HL * */ private int eightBitStoreHL() { int address = registers.getReg(GBRegisters.Reg.HL); int data = registers.getReg(GBRegisters.Reg.A); memory.writeByte(address, data); registers.setReg(GBRegisters.Reg.HL, address - 1); return 8; } /** * Put value at address HL into A, increment HL * */ private int eightBitLDIA() { int address = registers.getReg(GBRegisters.Reg.HL); registers.setReg(GBRegisters.Reg.A, memory.readByte(address)); registers.setReg(GBRegisters.Reg.HL, address + 1); return 8; } /** * Put A into memory at address HL. Increment HL * */ private int eightBitLDIHLA() { int address = registers.getReg(GBRegisters.Reg.HL); int data = registers.getReg(GBRegisters.Reg.A); memory.writeByte(address, data); registers.setReg(GBRegisters.Reg.HL, address + 1); return 8; } /** * LDH (n), A and LDH A, (n) * * LDH (n), A - Put A into memory address $FF00 + n * LDH A,(n) - Put memory address $FF00+n into A * * @param writeToMem (required) if true LDH (n),A. if false LDH A,(n) * */ private int eightBitLdhA(boolean writeToMem) { int offset = memory.readByte(pc); pc++; if (writeToMem) { int data = registers.getReg(GBRegisters.Reg.A); memory.writeByte(0xff00 + offset, data); } else { int data = memory.readByte(0xff00 + offset); registers.setReg(GBRegisters.Reg.A, data); } return 12; } /** * LD n, nn * * Put value nn into n * * nn - 16 Bit immediate value, n = BC, DE, HL * */ private int sixteenBitLdNNn(GBRegisters.Reg reg) { // read two byte data from memory LSB first int data = memory.readByte(pc); pc++; data = data | (memory.readByte(pc) << 8); pc++; switch(reg) { case BC: registers.setReg(GBRegisters.Reg.BC, data); case DE: registers.setReg(GBRegisters.Reg.DE, data); case HL: registers.setReg(GBRegisters.Reg.HL, data); } return 12; } /** * LD n, nn * Put value nn into SP * */ private int sixteenBitLdNNnSP() { int data = memory.readByte(pc); pc++; data = data | (memory.readByte(pc) << 8); pc++; sp = data; return 12; } /** * LD SP,HL * * Put HL into SP */ private int sixteenBitLdSpHl() { sp = registers.getReg(GBRegisters.Reg.HL); return 8; } /** * LDHL SP,n * * Put SP+n effective address into HL * * <p>n = one byte signed immediate value * Z - reset * N - reset * H - set or reset according to operation * C - set or reset according to operation * */ private int sixteenBitLdHlSp() { int offset = memory.readByte(pc); pc++; byte data = (byte)memory.readByte((sp + offset) & 0xffff); registers.setReg(GBRegisters.Reg.HL, data); registers.resetAll(); // NOT REALLY SURE HERE, CPU DOCUMENTATION NOT EXACT if (((sp + offset) & 0x1f) > 0xf) { registers.setH(); } if ((sp + offset) > 0xffff) { registers.setC(); } return 12; } /** * Put SP at address n (2 byte immediate address) * stored little endian */ private int sixteenBitLdNnSp() { int address = memory.readByte(pc); pc++; address = address | (memory.readByte(pc) << 8); pc++; memory.writeByte(address, sp & 0xff); memory.writeByte(address + 1, ((sp & 0xff00) >> 8)); return 20; } /** * Push Register Pair value to stack * * @param src (required) register pair to push to stack */ private int pushNN(GBRegisters.Reg src) { int registerPair = registers.getReg(src); sp--; memory.writeByte(sp, (registerPair & 0xff00) >> 8); sp--; memory.writeByte(sp, (registerPair & 0xff)); return 16; } /** * pop value off stack to a register pair * * @param dest (required) register to store data in */ private int popNN(GBRegisters.Reg dest) { int data = memory.readByte(sp); sp++; data = data | (memory.readByte(sp) << 8); sp++; registers.setReg(dest, data); return 12; } /** * ADD A,n * * Add n to A * * Flags: * Z - set if result is zero * N - Reset * H - set if carry from bit 3 * C - set if carry from bit 7 * * @param src (source to add from) * @param addCarry true if adding carry * @param readMem true if reading immediate value from memory * if true, src ignored */ private int addAN(GBRegisters.Reg src, boolean addCarry, boolean readMem) { int cycles; int regA = registers.getReg(GBRegisters.Reg.A); int toAdd; if (readMem) { toAdd = memory.readByte(pc); pc++; cycles = 8; } else if (src == GBRegisters.Reg.HL) { toAdd = memory.readByte(registers.getReg(src)); cycles = 8; } else { toAdd = registers.getReg(src); cycles = 4; } toAdd += (addCarry) ? 1 : 0; //add registers.setReg(GBRegisters.Reg.A, toAdd + regA); //flags registers.resetAll(); if (registers.getReg(GBRegisters.Reg.A) == 0) { registers.setZ(); } if ((regA & 0xf) + (toAdd & 0xf) > 0xf) { registers.setH(); } if (toAdd + regA > 0xff) { registers.setC(); } return cycles; } /** * SUB n, SUBC A,n * Subtract N from A * Z- Set if result is zero * N - Set * H - set if no borrow from bit 4 * C - set if no borrow * */ private int subAN(GBRegisters.Reg src, boolean addCarry, boolean readMem) { int cycles; int regA = registers.getReg(GBRegisters.Reg.A); int toSub; if (readMem) { toSub = memory.readByte(pc); pc++; cycles = 8; } else if (src == GBRegisters.Reg.HL) { toSub = memory.readByte(registers.getReg(src)); cycles = 8; } else { toSub = registers.getReg(src); cycles = 4; } toSub += (addCarry) ? 1 : 0; //sub registers.setReg(GBRegisters.Reg.A, regA - toSub); //flags registers.resetAll(); if (registers.getReg(GBRegisters.Reg.A) == 0) { registers.setZ(); } registers.setN(); if ((regA & 0xf) - (toSub & 0xf) < 0) { registers.setH(); } if (regA < toSub) { registers.setC(); } return cycles; } /** * And N with A, result in A * * FLAGS: * Z - Set if result is 0 * N - Reset * H - Set * C - Reset * * @param src (required) N to and * @param readMem (required) true if reading immediate value from * memory (if true, src is ignored) */ private int andN(GBRegisters.Reg src, boolean readMem) { int cycles; int data; if (readMem) { data = memory.readByte(pc); pc++; cycles = 8; } else if (src == GBRegisters.Reg.HL) { data = registers.getReg(src); cycles = 8; } else { data = registers.getReg(src); cycles = 4; } int regA = registers.getReg(GBRegisters.Reg.A); registers.setReg(GBRegisters.Reg.A, data & regA); registers.resetAll(); if ((data & regA) == 0) { registers.setZ(); } registers.setH(); return cycles; } /** * OR N with A, result in A * * FLAGS: * Z - Set if result is 0 * N - Reset * H - Reset * C - Reset * * @param src (required) N to and * @param readMem (required) true if reading immediate value from * memory (if true, src is ignored) */ private int orN(GBRegisters.Reg src, boolean readMem) { int cycles; int data; if (readMem) { data = memory.readByte(pc); pc++; cycles = 8; } else if (src == GBRegisters.Reg.HL) { data = registers.getReg(src); cycles = 8; } else { data = registers.getReg(src); cycles = 4; } int regA = registers.getReg(GBRegisters.Reg.A); registers.setReg(GBRegisters.Reg.A, data | regA); registers.resetAll(); if ((data | regA) == 0) { registers.setZ(); } return cycles; } /** * XOR n * * Logical XOR n, with A, result in A * * FLAGS * Z - set if result is 0 * N, H, C = Reset * @param src (required) src register * @param readMem (required) true if reading immediate value from * memory (if true src ignored) * @return clock cycles taken */ private int xorN(GBRegisters.Reg src, boolean readMem) { int cycles; int data; if (readMem) { data = memory.readByte(pc); pc++; cycles = 8; } else if (src == GBRegisters.Reg.HL) { data = registers.getReg(src); cycles = 8; } else { data = registers.getReg(src); cycles = 4; } int regA = registers.getReg(GBRegisters.Reg.A); registers.setReg(GBRegisters.Reg.A, data ^ regA); registers.resetAll(); if ((data ^ regA) == 0) { registers.setZ(); } return cycles; } /** * CP n * * Compare A with n. Basically A - n subtraction but * results are thrown away * * FLAGS * Z - set if result is 0 (if A == n) * N - set * H - Set if no borrow from bit 4 * C = set if no morrow (Set if A is less than n) * * @param src (required) src register * @param readMem (required) true if reading immediate value from * memory (if true src ignored) * @return clock cycles taken */ private int cpN(GBRegisters.Reg src, boolean readMem) { int cycles; int data; if (readMem) { data = memory.readByte(pc); pc++; cycles = 8; } else if (src == GBRegisters.Reg.HL) { data = registers.getReg(src); cycles = 8; } else { data = registers.getReg(src); cycles = 4; } int regA = registers.getReg(GBRegisters.Reg.A); registers.resetAll(); if (regA == data) { registers.setZ(); } registers.setN(); if ((regA & 0xf) - (data & 0xf) < 0) { registers.setH(); } if (regA < data) { registers.setC(); } return cycles; } /** * INC n * * Increment register n. * * FLAGS: * Z - Set if result is 0 * N - Reset * H - Set if carry from bit 3 * C - Not affected * @param src (required) register to increment */ private int incN(GBRegisters.Reg src) { int reg = registers.getReg(src); registers.setReg(src, reg + 1); registers.resetZ(); if (registers.getReg(src) == 0) { registers.setZ(); } registers.resetN(); registers.resetH(); if (((reg & 0xf) + 1) > 0xf) { registers.setH(); } return (src == GBRegisters.Reg.HL) ? 12 : 4; } /** * DEC n * * Decrement register n. * * FLAGS: * Z - Set if result is 0 * N - Set * H - Set if no borrow from bit 4 * C - Not affected * @param src (required) register to decrement */ private int decN(GBRegisters.Reg src) { int reg = registers.getReg(src); registers.resetZ(); if (registers.getReg(src) == 0) { registers.setZ(); } registers.setN(); registers.resetH(); if (((reg & 0xf) - 1) < 0) { registers.setH(); } return (src == GBRegisters.Reg.HL) ? 12 : 4; } /** * ADD HL,n * * Add n to HL * * n = BC,DE,HL,SP * * Flags * Z - Not affected * N - Reset * H - Set if carry from bit 11 * C - Set if carry from bit 15 * * @param src source register to add * @param addSP boolean (if true, adds stackpointer instead of register * to HL, ignores src) * @return clock cycles taken */ private int sixteenBitAdd(GBRegisters.Reg src, boolean addSP) { int toAdd; int regVal = registers.getReg(GBRegisters.Reg.HL); if (addSP) { toAdd = sp; } else { toAdd = registers.getReg(src); } registers.setReg(GBRegisters.Reg.HL, regVal + toAdd); //flags registers.resetN(); registers.resetH(); if ((regVal & 0xfff) + (toAdd & 0xfff) > 0xfff) { registers.setH(); } registers.resetC(); if ((regVal + toAdd) > 0xffff) { registers.setC(); } return 8; } /** * ADD SP,n * Add n to sp * * Flags: * Z, N - Reset * H, C - Set/reset according to operation???? */ private int addSPN() { byte offset = (byte)memory.readByte(pc); pc++; sp += offset; registers.resetAll(); if (((sp + offset) & 0x1f) > 0xf) { registers.setH(); } if (((sp & 0xffff) + offset) > 0xffff) { registers.setC(); } return 16; } /** * INC nn * * Increment register nn * * Affects NO FLAGS * * @param reg register to increment (ignored if incSP is true) * @param incSP boolean if true, ignore reg and increment sp */ private int incNN(GBRegisters.Reg reg, boolean incSP) { if (incSP) { sp++; } else { int value = registers.getReg(reg); registers.setReg(reg, value + 1); } return 8; } /** * DEC nn * * Decrement register nn * * no flags affected * * @param reg register to increment (ignored if incSP is true) * @param decSP boolean if true, ignore reg and increment sp */ private int decNN(GBRegisters.Reg reg, boolean decSP) { if (decSP) { sp--; } else { int value = registers.getReg(reg); registers.setReg(reg, value - 1); } return 8; } /** * Swap N * * swap upper and lower nibbles of n * * Flags Affected: * Z - set if result is 0 * NHC - reset * * @param reg (required) register to swap */ private int swapN(GBRegisters.Reg reg) { int data = registers.getReg(reg); registers.resetAll(); if (reg == GBRegisters.Reg.HL) { int lowNib = data & 0xf; int highNib = (data & 0xf000) >> 12; int midByte = (data & 0x0ff0) >> 4; data = (lowNib << 12) | (midByte << 4) | highNib; registers.setReg(reg, data); if (data == 0) { registers.setZ(); } return 16; } else { int lowNib = data & 0xf; int highNib = (data & 0xf0) >> 4; registers.setReg(reg, highNib | (lowNib << 4)); if ((highNib | (lowNib << 4)) == 0) { registers.setZ(); } return 8; } } /** * Decimal adjust register A * * MIGHT NOT BE CORRECT...instructions vague * * Flags: * z - Set if A is zero * N - Not affected * H - reset * C - set or reset according to operation */ private int decAdjust() { int flags = registers.getReg(GBRegisters.Reg.F); int reg = registers.getReg(GBRegisters.Reg.A); registers.resetC(); if (((flags & 0x20) == 0x20) || ((reg & 0xf) > 0x9)) { reg += 0x6; registers.setC(); //????? } if (((flags & 0x10) == 0x10) || ((reg & 0xf0) >> 4) > 0x9) { reg += 0x60; } registers.setReg(GBRegisters.Reg.A, reg); registers.resetZ(); if (reg == 0) { registers.setZ(); } registers.resetH(); return 4; } /** * Complement register A * * (toggles all bits) */ private int cplRegA() { int reg = registers.getReg(GBRegisters.Reg.A); reg = ~reg; registers.setReg(GBRegisters.Reg.A, reg & 0xffff); return 4; } /** * Complement carry flag * * FLAGS: * Z - not affected * H, N - reset * C - Complemented */ private int ccf() { registers.toggleC(); registers.resetN(); registers.resetH(); return 4; } /** * Set carry flag * Flags: * Z - Not affected * N,H - reset * C - Set */ private int scf() { registers.resetH(); registers.resetN(); registers.setC(); return 4; } /** * Jump to address * */ private int jump() { int address = memory.readByte(pc); pc++; address = address | (memory.readByte(pc) << 8); pc = address; return 12; } /** * Conditional jump * */ private int jumpC(int opcode) { int flags = registers.getReg(GBRegisters.Reg.F); int address = memory.readByte(pc); pc++; address = address | (memory.readByte(pc) << 8); pc++; switch (opcode) { case 0xca: if ((flags & 0x80) == 0x80) { pc = address; } break; case 0xc2: if ((flags & 0x80) == 0x0) { pc = address; } break; case 0xda: if ((flags & 0x10) == 0x10) { pc = address; } break; case 0xd2: if ((flags & 0x10) == 0x0) { pc = address; } break; default: break; } return 12; } /** * JP (HL) * * Jump to address contained in HL */ private int jumpHL() { pc = registers.getReg(GBRegisters.Reg.HL); return 4; } /** * JR n * * add n to current address and jump to it */ private int jumpN() { pc += (1 + (byte)memory.readByte(pc)); return 8; } /** * JR cc,n * * Conditional Jump with immediate offset * * @param opcode (required) opcode for jump condition */ private int jumpCN(int opcode) { int flags = registers.getReg(GBRegisters.Reg.F); byte offset = (byte)memory.readByte(pc); pc++; switch (opcode) { case 0x28: if ((flags & 0x80) == 0x80) { pc += offset; } break; case 0x20: if ((flags & 0x80) == 0x0) { pc += offset; } break; case 0x38: if ((flags & 0x10) == 0x10) { pc += offset; } break; case 0x30: if ((flags & 0x10) == 0x0) { pc += offset; } break; default: break; } return 8; } /** * Call nn * * push address of next instruction onto stack and jump to address * nn * */ private int call() { int address = memory.readByte(pc); pc++; address = address | (memory.readByte(pc) << 8); pc++; pushWordToStack(pc); pc = address; return 12; } /** * CALL cc,nn * * Call address n if following condition is true * Z flag set /reset * C flag set/reset * @param opcode opcode to check for condition */ private int callC(int opcode) { int flags = registers.getReg(GBRegisters.Reg.F); switch(opcode) { case 0xcc: if ((flags & 0x80) == 0x80) { return call(); } break; case 0xc4: if ((flags & 0x80) == 0x0) { return call(); } break; case 0xdc: if ((flags & 0x10) == 0x10) { return call(); } break; case 0xd4: if ((flags & 0x10) == 0x0) { return call(); } break; default: break; } return 12; } /** * RET * * pop two bytes from stack and jump to that address */ private int ret() { pc = popWordFromStack(); return 8; } /** * Pushes a 16 bit word to the stack * MSB pushed first */ private void pushWordToStack(int word) { sp--; memory.writeByte(sp, (word & 0xff00) >> 8); sp--; memory.writeByte(sp, word & 0xff); } /** * Pop a 16bit word off the stack * * LSB is first */ private int popWordFromStack() { int word = memory.readByte(sp); sp++; word = word | (memory.readByte(sp) << 8); sp++; return word; } /** * RST n * * Push present address onto stack, jump to address 0x0000 +n * */ private int restart(int offset) { pushWordToStack(pc); pc = offset; return 32; } /** * RET C * * Return if following condition is true * */ private int retC(int opcode) { int flags = registers.getReg(GBRegisters.Reg.F); switch(opcode) { case 0xc8: if ((flags & 0x80) == 0x80) { return ret(); } break; case 0xc0: if ((flags & 0x80) == 0x0) { return ret(); } break; case 0xd8: if ((flags & 0x10) == 0x10) { return ret(); } break; case 0xd0: if ((flags & 0x10) == 0x0) { return ret(); } break; default: break; } return 8; } /** * RCLA * * Rotate A left, Old bit 7 to Carry flag * * Flags * Z - set if result is 0 * H,N - Reset * C - Contains old bit 7 data * */ private int rlcA() { int reg = registers.getReg(GBRegisters.Reg.A); int msb = (reg & 0x80) >> 7; // rotate left reg = reg << 1; // set lsb to previous msb reg |= msb; registers.resetAll(); if (msb == 0x1) { registers.setC(); } if ((reg & 0xff) == 0) { registers.setZ(); } registers.setReg(GBRegisters.Reg.A, reg); return 4; } /** * RLA * Rotate A left through Carry Flag * * Flags Affected: * Z - Set if result is 0 * N,H - Reset * C - contains old bit 7 data * */ private int rlA() { int reg = registers.getReg(GBRegisters.Reg.A); int flags = registers.getReg(GBRegisters.Reg.F); // rotate left reg = reg << 1; // set lsb to FLAG C reg |= (flags & 0x10) >> 4; registers.resetAll(); if ((reg & 0x100) == 0x100) { registers.setC(); } if ((reg & 0xff) == 0) { registers.setZ(); } registers.setReg(GBRegisters.Reg.A, reg); return 4; } /** * RRCA * * Rotate A right, Old bit 0 to Carry flag * * Flags * Z - set if result is 0 * H,N - Reset * C - Contains old bit 0 data * */ private int rrcA() { int reg = registers.getReg(GBRegisters.Reg.A); int lsb = reg & 0x1; // rotate right reg = reg >> 1; // set msb to previous lsb reg |= lsb << 7; registers.resetAll(); if (lsb == 1) { registers.setC(); } if ((reg & 0xff) == 0) { registers.setZ(); } registers.setReg(GBRegisters.Reg.A, reg); return 4; } /** * RRA * Rotate A right through Carry Flag * * Flags Affected: * Z - Set if result is 0 * N,H - Reset * C - contains old bit 0 data * */ private int rrA() { int reg = registers.getReg(GBRegisters.Reg.A); int flags = registers.getReg(GBRegisters.Reg.F); int lsb = reg & 0x1; // rotate right reg = reg >> 1; // set msb to FLAG C reg |= (flags & 0x10) << 3; registers.resetAll(); if (lsb == 0x1) { registers.setC(); } if ((reg & 0xff) == 0) { registers.setZ(); } registers.setReg(GBRegisters.Reg.A, reg); return 4; } /** * RLC n * * Rotate n left. Old bit 7 to carry flag * * Flags: * Z - set if result is zero * N - Reset * H - Reset * C - Contains old bit 7 data * */ private int rlcN(GBRegisters.Reg src) { int data; int cycles; if (src == GBRegisters.Reg.HL) { data = memory.readByte(registers.getReg(src)); cycles = 16; } else { data = registers.getReg(src); cycles = 8; } int msb = (data & 0x80) >> 7; data = data << 1; data |= msb; registers.resetAll(); if (data == 0) { registers.setZ(); } if (msb == 1) { registers.setC(); } if (src == GBRegisters.Reg.HL) { memory.writeByte(registers.getReg(src), data); } else { registers.setReg(src, data); } return cycles; } /** * RL n * * Rotate n left through carry flag * * Flags: * Z - set if result is zero * N - Reset * H - Reset * C - Contains old bit 7 data */ private int rlN(GBRegisters.Reg src) { int data; int cycles; int flags = registers.getReg(GBRegisters.Reg.F); if (src == GBRegisters.Reg.HL) { data = memory.readByte(registers.getReg(src)); cycles = 16; } else { data = registers.getReg(src); cycles = 8; } int msb = (data & 0x80) >> 7; data = data << 1; data |= (flags & 0x10) >> 4; registers.resetAll(); if (data == 0) { registers.setZ(); } if (msb == 1) { registers.setC(); } if (src == GBRegisters.Reg.HL) { memory.writeByte(registers.getReg(src), data); } else { registers.setReg(src, data); } return cycles; } /** * RLC n * * Rotate n Right. Old bit 0 to carry flag * * Flags: * Z - set if result is zero * N - Reset * H - Reset * C - Contains old bit 0 data * */ private int rrcN(GBRegisters.Reg src) { int data; int cycles; if (src == GBRegisters.Reg.HL) { data = memory.readByte(registers.getReg(src)); cycles = 16; } else { data = registers.getReg(src); cycles = 8; } int lsb = data & 0x1; data = data >> 1; data |= lsb << 7; registers.resetAll(); if (data == 0) { registers.setZ(); } if (lsb == 1) { registers.setC(); } if (src == GBRegisters.Reg.HL) { memory.writeByte(registers.getReg(src), data); } else { registers.setReg(src, data); } return cycles; } /** * RR n * * Rotate n right through carry flag * * Flags: * Z - set if result is zero * N - Reset * H - Reset * C - Contains old bit 7 data */ private int rrN(GBRegisters.Reg src) { int data; int cycles; int flags = registers.getReg(GBRegisters.Reg.F); if (src == GBRegisters.Reg.HL) { data = memory.readByte(registers.getReg(src)); cycles = 16; } else { data = registers.getReg(src); cycles = 8; } int lsb = data & 0x1; data = data >> 1; data |= (flags & 0x10) << 3; registers.resetAll(); if (data == 0) { registers.setZ(); } if (lsb == 1) { registers.setC(); } if (src == GBRegisters.Reg.HL) { memory.writeByte(registers.getReg(src), data); } else { registers.setReg(src, data); } return cycles; } /** * SRA n/SRL n * * Shift n right into carry, sign extended if SRA, unsigned if SRL * * Z - set if result is zero * N,H - reset * C - contains old bit 0 data * @param unsignedShift if true SRL, if false SRA */ private int srAL(GBRegisters.Reg reg, boolean unsignedShift) { int cycles; int data; if (reg == GBRegisters.Reg.HL) { data = memory.readByte(registers.getReg(reg)); cycles = 16; } else { data = registers.getReg(reg); cycles = 8; } int lsb = data & 0x1; if (unsignedShift) { data = data >>> 1; } else { data = data >> 1; } registers.resetAll(); if (data == 0) { registers.setZ(); } if (lsb == 1) { registers.setC(); } if (reg == GBRegisters.Reg.HL) { memory.writeByte(registers.getReg(reg), data); } else { registers.setReg(reg, data); } return cycles; } /** * Prints the contents of the registers to STDOUT * * */ private void dumpRegisters() { System.out.println("AF: 0x" + Integer.toHexString(registers.getReg(GBRegisters.Reg.AF))); System.out.println("BC: 0x" + Integer.toHexString(registers.getReg(GBRegisters.Reg.BC))); System.out.println("DE: 0x" + Integer.toHexString(registers.getReg(GBRegisters.Reg.DE))); System.out.println("HL: 0x" + Integer.toHexString(registers.getReg(GBRegisters.Reg.HL))); System.out.println("SP: 0x" + Integer.toHexString(sp) + " PC: 0x" + Integer.toHexString(pc)); } }
src/gameboi/CPU.java
/* * Gameboi */ package gameboi; // for testing import java.util.Random; /** * Z80 Gameboy CPU * * Implementation of a gameboy cpu. Eight registers (a,b,c,d,e,f,h,l), a * stack pointer, program counter * * @author tomis007 */ public class CPU { // registers private final GBRegisters registers; // stack pointer, program counter private int sp; private int pc; //associated memory to use with CPU private final GBMem memory; /** * Constructor for gameboy z80 CPU * * @param memory GBMem object to associate with this cpu */ public CPU(GBMem memory) { pc = 0x100; sp = 0xfffe; this.memory = memory; registers = new GBRegisters(); } /** * Execute the next opcode in memory * * @return clock cycles taken to execute the opcode */ public int ExecuteOpcode() { int opcode = memory.readByte(pc); pc++; System.out.println("Executing opcode: 0x" + Integer.toHexString(opcode)); return runInstruction(opcode); } /** * Opcode Instructions for the Gameboy Z80 Chip. * * <p> * Runs the instruction associated with the opcode, and returns the * clock cycles taken. * * TODO HALT,STOP, EI,DI!!!!! * @param opcode (required) opcode to execute * @return number of cycles taken to execute */ private int runInstruction(int opcode) { switch (opcode) { case 0x0: return 4; //NOP /*****8 BIT LOADS*****/ // LD nn,n case 0x06: return eightBitLdNnN(GBRegisters.Reg.B); case 0x0e: return eightBitLdNnN(GBRegisters.Reg.C); case 0x16: return eightBitLdNnN(GBRegisters.Reg.D); case 0x1e: return eightBitLdNnN(GBRegisters.Reg.E); case 0x26: return eightBitLdNnN(GBRegisters.Reg.H); case 0x2e: return eightBitLdNnN(GBRegisters.Reg.L); //LD r1,r2 case 0x7f: return eightBitLdR1R2(GBRegisters.Reg.A, GBRegisters.Reg.A); case 0x78: return eightBitLdR1R2(GBRegisters.Reg.A, GBRegisters.Reg.B); case 0x79: return eightBitLdR1R2(GBRegisters.Reg.A, GBRegisters.Reg.C); case 0x7a: return eightBitLdR1R2(GBRegisters.Reg.A, GBRegisters.Reg.D); case 0x7b: return eightBitLdR1R2(GBRegisters.Reg.A, GBRegisters.Reg.E); case 0x7c: return eightBitLdR1R2(GBRegisters.Reg.A, GBRegisters.Reg.H); case 0x7d: return eightBitLdR1R2(GBRegisters.Reg.A, GBRegisters.Reg.L); case 0x7e: return eightBitLdR1R2(GBRegisters.Reg.A, GBRegisters.Reg.HL); case 0x40: return eightBitLdR1R2(GBRegisters.Reg.B, GBRegisters.Reg.B); case 0x41: return eightBitLdR1R2(GBRegisters.Reg.B, GBRegisters.Reg.C); case 0x42: return eightBitLdR1R2(GBRegisters.Reg.B, GBRegisters.Reg.D); case 0x43: return eightBitLdR1R2(GBRegisters.Reg.B, GBRegisters.Reg.E); case 0x44: return eightBitLdR1R2(GBRegisters.Reg.B, GBRegisters.Reg.H); case 0x45: return eightBitLdR1R2(GBRegisters.Reg.B, GBRegisters.Reg.L); case 0x46: return eightBitLdR1R2(GBRegisters.Reg.B, GBRegisters.Reg.HL); case 0x48: return eightBitLdR1R2(GBRegisters.Reg.C, GBRegisters.Reg.B); case 0x49: return eightBitLdR1R2(GBRegisters.Reg.C, GBRegisters.Reg.C); case 0x4a: return eightBitLdR1R2(GBRegisters.Reg.C, GBRegisters.Reg.D); case 0x4b: return eightBitLdR1R2(GBRegisters.Reg.C, GBRegisters.Reg.E); case 0x4c: return eightBitLdR1R2(GBRegisters.Reg.C, GBRegisters.Reg.H); case 0x4d: return eightBitLdR1R2(GBRegisters.Reg.C, GBRegisters.Reg.L); case 0x4e: return eightBitLdR1R2(GBRegisters.Reg.C, GBRegisters.Reg.HL); case 0x50: return eightBitLdR1R2(GBRegisters.Reg.D, GBRegisters.Reg.B); case 0x51: return eightBitLdR1R2(GBRegisters.Reg.D, GBRegisters.Reg.C); case 0x52: return eightBitLdR1R2(GBRegisters.Reg.D, GBRegisters.Reg.D); case 0x53: return eightBitLdR1R2(GBRegisters.Reg.D, GBRegisters.Reg.E); case 0x54: return eightBitLdR1R2(GBRegisters.Reg.D, GBRegisters.Reg.H); case 0x55: return eightBitLdR1R2(GBRegisters.Reg.D, GBRegisters.Reg.L); case 0x56: return eightBitLdR1R2(GBRegisters.Reg.D, GBRegisters.Reg.HL); case 0x58: return eightBitLdR1R2(GBRegisters.Reg.E, GBRegisters.Reg.B); case 0x59: return eightBitLdR1R2(GBRegisters.Reg.E, GBRegisters.Reg.C); case 0x5a: return eightBitLdR1R2(GBRegisters.Reg.E, GBRegisters.Reg.D); case 0x5b: return eightBitLdR1R2(GBRegisters.Reg.E, GBRegisters.Reg.E); case 0x5c: return eightBitLdR1R2(GBRegisters.Reg.E, GBRegisters.Reg.H); case 0x5d: return eightBitLdR1R2(GBRegisters.Reg.E, GBRegisters.Reg.L); case 0x5e: return eightBitLdR1R2(GBRegisters.Reg.E, GBRegisters.Reg.HL); case 0x60: return eightBitLdR1R2(GBRegisters.Reg.H, GBRegisters.Reg.B); case 0x61: return eightBitLdR1R2(GBRegisters.Reg.H, GBRegisters.Reg.C); case 0x62: return eightBitLdR1R2(GBRegisters.Reg.H, GBRegisters.Reg.D); case 0x63: return eightBitLdR1R2(GBRegisters.Reg.H, GBRegisters.Reg.E); case 0x64: return eightBitLdR1R2(GBRegisters.Reg.H, GBRegisters.Reg.H); case 0x65: return eightBitLdR1R2(GBRegisters.Reg.H, GBRegisters.Reg.L); case 0x66: return eightBitLdR1R2(GBRegisters.Reg.H, GBRegisters.Reg.HL); case 0x68: return eightBitLdR1R2(GBRegisters.Reg.L, GBRegisters.Reg.B); case 0x69: return eightBitLdR1R2(GBRegisters.Reg.L, GBRegisters.Reg.C); case 0x6a: return eightBitLdR1R2(GBRegisters.Reg.L, GBRegisters.Reg.D); case 0x6b: return eightBitLdR1R2(GBRegisters.Reg.L, GBRegisters.Reg.E); case 0x6c: return eightBitLdR1R2(GBRegisters.Reg.L, GBRegisters.Reg.H); case 0x6d: return eightBitLdR1R2(GBRegisters.Reg.L, GBRegisters.Reg.L); case 0x6e: return eightBitLdR1R2(GBRegisters.Reg.L, GBRegisters.Reg.HL); case 0x70: return eightBitLdR1R2(GBRegisters.Reg.HL, GBRegisters.Reg.B); case 0x71: return eightBitLdR1R2(GBRegisters.Reg.HL, GBRegisters.Reg.C); case 0x72: return eightBitLdR1R2(GBRegisters.Reg.HL, GBRegisters.Reg.D); case 0x73: return eightBitLdR1R2(GBRegisters.Reg.HL, GBRegisters.Reg.E); case 0x74: return eightBitLdR1R2(GBRegisters.Reg.HL, GBRegisters.Reg.H); case 0x75: return eightBitLdR1R2(GBRegisters.Reg.HL, GBRegisters.Reg.L); // special 8 bit load from memory case 0x36: return eightBitLoadFromMem(); // LD A,n case 0x0a: return eightBitLdAN(GBRegisters.Reg.BC); case 0x1a: return eightBitLdAN(GBRegisters.Reg.DE); case 0xfa: return eightBitALoadMem(true); case 0x3e: return eightBitALoadMem(false); // LD n,A case 0x47: return eightBitLdR1R2(GBRegisters.Reg.B, GBRegisters.Reg.A); case 0x4f: return eightBitLdR1R2(GBRegisters.Reg.C, GBRegisters.Reg.A); case 0x57: return eightBitLdR1R2(GBRegisters.Reg.D, GBRegisters.Reg.A); case 0x5f: return eightBitLdR1R2(GBRegisters.Reg.E, GBRegisters.Reg.A); case 0x67: return eightBitLdR1R2(GBRegisters.Reg.H, GBRegisters.Reg.A); case 0x6f: return eightBitLdR1R2(GBRegisters.Reg.L, GBRegisters.Reg.A); case 0x02: return eightBitLdR1R2(GBRegisters.Reg.BC, GBRegisters.Reg.A); case 0x12: return eightBitLdR1R2(GBRegisters.Reg.DE, GBRegisters.Reg.A); case 0x77: return eightBitLdR1R2(GBRegisters.Reg.HL, GBRegisters.Reg.A); case 0xea: return eightBitLoadToMem(); // LD A, (C) case 0xf2: return eightBitLDfromAC(); case 0xe2: return eightBitLDtoAC(); // LDD A,(HL) case 0x3a: return eightBitLDAHl(); // LDD (HL), A case 0x32: return eightBitStoreHL(); // LDI (HL), A case 0x2a: return eightBitLDIA(); // LDI (HL), A case 0x22: return eightBitLDIHLA(); // LDH (n), A, LDH A,(n) case 0xe0: return eightBitLdhA(true); case 0xf0: return eightBitLdhA(false); /*****16 BIT LOADS*****/ //LD n, nn case 0x01: return sixteenBitLdNNn(GBRegisters.Reg.BC); case 0x11: return sixteenBitLdNNn(GBRegisters.Reg.DE); case 0x21: return sixteenBitLdNNn(GBRegisters.Reg.HL); case 0x31: return sixteenBitLdNNnSP(); //LD SP,HL case 0xf9: return sixteenBitLdSpHl(); case 0xf8: return sixteenBitLdHlSp(); //LD (nn), SP case 0x08: return sixteenBitLdNnSp(); //Push nn to stack case 0xf5: return pushNN(GBRegisters.Reg.AF); case 0xc5: return pushNN(GBRegisters.Reg.BC); case 0xd5: return pushNN(GBRegisters.Reg.DE); case 0xe5: return pushNN(GBRegisters.Reg.HL); //POP nn off stack case 0xf1: return popNN(GBRegisters.Reg.AF); case 0xc1: return popNN(GBRegisters.Reg.BC); case 0xd1: return popNN(GBRegisters.Reg.DE); case 0xe1: return popNN(GBRegisters.Reg.HL); /******8-BIT ALU*****/ //ADD A,n case 0x87: return addAN(GBRegisters.Reg.A, false, false); case 0x80: return addAN(GBRegisters.Reg.B, false, false); case 0x81: return addAN(GBRegisters.Reg.C, false, false); case 0x82: return addAN(GBRegisters.Reg.D, false, false); case 0x83: return addAN(GBRegisters.Reg.E, false, false); case 0x84: return addAN(GBRegisters.Reg.H, false, false); case 0x85: return addAN(GBRegisters.Reg.L, false, false); case 0x86: return addAN(GBRegisters.Reg.HL, false, false); case 0xc6: return addAN(GBRegisters.Reg.A, false, true); //ADC A,n case 0x8f: return addAN(GBRegisters.Reg.A, true, false); case 0x88: return addAN(GBRegisters.Reg.B, true, false); case 0x89: return addAN(GBRegisters.Reg.C, true, false); case 0x8a: return addAN(GBRegisters.Reg.D, true, false); case 0x8b: return addAN(GBRegisters.Reg.E, true, false); case 0x8c: return addAN(GBRegisters.Reg.H, true, false); case 0x8d: return addAN(GBRegisters.Reg.L, true, false); case 0x8e: return addAN(GBRegisters.Reg.HL, true, false); case 0xce: return addAN(GBRegisters.Reg.A, true, true); //SUB n case 0x97: return subAN(GBRegisters.Reg.A, false, false); case 0x90: return subAN(GBRegisters.Reg.B, false, false); case 0x91: return subAN(GBRegisters.Reg.C, false, false); case 0x92: return subAN(GBRegisters.Reg.D, false, false); case 0x93: return subAN(GBRegisters.Reg.E, false, false); case 0x94: return subAN(GBRegisters.Reg.H, false, false); case 0x95: return subAN(GBRegisters.Reg.L, false, false); case 0x96: return subAN(GBRegisters.Reg.HL, false, false); case 0xd6: return subAN(GBRegisters.Reg.A, false, true); //SUBC A,n case 0x9f: return subAN(GBRegisters.Reg.A, true, false); case 0x98: return subAN(GBRegisters.Reg.B, true, false); case 0x99: return subAN(GBRegisters.Reg.C, true, false); case 0x9a: return subAN(GBRegisters.Reg.D, true, false); case 0x9b: return subAN(GBRegisters.Reg.E, true, false); case 0x9c: return subAN(GBRegisters.Reg.H, true, false); case 0x9d: return subAN(GBRegisters.Reg.L, true, false); case 0x9e: return subAN(GBRegisters.Reg.HL, true, false); case 0xde: return subAN(GBRegisters.Reg.A, true, true); //AND N case 0xa7: return andN(GBRegisters.Reg.A, false); case 0xa0: return andN(GBRegisters.Reg.B, false); case 0xa1: return andN(GBRegisters.Reg.C, false); case 0xa2: return andN(GBRegisters.Reg.D, false); case 0xa3: return andN(GBRegisters.Reg.E, false); case 0xa4: return andN(GBRegisters.Reg.H, false); case 0xa5: return andN(GBRegisters.Reg.L, false); case 0xa6: return andN(GBRegisters.Reg.HL, false); case 0xe6: return andN(GBRegisters.Reg.A, true); //OR N case 0xb7: return orN(GBRegisters.Reg.A, false); case 0xb0: return orN(GBRegisters.Reg.B, false); case 0xb1: return orN(GBRegisters.Reg.C, false); case 0xb2: return orN(GBRegisters.Reg.D, false); case 0xb3: return orN(GBRegisters.Reg.E, false); case 0xb4: return orN(GBRegisters.Reg.H, false); case 0xb5: return orN(GBRegisters.Reg.L, false); case 0xb6: return orN(GBRegisters.Reg.HL, false); case 0xf6: return orN(GBRegisters.Reg.A, true); // XOR n case 0xaf: return xorN(GBRegisters.Reg.A, false); case 0xa8: return xorN(GBRegisters.Reg.B, false); case 0xa9: return xorN(GBRegisters.Reg.C, false); case 0xaa: return xorN(GBRegisters.Reg.D, false); case 0xab: return xorN(GBRegisters.Reg.E, false); case 0xac: return xorN(GBRegisters.Reg.H, false); case 0xad: return xorN(GBRegisters.Reg.L, false); case 0xae: return xorN(GBRegisters.Reg.HL, false); case 0xee: return xorN(GBRegisters.Reg.A, true); // CP n case 0xbf: return cpN(GBRegisters.Reg.A, false); case 0xb8: return cpN(GBRegisters.Reg.B, false); case 0xb9: return cpN(GBRegisters.Reg.C, false); case 0xba: return cpN(GBRegisters.Reg.D, false); case 0xbb: return cpN(GBRegisters.Reg.E, false); case 0xbc: return cpN(GBRegisters.Reg.H, false); case 0xbd: return cpN(GBRegisters.Reg.L, false); case 0xbe: return cpN(GBRegisters.Reg.HL, false); case 0xfe: return cpN(GBRegisters.Reg.A, false); // INC n case 0x3c: return incN(GBRegisters.Reg.A); case 0x04: return incN(GBRegisters.Reg.B); case 0x0c: return incN(GBRegisters.Reg.C); case 0x14: return incN(GBRegisters.Reg.D); case 0x1c: return incN(GBRegisters.Reg.E); case 0x24: return incN(GBRegisters.Reg.H); case 0x2c: return incN(GBRegisters.Reg.L); case 0x34: return incN(GBRegisters.Reg.HL); // DEC n case 0x3d: return decN(GBRegisters.Reg.A); case 0x05: return decN(GBRegisters.Reg.B); case 0x0d: return decN(GBRegisters.Reg.C); case 0x15: return decN(GBRegisters.Reg.D); case 0x1d: return decN(GBRegisters.Reg.E); case 0x25: return decN(GBRegisters.Reg.H); case 0x2d: return decN(GBRegisters.Reg.L); case 0x35: return decN(GBRegisters.Reg.HL); //ADD HL,n case 0x09: return sixteenBitAdd(GBRegisters.Reg.BC, false); case 0x19: return sixteenBitAdd(GBRegisters.Reg.DE, false); case 0x29: return sixteenBitAdd(GBRegisters.Reg.HL, false); case 0x39: return sixteenBitAdd(GBRegisters.Reg.BC, true); //ADD SP,n case 0xe8: return addSPN(); //INC nn case 0x03: return incNN(GBRegisters.Reg.BC, false); case 0x13: return incNN(GBRegisters.Reg.DE, false); case 0x23: return incNN(GBRegisters.Reg.HL, false); case 0x33: return incNN(GBRegisters.Reg.BC, true); //DEC nn case 0x0B: return decNN(GBRegisters.Reg.BC, false); case 0x1B: return decNN(GBRegisters.Reg.DE, false); case 0x2B: return decNN(GBRegisters.Reg.HL, false); case 0x3B: return decNN(GBRegisters.Reg.BC, true); // extended case 0xcb: return extendedOpcode(); // DAA, PROBABLY NOT CORRECT case 0x27: return decAdjust(); //CPL case 0x2f: return cplRegA(); //CCF case 0x3f: return ccf(); //SCF case 0x37: return scf(); //Jumps case 0xc3: return jump(); // conditional jump case 0xc2: return jumpC(opcode); case 0xca: return jumpC(opcode); case 0xd2: return jumpC(opcode); case 0xda: return jumpC(opcode); // JP (HL) case 0xe9: return jumpHL(); //JR n case 0x18: return jumpN(); //JR cc, n case 0x20: return jumpC(opcode); case 0x28: return jumpC(opcode); case 0x30: return jumpC(opcode); case 0x38: return jumpC(opcode); //TODO HALT,STOP, EI,DI case 0x76: case 0x10: case 0xf3: case 0xfb: System.err.println("TODO!!!!"); System.exit(1); //calls case 0xcd: return call(); case 0xc4: return callC(opcode); case 0xcc: return callC(opcode); case 0xd4: return callC(opcode); case 0xdc: return callC(opcode); //restarts case 0xc7: return restart(0x00); case 0xcf: return restart(0x08); case 0xd7: return restart(0x10); case 0xdf: return restart(0x18); case 0xe7: return restart(0x20); case 0xef: return restart(0x28); case 0xf7: return restart(0x30); case 0xff: return restart(0x38); //RETURNs case 0xc9: return ret(); case 0xc0: return retC(opcode); case 0xc8: return retC(opcode); case 0xd0: return retC(opcode); case 0xd8: return retC(opcode); //TODO RETI case 0xd9: System.err.println("Unimplemented RETI"); System.exit(1); //ROTATES AND SHIFTS //RLCA case 0x07: return rlcA(); //RLA case 0x17: return rlA(); //RRCA case 0x0f: return rrcA(); case 0x1f: return rrA(); default: System.err.println("Unimplemented opcode: 0x" + Integer.toHexString(opcode)); System.exit(1); } return 0; } private int extendedOpcode() { int opcode = memory.readByte(pc); pc++; switch(opcode) { //SWAP N case 0x37: return swapN(GBRegisters.Reg.A); case 0x30: return swapN(GBRegisters.Reg.B); case 0x31: return swapN(GBRegisters.Reg.C); case 0x32: return swapN(GBRegisters.Reg.D); case 0x33: return swapN(GBRegisters.Reg.E); case 0x34: return swapN(GBRegisters.Reg.H); case 0x35: return swapN(GBRegisters.Reg.L); case 0x36: return swapN(GBRegisters.Reg.HL); //RLC n case 0x07: return rlcN(GBRegisters.Reg.A); case 0x00: return rlcN(GBRegisters.Reg.B); case 0x01: return rlcN(GBRegisters.Reg.C); case 0x02: return rlcN(GBRegisters.Reg.D); case 0x03: return rlcN(GBRegisters.Reg.E); case 0x04: return rlcN(GBRegisters.Reg.H); case 0x05: return rlcN(GBRegisters.Reg.L); case 0x06: return rlcN(GBRegisters.Reg.HL); //RL n case 0x17: return rlN(GBRegisters.Reg.A); case 0x10: return rlN(GBRegisters.Reg.B); case 0x11: return rlN(GBRegisters.Reg.C); case 0x12: return rlN(GBRegisters.Reg.D); case 0x13: return rlN(GBRegisters.Reg.E); case 0x14: return rlN(GBRegisters.Reg.H); case 0x15: return rlN(GBRegisters.Reg.L); case 0x16: return rlN(GBRegisters.Reg.HL); //RRC n case 0x0f: return rrcN(GBRegisters.Reg.A); case 0x08: return rrcN(GBRegisters.Reg.B); case 0x09: return rrcN(GBRegisters.Reg.C); case 0x0a: return rrcN(GBRegisters.Reg.D); case 0x0b: return rrcN(GBRegisters.Reg.E); case 0x0c: return rrcN(GBRegisters.Reg.H); case 0x0d: return rrcN(GBRegisters.Reg.L); case 0x0e: return rrcN(GBRegisters.Reg.HL); //RR n case 0x1f: return rrN(GBRegisters.Reg.A); case 0x18: return rrN(GBRegisters.Reg.B); case 0x19: return rrN(GBRegisters.Reg.C); case 0x1a: return rrN(GBRegisters.Reg.D); case 0x1b: return rrN(GBRegisters.Reg.E); case 0x1c: return rrN(GBRegisters.Reg.H); case 0x1d: return rrN(GBRegisters.Reg.L); case 0x1e: return rrN(GBRegisters.Reg.HL); //SRA n case 0x2f: return srAL(GBRegisters.Reg.A, false); case 0x28: return srAL(GBRegisters.Reg.B, false); case 0x29: return srAL(GBRegisters.Reg.C, false); case 0x2a: return srAL(GBRegisters.Reg.D, false); case 0x2b: return srAL(GBRegisters.Reg.E, false); case 0x2c: return srAL(GBRegisters.Reg.H, false); case 0x2d: return srAL(GBRegisters.Reg.L, false); case 0x2e: return srAL(GBRegisters.Reg.HL, false); //SRL n case 0x3f: return srAL(GBRegisters.Reg.A, true); case 0x38: return srAL(GBRegisters.Reg.B, true); case 0x39: return srAL(GBRegisters.Reg.C, true); case 0x3a: return srAL(GBRegisters.Reg.D, true); case 0x3b: return srAL(GBRegisters.Reg.E, true); case 0x3c: return srAL(GBRegisters.Reg.H, true); case 0x3d: return srAL(GBRegisters.Reg.L, true); case 0x3e: return srAL(GBRegisters.Reg.HL, true); default: System.err.println("Unimplemented opcode: 0xcb" + Integer.toHexString(opcode)); System.exit(1); } return 0; } /** * LD nn,n. Put value nn into n. * * <p>nn = B,C,D,E,H,L,BC,DE,HL,SP * n = 8 bit immediate value * * @param register (required) register (nn) to load to */ private int eightBitLdNnN(GBRegisters.Reg register) { int data = memory.readByte(pc); pc++; registers.setReg(register, data); return 8; } /** * Testing function for EightBitLdNnN * * Tests the eightBitLdNnN function with random input data * to make sure the function works correctly */ public void testEightBitLdNnN() { // Random rand = new Random(); // for (int i = 0; i < 2000; ++i) { // int data = rand.nextInt(256); // for (int j = 0; j < 200; ++j) { // eightBitLdNnN(GBRegisters.Reg.E, data); // if (registers.getReg(GBRegisters.Reg.E)!= data) { // System.err.println("Error failed register E test"); // } // data = rand.nextInt(256); // eightBitLdNnN(GBRegisters.Reg.B, data); // if (registers.getReg(GBRegisters.Reg.B)!= data) { // System.err.println("Error failed register B test"); // } // data = rand.nextInt(256); // eightBitLdNnN(GBRegisters.Reg.C, data); // if (registers.getReg(GBRegisters.Reg.C) != data) { // System.err.println("Error failed register C test"); // } // data = rand.nextInt(256); // eightBitLdNnN(GBRegisters.Reg.D, data); // if (registers.getReg(GBRegisters.Reg.D) != data) { // System.err.println("Error failed register D test"); // } // data = rand.nextInt(256); // eightBitLdNnN(GBRegisters.Reg.H, data); // if (registers.getReg(GBRegisters.Reg.H) != data) { // System.err.println("Error failed register H test"); // } // data = rand.nextInt(256); // eightBitLdNnN(GBRegisters.Reg.L, data); // if (registers.getReg(GBRegisters.Reg.L) != data) { // System.err.println("Error failed register L test"); // } // } // } // System.out.println("Finished and reported all error messages"); } /** * Put value r2 into r2. * * <p> Use with: r1,r2 = A,B,C,D,E,H,L,(HL) * * @param dest destination register * @param scr source register */ private int eightBitLdR1R2(GBRegisters.Reg dest, GBRegisters.Reg src) { if (src == GBRegisters.Reg.HL) { int data = memory.readByte(registers.getReg(GBRegisters.Reg.HL)); registers.setReg(dest, data); return 8; } else if ((dest == GBRegisters.Reg.HL) || (dest == GBRegisters.Reg.BC) || (dest == GBRegisters.Reg.DE)) { memory.writeByte(registers.getReg(dest), registers.getReg(src)); return 8; } else { registers.setReg(dest, registers.getReg(src)); return 4; } } /** * Special function for opcode 0x36 * * LD (HL), n */ private int eightBitLoadFromMem() { int data = memory.readByte(pc); pc++; memory.writeByte(registers.getReg(GBRegisters.Reg.HL), data); return 12; } /** * Special function for opcode 0xea * */ private int eightBitLoadToMem() { int address = memory.readByte(pc); pc++; address = address | (memory.readByte(pc) << 8); memory.writeByte(address, registers.getReg(GBRegisters.Reg.A)); return 16; } /** * LD A,n * * Put value n into A. For opcodes 0x0a, 0x1a * * * @param src value n */ private int eightBitLdAN(GBRegisters.Reg src) { int data = memory.readByte(registers.getReg(src)); registers.setReg(GBRegisters.Reg.A, data); return 8; } /** * LD A,n (where n is located in rom, or an address in rom) * * For opcodes: 0xfa, 0x3e * * @param isPointer If true, next two bytes are address in memory to load * from. If false, eight bit immediate value is loaded. */ private int eightBitALoadMem(boolean isPointer) { if (isPointer) { int address = memory.readByte(pc); pc++; address = address | (memory.readByte(pc) << 8); pc++; registers.setReg(GBRegisters.Reg.A, memory.readByte(address)); return 16; } else { int data = memory.readByte(pc); pc++; registers.setReg(GBRegisters.Reg.A, data); return 8; } } /** * LD A, (C) * * put value at address $FF00 + register C into A * Same as: LD A, ($FF00 + C) */ private int eightBitLDfromAC() { int data = memory.readByte(registers.getReg(GBRegisters.Reg.C) + 0xff00); registers.setReg(GBRegisters.Reg.A, data); return 8; } /** * LD (C), A * * Put A into address $FF00 + register C * */ private int eightBitLDtoAC() { int address = registers.getReg(GBRegisters.Reg.C); int data = registers.getReg(GBRegisters.Reg.A); memory.writeByte(address + 0xff00, data); return 8; } /** LDD A, (HL) * * Put value at address HL into A, decrement HL * */ private int eightBitLDAHl() { int address = registers.getReg(GBRegisters.Reg.HL); registers.setReg(GBRegisters.Reg.A, memory.readByte(address)); registers.setReg(GBRegisters.Reg.HL, address - 1); return 8; } /** * LDD (HL), A * Put A into memory address HL, Decrement HL * */ private int eightBitStoreHL() { int address = registers.getReg(GBRegisters.Reg.HL); int data = registers.getReg(GBRegisters.Reg.A); memory.writeByte(address, data); registers.setReg(GBRegisters.Reg.HL, address - 1); return 8; } /** * Put value at address HL into A, increment HL * */ private int eightBitLDIA() { int address = registers.getReg(GBRegisters.Reg.HL); registers.setReg(GBRegisters.Reg.A, memory.readByte(address)); registers.setReg(GBRegisters.Reg.HL, address + 1); return 8; } /** * Put A into memory at address HL. Increment HL * */ private int eightBitLDIHLA() { int address = registers.getReg(GBRegisters.Reg.HL); int data = registers.getReg(GBRegisters.Reg.A); memory.writeByte(address, data); registers.setReg(GBRegisters.Reg.HL, address + 1); return 8; } /** * LDH (n), A and LDH A, (n) * * LDH (n), A - Put A into memory address $FF00 + n * LDH A,(n) - Put memory address $FF00+n into A * * @param writeToMem (required) if true LDH (n),A. if false LDH A,(n) * */ private int eightBitLdhA(boolean writeToMem) { int offset = memory.readByte(pc); pc++; if (writeToMem) { int data = registers.getReg(GBRegisters.Reg.A); memory.writeByte(0xff00 + offset, data); } else { int data = memory.readByte(0xff00 + offset); registers.setReg(GBRegisters.Reg.A, data); } return 12; } /** * LD n, nn * * Put value nn into n * * nn - 16 Bit immediate value, n = BC, DE, HL * */ private int sixteenBitLdNNn(GBRegisters.Reg reg) { // read two byte data from memory LSB first int data = memory.readByte(pc); pc++; data = data | (memory.readByte(pc) << 8); pc++; switch(reg) { case BC: registers.setReg(GBRegisters.Reg.BC, data); case DE: registers.setReg(GBRegisters.Reg.DE, data); case HL: registers.setReg(GBRegisters.Reg.HL, data); } return 12; } /** * LD n, nn * Put value nn into SP * */ private int sixteenBitLdNNnSP() { int data = memory.readByte(pc); pc++; data = data | (memory.readByte(pc) << 8); pc++; sp = data; return 12; } /** * LD SP,HL * * Put HL into SP */ private int sixteenBitLdSpHl() { sp = registers.getReg(GBRegisters.Reg.HL); return 8; } /** * LDHL SP,n * * Put SP+n effective address into HL * * <p>n = one byte signed immediate value * Z - reset * N - reset * H - set or reset according to operation * C - set or reset according to operation * */ private int sixteenBitLdHlSp() { int offset = memory.readByte(pc); pc++; byte data = (byte)memory.readByte((sp + offset) & 0xffff); registers.setReg(GBRegisters.Reg.HL, data); registers.resetAll(); // NOT REALLY SURE HERE, CPU DOCUMENTATION NOT EXACT if (((sp + offset) & 0x1f) > 0xf) { registers.setH(); } if ((sp + offset) > 0xffff) { registers.setC(); } return 12; } /** * Put SP at address n (2 byte immediate address) * stored little endian */ private int sixteenBitLdNnSp() { int address = memory.readByte(pc); pc++; address = address | (memory.readByte(pc) << 8); pc++; memory.writeByte(address, sp & 0xff); memory.writeByte(address + 1, ((sp & 0xff00) >> 8)); return 20; } /** * Push Register Pair value to stack * * @param src (required) register pair to push to stack */ private int pushNN(GBRegisters.Reg src) { int registerPair = registers.getReg(src); sp--; memory.writeByte(sp, (registerPair & 0xff00) >> 8); sp--; memory.writeByte(sp, (registerPair & 0xff)); return 16; } /** * pop value off stack to a register pair * * @param dest (required) register to store data in */ private int popNN(GBRegisters.Reg dest) { int data = memory.readByte(sp); sp++; data = data | (memory.readByte(sp) << 8); sp++; registers.setReg(dest, data); return 12; } /** * ADD A,n * * Add n to A * * Flags: * Z - set if result is zero * N - Reset * H - set if carry from bit 3 * C - set if carry from bit 7 * * @param src (source to add from) * @param addCarry true if adding carry * @param readMem true if reading immediate value from memory * if true, src ignored */ private int addAN(GBRegisters.Reg src, boolean addCarry, boolean readMem) { int cycles; int regA = registers.getReg(GBRegisters.Reg.A); int toAdd; if (readMem) { toAdd = memory.readByte(pc); pc++; cycles = 8; } else if (src == GBRegisters.Reg.HL) { toAdd = memory.readByte(registers.getReg(src)); cycles = 8; } else { toAdd = registers.getReg(src); cycles = 4; } toAdd += (addCarry) ? 1 : 0; //add registers.setReg(GBRegisters.Reg.A, toAdd + regA); //flags registers.resetAll(); if (registers.getReg(GBRegisters.Reg.A) == 0) { registers.setZ(); } if ((regA & 0xf) + (toAdd & 0xf) > 0xf) { registers.setH(); } if (toAdd + regA > 0xff) { registers.setC(); } return cycles; } /** * SUB n, SUBC A,n * Subtract N from A * Z- Set if result is zero * N - Set * H - set if no borrow from bit 4 * C - set if no borrow * */ private int subAN(GBRegisters.Reg src, boolean addCarry, boolean readMem) { int cycles; int regA = registers.getReg(GBRegisters.Reg.A); int toSub; if (readMem) { toSub = memory.readByte(pc); pc++; cycles = 8; } else if (src == GBRegisters.Reg.HL) { toSub = memory.readByte(registers.getReg(src)); cycles = 8; } else { toSub = registers.getReg(src); cycles = 4; } toSub += (addCarry) ? 1 : 0; //sub registers.setReg(GBRegisters.Reg.A, regA - toSub); //flags registers.resetAll(); if (registers.getReg(GBRegisters.Reg.A) == 0) { registers.setZ(); } registers.setN(); if ((regA & 0xf) - (toSub & 0xf) < 0) { registers.setH(); } if (regA < toSub) { registers.setC(); } return cycles; } /** * And N with A, result in A * * FLAGS: * Z - Set if result is 0 * N - Reset * H - Set * C - Reset * * @param src (required) N to and * @param readMem (required) true if reading immediate value from * memory (if true, src is ignored) */ private int andN(GBRegisters.Reg src, boolean readMem) { int cycles; int data; if (readMem) { data = memory.readByte(pc); pc++; cycles = 8; } else if (src == GBRegisters.Reg.HL) { data = registers.getReg(src); cycles = 8; } else { data = registers.getReg(src); cycles = 4; } int regA = registers.getReg(GBRegisters.Reg.A); registers.setReg(GBRegisters.Reg.A, data & regA); registers.resetAll(); if ((data & regA) == 0) { registers.setZ(); } registers.setH(); return cycles; } /** * OR N with A, result in A * * FLAGS: * Z - Set if result is 0 * N - Reset * H - Reset * C - Reset * * @param src (required) N to and * @param readMem (required) true if reading immediate value from * memory (if true, src is ignored) */ private int orN(GBRegisters.Reg src, boolean readMem) { int cycles; int data; if (readMem) { data = memory.readByte(pc); pc++; cycles = 8; } else if (src == GBRegisters.Reg.HL) { data = registers.getReg(src); cycles = 8; } else { data = registers.getReg(src); cycles = 4; } int regA = registers.getReg(GBRegisters.Reg.A); registers.setReg(GBRegisters.Reg.A, data | regA); registers.resetAll(); if ((data | regA) == 0) { registers.setZ(); } return cycles; } /** * XOR n * * Logical XOR n, with A, result in A * * FLAGS * Z - set if result is 0 * N, H, C = Reset * @param src (required) src register * @param readMem (required) true if reading immediate value from * memory (if true src ignored) * @return clock cycles taken */ private int xorN(GBRegisters.Reg src, boolean readMem) { int cycles; int data; if (readMem) { data = memory.readByte(pc); pc++; cycles = 8; } else if (src == GBRegisters.Reg.HL) { data = registers.getReg(src); cycles = 8; } else { data = registers.getReg(src); cycles = 4; } int regA = registers.getReg(GBRegisters.Reg.A); registers.setReg(GBRegisters.Reg.A, data ^ regA); registers.resetAll(); if ((data ^ regA) == 0) { registers.setZ(); } return cycles; } /** * CP n * * Compare A with n. Basically A - n subtraction but * results are thrown away * * FLAGS * Z - set if result is 0 (if A == n) * N - set * H - Set if no borrow from bit 4 * C = set if no morrow (Set if A is less than n) * * @param src (required) src register * @param readMem (required) true if reading immediate value from * memory (if true src ignored) * @return clock cycles taken */ private int cpN(GBRegisters.Reg src, boolean readMem) { int cycles; int data; if (readMem) { data = memory.readByte(pc); pc++; cycles = 8; } else if (src == GBRegisters.Reg.HL) { data = registers.getReg(src); cycles = 8; } else { data = registers.getReg(src); cycles = 4; } int regA = registers.getReg(GBRegisters.Reg.A); registers.resetAll(); if (regA == data) { registers.setZ(); } registers.setN(); if ((regA & 0xf) - (data & 0xf) < 0) { registers.setH(); } if (regA < data) { registers.setC(); } return cycles; } /** * INC n * * Increment register n. * * FLAGS: * Z - Set if result is 0 * N - Reset * H - Set if carry from bit 3 * C - Not affected * @param src (required) register to increment */ private int incN(GBRegisters.Reg src) { int reg = registers.getReg(src); registers.setReg(src, reg + 1); registers.resetZ(); if (registers.getReg(src) == 0) { registers.setZ(); } registers.resetN(); registers.resetH(); if (((reg & 0xf) + 1) > 0xf) { registers.setH(); } return (src == GBRegisters.Reg.HL) ? 12 : 4; } /** * DEC n * * Decrement register n. * * FLAGS: * Z - Set if result is 0 * N - Set * H - Set if no borrow from bit 4 * C - Not affected * @param src (required) register to decrement */ private int decN(GBRegisters.Reg src) { int reg = registers.getReg(src); registers.setReg(src, reg - 1); registers.resetZ(); if (registers.getReg(src) == 0) { registers.setZ(); } registers.setN(); registers.resetH(); if (((reg & 0xf) - 1) < 0) { registers.setH(); } return (src == GBRegisters.Reg.HL) ? 12 : 4; } /** * ADD HL,n * * Add n to HL * * n = BC,DE,HL,SP * * Flags * Z - Not affected * N - Reset * H - Set if carry from bit 11 * C - Set if carry from bit 15 * * @param src source register to add * @param addSP boolean (if true, adds stackpointer instead of register * to HL, ignores src) * @return clock cycles taken */ private int sixteenBitAdd(GBRegisters.Reg src, boolean addSP) { int toAdd; int regVal = registers.getReg(GBRegisters.Reg.HL); if (addSP) { toAdd = sp; } else { toAdd = registers.getReg(src); } registers.setReg(GBRegisters.Reg.HL, regVal + toAdd); //flags registers.resetN(); registers.resetH(); if ((regVal & 0xfff) + (toAdd & 0xfff) > 0xfff) { registers.setH(); } registers.resetC(); if ((regVal + toAdd) > 0xffff) { registers.setC(); } return 8; } /** * ADD SP,n * Add n to sp * * Flags: * Z, N - Reset * H, C - Set/reset according to operation???? */ private int addSPN() { byte offset = (byte)memory.readByte(pc); pc++; sp += offset; registers.resetAll(); if (((sp + offset) & 0x1f) > 0xf) { registers.setH(); } if (((sp & 0xffff) + offset) > 0xffff) { registers.setC(); } return 16; } /** * INC nn * * Increment register nn * * Affects NO FLAGS * * @param reg register to increment (ignored if incSP is true) * @param incSP boolean if true, ignore reg and increment sp */ private int incNN(GBRegisters.Reg reg, boolean incSP) { if (incSP) { sp++; } else { int value = registers.getReg(reg); registers.setReg(reg, value + 1); } return 8; } /** * DEC nn * * Decrement register nn * * no flags affected * * @param reg register to increment (ignored if incSP is true) * @param decSP boolean if true, ignore reg and increment sp */ private int decNN(GBRegisters.Reg reg, boolean decSP) { if (decSP) { sp--; } else { int value = registers.getReg(reg); registers.setReg(reg, value - 1); } return 8; } /** * Swap N * * swap upper and lower nibbles of n * * Flags Affected: * Z - set if result is 0 * NHC - reset * * @param reg (required) register to swap */ private int swapN(GBRegisters.Reg reg) { int data = registers.getReg(reg); registers.resetAll(); if (reg == GBRegisters.Reg.HL) { int lowNib = data & 0xf; int highNib = (data & 0xf000) >> 12; int midByte = (data & 0x0ff0) >> 4; data = (lowNib << 12) | (midByte << 4) | highNib; registers.setReg(reg, data); if (data == 0) { registers.setZ(); } return 16; } else { int lowNib = data & 0xf; int highNib = (data & 0xf0) >> 4; registers.setReg(reg, highNib | (lowNib << 4)); if ((highNib | (lowNib << 4)) == 0) { registers.setZ(); } return 8; } } /** * Decimal adjust register A * * MIGHT NOT BE CORRECT...instructions vague * * Flags: * z - Set if A is zero * N - Not affected * H - reset * C - set or reset according to operation */ private int decAdjust() { int flags = registers.getReg(GBRegisters.Reg.F); int reg = registers.getReg(GBRegisters.Reg.A); registers.resetC(); if (((flags & 0x20) == 0x20) || ((reg & 0xf) > 0x9)) { reg += 0x6; registers.setC(); //????? } if (((flags & 0x10) == 0x10) || ((reg & 0xf0) >> 4) > 0x9) { reg += 0x60; } registers.setReg(GBRegisters.Reg.A, reg); registers.resetZ(); if (reg == 0) { registers.setZ(); } registers.resetH(); return 4; } /** * Complement register A * * (toggles all bits) */ private int cplRegA() { int reg = registers.getReg(GBRegisters.Reg.A); reg = ~reg; registers.setReg(GBRegisters.Reg.A, reg & 0xffff); return 4; } /** * Complement carry flag * * FLAGS: * Z - not affected * H, N - reset * C - Complemented */ private int ccf() { registers.toggleC(); registers.resetN(); registers.resetH(); return 4; } /** * Set carry flag * Flags: * Z - Not affected * N,H - reset * C - Set */ private int scf() { registers.resetH(); registers.resetN(); registers.setC(); return 4; } /** * Jump to address * */ private int jump() { int address = memory.readByte(pc); pc++; address = address | (memory.readByte(pc) << 8); pc = address; return 12; } /** * Conditional jump * */ private int jumpC(int opcode) { int flags = registers.getReg(GBRegisters.Reg.F); int address = memory.readByte(pc); pc++; address = address | (memory.readByte(pc) << 8); pc++; switch (opcode) { case 0xca: if ((flags & 0x80) == 0x80) { pc = address; } break; case 0xc2: if ((flags & 0x80) == 0x0) { pc = address; } break; case 0xda: if ((flags & 0x10) == 0x10) { pc = address; } break; case 0xd2: if ((flags & 0x10) == 0x0) { pc = address; } break; default: break; } return 12; } /** * JP (HL) * * Jump to address contained in HL */ private int jumpHL() { pc = registers.getReg(GBRegisters.Reg.HL); return 4; } /** * JR n * * add n to current address and jump to it */ private int jumpN() { pc += (1 + (byte)memory.readByte(pc)); return 8; } /** * JR cc,n * * Conditional Jump with immediate offset * * @param opcode (required) opcode for jump condition */ private int jumpCN(int opcode) { int flags = registers.getReg(GBRegisters.Reg.A); byte offset = (byte)memory.readByte(pc); pc++; switch (opcode) { case 0x28: if ((flags & 0x80) == 0x80) { pc += offset; } break; case 0x20: if ((flags & 0x80) == 0x0) { pc += offset; } break; case 0x38: if ((flags & 0x10) == 0x10) { pc += offset; } break; case 0x30: if ((flags & 0x10) == 0x0) { pc += offset; } break; default: break; } return 8; } /** * Call nn * * push address of next instruction onto stack and jump to address * nn * */ private int call() { int address = memory.readByte(pc); pc++; address = address | (memory.readByte(pc) << 8); pc++; pushWordToStack(pc); pc = address; return 12; } /** * CALL cc,nn * * Call address n if following condition is true * Z flag set /reset * C flag set/reset * @param opcode opcode to check for condition */ private int callC(int opcode) { int flags = registers.getReg(GBRegisters.Reg.F); switch(opcode) { case 0xcc: if ((flags & 0x80) == 0x80) { return call(); } break; case 0xc4: if ((flags & 0x80) == 0x0) { return call(); } break; case 0xdc: if ((flags & 0x10) == 0x10) { return call(); } break; case 0xd4: if ((flags & 0x10) == 0x0) { return call(); } break; default: break; } return 12; } /** * RET * * pop two bytes from stack and jump to that address */ private int ret() { pc = popWordFromStack(); return 8; } /** * Pushes a 16 bit word to the stack * MSB pushed first */ private void pushWordToStack(int word) { sp--; memory.writeByte(sp, (word & 0xff00) >> 8); sp--; memory.writeByte(sp, word & 0xff); } /** * Pop a 16bit word off the stack * * LSB is first */ private int popWordFromStack() { int word = memory.readByte(sp); sp++; word = word | (memory.readByte(sp) << 8); sp++; return word; } /** * RST n * * Push present address onto stack, jump to address 0x0000 +n * */ private int restart(int offset) { pushWordToStack(pc); pc = offset; return 32; } /** * RET C * * Return if following condition is true * */ private int retC(int opcode) { int flags = registers.getReg(GBRegisters.Reg.F); switch(opcode) { case 0xc8: if ((flags & 0x80) == 0x80) { return ret(); } break; case 0xc0: if ((flags & 0x80) == 0x0) { return ret(); } break; case 0xd8: if ((flags & 0x10) == 0x10) { return ret(); } break; case 0xd0: if ((flags & 0x10) == 0x0) { return ret(); } break; default: break; } return 8; } /** * RCLA * * Rotate A left, Old bit 7 to Carry flag * * Flags * Z - set if result is 0 * H,N - Reset * C - Contains old bit 7 data * */ private int rlcA() { int reg = registers.getReg(GBRegisters.Reg.A); int msb = (reg & 0x80) >> 7; // rotate left reg = reg << 1; // set lsb to previous msb reg |= msb; registers.resetAll(); if (msb == 0x1) { registers.setC(); } if ((reg & 0xff) == 0) { registers.setZ(); } registers.setReg(GBRegisters.Reg.A, reg); return 4; } /** * RLA * Rotate A left through Carry Flag * * Flags Affected: * Z - Set if result is 0 * N,H - Reset * C - contains old bit 7 data * */ private int rlA() { int reg = registers.getReg(GBRegisters.Reg.A); int flags = registers.getReg(GBRegisters.Reg.F); // rotate left reg = reg << 1; // set lsb to FLAG C reg |= (flags & 0x10) >> 4; registers.resetAll(); if ((reg & 0x100) == 0x100) { registers.setC(); } if ((reg & 0xff) == 0) { registers.setZ(); } registers.setReg(GBRegisters.Reg.A, reg); return 4; } /** * RRCA * * Rotate A right, Old bit 0 to Carry flag * * Flags * Z - set if result is 0 * H,N - Reset * C - Contains old bit 0 data * */ private int rrcA() { int reg = registers.getReg(GBRegisters.Reg.A); int lsb = reg & 0x1; // rotate right reg = reg >> 1; // set msb to previous lsb reg |= lsb << 7; registers.resetAll(); if (lsb == 1) { registers.setC(); } if ((reg & 0xff) == 0) { registers.setZ(); } registers.setReg(GBRegisters.Reg.A, reg); return 4; } /** * RRA * Rotate A right through Carry Flag * * Flags Affected: * Z - Set if result is 0 * N,H - Reset * C - contains old bit 0 data * */ private int rrA() { int reg = registers.getReg(GBRegisters.Reg.A); int flags = registers.getReg(GBRegisters.Reg.F); int lsb = reg & 0x1; // rotate right reg = reg >> 1; // set msb to FLAG C reg |= (flags & 0x10) << 3; registers.resetAll(); if (lsb == 0x1) { registers.setC(); } if ((reg & 0xff) == 0) { registers.setZ(); } registers.setReg(GBRegisters.Reg.A, reg); return 4; } /** * RLC n * * Rotate n left. Old bit 7 to carry flag * * Flags: * Z - set if result is zero * N - Reset * H - Reset * C - Contains old bit 7 data * */ private int rlcN(GBRegisters.Reg src) { int data; int cycles; if (src == GBRegisters.Reg.HL) { data = memory.readByte(registers.getReg(src)); cycles = 16; } else { data = registers.getReg(src); cycles = 8; } int msb = (data & 0x80) >> 7; data = data << 1; data |= msb; registers.resetAll(); if (data == 0) { registers.setZ(); } if (msb == 1) { registers.setC(); } if (src == GBRegisters.Reg.HL) { memory.writeByte(registers.getReg(src), data); } else { registers.setReg(src, data); } return cycles; } /** * RL n * * Rotate n left through carry flag * * Flags: * Z - set if result is zero * N - Reset * H - Reset * C - Contains old bit 7 data */ private int rlN(GBRegisters.Reg src) { int data; int cycles; int flags = registers.getReg(GBRegisters.Reg.F); if (src == GBRegisters.Reg.HL) { data = memory.readByte(registers.getReg(src)); cycles = 16; } else { data = registers.getReg(src); cycles = 8; } int msb = (data & 0x80) >> 7; data = data << 1; data |= (flags & 0x10) >> 4; registers.resetAll(); if (data == 0) { registers.setZ(); } if (msb == 1) { registers.setC(); } if (src == GBRegisters.Reg.HL) { memory.writeByte(registers.getReg(src), data); } else { registers.setReg(src, data); } return cycles; } /** * RLC n * * Rotate n Right. Old bit 0 to carry flag * * Flags: * Z - set if result is zero * N - Reset * H - Reset * C - Contains old bit 0 data * */ private int rrcN(GBRegisters.Reg src) { int data; int cycles; if (src == GBRegisters.Reg.HL) { data = memory.readByte(registers.getReg(src)); cycles = 16; } else { data = registers.getReg(src); cycles = 8; } int lsb = data & 0x1; data = data >> 1; data |= lsb << 7; registers.resetAll(); if (data == 0) { registers.setZ(); } if (lsb == 1) { registers.setC(); } if (src == GBRegisters.Reg.HL) { memory.writeByte(registers.getReg(src), data); } else { registers.setReg(src, data); } return cycles; } /** * RR n * * Rotate n right through carry flag * * Flags: * Z - set if result is zero * N - Reset * H - Reset * C - Contains old bit 7 data */ private int rrN(GBRegisters.Reg src) { int data; int cycles; int flags = registers.getReg(GBRegisters.Reg.F); if (src == GBRegisters.Reg.HL) { data = memory.readByte(registers.getReg(src)); cycles = 16; } else { data = registers.getReg(src); cycles = 8; } int lsb = data & 0x1; data = data >> 1; data |= (flags & 0x10) << 3; registers.resetAll(); if (data == 0) { registers.setZ(); } if (lsb == 1) { registers.setC(); } if (src == GBRegisters.Reg.HL) { memory.writeByte(registers.getReg(src), data); } else { registers.setReg(src, data); } return cycles; } /** * SRA n/SRL n * * Shift n right into carry, sign extended if SRA, unsigned if SRL * * Z - set if result is zero * N,H - reset * C - contains old bit 0 data * @param unsignedShift if true SRL, if false SRA */ private int srAL(GBRegisters.Reg reg, boolean unsignedShift) { int cycles; int data; if (reg == GBRegisters.Reg.HL) { data = memory.readByte(registers.getReg(reg)); cycles = 16; } else { data = registers.getReg(reg); cycles = 8; } int lsb = data & 0x1; if (unsignedShift) { data = data >>> 1; } else { data = data >> 1; } registers.resetAll(); if (data == 0) { registers.setZ(); } if (lsb == 1) { registers.setC(); } if (reg == GBRegisters.Reg.HL) { memory.writeByte(registers.getReg(reg), data); } else { registers.setReg(reg, data); } return cycles; } }
fixed some bugs, added basic debugging loop
src/gameboi/CPU.java
fixed some bugs, added basic debugging loop
Java
mit
cde77c08f00cd7e6a8b3b61d449b2e9eefeabedc
0
markovandooren/chameleon
package chameleon.input; import java.io.File; import java.util.Set; import chameleon.core.namespace.Namespace; public interface MetaModelFactory { // public Namespace getMetaModel(ILinkageFactory fact, Set<File> files) throws Exception; public Set loadFiles(String path, String extension, boolean recursive); }
src/chameleon/input/MetaModelFactory.java
package chameleon.input; import java.io.File; import java.util.Set; import chameleon.core.namespace.Namespace; import chameleon.editor.toolextension.ILinkageFactory; public interface MetaModelFactory { public Namespace getMetaModel(ILinkageFactory fact, Set<File> files) throws Exception; public Set loadFiles(String path, String extension, boolean recursive); }
removed methods that should not be there
src/chameleon/input/MetaModelFactory.java
removed methods that should not be there
Java
mit
0afecaabc89046035ce0e12c67fd55bf7a76b277
0
krupt/yast
package ru.krupt.yast; import ru.krupt.yast.exception.InvalidParameterFormat; import ru.krupt.yast.exception.ParameterIsNullAndNotHaveDefaultValueException; import ru.krupt.yast.util.IgnoreNullAndRemoveQuotesStringBuilder; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Template { private static final Pattern FORMAT_PATTERN = Pattern.compile("('.*')?(\\d{1,2})('.*?')?(\\?('.*')?)?", Pattern.DOTALL); private static final Pattern PARAMETER_PATTERN = Pattern.compile("\\$\\{.*?\\}", Pattern.DOTALL); private static final int START_DELIMITER_LENGTH = 2; private static final int END_DELIMITER_LENGTH = 1; private final Iterable<Part> parts; public Template(String template) throws InvalidParameterFormat { if (template == null) { throw new NullPointerException("Template can't be null"); } parts = parseTemplate(template); } private Iterable<Part> parseTemplate(String template) throws InvalidParameterFormat { ArrayList<Part> parts = new ArrayList<Part>(); Matcher parameterFinder = PARAMETER_PATTERN.matcher(template); int end = 0; while (parameterFinder.find()) { int start = parameterFinder.start(); int parameterEnd = parameterFinder.end(); String paramString = template.substring(start + START_DELIMITER_LENGTH, parameterEnd - END_DELIMITER_LENGTH); Matcher formatMatcher = FORMAT_PATTERN.matcher(paramString); if (!formatMatcher.matches()) { throw new InvalidParameterFormat(paramString); } String text = template.substring(end, start); String before = formatMatcher.group(1); int parameterNo = Integer.parseInt(formatMatcher.group(2)) - 1; String after = formatMatcher.group(3); String defaultValueGroup = formatMatcher.group(4); String defaultValue = formatMatcher.group(5); parts.add(new Part(text, before, parameterNo, after, defaultValueGroup != null, defaultValue)); end = parameterEnd; } if (end != template.length()) { parts.add(new Part(template.substring(end))); } parts.trimToSize(); return parts; } public String render(List<String> parameters) throws ParameterIsNullAndNotHaveDefaultValueException { if (parameters == null) { parameters = Collections.emptyList(); } IgnoreNullAndRemoveQuotesStringBuilder builder = new IgnoreNullAndRemoveQuotesStringBuilder(); for (Part part : parts) { builder.append(part.getText()); OptionalInt parameterNo = part.getParameterNo(); if (parameterNo.isPresent()) { String parameterValue = null; try { parameterValue = parameters.get(parameterNo.getAsInt()); } catch (IndexOutOfBoundsException e) { // Ignore } if (parameterValue != null) { builder.append(part.getBeforeParameterValue()) .append(parameterValue) .append(part.getAfterParameterValue()); } else { if (part.isDefaultValueExists()) { builder.append(part.getDefaultValue()); } else { throw new ParameterIsNullAndNotHaveDefaultValueException(parameterNo.getAsInt() + 1); } } } } return builder.toString(); } }
src/main/java/ru/krupt/yast/Template.java
package ru.krupt.yast; import ru.krupt.yast.exception.InvalidParameterFormat; import ru.krupt.yast.exception.ParameterIsNullAndNotHaveDefaultValueException; import ru.krupt.yast.util.IgnoreNullAndRemoveQuotesStringBuilder; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Template { private static final Pattern FORMAT_PATTERN = Pattern.compile("('.*')?(\\d{1,2})('.*?')?(\\?('.*')?)?", Pattern.DOTALL); private static final Pattern PARAMETER_PATTERN = Pattern.compile("\\$\\{.*?\\}", Pattern.DOTALL); private static final int START_DELIMITER_LENGTH = 2; private static final int END_DELIMITER_LENGTH = 1; private final Iterable<Part> parts; public Template(String template) throws InvalidParameterFormat { Objects.requireNonNull(template, "Template can't be null"); parts = parseTemplate(template); } private Iterable<Part> parseTemplate(String template) throws InvalidParameterFormat { ArrayList<Part> parts = new ArrayList<Part>(); Matcher parameterFinder = PARAMETER_PATTERN.matcher(template); int end = 0; while (parameterFinder.find()) { int start = parameterFinder.start(); int parameterEnd = parameterFinder.end(); String paramString = template.substring(start + START_DELIMITER_LENGTH, parameterEnd - END_DELIMITER_LENGTH); Matcher formatMatcher = FORMAT_PATTERN.matcher(paramString); if (!formatMatcher.matches()) { throw new InvalidParameterFormat(paramString); } String text = template.substring(end, start); String before = formatMatcher.group(1); int parameterNo = Integer.parseInt(formatMatcher.group(2)) - 1; String after = formatMatcher.group(3); String defaultValueGroup = formatMatcher.group(4); String defaultValue = formatMatcher.group(5); parts.add(new Part(text, before, parameterNo, after, defaultValueGroup != null, defaultValue)); end = parameterEnd; } if (end != template.length()) { parts.add(new Part(template.substring(end))); } parts.trimToSize(); return parts; } public String render(List<String> parameters) throws ParameterIsNullAndNotHaveDefaultValueException { if (parameters == null) { parameters = Collections.emptyList(); } IgnoreNullAndRemoveQuotesStringBuilder builder = new IgnoreNullAndRemoveQuotesStringBuilder(); for (Part part : parts) { builder.append(part.getText()); OptionalInt parameterNo = part.getParameterNo(); if (parameterNo.isPresent()) { String parameterValue = null; try { parameterValue = parameters.get(parameterNo.getAsInt()); } catch (IndexOutOfBoundsException e) { // Ignore } if (parameterValue != null) { builder.append(part.getBeforeParameterValue()) .append(parameterValue) .append(part.getAfterParameterValue()); } else { if (part.isDefaultValueExists()) { builder.append(part.getDefaultValue()); } else { throw new ParameterIsNullAndNotHaveDefaultValueException(parameterNo.getAsInt() + 1); } } } } return builder.toString(); } }
Java 5
src/main/java/ru/krupt/yast/Template.java
Java 5
Java
mit
09773b3e73f3d844d0c939477ab26c2b307a6821
0
AlexDeveloper81/SpeechRecognitionPlugin,ochakov/SpeechRecognitionPlugin,jakestreett/SpeechRecognitionPlugin,macdonst/SpeechRecognitionPlugin,AlexDeveloper81/SpeechRecognitionPlugin,jakestreett/SpeechRecognitionPlugin,macdonst/SpeechRecognitionPlugin,ochakov/SpeechRecognitionPlugin,ElodieC/SpeechRecognitionPlugin,ElodieC/SpeechRecognitionPlugin
package org.apache.cordova.speech; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import android.util.Log; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.speech.RecognitionListener; import android.speech.RecognizerIntent; import android.speech.SpeechRecognizer; /** * Style and such borrowed from the TTS and PhoneListener plugins */ public class SpeechRecognition extends CordovaPlugin { private static final String LOG_TAG = SpeechRecognition.class.getSimpleName(); public static final String ACTION_INIT = "init"; public static final String ACTION_SPEECH_RECOGNIZE_START = "start"; public static final String ACTION_SPEECH_RECOGNIZE_STOP = "stop"; public static final String ACTION_SPEECH_RECOGNIZE_ABORT = "abort"; public static final String NOT_PRESENT_MESSAGE = "Speech recognition is not present or enabled"; private CallbackContext speechRecognizerCallbackContext; private boolean recognizerPresent = false; private SpeechRecognizer recognizer; private boolean aborted = false; @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { // Dispatcher if (ACTION_INIT.equals(action)) { // init if (DoInit()) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); Handler loopHandler = new Handler(Looper.getMainLooper()); loopHandler.post(new Runnable() { @Override public void run() { recognizer = SpeechRecognizer.createSpeechRecognizer(cordova.getActivity().getBaseContext()); recognizer.setRecognitionListener(new SpeechRecognitionListner()); } }); } else { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, NOT_PRESENT_MESSAGE)); } } else if (ACTION_SPEECH_RECOGNIZE_START.equals(action)) { // recognize speech if (!recognizerPresent) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, NOT_PRESENT_MESSAGE)); } this.speechRecognizerCallbackContext = callbackContext; final Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test"); intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,5); Handler loopHandler = new Handler(Looper.getMainLooper()); loopHandler.post(new Runnable() { @Override public void run() { recognizer.startListening(intent); } }); PluginResult res = new PluginResult(PluginResult.Status.NO_RESULT); res.setKeepCallback(true); callbackContext.sendPluginResult(res); } else if (ACTION_SPEECH_RECOGNIZE_STOP.equals(action)) { stop(false); } else if (ACTION_SPEECH_RECOGNIZE_ABORT.equals(action)) { stop(true); } else { // Invalid action String res = "Unknown action: " + action; return false; } return true; } private void stop(boolean abort) { this.aborted = abort; Handler loopHandler = new Handler(Looper.getMainLooper()); loopHandler.post(new Runnable() { @Override public void run() { recognizer.stopListening(); } }); } /** * Initialize the speech recognizer by checking if one exists. */ private boolean DoInit() { this.recognizerPresent = SpeechRecognizer.isRecognitionAvailable(this.cordova.getActivity().getBaseContext()); return this.recognizerPresent; } private void fireRecognitionEvent(ArrayList<String> transcripts, float[] confidences) { JSONObject event = new JSONObject(); JSONArray results = new JSONArray(); try { for(int i=0; i<transcripts.size(); i++) { JSONArray alternatives = new JSONArray(); JSONObject result = new JSONObject(); result.put("transcript", transcripts.get(i)); result.put("final", true); if (confidences != null) { result.put("confidence", confidences[i]); } alternatives.put(result); results.put(alternatives); } event.put("type", "result"); event.put("emma", null); event.put("interpretation", null); event.put("results", results); } catch (JSONException e) { // this will never happen } PluginResult pr = new PluginResult(PluginResult.Status.OK, event); pr.setKeepCallback(true); this.speechRecognizerCallbackContext.sendPluginResult(pr); } private void fireEvent(String type) { JSONObject event = new JSONObject(); try { event.put("type",type); } catch (JSONException e) { // this will never happen } PluginResult pr = new PluginResult(PluginResult.Status.OK, event); pr.setKeepCallback(true); this.speechRecognizerCallbackContext.sendPluginResult(pr); } private void fireErrorEvent() { JSONObject event = new JSONObject(); try { event.put("type","error"); } catch (JSONException e) { // this will never happen } PluginResult pr = new PluginResult(PluginResult.Status.ERROR, event); pr.setKeepCallback(false); this.speechRecognizerCallbackContext.sendPluginResult(pr); } class SpeechRecognitionListner implements RecognitionListener { @Override public void onBeginningOfSpeech() { Log.d(LOG_TAG, "begin speech"); fireEvent("start"); fireEvent("audiostart"); fireEvent("soundstart"); fireEvent("speechstart"); } @Override public void onBufferReceived(byte[] buffer) { Log.d(LOG_TAG, "buffer received"); } @Override public void onEndOfSpeech() { Log.d(LOG_TAG, "end speech"); fireEvent("speechend"); fireEvent("soundend"); fireEvent("audioend"); fireEvent("end"); } @Override public void onError(int error) { Log.d(LOG_TAG, "error speech"); fireErrorEvent(); fireEvent("end"); } @Override public void onEvent(int eventType, Bundle params) { Log.d(LOG_TAG, "event speech"); } @Override public void onPartialResults(Bundle partialResults) { Log.d(LOG_TAG, "partial results"); } @Override public void onReadyForSpeech(Bundle params) { Log.d(LOG_TAG, "ready for speech"); } @Override public void onResults(Bundle results) { Log.d(LOG_TAG, "results"); String str = new String(); Log.d(LOG_TAG, "onResults " + results); ArrayList<String> transcript = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); float[] confidence = results.getFloatArray(SpeechRecognizer.CONFIDENCE_SCORES); if (transcript.size() > 0) { Log.d(LOG_TAG, "fire recognition event"); fireRecognitionEvent(transcript, confidence); } else { Log.d(LOG_TAG, "fire no match event"); fireEvent("nomatch"); } } @Override public void onRmsChanged(float rmsdB) { Log.d(LOG_TAG, "rms changed"); } } }
src/android/SpeechRecognition.java
package org.apache.cordova.speech; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import android.util.Log; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.speech.RecognitionListener; import android.speech.RecognizerIntent; import android.speech.SpeechRecognizer; /** * Style and such borrowed from the TTS and PhoneListener plugins */ public class SpeechRecognition extends CordovaPlugin { private static final String LOG_TAG = SpeechRecognition.class.getSimpleName(); public static final String ACTION_INIT = "init"; public static final String ACTION_SPEECH_RECOGNIZE_START = "start"; public static final String ACTION_SPEECH_RECOGNIZE_STOP = "stop"; public static final String ACTION_SPEECH_RECOGNIZE_ABORT = "abort"; public static final String NOT_PRESENT_MESSAGE = "Speech recognition is not present or enabled"; private CallbackContext speechRecognizerCallbackContext; private boolean recognizerPresent = false; private SpeechRecognizer recognizer; private boolean aborted = false; @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { // Dispatcher if (ACTION_INIT.equals(action)) { // init if (DoInit()) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); Handler loopHandler = new Handler(Looper.getMainLooper()); loopHandler.post(new Runnable() { @Override public void run() { recognizer = SpeechRecognizer.createSpeechRecognizer(cordova.getActivity().getBaseContext()); recognizer.setRecognitionListener(new SpeechRecognitionListner()); } }); } else { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, NOT_PRESENT_MESSAGE)); } } else if (ACTION_SPEECH_RECOGNIZE_START.equals(action)) { // recognize speech if (!recognizerPresent) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, NOT_PRESENT_MESSAGE)); } this.speechRecognizerCallbackContext = callbackContext; final Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test"); intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,5); Handler loopHandler = new Handler(Looper.getMainLooper()); loopHandler.post(new Runnable() { @Override public void run() { recognizer.startListening(intent); } }); PluginResult res = new PluginResult(PluginResult.Status.NO_RESULT); res.setKeepCallback(true); callbackContext.sendPluginResult(res); } else if (ACTION_SPEECH_RECOGNIZE_STOP.equals(action)) { stop(false); } else if (ACTION_SPEECH_RECOGNIZE_ABORT.equals(action)) { stop(true); } else { // Invalid action String res = "Unknown action: " + action; return false; } return true; } private void stop(boolean abort) { this.aborted = abort; Handler loopHandler = new Handler(Looper.getMainLooper()); loopHandler.post(new Runnable() { @Override public void run() { recognizer.stopListening(); } }); } /** * Initialize the speech recognizer by checking if one exists. */ private boolean DoInit() { this.recognizerPresent = SpeechRecognizer.isRecognitionAvailable(this.cordova.getActivity().getBaseContext()); return this.recognizerPresent; } private void fireRecognitionEvent(ArrayList<String> transcripts, ArrayList<String> confidences) { JSONObject event = new JSONObject(); JSONArray results = new JSONArray(); JSONObject result = new JSONObject(); try { for(int i=0; i<transcripts.size(); i++) { result.put("transcript", transcripts.get(i)); //result.put("confidence", confidences.get(i)); results.put(result); } event.put("type", "result"); event.put("results", results); } catch (JSONException e) { // this will never happen } PluginResult pr = new PluginResult(PluginResult.Status.OK, event); pr.setKeepCallback(true); this.speechRecognizerCallbackContext.sendPluginResult(pr); } private void fireEvent(String type) { JSONObject event = new JSONObject(); try { event.put("type",type); } catch (JSONException e) { // this will never happen } PluginResult pr = new PluginResult(PluginResult.Status.OK, event); pr.setKeepCallback(true); this.speechRecognizerCallbackContext.sendPluginResult(pr); } private void fireErrorEvent() { JSONObject event = new JSONObject(); try { event.put("type","error"); } catch (JSONException e) { // this will never happen } PluginResult pr = new PluginResult(PluginResult.Status.ERROR, event); pr.setKeepCallback(false); this.speechRecognizerCallbackContext.sendPluginResult(pr); } class SpeechRecognitionListner implements RecognitionListener { @Override public void onBeginningOfSpeech() { Log.d(LOG_TAG, "begin speech"); fireEvent("start"); fireEvent("audiostart"); fireEvent("soundstart"); fireEvent("speechstart"); } @Override public void onBufferReceived(byte[] buffer) { Log.d(LOG_TAG, "buffer received"); } @Override public void onEndOfSpeech() { Log.d(LOG_TAG, "end speech"); fireEvent("speechend"); fireEvent("soundend"); fireEvent("audioend"); fireEvent("end"); } @Override public void onError(int error) { Log.d(LOG_TAG, "error speech"); fireErrorEvent(); fireEvent("end"); } @Override public void onEvent(int eventType, Bundle params) { Log.d(LOG_TAG, "event speech"); } @Override public void onPartialResults(Bundle partialResults) { Log.d(LOG_TAG, "partial results"); } @Override public void onReadyForSpeech(Bundle params) { Log.d(LOG_TAG, "ready for speech"); } @Override public void onResults(Bundle results) { Log.d(LOG_TAG, "results"); String str = new String(); Log.d(LOG_TAG, "onResults " + results); ArrayList<String> transcript = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); //ArrayList<String> confidence = results.getStringArrayList(SpeechRecognizer.CONFIDENCE_SCORES); if (transcript.size() > 0) { Log.d(LOG_TAG, "fire recognition event"); fireRecognitionEvent(transcript, null); } else { Log.d(LOG_TAG, "fire no match event"); fireEvent("nomatch"); } } @Override public void onRmsChanged(float rmsdB) { Log.d(LOG_TAG, "rms changed"); } } }
Add confidence values if available
src/android/SpeechRecognition.java
Add confidence values if available
Java
mit
ec13017bc6c252a99a8c5dc7291aaad1cdc6fa88
0
amishwins/project-cec-2013,amishwins/project-cec-2013
package cec.view; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.ScrollPaneLayout; import javax.swing.UIManager; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import cec.service.FolderService; import cec.service.EmailService; import cec.service.MeetingService; import cec.service.TemplateService; import cec.service.TreeModelBuilder; import exceptions.CannotDeleteSystemFolderException; import exceptions.FolderAlreadyExistsException; import exceptions.RootFolderSubfolderCreationException; import exceptions.SourceAndDestinationFoldersAreSameException; /** * Implements SWING packages to create the main window of C.E.C application's * user interface (UI) collecting user input and displaying output data from lower layers. * Extends the JFRAME top-level container that represents a specialized window * with OS controls/event handlers and contains all Swing components. * <p> * * Most important graphic components comprises: * - JTree <code>folders</code> which shows Email Directory structure * - JTable <code>emailTable</code> which shows the Emails of each selected folder * - JTextArea <code>emailBody</code> which shows the content of selected Email * * Different methods and inner classes interact with these objects retrieving values * and keeping them updated. * <p> * The JFrame also implements a Tree Selection Listener interface to be notified * when the user selects a node (folder) in the <code>folders</code> JTree. * Thus, whenever the value of the selection changes the method * <code>valueChanged()</code> is called. */ public class EmailClient extends JFrame implements TreeSelectionListener { private static final long serialVersionUID = 7366789547512037235L; JTree folders; JTable emailTable = new JTable(); JTextArea emailBody; FolderService folderService = new FolderService(); EmailService emailService = new EmailService(); TemplateService templateService = new TemplateService(); MeetingService meetingService = new MeetingService(); EmailViewEntity selectedEmailEntity; MeetingViewEntity selectedMeetingViewEntity; String lastSelectedFolder; JTextField searchField = new JTextField(null, 22); private static EmailClient instance; /*** * Returns a reference for the current instance (Main Window) to be used * by the <code>Email</code> class to refresh the JTable <code>emailTable</code> content * when the user "Send" or "Save as a Draft" an Email. * * @return a reference for the current instance */ public static EmailClient getReference() { if (instance == null) { instance = new EmailClient("Collaborative Email Client"); } return instance; } /*** * Refreshes the content of the JTable <code>emailTable</code> * requesting the persistence layer to check the Operating * system's File System and load an updated list of Email Entities (XML Files). */ public void updateEmailTable() { String[] emailTableViewColumns = { "From", "Subject", "Date" }; Iterable<EmailViewEntity> emailsInEachFolder = folderService.loadEmails(lastSelectedFolder); emailTable.setModel(new EmailListViewData(emailTableViewColumns, emailsInEachFolder)); defineEmailTableLayout(); } private void setSelectedEntity(EmailViewEntity emailViewEntity) { selectedEmailEntity = emailViewEntity; } private EmailViewEntity getSelectedEntity() { return selectedEmailEntity; } private EmailClient(String title) { super(title); initialize(); } private void initialize() { // OS look and Feel String lookAndFeel = UIManager.getSystemLookAndFeelClassName(); try { UIManager.setLookAndFeel(lookAndFeel); } catch (Exception e) { System.err.println("It was not possible to load Windows look and feel"); } // Layout Settings setSize(1024, 768); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout()); setLocationRelativeTo(null); setupMenuBar(); JPanel topPanel = new JPanel(); ImageIcon emailIcon = new ImageIcon("images/email_at.png"); JLabel titleLabel = new JLabel("CEC - Collaborative Email Client", emailIcon, JLabel.LEFT); titleLabel.setFont(new Font("Arial", Font.BOLD, 12)); //Search Panel JPanel searchPanel = new JPanel(); JButton searchBT = new JButton("Search"); searchField.setFont(new Font("Arial", Font.PLAIN, 12)); searchPanel.add(searchField, BorderLayout.CENTER); searchPanel.add(searchBT, BorderLayout.EAST); searchBT.addActionListener(new BarSearchEmails()); searchField.addKeyListener(new KeySearchEmails()); //Top Panel topPanel.setPreferredSize(new Dimension(1024, 45)); topPanel.setLayout(new BorderLayout(5, 5)); topPanel.add(titleLabel, BorderLayout.WEST); topPanel.add(searchPanel, BorderLayout.EAST); JPanel bottomPanel = new JPanel(); bottomPanel.setLayout(new BorderLayout(2, 2)); TreeModelBuilder tmb = new TreeModelBuilder(new DefaultMutableTreeNode()); Iterable<String> hierarchy = folderService.loadHierarchy(); TreeModel treeModel = tmb.buildTreeNodeFromFileList(hierarchy); folders = new JTree(treeModel); folders.setRootVisible(false); folders.addTreeSelectionListener(this); folders.addMouseListener(new FolderTreeMouseListener(folders)); showOneLevelOfTreeDisplayed(treeModel); folders.setPreferredSize(new java.awt.Dimension(200, 400)); JScrollPane leftPanel = new JScrollPane(folders, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); JPanel rightPanel = new JPanel(); rightPanel.setLayout(new BorderLayout()); emailTable.setFillsViewportHeight(true); emailTable.getSelectionModel().addListSelectionListener(new RowListener()); emailTable.addMouseListener(new EmailTableMouseListener()); emailTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); JScrollPane rightPanelChildTop = new JScrollPane(emailTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); rightPanelChildTop.setMaximumSize(new Dimension(1200, 150)); rightPanelChildTop.setMinimumSize(new Dimension(550, 200)); rightPanelChildTop.setPreferredSize(new Dimension(550, 200)); emailBody = new JTextArea(10, 10); emailBody.setEditable(false); JScrollPane rightPanelChildBottom = new JScrollPane(emailBody); rightPanelChildBottom.setLayout(new ScrollPaneLayout()); rightPanel.add(rightPanelChildTop, BorderLayout.BEFORE_FIRST_LINE); rightPanel.add(rightPanelChildBottom, BorderLayout.CENTER); bottomPanel.add(leftPanel, BorderLayout.WEST); bottomPanel.add(rightPanel, BorderLayout.CENTER); Container container = getContentPane(); container.add(topPanel, BorderLayout.NORTH); container.add(bottomPanel, BorderLayout.CENTER); selectInboxByDefault(); } private void selectInboxByDefault() { folders.setSelectionRow(1); } private void showOneLevelOfTreeDisplayed(TreeModel model) { DefaultMutableTreeNode currentNode = ((DefaultMutableTreeNode) model.getRoot()).getNextNode(); do { if (currentNode.getLevel() == 1) folders.expandPath(new TreePath(currentNode.getPath())); currentNode = currentNode.getNextNode(); } while (currentNode != null); } private void updateFolderTree() { TreeModelBuilder tmb = new TreeModelBuilder(new DefaultMutableTreeNode()); Iterable<String> hierarchy = folderService.loadHierarchy(); TreeModel treeModel = tmb.buildTreeNodeFromFileList(hierarchy); folders.setModel(treeModel); showOneLevelOfTreeDisplayed(treeModel); } private void setupMenuBar() { JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); setupFileMenu(menuBar); setupEditMenu(menuBar); } private void setupFileMenu(JMenuBar menuBar) { JMenu fileMenuBarEntry = new JMenu("File"); fileMenuBarEntry.setMnemonic('F'); menuBar.add(fileMenuBarEntry); JMenuItem newEmail = new JMenuItem("New Email", KeyEvent.VK_N); newEmail.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_DOWN_MASK)); fileMenuBarEntry.add(newEmail); JMenuItem newEmailFromTemplate = new JMenuItem("New Email From Template", KeyEvent.VK_C); newEmailFromTemplate.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_DOWN_MASK)); fileMenuBarEntry.add(newEmailFromTemplate); fileMenuBarEntry.addSeparator(); JMenuItem newMeeting = new JMenuItem("New Meeting", KeyEvent.VK_M); newMeeting.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, InputEvent.CTRL_DOWN_MASK)); fileMenuBarEntry.add(newMeeting); fileMenuBarEntry.addSeparator(); JMenuItem newTemplate = new JMenuItem("New Template", KeyEvent.VK_T); newTemplate.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.CTRL_DOWN_MASK)); fileMenuBarEntry.add(newTemplate); fileMenuBarEntry.addSeparator(); JMenuItem newSubfolder = new JMenuItem("New Sub-folder", KeyEvent.VK_F); newSubfolder.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.CTRL_DOWN_MASK)); fileMenuBarEntry.add(newSubfolder); fileMenuBarEntry.addSeparator(); JMenuItem openSelectedEmail = new JMenuItem("Open Email", KeyEvent.VK_O); openSelectedEmail.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK)); fileMenuBarEntry.add(openSelectedEmail); fileMenuBarEntry.addSeparator(); JMenuItem exitItem = new JMenuItem("Exit"); fileMenuBarEntry.add(exitItem); // Add all the action listeners for the File menu newEmail.addActionListener(new MenuFileNewEmail()); newEmailFromTemplate.addActionListener(new MenuFileNewEmailFromTemplate()); newMeeting.addActionListener(new MenuFileNewMeeting()); newTemplate.addActionListener(new MenuFileNewTemplate()); newSubfolder.addActionListener(new MenuFileNewSubFolder()); openSelectedEmail.addActionListener(new MenuFileOpenSelectedEmail()); exitItem.addActionListener(new MenuFileExit()); } private void setupEditMenu(JMenuBar menuBar) { JMenu editMenuBarEntry = new JMenu("Edit"); editMenuBarEntry.setMnemonic('E'); menuBar.add(editMenuBarEntry); JMenuItem moveSelectedEmail = new JMenuItem("Move Email...", KeyEvent.VK_M); moveSelectedEmail.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, InputEvent.CTRL_DOWN_MASK)); editMenuBarEntry.add(moveSelectedEmail); editMenuBarEntry.addSeparator(); JMenuItem deleteSelectedEmail = new JMenuItem("Delete Email", KeyEvent.VK_E); deleteSelectedEmail.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.CTRL_DOWN_MASK)); editMenuBarEntry.add(deleteSelectedEmail); JMenuItem deleteSelectedFolder = new JMenuItem("Delete Folder", KeyEvent.VK_R); deleteSelectedFolder.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, InputEvent.CTRL_DOWN_MASK)); editMenuBarEntry.add(deleteSelectedFolder); editMenuBarEntry.addSeparator(); JMenuItem editTemplate = new JMenuItem("Edit Template", KeyEvent.VK_Z); editTemplate.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, InputEvent.CTRL_DOWN_MASK)); editMenuBarEntry.add(editTemplate); // Add all the action listeners for the Edit menu moveSelectedEmail.addActionListener(new MenuEditMoveEmail()); deleteSelectedEmail.addActionListener(new MenuEditDeleteEmail()); deleteSelectedFolder.addActionListener(new MenuEditDeleteFolder()); editTemplate.addActionListener(new MenuEditEditTemplate()); } private void defineEmailTableLayout() { emailTable.getColumnModel().getColumn(0).setPreferredWidth(100); emailTable.getColumnModel().getColumn(1).setPreferredWidth(300); emailTable.getColumnModel().getColumn(2).setPreferredWidth(100); } /*** * Tree Selection Listener for JTree <code>folders</code>. * It's responsible for identifying the path of the selected node (folder) * and calling the <code>updateEmailTable()</code> that refreshes the Email table. */ @Override public void valueChanged(TreeSelectionEvent tse) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) folders.getLastSelectedPathComponent(); if (node == null) return; Object[] pathComponents = folders.getSelectionPath().getPath(); StringBuilder sb = new StringBuilder(); for (Object o : pathComponents) { sb.append(o); sb.append("/"); } sb.deleteCharAt(0); sb.deleteCharAt(sb.length() - 1); lastSelectedFolder = sb.toString(); updateEmailTable(); setSelectedEntity(null); } // EMAIL TABLE MAIN LISTENER private class RowListener implements ListSelectionListener { public void valueChanged(ListSelectionEvent event) { if (event.getValueIsAdjusting()) { return; } setSelectedEntity(((EmailListViewData) (emailTable.getModel())).getViewEntityAtIndex(emailTable.getSelectedRow())); emailBody.setText(getSelectedEntity().getBody()); } } // FILE > NEW SUB-FOLDER > private class MenuFileNewSubFolder implements ActionListener { public void actionPerformed(ActionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) folders .getLastSelectedPathComponent(); if (node == null) JOptionPane.showMessageDialog(null, "Select a parent folder"); else { String folderName = JOptionPane.showInputDialog(null, "Folder Name"); Validator validator = new Validator(); if (folderName != null) { if (folderName.trim().length() > 0 && validator.isValidFolderName(folderName)) { try { folderService.createSubFolder(lastSelectedFolder, folderName); updateFolderTree(); } catch (RootFolderSubfolderCreationException ex) { JOptionPane.showMessageDialog(null, "You may not create a subfolder under the root directory."); } catch (FolderAlreadyExistsException folderAlreadyExistsException) { JOptionPane.showMessageDialog(null, "A folder with that name already exists. Please enter another name."); } } else { JOptionPane.showMessageDialog(null, "Invalid Folder name"); } } } } } private class MenuEditEditTemplate implements ActionListener { public void actionPerformed(ActionEvent e) { new EmailFrame(TemplateContext.EDIT); } } // FILE > OPEN SELECTED EMAIL private class MenuFileOpenSelectedEmail implements ActionListener { public void actionPerformed(ActionEvent e) { if (getSelectedEntity() == null) { JOptionPane.showMessageDialog(null, "Select an email to display"); } else { new EmailFrame(selectedEmailEntity); } } } // EDIT > MOVE EMAIL > private class MenuEditMoveEmail implements ActionListener { public void actionPerformed(ActionEvent e) { if (getSelectedEntity() == null) { JOptionPane.showMessageDialog(null, "Select an email first"); } else { ArrayList<String> listOfFolders = (ArrayList<String>) folderService .loadHierarchy(); String[] selValues = new String[listOfFolders.size()]; int index = 0; for (String folder : listOfFolders) { selValues[index] = folder; index++; } int messageType = JOptionPane.QUESTION_MESSAGE; Object mov = JOptionPane.showInputDialog(null, "Select the destination folder", "Move Email", messageType, null, selValues, null); if (mov != null) { try { emailService.move(getSelectedEntity(), mov.toString()); updateEmailTable(); setSelectedEntity(null); } catch (SourceAndDestinationFoldersAreSameException ex) { } } } } } // EDIT > DELETE EMAIL > private class MenuEditDeleteEmail implements ActionListener { public void actionPerformed(ActionEvent e) { if (getSelectedEntity() == null) JOptionPane.showMessageDialog(null, "Select Email First"); if (getSelectedEntity() != null) { emailService.delete(getSelectedEntity()); updateEmailTable(); setSelectedEntity(null); } } } // EDIT > DELETE FOLDER > private class MenuEditDeleteFolder implements ActionListener { public void actionPerformed(ActionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) folders .getLastSelectedPathComponent(); if (node == null) JOptionPane.showMessageDialog(null, "Select a folder to delete"); try { folderService.delete(lastSelectedFolder); updateFolderTree(); } catch (CannotDeleteSystemFolderException ex) { JOptionPane.showMessageDialog(null, "Cannot delete system folders"); } } } // FOLDER TREE CONTEXT MENU (Right-Click) private class FolderTreeContextMenu extends JPopupMenu { private static final long serialVersionUID = -5926440670627487856L; JMenuItem newFolder; JMenuItem delFolder; public FolderTreeContextMenu() { newFolder = new JMenuItem("New Sub-folder..."); add(newFolder); delFolder = new JMenuItem("Delete Folder"); add(delFolder); newFolder.addActionListener(new MenuFileNewSubFolder()); delFolder.addActionListener(new MenuEditDeleteFolder()); } } // EMAIL TABLE CONTEXT MENU (Right-Click) private class EmailTableContextMenu extends JPopupMenu { private static final long serialVersionUID = 1L; JMenuItem movEmail; JMenuItem delEmail; public EmailTableContextMenu() { movEmail = new JMenuItem("Move Email..."); add(movEmail); delEmail = new JMenuItem("Delete Email"); add(delEmail); movEmail.addActionListener(new MenuEditMoveEmail()); delEmail.addActionListener(new MenuEditDeleteEmail()); } } // FOLDER TREE MOUSE LISTENER private class FolderTreeMouseListener extends MouseAdapter { JTree tree; int selNode; public FolderTreeMouseListener(JTree foldersTree) { this.tree = foldersTree; } public void mousePressed(MouseEvent e) { selNode = tree.getRowForLocation(e.getX(), e.getY()); TreePath selPath = tree.getPathForLocation(e.getX(), e.getY()); if (selNode != -1) { tree.setSelectionPath(selPath); if (e.isPopupTrigger()) Popup(e); } } public void mouseReleased(MouseEvent e) { if (selNode != -1) { if (e.isPopupTrigger()) Popup(e); } } private void Popup(MouseEvent e) { FolderTreeContextMenu menu = new FolderTreeContextMenu(); menu.show(e.getComponent(), e.getX() + 7, e.getY()); } } // EMAIL TABLE MOUSE LISTENER private class EmailTableMouseListener extends MouseAdapter { int selRow; public void mousePressed(MouseEvent e) { selRow = emailTable.rowAtPoint(e.getPoint()); if (selRow != -1) { emailTable.setRowSelectionInterval(selRow, selRow); if (e.isPopupTrigger()) Popup(e); } } public void mouseClicked(MouseEvent e) { if ((e.getClickCount() == 2) && (selRow != -1)) { new EmailFrame(selectedEmailEntity); } } public void mouseReleased(MouseEvent e) { if (selRow != -1) { if (e.isPopupTrigger()) Popup(e); } } private void Popup(MouseEvent e) { EmailTableContextMenu menu = new EmailTableContextMenu(); menu.show(e.getComponent(), e.getX() + 7, e.getY()); } } private class MenuFileNewEmail implements ActionListener { public void actionPerformed(ActionEvent e) { new EmailFrame(); } } // FILE -> NEW EMAIL FROM TEMPLATE private class MenuFileNewEmailFromTemplate implements ActionListener { public void actionPerformed(ActionEvent e) { new EmailFrame(TemplateContext.APPLY); } } private class MenuFileNewMeeting implements ActionListener{ public void actionPerformed(ActionEvent e) { new MeetingFrame(); } } private class MenuFileNewTemplate implements ActionListener { public void actionPerformed(ActionEvent e) { new EmailFrame(TemplateContext.NEW); } } private class MenuFileExit implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } private void updateEmailTableFound(String toFind) { String[] emailTableViewColumns = { "From", "Subject", "Date" }; Iterable<EmailViewEntity> emailsFoundInFolder=folderService.searchEmails(toFind); emailTable.setModel(new EmailListViewData(emailTableViewColumns, emailsFoundInFolder)); defineEmailTableLayout(); } public Object getSelectedTemplateFromDialog() { String[] selValues = templateService.getTemplateNames(); int messageType = JOptionPane.QUESTION_MESSAGE; Object mov = JOptionPane.showInputDialog(null, "Select the template", "Choose Template", messageType, null, selValues, null); return mov; } private void search() { String toFind = searchField.getText(); if(toFind.trim().length()>0) updateEmailTableFound(toFind); } private class BarSearchEmails implements ActionListener { public void actionPerformed(ActionEvent e) { search(); } } private class KeySearchEmails implements KeyListener { public void keyPressed(KeyEvent e) { if ( e.getKeyCode() == KeyEvent.VK_ENTER ){ search(); } } public void keyReleased(KeyEvent e) {} public void keyTyped(KeyEvent e) {} } }
CECProject/src/cec/view/EmailClient.java
package cec.view; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.ScrollPaneLayout; import javax.swing.UIManager; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import cec.service.FolderService; import cec.service.EmailService; import cec.service.MeetingService; import cec.service.TemplateService; import cec.service.TreeModelBuilder; import exceptions.CannotDeleteSystemFolderException; import exceptions.FolderAlreadyExistsException; import exceptions.RootFolderSubfolderCreationException; import exceptions.SourceAndDestinationFoldersAreSameException; /** * Implements SWING packages to create the main window of C.E.C application's * user interface (UI) collecting user input and displaying output data from lower layers. * Extends the JFRAME top-level container that represents a specialized window * with OS controls/event handlers and contains all Swing components. * <p> * * Most important graphic components comprises: * - JTree <code>folders</code> which shows Email Directory structure * - JTable <code>emailTable</code> which shows the Emails of each selected folder * - JTextArea <code>emailBody</code> which shows the content of selected Email * * Different methods and inner classes interact with these objects retrieving values * and keeping them updated. * <p> * The JFrame also implements a Tree Selection Listener interface to be notified * when the user selects a node (folder) in the <code>folders</code> JTree. * Thus, whenever the value of the selection changes the method * <code>valueChanged()</code> is called. */ public class EmailClient extends JFrame implements TreeSelectionListener { private static final long serialVersionUID = 7366789547512037235L; JTree folders; JTable emailTable = new JTable(); JTextArea emailBody; FolderService folderService = new FolderService(); EmailService emailService = new EmailService(); TemplateService templateService = new TemplateService(); MeetingService meetingService = new MeetingService(); EmailViewEntity selectedEmailEntity; MeetingViewEntity selectedMeetingViewEntity; String lastSelectedFolder; JTextField searchField = new JTextField(null, 22); private static EmailClient instance; /*** * Returns a reference for the current instance (Main Window) to be used * by the <code>Email</code> class to refresh the JTable <code>emailTable</code> content * when the user "Send" or "Save as a Draft" an Email. * * @return a reference for the current instance */ public static EmailClient getReference() { if (instance == null) { instance = new EmailClient("Collaborative Email Client"); } return instance; } /*** * Refreshes the content of the JTable <code>emailTable</code> * requesting the persistence layer to check the Operating * system's File System and load an updated list of Email Entities (XML Files). */ public void updateEmailTable() { String[] emailTableViewColumns = { "From", "Subject", "Date" }; Iterable<EmailViewEntity> emailsInEachFolder = folderService.loadEmails(lastSelectedFolder); emailTable.setModel(new EmailListViewData(emailTableViewColumns, emailsInEachFolder)); defineEmailTableLayout(); } private void setSelectedEntity(EmailViewEntity emailViewEntity) { selectedEmailEntity = emailViewEntity; } private EmailViewEntity getSelectedEntity() { return selectedEmailEntity; } private EmailClient(String title) { super(title); initialize(); } private void initialize() { // OS look and Feel String lookAndFeel = UIManager.getSystemLookAndFeelClassName(); try { UIManager.setLookAndFeel(lookAndFeel); } catch (Exception e) { System.err.println("It was not possible to load Windows look and feel"); } // Layout Settings setSize(1024, 768); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout()); setLocationRelativeTo(null); setupMenuBar(); JPanel topPanel = new JPanel(); ImageIcon emailIcon = new ImageIcon("images/email_at.png"); JLabel titleLabel = new JLabel("CEC - Collaborative Email Client", emailIcon, JLabel.LEFT); titleLabel.setFont(new Font("Arial", Font.BOLD, 12)); //Search Panel JPanel searchPanel = new JPanel(); JButton searchBT = new JButton("Search"); searchField.setFont(new Font("Arial", Font.PLAIN, 12)); searchPanel.add(searchField, BorderLayout.CENTER); searchPanel.add(searchBT, BorderLayout.EAST); searchBT.addActionListener(new BarSearchEmails()); searchField.addKeyListener(new KeySearchEmails()); //Top Panel topPanel.setPreferredSize(new Dimension(1024, 45)); topPanel.setLayout(new BorderLayout(5, 5)); topPanel.add(titleLabel, BorderLayout.WEST); topPanel.add(searchPanel, BorderLayout.EAST); JPanel bottomPanel = new JPanel(); bottomPanel.setLayout(new BorderLayout(2, 2)); TreeModelBuilder tmb = new TreeModelBuilder(new DefaultMutableTreeNode()); Iterable<String> hierarchy = folderService.loadHierarchy(); TreeModel treeModel = tmb.buildTreeNodeFromFileList(hierarchy); folders = new JTree(treeModel); folders.setRootVisible(false); folders.addTreeSelectionListener(this); folders.addMouseListener(new FolderTreeMouseListener(folders)); showOneLevelOfTreeDisplayed(treeModel); folders.setPreferredSize(new java.awt.Dimension(200, 400)); JScrollPane leftPanel = new JScrollPane(folders, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); JPanel rightPanel = new JPanel(); rightPanel.setLayout(new BorderLayout()); emailTable.setFillsViewportHeight(true); emailTable.getSelectionModel().addListSelectionListener(new RowListener()); emailTable.addMouseListener(new EmailTableMouseListener()); emailTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); JScrollPane rightPanelChildTop = new JScrollPane(emailTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); rightPanelChildTop.setMaximumSize(new Dimension(1200, 150)); rightPanelChildTop.setMinimumSize(new Dimension(550, 200)); rightPanelChildTop.setPreferredSize(new Dimension(550, 200)); emailBody = new JTextArea(10, 10); emailBody.setEditable(false); JScrollPane rightPanelChildBottom = new JScrollPane(emailBody); rightPanelChildBottom.setLayout(new ScrollPaneLayout()); rightPanel.add(rightPanelChildTop, BorderLayout.BEFORE_FIRST_LINE); rightPanel.add(rightPanelChildBottom, BorderLayout.CENTER); bottomPanel.add(leftPanel, BorderLayout.WEST); bottomPanel.add(rightPanel, BorderLayout.CENTER); Container container = getContentPane(); container.add(topPanel, BorderLayout.NORTH); container.add(bottomPanel, BorderLayout.CENTER); selectInboxByDefault(); } private void selectInboxByDefault() { folders.setSelectionRow(1); } private void showOneLevelOfTreeDisplayed(TreeModel model) { DefaultMutableTreeNode currentNode = ((DefaultMutableTreeNode) model.getRoot()).getNextNode(); do { if (currentNode.getLevel() == 1) folders.expandPath(new TreePath(currentNode.getPath())); currentNode = currentNode.getNextNode(); } while (currentNode != null); } private void updateFolderTree() { TreeModelBuilder tmb = new TreeModelBuilder(new DefaultMutableTreeNode()); Iterable<String> hierarchy = folderService.loadHierarchy(); TreeModel treeModel = tmb.buildTreeNodeFromFileList(hierarchy); folders.setModel(treeModel); showOneLevelOfTreeDisplayed(treeModel); } private void setupMenuBar() { JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); setupFileMenu(menuBar); setupEditMenu(menuBar); } private void setupFileMenu(JMenuBar menuBar) { JMenu fileMenuBarEntry = new JMenu("File"); fileMenuBarEntry.setMnemonic('F'); menuBar.add(fileMenuBarEntry); JMenuItem newEmail = new JMenuItem("New Email", KeyEvent.VK_N); newEmail.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_DOWN_MASK)); fileMenuBarEntry.add(newEmail); JMenuItem newEmailFromTemplate = new JMenuItem("New Email From Template", KeyEvent.VK_C); newEmailFromTemplate.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_DOWN_MASK)); fileMenuBarEntry.add(newEmailFromTemplate); fileMenuBarEntry.addSeparator(); JMenuItem newMeeting = new JMenuItem("New Meeting", KeyEvent.VK_A); newMeeting.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_DOWN_MASK)); fileMenuBarEntry.add(newMeeting); fileMenuBarEntry.addSeparator(); JMenuItem newTemplate = new JMenuItem("New Template", KeyEvent.VK_T); newTemplate.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.CTRL_DOWN_MASK)); fileMenuBarEntry.add(newTemplate); fileMenuBarEntry.addSeparator(); JMenuItem newSubfolder = new JMenuItem("New Sub-folder", KeyEvent.VK_F); newSubfolder.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.CTRL_DOWN_MASK)); fileMenuBarEntry.add(newSubfolder); fileMenuBarEntry.addSeparator(); JMenuItem openSelectedEmail = new JMenuItem("Open Email", KeyEvent.VK_O); openSelectedEmail.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK)); fileMenuBarEntry.add(openSelectedEmail); fileMenuBarEntry.addSeparator(); JMenuItem exitItem = new JMenuItem("Exit"); fileMenuBarEntry.add(exitItem); // Add all the action listeners for the File menu newEmail.addActionListener(new MenuFileNewEmail()); newEmailFromTemplate.addActionListener(new MenuFileNewEmailFromTemplate()); newMeeting.addActionListener(new MenuFileNewMeeting()); newTemplate.addActionListener(new MenuFileNewTemplate()); newSubfolder.addActionListener(new MenuFileNewSubFolder()); openSelectedEmail.addActionListener(new MenuFileOpenSelectedEmail()); exitItem.addActionListener(new MenuFileExit()); } private void setupEditMenu(JMenuBar menuBar) { JMenu editMenuBarEntry = new JMenu("Edit"); editMenuBarEntry.setMnemonic('E'); menuBar.add(editMenuBarEntry); JMenuItem moveSelectedEmail = new JMenuItem("Move Email...", KeyEvent.VK_M); moveSelectedEmail.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, InputEvent.CTRL_DOWN_MASK)); editMenuBarEntry.add(moveSelectedEmail); editMenuBarEntry.addSeparator(); JMenuItem deleteSelectedEmail = new JMenuItem("Delete Email", KeyEvent.VK_E); deleteSelectedEmail.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.CTRL_DOWN_MASK)); editMenuBarEntry.add(deleteSelectedEmail); JMenuItem deleteSelectedFolder = new JMenuItem("Delete Folder", KeyEvent.VK_R); deleteSelectedFolder.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, InputEvent.CTRL_DOWN_MASK)); editMenuBarEntry.add(deleteSelectedFolder); editMenuBarEntry.addSeparator(); JMenuItem editTemplate = new JMenuItem("Edit Template", KeyEvent.VK_Z); editTemplate.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, InputEvent.CTRL_DOWN_MASK)); editMenuBarEntry.add(editTemplate); // Add all the action listeners for the Edit menu moveSelectedEmail.addActionListener(new MenuEditMoveEmail()); deleteSelectedEmail.addActionListener(new MenuEditDeleteEmail()); deleteSelectedFolder.addActionListener(new MenuEditDeleteFolder()); editTemplate.addActionListener(new MenuEditEditTemplate()); } private void defineEmailTableLayout() { emailTable.getColumnModel().getColumn(0).setPreferredWidth(100); emailTable.getColumnModel().getColumn(1).setPreferredWidth(300); emailTable.getColumnModel().getColumn(2).setPreferredWidth(100); } /*** * Tree Selection Listener for JTree <code>folders</code>. * It's responsible for identifying the path of the selected node (folder) * and calling the <code>updateEmailTable()</code> that refreshes the Email table. */ @Override public void valueChanged(TreeSelectionEvent tse) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) folders.getLastSelectedPathComponent(); if (node == null) return; Object[] pathComponents = folders.getSelectionPath().getPath(); StringBuilder sb = new StringBuilder(); for (Object o : pathComponents) { sb.append(o); sb.append("/"); } sb.deleteCharAt(0); sb.deleteCharAt(sb.length() - 1); lastSelectedFolder = sb.toString(); updateEmailTable(); setSelectedEntity(null); } // EMAIL TABLE MAIN LISTENER private class RowListener implements ListSelectionListener { public void valueChanged(ListSelectionEvent event) { if (event.getValueIsAdjusting()) { return; } setSelectedEntity(((EmailListViewData) (emailTable.getModel())).getViewEntityAtIndex(emailTable.getSelectedRow())); emailBody.setText(getSelectedEntity().getBody()); } } // FILE > NEW SUB-FOLDER > private class MenuFileNewSubFolder implements ActionListener { public void actionPerformed(ActionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) folders .getLastSelectedPathComponent(); if (node == null) JOptionPane.showMessageDialog(null, "Select a parent folder"); else { String folderName = JOptionPane.showInputDialog(null, "Folder Name"); Validator validator = new Validator(); if (folderName != null) { if (folderName.trim().length() > 0 && validator.isValidFolderName(folderName)) { try { folderService.createSubFolder(lastSelectedFolder, folderName); updateFolderTree(); } catch (RootFolderSubfolderCreationException ex) { JOptionPane.showMessageDialog(null, "You may not create a subfolder under the root directory."); } catch (FolderAlreadyExistsException folderAlreadyExistsException) { JOptionPane.showMessageDialog(null, "A folder with that name already exists. Please enter another name."); } } else { JOptionPane.showMessageDialog(null, "Invalid Folder name"); } } } } } private class MenuEditEditTemplate implements ActionListener { public void actionPerformed(ActionEvent e) { new EmailFrame(TemplateContext.EDIT); } } // FILE > OPEN SELECTED EMAIL private class MenuFileOpenSelectedEmail implements ActionListener { public void actionPerformed(ActionEvent e) { if (getSelectedEntity() == null) { JOptionPane.showMessageDialog(null, "Select an email to display"); } else { new EmailFrame(selectedEmailEntity); } } } // EDIT > MOVE EMAIL > private class MenuEditMoveEmail implements ActionListener { public void actionPerformed(ActionEvent e) { if (getSelectedEntity() == null) { JOptionPane.showMessageDialog(null, "Select an email first"); } else { ArrayList<String> listOfFolders = (ArrayList<String>) folderService .loadHierarchy(); String[] selValues = new String[listOfFolders.size()]; int index = 0; for (String folder : listOfFolders) { selValues[index] = folder; index++; } int messageType = JOptionPane.QUESTION_MESSAGE; Object mov = JOptionPane.showInputDialog(null, "Select the destination folder", "Move Email", messageType, null, selValues, null); if (mov != null) { try { emailService.move(getSelectedEntity(), mov.toString()); updateEmailTable(); setSelectedEntity(null); } catch (SourceAndDestinationFoldersAreSameException ex) { } } } } } // EDIT > DELETE EMAIL > private class MenuEditDeleteEmail implements ActionListener { public void actionPerformed(ActionEvent e) { if (getSelectedEntity() == null) JOptionPane.showMessageDialog(null, "Select Email First"); if (getSelectedEntity() != null) { emailService.delete(getSelectedEntity()); updateEmailTable(); setSelectedEntity(null); } } } // EDIT > DELETE FOLDER > private class MenuEditDeleteFolder implements ActionListener { public void actionPerformed(ActionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) folders .getLastSelectedPathComponent(); if (node == null) JOptionPane.showMessageDialog(null, "Select a folder to delete"); try { folderService.delete(lastSelectedFolder); updateFolderTree(); } catch (CannotDeleteSystemFolderException ex) { JOptionPane.showMessageDialog(null, "Cannot delete system folders"); } } } // FOLDER TREE CONTEXT MENU (Right-Click) private class FolderTreeContextMenu extends JPopupMenu { private static final long serialVersionUID = -5926440670627487856L; JMenuItem newFolder; JMenuItem delFolder; public FolderTreeContextMenu() { newFolder = new JMenuItem("New Sub-folder..."); add(newFolder); delFolder = new JMenuItem("Delete Folder"); add(delFolder); newFolder.addActionListener(new MenuFileNewSubFolder()); delFolder.addActionListener(new MenuEditDeleteFolder()); } } // EMAIL TABLE CONTEXT MENU (Right-Click) private class EmailTableContextMenu extends JPopupMenu { private static final long serialVersionUID = 1L; JMenuItem movEmail; JMenuItem delEmail; public EmailTableContextMenu() { movEmail = new JMenuItem("Move Email..."); add(movEmail); delEmail = new JMenuItem("Delete Email"); add(delEmail); movEmail.addActionListener(new MenuEditMoveEmail()); delEmail.addActionListener(new MenuEditDeleteEmail()); } } // FOLDER TREE MOUSE LISTENER private class FolderTreeMouseListener extends MouseAdapter { JTree tree; int selNode; public FolderTreeMouseListener(JTree foldersTree) { this.tree = foldersTree; } public void mousePressed(MouseEvent e) { selNode = tree.getRowForLocation(e.getX(), e.getY()); TreePath selPath = tree.getPathForLocation(e.getX(), e.getY()); if (selNode != -1) { tree.setSelectionPath(selPath); if (e.isPopupTrigger()) Popup(e); } } public void mouseReleased(MouseEvent e) { if (selNode != -1) { if (e.isPopupTrigger()) Popup(e); } } private void Popup(MouseEvent e) { FolderTreeContextMenu menu = new FolderTreeContextMenu(); menu.show(e.getComponent(), e.getX() + 7, e.getY()); } } // EMAIL TABLE MOUSE LISTENER private class EmailTableMouseListener extends MouseAdapter { int selRow; public void mousePressed(MouseEvent e) { selRow = emailTable.rowAtPoint(e.getPoint()); if (selRow != -1) { emailTable.setRowSelectionInterval(selRow, selRow); if (e.isPopupTrigger()) Popup(e); } } public void mouseClicked(MouseEvent e) { if ((e.getClickCount() == 2) && (selRow != -1)) { new EmailFrame(selectedEmailEntity); } } public void mouseReleased(MouseEvent e) { if (selRow != -1) { if (e.isPopupTrigger()) Popup(e); } } private void Popup(MouseEvent e) { EmailTableContextMenu menu = new EmailTableContextMenu(); menu.show(e.getComponent(), e.getX() + 7, e.getY()); } } private class MenuFileNewEmail implements ActionListener { public void actionPerformed(ActionEvent e) { new EmailFrame(); } } // FILE -> NEW EMAIL FROM TEMPLATE private class MenuFileNewEmailFromTemplate implements ActionListener { public void actionPerformed(ActionEvent e) { new EmailFrame(TemplateContext.APPLY); } } private class MenuFileNewMeeting implements ActionListener{ public void actionPerformed(ActionEvent e) { new MeetingFrame(); } } private class MenuFileNewTemplate implements ActionListener { public void actionPerformed(ActionEvent e) { new EmailFrame(TemplateContext.NEW); } } private class MenuFileExit implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } private void updateEmailTableFound(String toFind) { String[] emailTableViewColumns = { "From", "Subject", "Date" }; Iterable<EmailViewEntity> emailsFoundInFolder=folderService.searchEmails(toFind); emailTable.setModel(new EmailListViewData(emailTableViewColumns, emailsFoundInFolder)); defineEmailTableLayout(); } public Object getSelectedTemplateFromDialog() { String[] selValues = templateService.getTemplateNames(); int messageType = JOptionPane.QUESTION_MESSAGE; Object mov = JOptionPane.showInputDialog(null, "Select the template", "Choose Template", messageType, null, selValues, null); return mov; } private void search() { String toFind = searchField.getText(); if(toFind.trim().length()>0) updateEmailTableFound(toFind); } private class BarSearchEmails implements ActionListener { public void actionPerformed(ActionEvent e) { search(); } } private class KeySearchEmails implements KeyListener { public void keyPressed(KeyEvent e) { if ( e.getKeyCode() == KeyEvent.VK_ENTER ){ search(); } } public void keyReleased(KeyEvent e) {} public void keyTyped(KeyEvent e) {} } }
Meeting hotKey to M
CECProject/src/cec/view/EmailClient.java
Meeting hotKey to M
Java
epl-1.0
1f4cc222a9d43fa51361ef7cedfbf89b0c76d558
0
rrimmana/birt-1,Charling-Huang/birt,sguan-actuate/birt,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1,Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,Charling-Huang/birt,Charling-Huang/birt
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.chart.reportitem; import java.net.URL; import java.util.logging.Level; import org.eclipse.birt.chart.log.ILogger; import org.eclipse.birt.chart.log.Logger; import org.eclipse.birt.chart.model.Chart; import org.eclipse.birt.chart.model.attribute.ColorDefinition; import org.eclipse.birt.chart.model.attribute.FontDefinition; import org.eclipse.birt.chart.model.attribute.HorizontalAlignment; import org.eclipse.birt.chart.model.attribute.StyledComponent; import org.eclipse.birt.chart.model.attribute.TextAlignment; import org.eclipse.birt.chart.model.attribute.VerticalAlignment; import org.eclipse.birt.chart.model.attribute.impl.ColorDefinitionImpl; import org.eclipse.birt.chart.model.attribute.impl.FontDefinitionImpl; import org.eclipse.birt.chart.model.attribute.impl.ImageImpl; import org.eclipse.birt.chart.model.attribute.impl.InsetsImpl; import org.eclipse.birt.chart.model.attribute.impl.TextAlignmentImpl; import org.eclipse.birt.chart.style.IStyle; import org.eclipse.birt.chart.style.IStyleProcessor; import org.eclipse.birt.chart.style.SimpleStyle; import org.eclipse.birt.report.engine.css.engine.StyleConstants; import org.eclipse.birt.report.engine.css.engine.value.FloatValue; import org.eclipse.birt.report.engine.css.engine.value.RGBColorValue; import org.eclipse.birt.report.engine.css.engine.value.StringValue; import org.eclipse.birt.report.engine.css.engine.value.css.CSSConstants; import org.eclipse.birt.report.model.api.ColorHandle; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.DimensionHandle; import org.eclipse.birt.report.model.api.GroupHandle; import org.eclipse.birt.report.model.api.ModuleHandle; import org.eclipse.birt.report.model.api.ReportItemHandle; import org.eclipse.birt.report.model.api.StyleHandle; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.birt.report.model.api.metadata.DimensionValue; import org.eclipse.birt.report.model.api.util.DimensionUtil; import org.w3c.dom.css.CSSPrimitiveValue; import org.w3c.dom.css.CSSValue; import org.w3c.dom.css.CSSValueList; /** * ChartReportStyleProcessor */ public class ChartReportStyleProcessor implements IStyleProcessor { private static final String[][] fontSizes = { { DesignChoiceConstants.FONT_SIZE_XX_SMALL, "7"}, //$NON-NLS-1$ { DesignChoiceConstants.FONT_SIZE_X_SMALL, "8"}, //$NON-NLS-1$ { DesignChoiceConstants.FONT_SIZE_SMALL, "9"}, //$NON-NLS-1$ { DesignChoiceConstants.FONT_SIZE_MEDIUM, "10"}, //$NON-NLS-1$ { DesignChoiceConstants.FONT_SIZE_LARGE, "11"}, //$NON-NLS-1$ { DesignChoiceConstants.FONT_SIZE_X_LARGE, "12"}, //$NON-NLS-1$ { DesignChoiceConstants.FONT_SIZE_XX_LARGE, "13"}, //$NON-NLS-1$ }; private DesignElementHandle handle; private boolean useCache; private org.eclipse.birt.report.engine.content.IStyle dstyle; private SimpleStyle cache = null; private static ILogger logger = Logger.getLogger( "org.eclipse.birt.chart.reportitem/trace" ); //$NON-NLS-1$ /** * The constructor. Default not using cache. * * @param handle */ public ChartReportStyleProcessor( DesignElementHandle handle ) { this( handle, false, null ); } /** * The constructor. * * @param handle * @param style */ public ChartReportStyleProcessor( DesignElementHandle handle, org.eclipse.birt.report.engine.content.IStyle style ) { this( handle, false, style ); } /** * The constructor. * * @param handle * @param useCache * specify if use cache. */ public ChartReportStyleProcessor( DesignElementHandle handle, boolean useCache ) { this( handle, useCache, null ); } /** * The constructor. Default not using cache. * * @param handle * @param useCache * specify if use cache. * @param style */ public ChartReportStyleProcessor( DesignElementHandle handle, boolean useCache, org.eclipse.birt.report.engine.content.IStyle dstyle ) { this.handle = handle; this.useCache = useCache; this.dstyle = dstyle; } /* * (non-Javadoc) * * @see org.eclipse.birt.chart.style.IStyleProcessor#getStyle(org.eclipse.birt.chart.model.attribute.StyledComponent) */ public IStyle getStyle( Chart model, StyledComponent name ) { SimpleStyle ss = null; if ( cache == null || !useCache ) { StyleHandle style = handle.getPrivateStyle( ); ss = new SimpleStyle( ); String fname = style.getFontFamilyHandle( ).getStringValue( ); int fsize = getFontSizeIntValue( handle ); boolean fbold = getFontWeight( style.getFontWeight( ) ) >= 700; boolean fitalic = DesignChoiceConstants.FONT_STYLE_ITALIC.equals( style.getFontStyle( ) ); boolean funder = DesignChoiceConstants.TEXT_UNDERLINE_UNDERLINE.equals( style.getTextUnderline( ) ); boolean fstrike = DesignChoiceConstants.TEXT_LINE_THROUGH_LINE_THROUGH.equals( style.getTextLineThrough( ) ); if ( dstyle != null ) { CSSValueList valueList = (CSSValueList)dstyle.getProperty( StyleConstants.STYLE_FONT_FAMILY ); if ( valueList.getLength( ) > 0 ) { fname = valueList.item( 0 ).getCssText( ); } fsize = getSize( dstyle.getProperty( StyleConstants.STYLE_FONT_SIZE )); fbold = isBoldFont( dstyle.getProperty( StyleConstants.STYLE_FONT_WEIGHT)); fitalic = isItalicFont( dstyle.getFontStyle( ) ); funder = CSSConstants.CSS_UNDERLINE_VALUE.equals( dstyle.getTextUnderline( ) ); fstrike = CSSConstants.CSS_LINE_THROUGH_VALUE.equals( dstyle.getTextLineThrough( ) ); } HorizontalAlignment ha = HorizontalAlignment.LEFT_LITERAL; if ( DesignChoiceConstants.TEXT_ALIGN_CENTER.equals( style.getTextAlign( ) ) ) { ha = HorizontalAlignment.CENTER_LITERAL; } else if ( DesignChoiceConstants.TEXT_ALIGN_RIGHT.equals( style.getTextAlign( ) ) ) { ha = HorizontalAlignment.RIGHT_LITERAL; } VerticalAlignment va = VerticalAlignment.TOP_LITERAL; if ( DesignChoiceConstants.VERTICAL_ALIGN_MIDDLE.equals( style.getVerticalAlign( ) ) ) { va = VerticalAlignment.CENTER_LITERAL; } else if ( DesignChoiceConstants.VERTICAL_ALIGN_BOTTOM.equals( style.getVerticalAlign( ) ) ) { va = VerticalAlignment.BOTTOM_LITERAL; } TextAlignment ta = TextAlignmentImpl.create( ); ta.setHorizontalAlignment( ha ); ta.setVerticalAlignment( va ); FontDefinition fd = FontDefinitionImpl.create( fname, fsize, fbold, fitalic, funder, fstrike, true, 0, ta ); ss.setFont( fd ); ColorHandle ch = style.getColor( ); if ( dstyle != null ) { ss.setColor( getColor( dstyle.getProperty( StyleConstants.STYLE_COLOR ) ) ); } else if ( ch != null && ch.getRGB( ) != -1 ) { int rgbValue = ch.getRGB( ); ColorDefinition cd = ColorDefinitionImpl.create( ( rgbValue >> 16 ) & 0xff, ( rgbValue >> 8 ) & 0xff, rgbValue & 0xff ); ss.setColor( cd ); } else { ss.setColor( ColorDefinitionImpl.BLACK( ) ); } ch = style.getBackgroundColor( ); if ( dstyle != null ) { ss.setBackgroundColor( getColor( dstyle.getProperty( StyleConstants.STYLE_BACKGROUND_COLOR ) ) ); } else if ( ch != null && ch.getRGB( ) != -1 ) { int rgbValue = ch.getRGB( ); ColorDefinition cd = ColorDefinitionImpl.create( ( rgbValue >> 16 ) & 0xff, ( rgbValue >> 8 ) & 0xff, rgbValue & 0xff ); ss.setBackgroundColor( cd ); } if ( style.getBackgroundImage( ) != null && style.getBackgroundImage( ).length( ) > 0 ) { String urlString = style.getBackgroundImage( ); try { new URL( urlString ); ss.setBackgroundImage( ImageImpl.create( urlString ) ); } catch ( Exception _ ) { // try with "file" prefix urlString = "file:///" + urlString; //$NON-NLS-1$ try { new URL( urlString ); ss.setBackgroundImage( ImageImpl.create( urlString ) ); } catch ( Exception __ ) { logger.log( _ ); } } } double pt = convertToPixel( style.getPaddingTop( ) ); double pb = convertToPixel( style.getPaddingBottom( ) ); double pl = convertToPixel( style.getPaddingLeft( ) ); double pr = convertToPixel( style.getPaddingRight( ) ); ss.setPadding( InsetsImpl.create( pt, pl, pb, pr ) ); if ( useCache ) { cache = ss; } } if ( useCache ) { ss = cache.copy( ); } return ss; } /** * Gets the int value of a String described font weight. * * @param fontWeight * The String deccribed font weight.s */ private static int getFontWeight( String fontWeight ) { int weight = 400; if ( fontWeight.equals( DesignChoiceConstants.FONT_WEIGHT_100 ) ) { weight = 100; } else if ( fontWeight.equals( DesignChoiceConstants.FONT_WEIGHT_200 ) ) { weight = 200; } else if ( fontWeight.equals( DesignChoiceConstants.FONT_WEIGHT_300 ) ) { weight = 300; } else if ( fontWeight.equals( DesignChoiceConstants.FONT_WEIGHT_400 ) ) { weight = 400; } else if ( fontWeight.equals( DesignChoiceConstants.FONT_WEIGHT_500 ) ) { weight = 500; } else if ( fontWeight.equals( DesignChoiceConstants.FONT_WEIGHT_600 ) ) { weight = 600; } else if ( fontWeight.equals( DesignChoiceConstants.FONT_WEIGHT_700 ) ) { weight = 700; } else if ( fontWeight.equals( DesignChoiceConstants.FONT_WEIGHT_800 ) ) { weight = 800; } else if ( fontWeight.equals( DesignChoiceConstants.FONT_WEIGHT_900 ) ) { weight = 900; } else if ( fontWeight.equals( DesignChoiceConstants.FONT_WEIGHT_NORMAL ) ) { weight = 400; } else if ( fontWeight.equals( DesignChoiceConstants.FONT_WEIGHT_BOLD ) ) { weight = 700; } return weight; } /** * Get the handle's font size int value. if the font size is relative, * calculate the actual size according to its parent. * * @param handle * The style handle to work with the style properties of this * element. * @return The font size int value */ private static int getFontSizeIntValue( DesignElementHandle handle ) { if ( handle == null ) { // defulat Medium size. return 10; } if ( !( handle instanceof ReportItemHandle ) ) { if ( handle instanceof ModuleHandle ) { // defulat Medium size. return 10; } if ( handle instanceof GroupHandle ) { handle = handle.getContainer( ); } } Object fontSizeValue = handle.getPrivateStyle( ) .getFontSize( ) .getValue( ); if ( fontSizeValue instanceof DimensionValue ) { // use parent's font size as the base size for converting sizeValue // to a int value. int size = getFontSizeIntValue( handle.getContainer( ) ); return (int) convertToPoint( fontSizeValue, size ); } else if ( fontSizeValue instanceof String ) { String fontSize = (String) fontSizeValue; if ( fontSize.equals( DesignChoiceConstants.FONT_SIZE_LARGER ) ) { return getLargerFontSizeIntValue( handle.getContainer( ) ); } else if ( fontSize.equals( DesignChoiceConstants.FONT_SIZE_SMALLER ) ) { return getSmallerFontSizeIntValue( handle.getContainer( ) ); } else { for ( int i = 0; i < fontSizes.length; i++ ) { if ( fontSizes[i][0].equals( fontSize ) ) { return Integer.parseInt( fontSizes[i][1] ); } } } } // return Medium default. return 10; } private static int getLargerFontSizeIntValue( DesignElementHandle handle ) { if ( handle == null ) { // defulat Medium size + 1. return 10 + 1; } if ( !( handle instanceof ReportItemHandle ) ) { if ( handle instanceof ModuleHandle ) { // return Medium default + 1. return 10 + 1; } if ( handle instanceof GroupHandle ) { handle = handle.getContainer( ); } } Object fontSizeValue = handle.getPrivateStyle( ) .getFontSize( ) .getValue( ); if ( fontSizeValue instanceof DimensionValue ) { int size = getFontSizeIntValue( handle.getContainer( ) ); return (int) convertToPoint( fontSizeValue, size ) + 1; } else if ( fontSizeValue instanceof String ) { String fontSize = (String) fontSizeValue; if ( fontSize.equals( DesignChoiceConstants.FONT_SIZE_LARGER ) ) { return getLargerFontSizeIntValue( handle.getContainer( ) ); } else if ( fontSize.equals( DesignChoiceConstants.FONT_SIZE_SMALLER ) ) { return getSmallerFontSizeIntValue( handle.getContainer( ) ); } else { for ( int i = 0; i < fontSizes.length - 1; i++ ) { if ( fontSize.equals( fontSizes[i][0] ) ) { return Integer.parseInt( fontSizes[i + 1][1] ); } } return Integer.parseInt( fontSizes[fontSizes.length - 1][1] ); } } else { // return Medium default + 1. return 10 + 1; } } private static int getSmallerFontSizeIntValue( DesignElementHandle handle ) { if ( handle == null ) { // defulat Medium size - 1. return 10 - 1; } if ( !( handle instanceof ReportItemHandle ) ) { if ( handle instanceof ModuleHandle ) { // return Medium default - 1. return 10 - 1; } if ( handle instanceof GroupHandle ) { handle = handle.getContainer( ); } } Object fontSizeValue = handle.getPrivateStyle( ) .getFontSize( ) .getValue( ); if ( fontSizeValue instanceof DimensionValue ) { int gParentFontSize = getFontSizeIntValue( handle.getContainer( ) ); int size = (int) convertToPoint( fontSizeValue, gParentFontSize ) - 1; if ( size < 1 ) { return 1; } else { return size; } } else if ( fontSizeValue instanceof String ) { String fontSize = (String) fontSizeValue; if ( fontSize.equals( DesignChoiceConstants.FONT_SIZE_LARGER ) ) { return getLargerFontSizeIntValue( handle.getContainer( ) ); } else if ( fontSize.equals( DesignChoiceConstants.FONT_SIZE_SMALLER ) ) { return getSmallerFontSizeIntValue( handle.getContainer( ) ); } else { for ( int i = fontSizes.length - 1; i > 0; i-- ) { if ( fontSize.equals( fontSizes[i][0] ) ) { return Integer.parseInt( fontSizes[i - 1][1] ); } } return Integer.parseInt( fontSizes[0][1] ); } } else { // return Medium default - 1. return 10 - 1; } } /** * Converts object 's units to pixel. * * @param object * @return The pixel value. */ private static double convertToPoint( Object object, int baseSize ) { return convertToInch( object, baseSize ) * 72; } /** * Converts object 's units to pixel. * * @param object * @return The pixel value. */ private static double convertToPixel( Object object ) { return convertToInch( object, 0 ) * 72; } /** * Converts object 's units to inch, with baseSize to compute the relative * unit. * * @param object * The origine object, may be DimensionValue or DimensionHandle. * @param baseSize * The given baseSize used to compute relative unit. * @return The inch value. */ private static double convertToInch( Object object, int baseSize ) { double inchValue = 0; double measure = 0; String units = ""; //$NON-NLS-1$ if ( object instanceof DimensionValue ) { DimensionValue dimension = (DimensionValue) object; measure = dimension.getMeasure( ); units = dimension.getUnits( ); } else if ( object instanceof DimensionHandle ) { DimensionHandle dimension = (DimensionHandle) object; measure = dimension.getMeasure( ); units = dimension.getUnits( ); } else { // assert false; } if ( "".equalsIgnoreCase( units ) )//$NON-NLS-1$ { units = DesignChoiceConstants.UNITS_IN; } if ( DesignChoiceConstants.UNITS_IN.equals( units ) ) { return measure; } // sets default baseSize to JFace Resources 's default font data 's // height. if ( baseSize == 0 ) { baseSize = 10; } // converts relative units to inch. if ( DesignChoiceConstants.UNITS_EM.equals( units ) ) { inchValue = DimensionUtil.convertTo( measure * baseSize, DesignChoiceConstants.UNITS_PT, DesignChoiceConstants.UNITS_IN ).getMeasure( ); } else if ( DesignChoiceConstants.UNITS_EX.equals( units ) ) { inchValue = DimensionUtil.convertTo( measure * baseSize / 3, DesignChoiceConstants.UNITS_PT, DesignChoiceConstants.UNITS_IN ).getMeasure( ); } else if ( DesignChoiceConstants.UNITS_PERCENTAGE.equals( units ) ) { inchValue = DimensionUtil.convertTo( measure * baseSize / 100, DesignChoiceConstants.UNITS_PT, DesignChoiceConstants.UNITS_IN ).getMeasure( ); } else if ( DesignChoiceConstants.UNITS_PX.equals( units ) ) { inchValue = measure / 72d; } else { // converts absolute units to inch. inchValue = DimensionUtil.convertTo( measure, units, DesignChoiceConstants.UNITS_IN ).getMeasure( ); } return inchValue; } private ColorDefinition getColor( CSSValue value ) { if ( value != null && value instanceof RGBColorValue ) { RGBColorValue color = (RGBColorValue) value; try { return ColorDefinitionImpl.create( Math.round( color.getRed( ) .getFloatValue( CSSPrimitiveValue.CSS_NUMBER ) ), Math.round( color.getGreen( ) .getFloatValue( CSSPrimitiveValue.CSS_NUMBER ) ), Math.round( color.getBlue( ) .getFloatValue( CSSPrimitiveValue.CSS_NUMBER ) ) ); } catch ( RuntimeException ex ) { logger.log( Level.WARNING.intValue( ), "invalid color: {0}" + value.toString( ) ); //$NON-NLS-1$ } } return null; } private int getSize( CSSValue value ) { if ( value != null && ( value instanceof FloatValue ) ) { return (int) ( ( (FloatValue) value ).getFloatValue( ) / 1000 ); } return 0; } private boolean isBoldFont(CSSValue value) { if(value instanceof StringValue && value!=null) { String weight = ((StringValue)value).getStringValue(); if("bold".equals(weight.toLowerCase()) || "bolder".equals(weight.toLowerCase()) //$NON-NLS-1$ //$NON-NLS-2$ || "600".equals(weight) || "700".equals(weight) //$NON-NLS-1$//$NON-NLS-2$ || "800".equals(weight) || "900".equals(weight)) //$NON-NLS-1$//$NON-NLS-2$ { return true; } } return false; } private boolean isItalicFont( String italic ) { if (CSSConstants.CSS_OBLIQUE_VALUE.equals( italic ) || CSSConstants.CSS_ITALIC_VALUE.equals(italic)) { return true; } return false; } }
chart/org.eclipse.birt.chart.reportitem/src/org/eclipse/birt/chart/reportitem/ChartReportStyleProcessor.java
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.chart.reportitem; import java.net.URL; import java.util.logging.Level; import org.eclipse.birt.chart.log.ILogger; import org.eclipse.birt.chart.log.Logger; import org.eclipse.birt.chart.model.Chart; import org.eclipse.birt.chart.model.attribute.ColorDefinition; import org.eclipse.birt.chart.model.attribute.FontDefinition; import org.eclipse.birt.chart.model.attribute.HorizontalAlignment; import org.eclipse.birt.chart.model.attribute.StyledComponent; import org.eclipse.birt.chart.model.attribute.TextAlignment; import org.eclipse.birt.chart.model.attribute.VerticalAlignment; import org.eclipse.birt.chart.model.attribute.impl.ColorDefinitionImpl; import org.eclipse.birt.chart.model.attribute.impl.FontDefinitionImpl; import org.eclipse.birt.chart.model.attribute.impl.ImageImpl; import org.eclipse.birt.chart.model.attribute.impl.InsetsImpl; import org.eclipse.birt.chart.model.attribute.impl.TextAlignmentImpl; import org.eclipse.birt.chart.style.IStyle; import org.eclipse.birt.chart.style.IStyleProcessor; import org.eclipse.birt.chart.style.SimpleStyle; import org.eclipse.birt.report.engine.css.engine.StyleConstants; import org.eclipse.birt.report.engine.css.engine.value.FloatValue; import org.eclipse.birt.report.engine.css.engine.value.RGBColorValue; import org.eclipse.birt.report.engine.css.engine.value.StringValue; import org.eclipse.birt.report.engine.css.engine.value.css.CSSConstants; import org.eclipse.birt.report.model.api.ColorHandle; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.DimensionHandle; import org.eclipse.birt.report.model.api.GroupHandle; import org.eclipse.birt.report.model.api.ModuleHandle; import org.eclipse.birt.report.model.api.ReportItemHandle; import org.eclipse.birt.report.model.api.StyleHandle; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.birt.report.model.api.metadata.DimensionValue; import org.eclipse.birt.report.model.api.util.DimensionUtil; import org.w3c.dom.css.CSSPrimitiveValue; import org.w3c.dom.css.CSSValue; import org.w3c.dom.css.CSSValueList; /** * ChartReportStyleProcessor */ public class ChartReportStyleProcessor implements IStyleProcessor { private static final String[][] fontSizes = { { DesignChoiceConstants.FONT_SIZE_XX_SMALL, "7"}, //$NON-NLS-1$ { DesignChoiceConstants.FONT_SIZE_X_SMALL, "8"}, //$NON-NLS-1$ { DesignChoiceConstants.FONT_SIZE_SMALL, "9"}, //$NON-NLS-1$ { DesignChoiceConstants.FONT_SIZE_MEDIUM, "10"}, //$NON-NLS-1$ { DesignChoiceConstants.FONT_SIZE_LARGE, "11"}, //$NON-NLS-1$ { DesignChoiceConstants.FONT_SIZE_X_LARGE, "12"}, //$NON-NLS-1$ { DesignChoiceConstants.FONT_SIZE_XX_LARGE, "13"}, //$NON-NLS-1$ }; private DesignElementHandle handle; private boolean useCache; private org.eclipse.birt.report.engine.content.IStyle dstyle; private SimpleStyle cache = null; private static ILogger logger = Logger.getLogger( "org.eclipse.birt.chart.reportitem/trace" ); //$NON-NLS-1$ /** * The constructor. Default not using cache. * * @param handle */ public ChartReportStyleProcessor( DesignElementHandle handle ) { this( handle, false, null ); } /** * The constructor. * * @param handle * @param style */ public ChartReportStyleProcessor( DesignElementHandle handle, org.eclipse.birt.report.engine.content.IStyle style ) { this( handle, false, style ); } /** * The constructor. * * @param handle * @param useCache * specify if use cache. */ public ChartReportStyleProcessor( DesignElementHandle handle, boolean useCache ) { this( handle, useCache, null ); } /** * The constructor. Default not using cache. * * @param handle * @param useCache * specify if use cache. * @param style */ public ChartReportStyleProcessor( DesignElementHandle handle, boolean useCache, org.eclipse.birt.report.engine.content.IStyle dstyle ) { this.handle = handle; this.useCache = useCache; this.dstyle = dstyle; } /* * (non-Javadoc) * * @see org.eclipse.birt.chart.style.IStyleProcessor#getStyle(org.eclipse.birt.chart.model.attribute.StyledComponent) */ public IStyle getStyle( Chart model, StyledComponent name ) { SimpleStyle ss = null; if ( cache == null || !useCache ) { StyleHandle style = handle.getPrivateStyle( ); ss = new SimpleStyle( ); String fname = style.getFontFamilyHandle( ).getStringValue( ); int fsize = getFontSizeIntValue( handle ); boolean fbold = getFontWeight( style.getFontWeight( ) ) >= 700; boolean fitalic = DesignChoiceConstants.FONT_STYLE_ITALIC.equals( style.getFontStyle( ) ); boolean funder = DesignChoiceConstants.TEXT_UNDERLINE_UNDERLINE.equals( style.getTextUnderline( ) ); boolean fstrike = DesignChoiceConstants.TEXT_LINE_THROUGH_LINE_THROUGH.equals( style.getTextLineThrough( ) ); if ( dstyle != null ) { fname = dstyle.getFontFamily( ); fsize = getSize( dstyle.getProperty( StyleConstants.STYLE_FONT_SIZE )); fbold = isBoldFont( dstyle.getProperty( StyleConstants.STYLE_FONT_WEIGHT)); fitalic = isItalicFont( dstyle.getFontStyle( ) ); funder = CSSConstants.CSS_UNDERLINE_VALUE.equals( dstyle.getTextUnderline( ) ); fstrike = CSSConstants.CSS_LINE_THROUGH_VALUE.equals( dstyle.getTextLineThrough( ) ); } HorizontalAlignment ha = HorizontalAlignment.LEFT_LITERAL; if ( DesignChoiceConstants.TEXT_ALIGN_CENTER.equals( style.getTextAlign( ) ) ) { ha = HorizontalAlignment.CENTER_LITERAL; } else if ( DesignChoiceConstants.TEXT_ALIGN_RIGHT.equals( style.getTextAlign( ) ) ) { ha = HorizontalAlignment.RIGHT_LITERAL; } VerticalAlignment va = VerticalAlignment.TOP_LITERAL; if ( DesignChoiceConstants.VERTICAL_ALIGN_MIDDLE.equals( style.getVerticalAlign( ) ) ) { va = VerticalAlignment.CENTER_LITERAL; } else if ( DesignChoiceConstants.VERTICAL_ALIGN_BOTTOM.equals( style.getVerticalAlign( ) ) ) { va = VerticalAlignment.BOTTOM_LITERAL; } TextAlignment ta = TextAlignmentImpl.create( ); ta.setHorizontalAlignment( ha ); ta.setVerticalAlignment( va ); FontDefinition fd = FontDefinitionImpl.create( fname, fsize, fbold, fitalic, funder, fstrike, true, 0, ta ); ss.setFont( fd ); ColorHandle ch = style.getColor( ); if ( dstyle != null ) { ss.setColor( getColor( dstyle.getProperty( StyleConstants.STYLE_COLOR ) ) ); } else if ( ch != null && ch.getRGB( ) != -1 ) { int rgbValue = ch.getRGB( ); ColorDefinition cd = ColorDefinitionImpl.create( ( rgbValue >> 16 ) & 0xff, ( rgbValue >> 8 ) & 0xff, rgbValue & 0xff ); ss.setColor( cd ); } else { ss.setColor( ColorDefinitionImpl.BLACK( ) ); } ch = style.getBackgroundColor( ); if ( dstyle != null ) { ss.setBackgroundColor( getColor( dstyle.getProperty( StyleConstants.STYLE_BACKGROUND_COLOR ) ) ); } else if ( ch != null && ch.getRGB( ) != -1 ) { int rgbValue = ch.getRGB( ); ColorDefinition cd = ColorDefinitionImpl.create( ( rgbValue >> 16 ) & 0xff, ( rgbValue >> 8 ) & 0xff, rgbValue & 0xff ); ss.setBackgroundColor( cd ); } if ( style.getBackgroundImage( ) != null && style.getBackgroundImage( ).length( ) > 0 ) { String urlString = style.getBackgroundImage( ); try { new URL( urlString ); ss.setBackgroundImage( ImageImpl.create( urlString ) ); } catch ( Exception _ ) { // try with "file" prefix urlString = "file:///" + urlString; //$NON-NLS-1$ try { new URL( urlString ); ss.setBackgroundImage( ImageImpl.create( urlString ) ); } catch ( Exception __ ) { logger.log( _ ); } } } double pt = convertToPixel( style.getPaddingTop( ) ); double pb = convertToPixel( style.getPaddingBottom( ) ); double pl = convertToPixel( style.getPaddingLeft( ) ); double pr = convertToPixel( style.getPaddingRight( ) ); ss.setPadding( InsetsImpl.create( pt, pl, pb, pr ) ); if ( useCache ) { cache = ss; } } if ( useCache ) { ss = cache.copy( ); } return ss; } /** * Gets the int value of a String described font weight. * * @param fontWeight * The String deccribed font weight.s */ private static int getFontWeight( String fontWeight ) { int weight = 400; if ( fontWeight.equals( DesignChoiceConstants.FONT_WEIGHT_100 ) ) { weight = 100; } else if ( fontWeight.equals( DesignChoiceConstants.FONT_WEIGHT_200 ) ) { weight = 200; } else if ( fontWeight.equals( DesignChoiceConstants.FONT_WEIGHT_300 ) ) { weight = 300; } else if ( fontWeight.equals( DesignChoiceConstants.FONT_WEIGHT_400 ) ) { weight = 400; } else if ( fontWeight.equals( DesignChoiceConstants.FONT_WEIGHT_500 ) ) { weight = 500; } else if ( fontWeight.equals( DesignChoiceConstants.FONT_WEIGHT_600 ) ) { weight = 600; } else if ( fontWeight.equals( DesignChoiceConstants.FONT_WEIGHT_700 ) ) { weight = 700; } else if ( fontWeight.equals( DesignChoiceConstants.FONT_WEIGHT_800 ) ) { weight = 800; } else if ( fontWeight.equals( DesignChoiceConstants.FONT_WEIGHT_900 ) ) { weight = 900; } else if ( fontWeight.equals( DesignChoiceConstants.FONT_WEIGHT_NORMAL ) ) { weight = 400; } else if ( fontWeight.equals( DesignChoiceConstants.FONT_WEIGHT_BOLD ) ) { weight = 700; } return weight; } /** * Get the handle's font size int value. if the font size is relative, * calculate the actual size according to its parent. * * @param handle * The style handle to work with the style properties of this * element. * @return The font size int value */ private static int getFontSizeIntValue( DesignElementHandle handle ) { if ( handle == null ) { // defulat Medium size. return 10; } if ( !( handle instanceof ReportItemHandle ) ) { if ( handle instanceof ModuleHandle ) { // defulat Medium size. return 10; } if ( handle instanceof GroupHandle ) { handle = handle.getContainer( ); } } Object fontSizeValue = handle.getPrivateStyle( ) .getFontSize( ) .getValue( ); if ( fontSizeValue instanceof DimensionValue ) { // use parent's font size as the base size for converting sizeValue // to a int value. int size = getFontSizeIntValue( handle.getContainer( ) ); return (int) convertToPoint( fontSizeValue, size ); } else if ( fontSizeValue instanceof String ) { String fontSize = (String) fontSizeValue; if ( fontSize.equals( DesignChoiceConstants.FONT_SIZE_LARGER ) ) { return getLargerFontSizeIntValue( handle.getContainer( ) ); } else if ( fontSize.equals( DesignChoiceConstants.FONT_SIZE_SMALLER ) ) { return getSmallerFontSizeIntValue( handle.getContainer( ) ); } else { for ( int i = 0; i < fontSizes.length; i++ ) { if ( fontSizes[i][0].equals( fontSize ) ) { return Integer.parseInt( fontSizes[i][1] ); } } } } // return Medium default. return 10; } private static int getLargerFontSizeIntValue( DesignElementHandle handle ) { if ( handle == null ) { // defulat Medium size + 1. return 10 + 1; } if ( !( handle instanceof ReportItemHandle ) ) { if ( handle instanceof ModuleHandle ) { // return Medium default + 1. return 10 + 1; } if ( handle instanceof GroupHandle ) { handle = handle.getContainer( ); } } Object fontSizeValue = handle.getPrivateStyle( ) .getFontSize( ) .getValue( ); if ( fontSizeValue instanceof DimensionValue ) { int size = getFontSizeIntValue( handle.getContainer( ) ); return (int) convertToPoint( fontSizeValue, size ) + 1; } else if ( fontSizeValue instanceof String ) { String fontSize = (String) fontSizeValue; if ( fontSize.equals( DesignChoiceConstants.FONT_SIZE_LARGER ) ) { return getLargerFontSizeIntValue( handle.getContainer( ) ); } else if ( fontSize.equals( DesignChoiceConstants.FONT_SIZE_SMALLER ) ) { return getSmallerFontSizeIntValue( handle.getContainer( ) ); } else { for ( int i = 0; i < fontSizes.length - 1; i++ ) { if ( fontSize.equals( fontSizes[i][0] ) ) { return Integer.parseInt( fontSizes[i + 1][1] ); } } return Integer.parseInt( fontSizes[fontSizes.length - 1][1] ); } } else { // return Medium default + 1. return 10 + 1; } } private static int getSmallerFontSizeIntValue( DesignElementHandle handle ) { if ( handle == null ) { // defulat Medium size - 1. return 10 - 1; } if ( !( handle instanceof ReportItemHandle ) ) { if ( handle instanceof ModuleHandle ) { // return Medium default - 1. return 10 - 1; } if ( handle instanceof GroupHandle ) { handle = handle.getContainer( ); } } Object fontSizeValue = handle.getPrivateStyle( ) .getFontSize( ) .getValue( ); if ( fontSizeValue instanceof DimensionValue ) { int gParentFontSize = getFontSizeIntValue( handle.getContainer( ) ); int size = (int) convertToPoint( fontSizeValue, gParentFontSize ) - 1; if ( size < 1 ) { return 1; } else { return size; } } else if ( fontSizeValue instanceof String ) { String fontSize = (String) fontSizeValue; if ( fontSize.equals( DesignChoiceConstants.FONT_SIZE_LARGER ) ) { return getLargerFontSizeIntValue( handle.getContainer( ) ); } else if ( fontSize.equals( DesignChoiceConstants.FONT_SIZE_SMALLER ) ) { return getSmallerFontSizeIntValue( handle.getContainer( ) ); } else { for ( int i = fontSizes.length - 1; i > 0; i-- ) { if ( fontSize.equals( fontSizes[i][0] ) ) { return Integer.parseInt( fontSizes[i - 1][1] ); } } return Integer.parseInt( fontSizes[0][1] ); } } else { // return Medium default - 1. return 10 - 1; } } /** * Converts object 's units to pixel. * * @param object * @return The pixel value. */ private static double convertToPoint( Object object, int baseSize ) { return convertToInch( object, baseSize ) * 72; } /** * Converts object 's units to pixel. * * @param object * @return The pixel value. */ private static double convertToPixel( Object object ) { return convertToInch( object, 0 ) * 72; } /** * Converts object 's units to inch, with baseSize to compute the relative * unit. * * @param object * The origine object, may be DimensionValue or DimensionHandle. * @param baseSize * The given baseSize used to compute relative unit. * @return The inch value. */ private static double convertToInch( Object object, int baseSize ) { double inchValue = 0; double measure = 0; String units = ""; //$NON-NLS-1$ if ( object instanceof DimensionValue ) { DimensionValue dimension = (DimensionValue) object; measure = dimension.getMeasure( ); units = dimension.getUnits( ); } else if ( object instanceof DimensionHandle ) { DimensionHandle dimension = (DimensionHandle) object; measure = dimension.getMeasure( ); units = dimension.getUnits( ); } else { // assert false; } if ( "".equalsIgnoreCase( units ) )//$NON-NLS-1$ { units = DesignChoiceConstants.UNITS_IN; } if ( DesignChoiceConstants.UNITS_IN.equals( units ) ) { return measure; } // sets default baseSize to JFace Resources 's default font data 's // height. if ( baseSize == 0 ) { baseSize = 10; } // converts relative units to inch. if ( DesignChoiceConstants.UNITS_EM.equals( units ) ) { inchValue = DimensionUtil.convertTo( measure * baseSize, DesignChoiceConstants.UNITS_PT, DesignChoiceConstants.UNITS_IN ).getMeasure( ); } else if ( DesignChoiceConstants.UNITS_EX.equals( units ) ) { inchValue = DimensionUtil.convertTo( measure * baseSize / 3, DesignChoiceConstants.UNITS_PT, DesignChoiceConstants.UNITS_IN ).getMeasure( ); } else if ( DesignChoiceConstants.UNITS_PERCENTAGE.equals( units ) ) { inchValue = DimensionUtil.convertTo( measure * baseSize / 100, DesignChoiceConstants.UNITS_PT, DesignChoiceConstants.UNITS_IN ).getMeasure( ); } else if ( DesignChoiceConstants.UNITS_PX.equals( units ) ) { inchValue = measure / 72d; } else { // converts absolute units to inch. inchValue = DimensionUtil.convertTo( measure, units, DesignChoiceConstants.UNITS_IN ).getMeasure( ); } return inchValue; } private ColorDefinition getColor( CSSValue value ) { if ( value != null && value instanceof RGBColorValue ) { RGBColorValue color = (RGBColorValue) value; try { return ColorDefinitionImpl.create( Math.round( color.getRed( ) .getFloatValue( CSSPrimitiveValue.CSS_NUMBER ) ), Math.round( color.getGreen( ) .getFloatValue( CSSPrimitiveValue.CSS_NUMBER ) ), Math.round( color.getBlue( ) .getFloatValue( CSSPrimitiveValue.CSS_NUMBER ) ) ); } catch ( RuntimeException ex ) { logger.log( Level.WARNING.intValue( ), "invalid color: {0}" + value.toString( ) ); //$NON-NLS-1$ } } return null; } private int getSize( CSSValue value ) { if ( value != null && ( value instanceof FloatValue ) ) { return (int) ( ( (FloatValue) value ).getFloatValue( ) / 1000 ); } return 0; } private boolean isBoldFont(CSSValue value) { if(value instanceof StringValue && value!=null) { String weight = ((StringValue)value).getStringValue(); if("bold".equals(weight.toLowerCase()) || "bolder".equals(weight.toLowerCase()) //$NON-NLS-1$ //$NON-NLS-2$ || "600".equals(weight) || "700".equals(weight) //$NON-NLS-1$//$NON-NLS-2$ || "800".equals(weight) || "900".equals(weight)) //$NON-NLS-1$//$NON-NLS-2$ { return true; } } return false; } private boolean isItalicFont( String italic ) { if (CSSConstants.CSS_OBLIQUE_VALUE.equals( italic ) || CSSConstants.CSS_ITALIC_VALUE.equals(italic)) { return true; } return false; } }
- Summary: Highlight doesn't work in chart. - Bugzilla Bug (s) Resolved: 136035 - Description: Use CSSValueList instead of accessing the FontFamily directly. - Tests Description: Test Manually. - Files Edited: - Files Added: - Notes to Build Team: None - Notes to Developers: None - Notes to QA: None - Notes to Documentation: None
chart/org.eclipse.birt.chart.reportitem/src/org/eclipse/birt/chart/reportitem/ChartReportStyleProcessor.java
- Summary: Highlight doesn't work in chart.
Java
epl-1.0
91c5b9f68b83e5630a673caab47a0ae6fb1f1e7e
0
rohitmohan96/ceylon-ide-eclipse,rohitmohan96/ceylon-ide-eclipse
package com.redhat.ceylon.eclipse.code.outline; import static com.redhat.ceylon.compiler.typechecker.model.Util.getInterveningRefinements; import static com.redhat.ceylon.compiler.typechecker.model.Util.getSignature; import static com.redhat.ceylon.compiler.typechecker.model.Util.isAbstraction; import static com.redhat.ceylon.eclipse.code.outline.CeylonHierarchyNode.getDeclarationInUnit; import static com.redhat.ceylon.eclipse.code.outline.CeylonHierarchyNode.getTypeChecker; import static com.redhat.ceylon.eclipse.code.outline.HierarchyMode.HIERARCHY; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.Viewer; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPartSite; import com.redhat.ceylon.compiler.typechecker.TypeChecker; import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleManager; import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypeParameter; import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration; import com.redhat.ceylon.compiler.typechecker.model.Unit; import com.redhat.ceylon.compiler.typechecker.tree.Tree.CompilationUnit; import com.redhat.ceylon.eclipse.code.editor.CeylonEditor; public final class CeylonHierarchyContentProvider implements ITreeContentProvider { private final IWorkbenchPartSite site; private HierarchyMode mode = HIERARCHY; private CeylonHierarchyNode hierarchyRoot; private CeylonHierarchyNode supertypesRoot; private CeylonHierarchyNode subtypesRoot; private boolean showingRefinements; private boolean empty; private int depthInHierarchy; private boolean veryAbstractType; private String description; CeylonHierarchyContentProvider(IWorkbenchPartSite site) { this.site = site; } Declaration getDeclaration(IProject project) { return subtypesRoot.getDeclaration(project); } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { if (newInput!=null && newInput!=oldInput) { HierarchyInput rootNode = (HierarchyInput) newInput; Declaration declaration = rootNode.declaration; if (declaration instanceof TypedDeclaration) { TypedDeclaration td = (TypedDeclaration) declaration; if (td.getTypeDeclaration().isAnonymous()) { declaration = ((TypedDeclaration) declaration).getTypeDeclaration(); } } showingRefinements = !(declaration instanceof TypeDeclaration); empty = declaration==null; if (!empty) { String name = declaration.getQualifiedNameString(); veryAbstractType = name.equals("ceylon.language::Object") || name.equals("ceylon.language::Anything") || name.equals("ceylon.language::Basic") || name.equals("ceylon.language::Identifiable"); description = declaration.getName();//getDescriptionFor(declaration); if (isShowingRefinements() && declaration.isClassOrInterfaceMember()) { ClassOrInterface classOrInterface = (ClassOrInterface) declaration.getContainer(); description = classOrInterface.getName() + '.' + description; } try { site.getWorkbenchWindow().run(true, true, new Runnable(rootNode.project, declaration)); } catch (Exception e) { e.printStackTrace(); } rootNode.declaration=null;//don't hang onto hard ref } } } boolean isVeryAbstractType() { return veryAbstractType; } boolean isShowingRefinements() { return showingRefinements; } public boolean isEmpty() { return empty; } @Override public void dispose() {} @Override public boolean hasChildren(Object element) { return getChildren(element).length>0; } @Override public Object getParent(Object element) { return null; } @Override public Object[] getElements(Object inputElement) { return getChildren(inputElement); } @Override public CeylonHierarchyNode[] getChildren(Object parentElement) { if (parentElement instanceof HierarchyInput) { switch (mode) { case HIERARCHY: return new CeylonHierarchyNode[] { hierarchyRoot }; case SUPERTYPES: return new CeylonHierarchyNode[] { supertypesRoot }; case SUBTYPES: return new CeylonHierarchyNode[] { subtypesRoot }; default: throw new RuntimeException(); } } else if (parentElement instanceof CeylonHierarchyNode) { List<CeylonHierarchyNode> children = ((CeylonHierarchyNode) parentElement).getChildren(); CeylonHierarchyNode[] array = children.toArray(new CeylonHierarchyNode[children.size()]); Arrays.sort(array); return array; } else { return null; } } HierarchyMode getMode() { return mode; } void setMode(HierarchyMode mode) { this.mode = mode; } int getDepthInHierarchy() { return depthInHierarchy; } private class Runnable implements IRunnableWithProgress { private final IProject project; private final Declaration declaration; private final Map<Declaration, CeylonHierarchyNode> subtypesOfSupertypes = new HashMap<Declaration, CeylonHierarchyNode>(); private final Map<Declaration, CeylonHierarchyNode> subtypesOfAllTypes = new HashMap<Declaration, CeylonHierarchyNode>(); private final Map<Declaration, CeylonHierarchyNode> supertypesOfAllTypes = new HashMap<Declaration, CeylonHierarchyNode>(); private void add(Declaration td, Declaration etd) { getSubtypeHierarchyNode(etd).addChild(getSubtypeHierarchyNode(td)); getSupertypeHierarchyNode(td).addChild(getSupertypeHierarchyNode(etd)); } private CeylonHierarchyNode getSubtypePathNode(Declaration d) { CeylonHierarchyNode n = subtypesOfSupertypes.get(d); if (n==null) { n = new CeylonHierarchyNode(d); subtypesOfSupertypes.put(d, n); } return n; } private CeylonHierarchyNode getSubtypeHierarchyNode(Declaration d) { CeylonHierarchyNode n = subtypesOfAllTypes.get(d); if (n==null) { n = new CeylonHierarchyNode(d); subtypesOfAllTypes.put(d, n); } return n; } private CeylonHierarchyNode getSupertypeHierarchyNode(Declaration d) { CeylonHierarchyNode n = supertypesOfAllTypes.get(d); if (n==null) { n = new CeylonHierarchyNode(d); supertypesOfAllTypes.put(d, n); } return n; } public Runnable(IProject project, Declaration declaration) { this.project = project; this.declaration = declaration; } @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask("Building hierarchy", 100000); Unit unit = declaration.getUnit(); Module currentModule = unit.getPackage().getModule(); List<TypeChecker> tcs = getTypeChecker(project, currentModule.getNameAsString()); Set<Module> allModules = new HashSet<Module>(); for (TypeChecker tc: tcs) { ModuleManager moduleManager = tc.getPhasedUnits().getModuleManager(); allModules.addAll(moduleManager.getCompiledModules()); allModules.add(currentModule); } // boolean isFromUnversionedModule = declaration.getUnit().getPackage() // .getModule().getVersion()==null; monitor.worked(10000); Set<Package> packages = new HashSet<Package>(); int ams = allModules.size(); for (Module m: allModules) { // if (m.getVersion()!=null || isFromUnversionedModule) { packages.addAll(m.getAllPackages()); monitor.worked(10000/ams); if (monitor.isCanceled()) return; // } } subtypesOfAllTypes.put(declaration, getSubtypePathNode(declaration)); Declaration root = declaration; if (declaration instanceof TypeDeclaration) { TypeDeclaration dec = (TypeDeclaration) declaration; while (dec!=null) { depthInHierarchy++; root = dec; ClassOrInterface superDec = dec.getExtendedTypeDeclaration(); if (superDec!=null) { if (!dec.getSatisfiedTypeDeclarations().isEmpty()) { getSubtypePathNode(superDec).setNonUnique(true); } getSubtypePathNode(superDec).addChild(getSubtypePathNode(dec)); } dec = superDec; } } else if (declaration instanceof TypedDeclaration) { Declaration memberDec = declaration; Declaration refinedDeclaration = declaration.getRefinedDeclaration(); Scope container = declaration.getContainer(); if (container instanceof TypeDeclaration) { TypeDeclaration dec = (TypeDeclaration) container; List<ProducedType> signature = getSignature(declaration); depthInHierarchy++; root = memberDec; //first walk up the superclass hierarchy while (dec!=null) { ClassOrInterface superDec = dec.getExtendedTypeDeclaration(); if (superDec!=null) { Declaration superMemberDec = superDec.getDirectMember(declaration.getName(), signature, false); if (superMemberDec!=null && !isAbstraction(superMemberDec) && superMemberDec.getRefinedDeclaration() .equals(refinedDeclaration)) { List<Declaration> directlyInheritedMembers = getInterveningRefinements(declaration.getName(), signature, refinedDeclaration, (TypeDeclaration) memberDec.getContainer(), superDec); List<Declaration> all = getInterveningRefinements(declaration.getName(), signature, refinedDeclaration, (TypeDeclaration) memberDec.getContainer(), (TypeDeclaration) refinedDeclaration.getContainer()); for (Declaration d: all) { TypeDeclaration dtd = (TypeDeclaration) d.getContainer(); if (!superDec.inherits(dtd)) { getSubtypePathNode(superMemberDec).setNonUnique(true); } } directlyInheritedMembers.remove(superMemberDec); if (directlyInheritedMembers.size()>0) { getSubtypePathNode(superMemberDec).setNonUnique(true); } getSubtypePathNode(superMemberDec).addChild(getSubtypePathNode(memberDec)); depthInHierarchy++; root = superMemberDec; memberDec = superMemberDec; } //TODO else add an "empty" node to the hierarchy like in JDT } dec = superDec; } //now look at the very top of the hierarchy, even if it is an interface if (!memberDec.equals(refinedDeclaration)) { List<Declaration> directlyInheritedMembers = getInterveningRefinements(declaration.getName(), signature, declaration.getRefinedDeclaration(), (TypeDeclaration) memberDec.getContainer(), (TypeDeclaration) refinedDeclaration.getContainer()); directlyInheritedMembers.remove(refinedDeclaration); if (directlyInheritedMembers.size()>1) { //multiple intervening interfaces CeylonHierarchyNode n = new CeylonHierarchyNode(memberDec); n.setMultiple(true); n.addChild(getSubtypePathNode(memberDec)); getSubtypePathNode(refinedDeclaration).addChild(n); } else if (directlyInheritedMembers.size()==1) { //exactly one intervening interface Declaration idec = directlyInheritedMembers.get(0); getSubtypePathNode(idec).addChild(getSubtypePathNode(memberDec)); getSubtypePathNode(refinedDeclaration).addChild(getSubtypePathNode(idec)); } else { //no intervening interfaces getSubtypePathNode(refinedDeclaration).addChild(getSubtypePathNode(memberDec)); } root = refinedDeclaration; } } } hierarchyRoot = getSubtypePathNode(root); subtypesRoot = getSubtypeHierarchyNode(declaration); supertypesRoot = getSupertypeHierarchyNode(declaration); if (monitor.isCanceled()) return; IEditorPart part = site.getPage().getActiveEditor(); List<ProducedType> signature = getSignature(declaration); int ps = packages.size(); for (Package p: packages) { //workaround CME int ms = p.getMembers().size(); monitor.subTask("Building hierarchy - scanning " + p.getNameAsString()); for (Unit u: p.getUnits()) { try { //TODO: unshared inner types get // missed for binary modules for (Declaration d: u.getDeclarations()) { d = replaceWithCurrentEditorDeclaration(part, p, d); //TODO: not enough to catch *new* subtypes in the dirty editor if (d instanceof ClassOrInterface || d instanceof TypeParameter) { try { if (declaration instanceof TypeDeclaration) { TypeDeclaration td = (TypeDeclaration) d; ClassOrInterface etd = td.getExtendedTypeDeclaration(); if (etd!=null) { add(td, etd); } for (TypeDeclaration std: td.getSatisfiedTypeDeclarations()) { add(td, std); } } else if (declaration instanceof TypedDeclaration) { Declaration refinedDeclaration = declaration.getRefinedDeclaration(); TypeDeclaration td = (TypeDeclaration) d; Declaration dec = td.getDirectMember(declaration.getName(), signature, false); if (dec!=null && dec.getRefinedDeclaration()!=null && dec.getRefinedDeclaration().equals(refinedDeclaration)) { List<Declaration> refinements = getInterveningRefinements(declaration.getName(), signature, refinedDeclaration, td, (TypeDeclaration) refinedDeclaration.getContainer()); //TODO: keep the directly refined declarations in the model // (get the typechecker to set this up) for (Declaration candidate: refinements) { if (getInterveningRefinements(declaration.getName(), signature, refinedDeclaration, td, (TypeDeclaration) candidate.getContainer()) .size()==1) { add(dec, candidate); } } } } } catch (Exception e) { System.err.println(d.getQualifiedNameString()); throw e; } } monitor.worked(15000/ps/ms); if (monitor.isCanceled()) return; } } catch (Exception e) { e.printStackTrace(); } } if (monitor.isCanceled()) return; } monitor.done(); } private Declaration replaceWithCurrentEditorDeclaration(IEditorPart part, Package p, Declaration d) { if (part instanceof CeylonEditor && part.isDirty()) { CompilationUnit rootNode = ((CeylonEditor) part).getParseController() .getRootNode(); if (rootNode!=null && rootNode.getUnit()!=null) { Unit un = rootNode.getUnit(); if (un.getPackage().equals(p)) { Declaration result = getDeclarationInUnit(d.getQualifiedNameString(), un); if (result!=null) { return result; } } } } return d; } } String getDescription() { if (isShowingRefinements()) { switch (getMode()) { case HIERARCHY: return "Quick Hierarchy - refinement hierarchy of '" + description + "'"; case SUPERTYPES: return "Quick Hierarchy - generalizations of '" + description + "'"; case SUBTYPES: return "Quick Hierarchy - refinements of '" + description + "'"; default: throw new RuntimeException(); } } else { switch (getMode()) { case HIERARCHY: return "Quick Hierarchy - type hierarchy of '" + description + "'"; case SUPERTYPES: return "Quick Hierarchy - supertypes of '" + description + "'"; case SUBTYPES: return "Quick Hierarchy - subtypes of '" + description + "'"; default: throw new RuntimeException(); } } } }
plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/outline/CeylonHierarchyContentProvider.java
package com.redhat.ceylon.eclipse.code.outline; import static com.redhat.ceylon.compiler.typechecker.model.Util.getInterveningRefinements; import static com.redhat.ceylon.compiler.typechecker.model.Util.getSignature; import static com.redhat.ceylon.compiler.typechecker.model.Util.isAbstraction; import static com.redhat.ceylon.eclipse.code.outline.CeylonHierarchyNode.getDeclarationInUnit; import static com.redhat.ceylon.eclipse.code.outline.CeylonHierarchyNode.getTypeChecker; import static com.redhat.ceylon.eclipse.code.outline.HierarchyMode.HIERARCHY; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.Viewer; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPartSite; import com.redhat.ceylon.compiler.typechecker.TypeChecker; import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleManager; import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypeParameter; import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration; import com.redhat.ceylon.compiler.typechecker.model.Unit; import com.redhat.ceylon.compiler.typechecker.tree.Tree.CompilationUnit; import com.redhat.ceylon.eclipse.code.editor.CeylonEditor; public final class CeylonHierarchyContentProvider implements ITreeContentProvider { private final IWorkbenchPartSite site; private HierarchyMode mode = HIERARCHY; private CeylonHierarchyNode hierarchyRoot; private CeylonHierarchyNode supertypesRoot; private CeylonHierarchyNode subtypesRoot; private boolean showingRefinements; private boolean empty; private int depthInHierarchy; private boolean veryAbstractType; private String description; CeylonHierarchyContentProvider(IWorkbenchPartSite site) { this.site = site; } Declaration getDeclaration(IProject project) { return subtypesRoot.getDeclaration(project); } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { if (newInput!=null && newInput!=oldInput) { HierarchyInput rootNode = (HierarchyInput) newInput; Declaration declaration = rootNode.declaration; if (declaration instanceof TypedDeclaration) { TypedDeclaration td = (TypedDeclaration) declaration; if (td.getTypeDeclaration().isAnonymous()) { declaration = ((TypedDeclaration) declaration).getTypeDeclaration(); } } showingRefinements = !(declaration instanceof TypeDeclaration); empty = declaration==null; if (!empty) { String name = declaration.getQualifiedNameString(); veryAbstractType = name.equals("ceylon.language::Object") || name.equals("ceylon.language::Anything") || name.equals("ceylon.language::Basic") || name.equals("ceylon.language::Identifiable"); description = declaration.getName();//getDescriptionFor(declaration); if (isShowingRefinements() && declaration.isClassOrInterfaceMember()) { ClassOrInterface classOrInterface = (ClassOrInterface) declaration.getContainer(); description = classOrInterface.getName() + '.' + description; } try { site.getWorkbenchWindow().run(true, true, new Runnable(rootNode.project, declaration)); } catch (Exception e) { e.printStackTrace(); } rootNode.declaration=null;//don't hang onto hard ref } } } boolean isVeryAbstractType() { return veryAbstractType; } boolean isShowingRefinements() { return showingRefinements; } public boolean isEmpty() { return empty; } @Override public void dispose() {} @Override public boolean hasChildren(Object element) { return getChildren(element).length>0; } @Override public Object getParent(Object element) { return null; } @Override public Object[] getElements(Object inputElement) { return getChildren(inputElement); } @Override public CeylonHierarchyNode[] getChildren(Object parentElement) { if (parentElement instanceof HierarchyInput) { switch (mode) { case HIERARCHY: return new CeylonHierarchyNode[] { hierarchyRoot }; case SUPERTYPES: return new CeylonHierarchyNode[] { supertypesRoot }; case SUBTYPES: return new CeylonHierarchyNode[] { subtypesRoot }; default: throw new RuntimeException(); } } else if (parentElement instanceof CeylonHierarchyNode) { List<CeylonHierarchyNode> children = ((CeylonHierarchyNode) parentElement).getChildren(); CeylonHierarchyNode[] array = children.toArray(new CeylonHierarchyNode[children.size()]); Arrays.sort(array); return array; } else { return null; } } HierarchyMode getMode() { return mode; } void setMode(HierarchyMode mode) { this.mode = mode; } int getDepthInHierarchy() { return depthInHierarchy; } private class Runnable implements IRunnableWithProgress { private final IProject project; private final Declaration declaration; private final Map<Declaration, CeylonHierarchyNode> subtypesOfSupertypes = new HashMap<Declaration, CeylonHierarchyNode>(); private final Map<Declaration, CeylonHierarchyNode> subtypesOfAllTypes = new HashMap<Declaration, CeylonHierarchyNode>(); private final Map<Declaration, CeylonHierarchyNode> supertypesOfAllTypes = new HashMap<Declaration, CeylonHierarchyNode>(); private void add(Declaration td, Declaration etd) { getSubtypeHierarchyNode(etd).addChild(getSubtypeHierarchyNode(td)); getSupertypeHierarchyNode(td).addChild(getSupertypeHierarchyNode(etd)); } private CeylonHierarchyNode getSubtypePathNode(Declaration d) { CeylonHierarchyNode n = subtypesOfSupertypes.get(d); if (n==null) { n = new CeylonHierarchyNode(d); subtypesOfSupertypes.put(d, n); } return n; } private CeylonHierarchyNode getSubtypeHierarchyNode(Declaration d) { CeylonHierarchyNode n = subtypesOfAllTypes.get(d); if (n==null) { n = new CeylonHierarchyNode(d); subtypesOfAllTypes.put(d, n); } return n; } private CeylonHierarchyNode getSupertypeHierarchyNode(Declaration d) { CeylonHierarchyNode n = supertypesOfAllTypes.get(d); if (n==null) { n = new CeylonHierarchyNode(d); supertypesOfAllTypes.put(d, n); } return n; } public Runnable(IProject project, Declaration declaration) { this.project = project; this.declaration = declaration; } @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask("Building hierarchy", 100000); Unit unit = declaration.getUnit(); Module currentModule = unit.getPackage().getModule(); List<TypeChecker> tcs = getTypeChecker(project, currentModule.getNameAsString()); Set<Module> allModules = new HashSet<Module>(); for (TypeChecker tc: tcs) { ModuleManager moduleManager = tc.getPhasedUnits().getModuleManager(); allModules.addAll(moduleManager.getCompiledModules()); allModules.add(currentModule); } // boolean isFromUnversionedModule = declaration.getUnit().getPackage() // .getModule().getVersion()==null; monitor.worked(10000); Set<Package> packages = new HashSet<Package>(); int ams = allModules.size(); for (Module m: allModules) { // if (m.getVersion()!=null || isFromUnversionedModule) { packages.addAll(m.getAllPackages()); monitor.worked(10000/ams); if (monitor.isCanceled()) return; // } } subtypesOfAllTypes.put(declaration, getSubtypePathNode(declaration)); Declaration root = declaration; if (declaration instanceof TypeDeclaration) { TypeDeclaration dec = (TypeDeclaration) declaration; while (dec!=null) { depthInHierarchy++; root = dec; ClassOrInterface superDec = dec.getExtendedTypeDeclaration(); if (superDec!=null) { if (!dec.getSatisfiedTypeDeclarations().isEmpty()) { getSubtypePathNode(superDec).setNonUnique(true); } getSubtypePathNode(superDec).addChild(getSubtypePathNode(dec)); } dec = superDec; } } else if (declaration instanceof TypedDeclaration) { Declaration memberDec = declaration; Declaration refinedDeclaration = declaration.getRefinedDeclaration(); Scope container = declaration.getContainer(); if (container instanceof TypeDeclaration) { TypeDeclaration dec = (TypeDeclaration) container; List<ProducedType> signature = getSignature(declaration); depthInHierarchy++; root = memberDec; //first walk up the superclass hierarchy while (dec!=null) { ClassOrInterface superDec = dec.getExtendedTypeDeclaration(); if (superDec!=null) { Declaration superMemberDec = superDec.getDirectMember(declaration.getName(), signature, false); if (superMemberDec!=null && !isAbstraction(superMemberDec) && superMemberDec.getRefinedDeclaration() .equals(refinedDeclaration)) { List<Declaration> directlyInheritedMembers = getInterveningRefinements(declaration.getName(), signature, refinedDeclaration, (TypeDeclaration) memberDec.getContainer(), superDec); List<Declaration> all = getInterveningRefinements(declaration.getName(), signature, refinedDeclaration, (TypeDeclaration) memberDec.getContainer(), (TypeDeclaration) refinedDeclaration.getContainer()); for (Declaration d: all) { TypeDeclaration dtd = (TypeDeclaration) d.getContainer(); if (!superDec.inherits(dtd)) { getSubtypePathNode(superMemberDec).setNonUnique(true); } } directlyInheritedMembers.remove(superMemberDec); if (directlyInheritedMembers.size()>0) { getSubtypePathNode(superMemberDec).setNonUnique(true); } getSubtypePathNode(superMemberDec).addChild(getSubtypePathNode(memberDec)); depthInHierarchy++; root = superMemberDec; memberDec = superMemberDec; } //TODO else add an "empty" node to the hierarchy like in JDT } dec = superDec; } //now look at the very top of the hierarchy, even if it is an interface if (!memberDec.equals(refinedDeclaration)) { List<Declaration> directlyInheritedMembers = getInterveningRefinements(declaration.getName(), signature, declaration.getRefinedDeclaration(), (TypeDeclaration) memberDec.getContainer(), (TypeDeclaration) refinedDeclaration.getContainer()); directlyInheritedMembers.remove(refinedDeclaration); if (directlyInheritedMembers.size()>1) { //multiple intervening interfaces CeylonHierarchyNode n = new CeylonHierarchyNode(memberDec); n.setMultiple(true); n.addChild(getSubtypePathNode(memberDec)); getSubtypePathNode(refinedDeclaration).addChild(n); } else if (directlyInheritedMembers.size()==1) { //exactly one intervening interface Declaration idec = directlyInheritedMembers.get(0); getSubtypePathNode(idec).addChild(getSubtypePathNode(memberDec)); getSubtypePathNode(refinedDeclaration).addChild(getSubtypePathNode(idec)); } else { //no intervening interfaces getSubtypePathNode(refinedDeclaration).addChild(getSubtypePathNode(memberDec)); } root = refinedDeclaration; } } } hierarchyRoot = getSubtypePathNode(root); subtypesRoot = getSubtypeHierarchyNode(declaration); supertypesRoot = getSupertypeHierarchyNode(declaration); if (monitor.isCanceled()) return; IEditorPart part = site.getPage().getActiveEditor(); List<ProducedType> signature = getSignature(declaration); int ps = packages.size(); for (Package p: packages) { //workaround CME int ms = p.getMembers().size(); monitor.subTask("Building hierarchy - scanning " + p.getNameAsString()); for (Unit u: p.getUnits()) { try { //TODO: unshared inner types get // missed for binary modules for (Declaration d: u.getDeclarations()) { d = replaceWithCurrentEditorDeclaration(part, p, d); //TODO: not enough to catch *new* subtypes in the dirty editor if (d instanceof ClassOrInterface || d instanceof TypeParameter) { try { if (declaration instanceof TypeDeclaration) { TypeDeclaration td = (TypeDeclaration) d; ClassOrInterface etd = td.getExtendedTypeDeclaration(); if (etd!=null) { add(td, etd); } for (TypeDeclaration std: td.getSatisfiedTypeDeclarations()) { add(td, std); } } else if (declaration instanceof TypedDeclaration) { Declaration refinedDeclaration = declaration.getRefinedDeclaration(); TypeDeclaration td = (TypeDeclaration) d; Declaration dec = td.getDirectMember(declaration.getName(), signature, false); if (dec!=null && dec.getRefinedDeclaration()!=null && dec.getRefinedDeclaration().equals(refinedDeclaration)) { List<Declaration> refinements = getInterveningRefinements(declaration.getName(), signature, refinedDeclaration, td, (TypeDeclaration) refinedDeclaration.getContainer()); //TODO: keep the directly refined declarations in the model // (get the typechecker to set this up) for (Declaration candidate: refinements) { if (getInterveningRefinements(declaration.getName(), signature, refinedDeclaration, td, (TypeDeclaration) candidate.getContainer()) .size()==1) { add(dec, candidate); } } } } } catch (Exception e) { System.err.println(d.getQualifiedNameString()); throw e; } } monitor.worked(15000/ps/ms); if (monitor.isCanceled()) return; } } catch (Exception e) { e.printStackTrace(); } } if (monitor.isCanceled()) return; } monitor.done(); } private Declaration replaceWithCurrentEditorDeclaration(IEditorPart part, Package p, Declaration d) { if (part instanceof CeylonEditor && part.isDirty()) { CompilationUnit rootNode = ((CeylonEditor) part).getParseController() .getRootNode(); if (rootNode!=null && rootNode.getUnit()!=null) { Unit un = rootNode.getUnit(); if (un.getPackage().equals(p)) { Declaration result = getDeclarationInUnit(d.getQualifiedNameString(), un); if (result!=null) { return result; } } } } return d; } } String getDescription() { if (isShowingRefinements()) { switch (getMode()) { case HIERARCHY: return "Quick Hierarchy - refinement hierarchy of '" + description + "'"; case SUPERTYPES: return "Quick Hierarchy - generalizations of '" + description + "'"; case SUBTYPES: return "Quick Hierarchy - refinements '" + description + "'"; default: throw new RuntimeException(); } } else { switch (getMode()) { case HIERARCHY: return "Quick Hierarchy - type hierarchy of '" + description + "'"; case SUPERTYPES: return "Quick Hierarchy - supertypes of '" + description + "'"; case SUBTYPES: return "Quick Hierarchy - subtypes of '" + description + "'"; default: throw new RuntimeException(); } } } }
fix label
plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/outline/CeylonHierarchyContentProvider.java
fix label
Java
epl-1.0
2e21a9e420afaa51beb4a1237ec1cb13c6e453db
0
jtrfp/terminal-recall,jtrfp/terminal-recall,jtrfp/terminal-recall
/******************************************************************************* * This file is part of TERMINAL RECALL * Copyright (c) 2012, 2013 Chuck Ritola. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the COPYING and CREDITS files for more details. * * Contributors: * chuck - initial API and implementation ******************************************************************************/ package org.jtrfp.trcl; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.util.concurrent.Future; public class GLFont { //private final Font realFont; private final Future<Texture>[] textures; //private Graphics2D g; //private FontMetrics metrics; private double maxAdvance=-1; private final int [] widths = new int[256]; private final double [] glWidths=new double[256]; private static final int sideLength=64; private static final Color TEXT_COLOR=new Color(80,200,180); public GLFont(Font realFont) { final Font font=realFont.deriveFont((float)sideLength).deriveFont(Font.BOLD); //Generate the textures textures = new Future[256]; Texture empty=renderToTexture(' ',realFont); for(int c=0; c<256; c++) {textures[c]=new DummyFuture<Texture>(realFont.canDisplay(c)?renderToTexture(c,font):empty);} }//end constructor public Future<Texture>[] getTextures() {return textures;} private Texture renderToTexture(int c, Font font) { BufferedImage img = new BufferedImage(sideLength, sideLength, BufferedImage.TYPE_INT_ARGB); final Graphics2D g=img.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g.setFont(font); FontMetrics metrics=g.getFontMetrics(); maxAdvance=metrics.getMaxAdvance(); if(metrics.charWidth(c)>=getTextureSideLength()) {int size=g.getFont().getSize(); g.setFont(font.deriveFont((float)(size*size)/(float)metrics.charWidth(c)*.9f)); metrics=g.getFontMetrics(); }//end if(too big to fit) g.setColor(TEXT_COLOR); g.drawChars(new char [] {(char)c}, 0, 1, (int)((double)getTextureSideLength()*.05), (int)((double)getTextureSideLength()*.95)); widths[c]=metrics.charWidth(c); glWidths[c]=(double)widths[c]/(double)getTextureSideLength(); g.dispose(); return new Texture(img,"GLFont "+(char)c); } public static double getTextureSideLength(){return sideLength;} public double glWidthOf(char currentChar) {return glWidths[currentChar];} public double height(){return maxAdvance;} }//end GLFont
src/main/java/org/jtrfp/trcl/GLFont.java
/******************************************************************************* * This file is part of TERMINAL RECALL * Copyright (c) 2012, 2013 Chuck Ritola. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the COPYING and CREDITS files for more details. * * Contributors: * chuck - initial API and implementation ******************************************************************************/ package org.jtrfp.trcl; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.util.concurrent.Future; public class GLFont { private final Font realFont; private final Future<Texture>[] textures; private Graphics2D g; private FontMetrics metrics; private final int [] widths = new int[256]; private final double [] glWidths=new double[256]; private static final int sideLength=64; private static final Color TEXT_COLOR=new Color(80,200,180); public GLFont(Font realFont) { this.realFont=realFont.deriveFont((float)sideLength).deriveFont(Font.BOLD); //Generate the textures textures = new Future[256]; Texture empty=renderToTexture(' '); for(int c=0; c<256; c++) {textures[c]=new DummyFuture<Texture>(realFont.canDisplay(c)?renderToTexture(c):empty);} }//end constructor public Future<Texture>[] getTextures() {return textures;} private Texture renderToTexture(int c) { BufferedImage img = new BufferedImage(sideLength, sideLength, BufferedImage.TYPE_INT_ARGB); g=img.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g.setFont(realFont); metrics=g.getFontMetrics(); if(metrics.charWidth(c)>=getTextureSideLength()) {int size=g.getFont().getSize(); g.setFont(realFont.deriveFont((float)(size*size)/(float)metrics.charWidth(c)*.9f)); metrics=g.getFontMetrics(); }//end if(too big to fit) g.setColor(TEXT_COLOR); g.drawChars(new char [] {(char)c}, 0, 1, (int)((double)getTextureSideLength()*.05), (int)((double)getTextureSideLength()*.95)); widths[c]=metrics.charWidth(c); glWidths[c]=(double)widths[c]/(double)getTextureSideLength(); g.dispose(); return new Texture(img,"GLFont "+(char)c); } public double getTextureSideLength(){return sideLength;} public double glWidthOf(char currentChar) {return glWidths[currentChar];} public double height(){return metrics.getMaxAdvance();} }//end GLFont
Prepared GLFont for non Font sources.
src/main/java/org/jtrfp/trcl/GLFont.java
Prepared GLFont for non Font sources.
Java
agpl-3.0
da681d3e0bca69bc4dc580885e45ecbc4cd8b2e8
0
teyden/phenotips,mjshepherd/phenotips,DeanWay/phenotips,tmarathe/phenotips,alexhenrie/phenotips,mjshepherd/phenotips,danielpgross/phenotips,JKereliuk/phenotips,veronikaslc/phenotips,itaiGershtansky/phenotips,JKereliuk/phenotips,mjshepherd/phenotips,veronikaslc/phenotips,phenotips/phenotips,tmarathe/phenotips,alexhenrie/phenotips,phenotips/phenotips,teyden/phenotips,teyden/phenotips,danielpgross/phenotips,phenotips/phenotips,DeanWay/phenotips,JKereliuk/phenotips,tmarathe/phenotips,phenotips/phenotips,alexhenrie/phenotips,phenotips/phenotips,teyden/phenotips,teyden/phenotips,itaiGershtansky/phenotips,DeanWay/phenotips,danielpgross/phenotips,veronikaslc/phenotips,itaiGershtansky/phenotips
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.phenotips.data.permissions.internal; import org.phenotips.data.Patient; import org.xwiki.bridge.event.DocumentCreatingEvent; import org.xwiki.bridge.event.DocumentUpdatingEvent; import org.xwiki.component.manager.ComponentLookupException; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.EntityReference; import org.xwiki.observation.EventListener; import org.xwiki.observation.event.Event; import org.xwiki.test.mockito.MockitoComponentMockingRule; import org.apache.commons.lang3.StringUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.objects.BaseObject; import static org.mockito.Matchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Tests for the {@link RightsUpdateEventListener} * * @version $Id$ */ public class RightsUpdateEventListenerTest { @Rule public final MockitoComponentMockingRule<EventListener> mocker = new MockitoComponentMockingRule<EventListener>(RightsUpdateEventListener.class); @Mock private Event event; @Mock private XWikiDocument doc; private DocumentReference reference = new DocumentReference("x", "data", "P0000001"); @Mock private XWikiContext context; @Mock private BaseObject patientObject; @Mock private BaseObject manageRightsObject; @Mock private BaseObject editRightObject; @Mock private BaseObject viewRightObject; @Before public void setUp() throws ComponentLookupException { MockitoAnnotations.initMocks(this); } @Test public void listensToDocumentCreation() throws ComponentLookupException { boolean found = false; for (Event e : this.mocker.getComponentUnderTest().getEvents()) { if (e instanceof DocumentCreatingEvent) { found = true; break; } } Assert.assertTrue(found); } @Test public void listensToDocumentUpdates() throws ComponentLookupException { boolean found = false; for (Event e : this.mocker.getComponentUnderTest().getEvents()) { if (e instanceof DocumentUpdatingEvent) { found = true; break; } } Assert.assertTrue(found); } @Test public void hasName() throws ComponentLookupException { String name = this.mocker.getComponentUnderTest().getName(); Assert.assertTrue(StringUtils.isNotBlank(name)); Assert.assertFalse("default".equals(name)); } @Test public void ignoresNonPatients() throws ComponentLookupException, XWikiException { when(this.doc.getXObject(Patient.CLASS_REFERENCE)).thenReturn(null); this.mocker.getComponentUnderTest().onEvent(this.event, this.doc, this.context); verify(this.doc, never()).getXObjects(any(EntityReference.class)); verify(this.doc, never()).newXObject(any(EntityReference.class), any(XWikiContext.class)); } @Test public void ignoresTemplatePatient() throws ComponentLookupException, XWikiException { when(this.doc.getXObject(Patient.CLASS_REFERENCE)).thenReturn(this.patientObject); when(this.doc.getDocumentReference()).thenReturn(new DocumentReference("x", "PhenoTips", "PatientTemplate")); this.mocker.getComponentUnderTest().onEvent(this.event, this.doc, this.context); verify(this.doc, never()).getXObjects(any(EntityReference.class)); verify(this.doc, never()).newXObject(any(EntityReference.class), any(XWikiContext.class)); } }
components/patient-access-rules/api/src/test/java/org/phenotips/data/permissions/internal/RightsUpdateEventListenerTest.java
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.phenotips.data.permissions.internal; import org.xwiki.component.manager.ComponentLookupException; import org.xwiki.model.reference.EntityReference; import org.xwiki.test.mockito.MockitoComponentMockingRule; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Iterator; import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.objects.BaseObject; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Tests for the {@link RightsUpdateEventListener} * * @version $Id$ */ public class RightsUpdateEventListenerTest { @Rule public final MockitoComponentMockingRule<RightsUpdateEventListener> mocker = new MockitoComponentMockingRule<RightsUpdateEventListener>(RightsUpdateEventListener.class); public XWikiDocument doc = mock(XWikiDocument.class); public XWikiContext context = mock(XWikiContext.class); public RightsUpdateEventListener testComponent; @Before public void setUp() throws ComponentLookupException { this.testComponent = this.mocker.getComponentUnderTest(); } /** Basic test for {@link RightsUpdateEventListener#findRights} */ @Test public void findRightsTest() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { Class[] args = new Class[1]; args[0] = XWikiDocument.class; Method testMethod = this.testComponent.getClass().getDeclaredMethod("findRights", args); testMethod.setAccessible(true); List<BaseObject> mockRightObjects = mock(List.class); Iterator<BaseObject> mockRightIterator = mock(Iterator.class); BaseObject mockRightObject = mock(BaseObject.class); when(this.doc.getXObjects(any(EntityReference.class))).thenReturn(mockRightObjects); when(mockRightObjects.iterator()).thenReturn(mockRightIterator); when(mockRightIterator.hasNext()).thenReturn(true, false); when(mockRightIterator.next()).thenReturn(mockRightObject); testMethod.invoke(this.testComponent, this.doc); } }
[misc] Discarded bad test, wrote some new ones
components/patient-access-rules/api/src/test/java/org/phenotips/data/permissions/internal/RightsUpdateEventListenerTest.java
[misc] Discarded bad test, wrote some new ones
Java
agpl-3.0
ad0186adfe188f3c9002215f4879f86ea7fa7073
0
elki-project/elki,elki-project/elki,elki-project/elki
package de.lmu.ifi.dbs.algorithm; import de.lmu.ifi.dbs.algorithm.result.Result; import de.lmu.ifi.dbs.data.DatabaseObject; import de.lmu.ifi.dbs.database.connection.DatabaseConnection; import de.lmu.ifi.dbs.database.connection.FileBasedDatabaseConnection; import de.lmu.ifi.dbs.normalization.Normalization; import de.lmu.ifi.dbs.properties.Properties; import de.lmu.ifi.dbs.properties.PropertyDescription; import de.lmu.ifi.dbs.properties.PropertyName; import de.lmu.ifi.dbs.utilities.UnableToComplyException; import de.lmu.ifi.dbs.utilities.Util; import de.lmu.ifi.dbs.utilities.optionhandling.AttributeSettings; import de.lmu.ifi.dbs.utilities.optionhandling.NoParameterValueException; import de.lmu.ifi.dbs.utilities.optionhandling.OptionHandler; import de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable; import de.lmu.ifi.dbs.utilities.optionhandling.UnusedParameterException; import java.io.File; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; /** * Provides a KDDTask that can be used to perform any algorithm implementing * {@link Algorithm Algorithm} using any DatabaseConnection implementing * {@link de.lmu.ifi.dbs.database.connection.DatabaseConnection DatabaseConnection}. * * @author Arthur Zimek (<a * href="mailto:zimek@dbs.ifi.lmu.de">zimek@dbs.ifi.lmu.de</a>) */ public class KDDTask implements Parameterizable { /** * The String for calling this class' main routine on command line * interface. */ private static final String CALL = "java " + KDDTask.class.getName(); /** * The newline string according to system. */ public static final String NEWLINE = System.getProperty("line.separator"); /** * The parameter algorithm. */ public static final String ALGORITHM_P = "algorithm"; /** * Description for parameter algorithm. */ public static final String ALGORITHM_D = "<classname>classname of an algorithm implementing the interface " + Algorithm.class.getName() + ". Either full name to identify classpath or only classname, if its package is " + Algorithm.class.getPackage().getName() + "."; /** * Help flag. */ public static final String HELP_F = "h"; /** * Long help flag. */ public static final String HELPLONG_F = "help"; /** * Description for help flag. */ public static final String HELP_D = "flag to obtain help-message, either for the main-routine or for any specified algorithm. Causes immediate stop of the program."; /** * Description flag. */ public static final String DESCRIPTION_F = "description"; /** * Description for description flag. */ public static final String DESCRIPTION_D = "flag to obtain a description of any specified algorithm"; /** * The default database connection. */ private static final String DEFAULT_DATABASE_CONNECTION = FileBasedDatabaseConnection.class.getName(); /** * Parameter for database connection. */ public static final String DATABASE_CONNECTION_P = "dbc"; /** * Description for parameter database connection. */ public static final String DATABASE_CONNECTION_D = "<classname>classname of a class implementing the interface " + DatabaseConnection.class.getName() + ". Either full name to identify classpath or only classname, if its package is " + DatabaseConnection.class.getPackage().getName() + ". (Default: " + DEFAULT_DATABASE_CONNECTION + ")."; /** * Parameter output. */ public static final String OUTPUT_P = "out"; /** * Description for parameter output. */ public static final String OUTPUT_D = "<filename>file to write the obtained results in. If an algorithm requires several outputfiles, the given filename will be used as prefix followed by automatically created markers. If this parameter is omitted, per default the output will sequentially be given to STDOUT."; /** * Parameter normalization. */ public static final String NORMALIZATION_P = "norm"; /** * Description for parameter normalization. */ public static final String NORMALIZATION_D = "<class>a normalization (implementing " + Normalization.class.getName() + ") to use a database with normalized values"; /** * Flag normalization undo. */ public static final String NORMALIZATION_UNDO_F = "normUndo"; /** * Description for flag normalization undo. */ public static final String NORMALIZATION_UNDO_D = "flag to revert result to original values - invalid option if no normalization has been performed."; /** * The algorithm to run. */ private Algorithm algorithm; /** * The database connection to have the algorithm run with. */ private DatabaseConnection<DatabaseObject> databaseConnection; /** * The file to print results to. */ private File out; /** * Whether KDDTask has been properly initialized for calling the * {@link #run() run()}-method. */ private boolean initialized = false; /** * A normalization - per default no normalization is used. */ private Normalization normalization = null; /** * Whether to undo normalization for result. */ private boolean normalizationUndo = false; /** * OptionHandler for handling options. */ private OptionHandler optionHandler; /** * Provides a KDDTask. */ public KDDTask() { Map<String, String> parameterToDescription = new Hashtable<String, String>(); parameterToDescription.put(ALGORITHM_P + OptionHandler.EXPECTS_VALUE, ALGORITHM_D); parameterToDescription.put(HELP_F, HELP_D); parameterToDescription.put(HELPLONG_F, HELP_D); parameterToDescription.put(DESCRIPTION_F, DESCRIPTION_D); parameterToDescription.put(DATABASE_CONNECTION_P + OptionHandler.EXPECTS_VALUE, DATABASE_CONNECTION_D); parameterToDescription.put(OUTPUT_P + OptionHandler.EXPECTS_VALUE, OUTPUT_D); parameterToDescription.put(NORMALIZATION_P + OptionHandler.EXPECTS_VALUE, NORMALIZATION_D); parameterToDescription.put(NORMALIZATION_UNDO_F, NORMALIZATION_UNDO_D); optionHandler = new OptionHandler(parameterToDescription, CALL); } /** * Returns a description for printing on command line interface. * * @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#description() */ public String description() { StringBuffer description = new StringBuffer(); description.append(optionHandler.usage("")); description.append(NEWLINE); description.append("Subsequent options are firstly given to algorithm. Remaining parameters are given to databaseConnection."); description.append(NEWLINE); description.append(NEWLINE); description.append("Algorithms available within this framework:"); description.append(NEWLINE); for(PropertyDescription pd : Properties.KDD_FRAMEWORK_PROPERTIES.getProperties(PropertyName.ALGORITHM)) { description.append("Class: "); description.append(pd.getEntry()); description.append(NEWLINE); description.append(pd.getDescription()); description.append(NEWLINE); } description.append(NEWLINE); description.append(NEWLINE); description.append("DatabaseConnections available within this framework:"); description.append(NEWLINE); description.append(NEWLINE); for(PropertyDescription pd : Properties.KDD_FRAMEWORK_PROPERTIES.getProperties(PropertyName.DATABASE_CONNECTIONS)) { description.append("Class: "); description.append(pd.getEntry()); description.append(NEWLINE); description.append(pd.getDescription()); description.append(NEWLINE); } description.append(NEWLINE); return description.toString(); } /** * Returns a usage message with the specified message * as leading line, and information as provided by * optionHandler. * If an algorithm is specified, the description of the algorithm is * returned. * * @param message a message to be include in the usage message * @return a usage message with the specified message * as leading line, and information as provided by * optionHandler */ public String usage(String message) { StringBuffer usage = new StringBuffer(); usage.append(message); usage.append(NEWLINE); usage.append(optionHandler.usage("",false)); usage.append(NEWLINE); if(algorithm != null) { usage.append(OptionHandler.OPTION_PREFIX); usage.append(ALGORITHM_P); usage.append(" "); usage.append(algorithm.description()); usage.append(NEWLINE); } return usage.toString(); } /** * Sets the options accordingly to the specified list of parameters. * * @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#setParameters(String[]) */ @SuppressWarnings("unchecked") public String[] setParameters(String[] args) throws IllegalArgumentException, AbortException { String[] remainingParameters = optionHandler.grabOptions(args); if(args.length == 0) { throw new AbortException("No options specified. Try flag -h to gain more information."); } if(optionHandler.isSet(HELP_F) || optionHandler.isSet(HELPLONG_F)) { throw new AbortException(description()); } try { String name = optionHandler.getOptionValue(ALGORITHM_P); algorithm = Util.instantiate(Algorithm.class,name); } catch(UnusedParameterException e) { throw new IllegalArgumentException(optionHandler.usage(e.getMessage(),false)); } catch(NoParameterValueException e) { throw new IllegalArgumentException(optionHandler.usage(e.getMessage(),false)); } if(optionHandler.isSet(DESCRIPTION_F)) { throw new AbortException(algorithm.getDescription().toString() + '\n' + algorithm.description()); } if(optionHandler.isSet(DATABASE_CONNECTION_P)) { String name = optionHandler.getOptionValue(DATABASE_CONNECTION_P); databaseConnection = Util.instantiate(DatabaseConnection.class, name); } else { databaseConnection = Util.instantiate(DatabaseConnection.class,DEFAULT_DATABASE_CONNECTION); } if(optionHandler.isSet(OUTPUT_P)) { out = new File(optionHandler.getOptionValue(OUTPUT_P)); } else { out = null; } if(optionHandler.isSet(NORMALIZATION_P)) { String name = optionHandler.getOptionValue(NORMALIZATION_P); normalization = Util.instantiate(Normalization.class,name); normalizationUndo = optionHandler.isSet(NORMALIZATION_UNDO_F); } else if(optionHandler.isSet(NORMALIZATION_UNDO_F)) { throw new IllegalArgumentException("Illegal parameter setting: Flag " + NORMALIZATION_UNDO_F + " is set, but no normalization is specified."); } remainingParameters = algorithm.setParameters(remainingParameters); remainingParameters = databaseConnection.setParameters(remainingParameters); initialized = true; return remainingParameters; } /** * Returns the parameter setting of the attributes. * * @return the parameter setting of the attributes */ public List<AttributeSettings> getAttributeSettings() { List<AttributeSettings> list = new ArrayList<AttributeSettings>(); // TODO parameter settings return list; } /** * Method to run the specified algorithm using the specified database * connection. * * @throws IllegalStateException * if initialization has not been done properly (i.e. * {@link #setParameters(String[]) setParameters(String[])} has * not been called before calling this method) */ @SuppressWarnings("unchecked") public Result run() throws IllegalStateException { if(initialized) { algorithm.run(databaseConnection.getDatabase(normalization)); try { Result result = algorithm.getResult(); // Why settings here? List<AttributeSettings> settings = databaseConnection.getAttributeSettings(); settings.addAll(algorithm.getAttributeSettings()); if(normalization != null) { settings.addAll(normalization.getAttributeSettings()); } if(normalizationUndo) { result.output(out, normalization, settings); } else { result.output(out, null, settings); } return result; } catch(UnableToComplyException e) { throw new IllegalStateException("Error in restoring result to original values.", e); } } else { throw new IllegalStateException("KDD-Task was not properly initialized. Need to set parameters first."); } } /** * Runs a KDD task accordingly to the specified parameters. * * @param args * parameter list according to description */ public static void main(String[] args) { KDDTask kddTask = new KDDTask(); try { kddTask.setParameters(args); kddTask.run(); } catch(AbortException e) { System.out.println(e.getMessage()); } catch(IllegalArgumentException e) { e.printStackTrace(); System.out.println(kddTask.usage(e.getMessage())); } catch(IllegalStateException e) { System.err.println(e.getMessage()); } } }
src/de/lmu/ifi/dbs/algorithm/KDDTask.java
package de.lmu.ifi.dbs.algorithm; import de.lmu.ifi.dbs.algorithm.result.Result; import de.lmu.ifi.dbs.data.DatabaseObject; import de.lmu.ifi.dbs.database.connection.DatabaseConnection; import de.lmu.ifi.dbs.database.connection.FileBasedDatabaseConnection; import de.lmu.ifi.dbs.normalization.Normalization; import de.lmu.ifi.dbs.properties.Properties; import de.lmu.ifi.dbs.properties.PropertyDescription; import de.lmu.ifi.dbs.properties.PropertyName; import de.lmu.ifi.dbs.utilities.UnableToComplyException; import de.lmu.ifi.dbs.utilities.Util; import de.lmu.ifi.dbs.utilities.optionhandling.AttributeSettings; import de.lmu.ifi.dbs.utilities.optionhandling.NoParameterValueException; import de.lmu.ifi.dbs.utilities.optionhandling.OptionHandler; import de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable; import de.lmu.ifi.dbs.utilities.optionhandling.UnusedParameterException; import java.io.File; import java.util.Hashtable; import java.util.List; import java.util.Map; /** * Provides a KDDTask that can be used to perform any algorithm implementing * {@link Algorithm Algorithm} using any DatabaseConnection implementing * {@link de.lmu.ifi.dbs.database.connection.DatabaseConnection DatabaseConnection}. * * @author Arthur Zimek (<a * href="mailto:zimek@dbs.ifi.lmu.de">zimek@dbs.ifi.lmu.de</a>) */ public class KDDTask implements Parameterizable { /** * The String for calling this class' main routine on command line * interface. */ private static final String CALL = "java " + KDDTask.class.getName(); /** * The newline string according to system. */ public static final String NEWLINE = System.getProperty("line.separator"); /** * The parameter algorithm. */ public static final String ALGORITHM_P = "algorithm"; /** * Description for parameter algorithm. */ public static final String ALGORITHM_D = "<classname>classname of an algorithm implementing the interface " + Algorithm.class.getName() + ". Either full name to identify classpath or only classname, if its package is " + Algorithm.class.getPackage().getName() + "."; /** * Help flag. */ public static final String HELP_F = "h"; /** * Long help flag. */ public static final String HELPLONG_F = "help"; /** * Description for help flag. */ public static final String HELP_D = "flag to obtain help-message, either for the main-routine or for any specified algorithm. Causes immediate stop of the program."; /** * Description flag. */ public static final String DESCRIPTION_F = "description"; /** * Description for description flag. */ public static final String DESCRIPTION_D = "flag to obtain a description of any specified algorithm"; /** * The default database connection. */ private static final String DEFAULT_DATABASE_CONNECTION = FileBasedDatabaseConnection.class.getName(); /** * Parameter for database connection. */ public static final String DATABASE_CONNECTION_P = "dbc"; /** * Description for parameter database connection. */ public static final String DATABASE_CONNECTION_D = "<classname>classname of a class implementing the interface " + DatabaseConnection.class.getName() + ". Either full name to identify classpath or only classname, if its package is " + DatabaseConnection.class.getPackage().getName() + ". (Default: " + DEFAULT_DATABASE_CONNECTION + ")."; /** * Parameter output. */ public static final String OUTPUT_P = "out"; /** * Description for parameter output. */ public static final String OUTPUT_D = "<filename>file to write the obtained results in. If an algorithm requires several outputfiles, the given filename will be used as prefix followed by automatically created markers. If this parameter is omitted, per default the output will sequentially be given to STDOUT."; /** * Parameter normalization. */ public static final String NORMALIZATION_P = "norm"; /** * Description for parameter normalization. */ public static final String NORMALIZATION_D = "<class>a normalization (implementing " + Normalization.class.getName() + ") to use a database with normalized values"; /** * Flag normalization undo. */ public static final String NORMALIZATION_UNDO_F = "normUndo"; /** * Description for flag normalization undo. */ public static final String NORMALIZATION_UNDO_D = "flag to revert result to original values - invalid option if no normalization has been performed."; /** * The algorithm to run. */ private Algorithm algorithm; /** * The database connection to have the algorithm run with. */ private DatabaseConnection<DatabaseObject> databaseConnection; /** * The file to print results to. */ private File out; /** * Whether KDDTask has been properly initialized for calling the * {@link #run() run()}-method. */ private boolean initialized = false; /** * A normalization - per default no normalization is used. */ private Normalization normalization = null; /** * Whether to undo normalization for result. */ private boolean normalizationUndo = false; /** * OptionHandler for handling options. */ private OptionHandler optionHandler; /** * Provides a KDDTask. */ public KDDTask() { Map<String, String> parameterToDescription = new Hashtable<String, String>(); parameterToDescription.put(ALGORITHM_P + OptionHandler.EXPECTS_VALUE, ALGORITHM_D); parameterToDescription.put(HELP_F, HELP_D); parameterToDescription.put(HELPLONG_F, HELP_D); parameterToDescription.put(DESCRIPTION_F, DESCRIPTION_D); parameterToDescription.put(DATABASE_CONNECTION_P + OptionHandler.EXPECTS_VALUE, DATABASE_CONNECTION_D); parameterToDescription.put(OUTPUT_P + OptionHandler.EXPECTS_VALUE, OUTPUT_D); parameterToDescription.put(NORMALIZATION_P + OptionHandler.EXPECTS_VALUE, NORMALIZATION_D); parameterToDescription.put(NORMALIZATION_UNDO_F, NORMALIZATION_UNDO_D); optionHandler = new OptionHandler(parameterToDescription, CALL); } /** * Returns a description for printing on command line interface. * * @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#description() */ public String description() { StringBuffer description = new StringBuffer(); description.append(optionHandler.usage("")); description.append(NEWLINE); description.append("Subsequent options are firstly given to algorithm. Remaining parameters are given to databaseConnection."); description.append(NEWLINE); description.append(NEWLINE); description.append("Algorithms available within this framework:"); description.append(NEWLINE); for(PropertyDescription pd : Properties.KDD_FRAMEWORK_PROPERTIES.getProperties(PropertyName.ALGORITHM)) { description.append("Class: "); description.append(pd.getEntry()); description.append(NEWLINE); description.append(pd.getDescription()); description.append(NEWLINE); } description.append(NEWLINE); description.append(NEWLINE); description.append("DatabaseConnections available within this framework:"); description.append(NEWLINE); description.append(NEWLINE); for(PropertyDescription pd : Properties.KDD_FRAMEWORK_PROPERTIES.getProperties(PropertyName.DATABASE_CONNECTIONS)) { description.append("Class: "); description.append(pd.getEntry()); description.append(NEWLINE); description.append(pd.getDescription()); description.append(NEWLINE); } description.append(NEWLINE); return description.toString(); } /** * Returns a usage message with the specified message * as leading line, and information as provided by * optionHandler. * If an algorithm is specified, the description of the algorithm is * returned. * * @param message a message to be include in the usage message * @return a usage message with the specified message * as leading line, and information as provided by * optionHandler */ public String usage(String message) { StringBuffer usage = new StringBuffer(); usage.append(message); usage.append(NEWLINE); usage.append(optionHandler.usage("",false)); usage.append(NEWLINE); if(algorithm != null) { usage.append(OptionHandler.OPTION_PREFIX); usage.append(ALGORITHM_P); usage.append(" "); usage.append(algorithm.description()); usage.append(NEWLINE); } return usage.toString(); } /** * Sets the options accordingly to the specified list of parameters. * * @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#setParameters(String[]) */ @SuppressWarnings("unchecked") public String[] setParameters(String[] args) throws IllegalArgumentException, AbortException { String[] remainingParameters = optionHandler.grabOptions(args); if(args.length == 0) { throw new AbortException("No options specified. Try flag -h to gain more information."); } if(optionHandler.isSet(HELP_F) || optionHandler.isSet(HELPLONG_F)) { throw new AbortException(description()); } try { String name = optionHandler.getOptionValue(ALGORITHM_P); algorithm = Util.instantiate(Algorithm.class,name); } catch(UnusedParameterException e) { throw new IllegalArgumentException(optionHandler.usage(e.getMessage(),false)); } catch(NoParameterValueException e) { throw new IllegalArgumentException(optionHandler.usage(e.getMessage(),false)); } if(optionHandler.isSet(DESCRIPTION_F)) { throw new AbortException(algorithm.getDescription().toString() + '\n' + algorithm.description()); } if(optionHandler.isSet(DATABASE_CONNECTION_P)) { String name = optionHandler.getOptionValue(DATABASE_CONNECTION_P); databaseConnection = Util.instantiate(DatabaseConnection.class, name); } else { databaseConnection = Util.instantiate(DatabaseConnection.class,DEFAULT_DATABASE_CONNECTION); } if(optionHandler.isSet(OUTPUT_P)) { out = new File(optionHandler.getOptionValue(OUTPUT_P)); } else { out = null; } if(optionHandler.isSet(NORMALIZATION_P)) { String name = optionHandler.getOptionValue(NORMALIZATION_P); normalization = Util.instantiate(Normalization.class,name); normalizationUndo = optionHandler.isSet(NORMALIZATION_UNDO_F); } else if(optionHandler.isSet(NORMALIZATION_UNDO_F)) { throw new IllegalArgumentException("Illegal parameter setting: Flag " + NORMALIZATION_UNDO_F + " is set, but no normalization is specified."); } remainingParameters = algorithm.setParameters(remainingParameters); remainingParameters = databaseConnection.setParameters(remainingParameters); initialized = true; return remainingParameters; } /** * Returns the parameter setting of the attributes. * * @return the parameter setting of the attributes */ public List<AttributeSettings> getAttributeSettings() { // TODO parameter settings return null; } /** * Method to run the specified algorithm using the specified database * connection. * * @throws IllegalStateException * if initialization has not been done properly (i.e. * {@link #setParameters(String[]) setParameters(String[])} has * not been called before calling this method) */ @SuppressWarnings("unchecked") public Result run() throws IllegalStateException { if(initialized) { algorithm.run(databaseConnection.getDatabase(normalization)); try { Result result = algorithm.getResult(); // Why settings here? List<AttributeSettings> settings = databaseConnection.getAttributeSettings(); settings.addAll(algorithm.getAttributeSettings()); if(normalization != null) { settings.addAll(normalization.getAttributeSettings()); } if(normalizationUndo) { result.output(out, normalization, settings); } else { result.output(out, null, settings); } return result; } catch(UnableToComplyException e) { throw new IllegalStateException("Error in restoring result to original values.", e); } } else { throw new IllegalStateException("KDD-Task was not properly initialized. Need to set parameters first."); } } /** * Runs a KDD task accordingly to the specified parameters. * * @param args * parameter list according to description */ public static void main(String[] args) { KDDTask kddTask = new KDDTask(); try { kddTask.setParameters(args); kddTask.run(); } catch(AbortException e) { System.out.println(e.getMessage()); } catch(IllegalArgumentException e) { e.printStackTrace(); System.out.println(kddTask.usage(e.getMessage())); } catch(IllegalStateException e) { System.err.println(e.getMessage()); } } }
returns list of attribute settings instead of null - but empty so far
src/de/lmu/ifi/dbs/algorithm/KDDTask.java
returns list of attribute settings instead of null - but empty so far
Java
agpl-3.0
342cc40c33b4f539785f161f02d621a1d807d754
0
picoded/JavaCommons,picoded/JavaCommons,picoded/JavaCommons,picoded/JavaCommons,picoded/JavaCommons,picoded/JavaCommons,picoded/JavaCommons
package picoded.struct; import java.util.List; import java.util.UUID; import picoded.conv.GenericConvert; package picoded.struct; import java.util.List; import java.util.UUID; import picoded.conv.GenericConvert; /** * The <tt>List</tt> interface provides four methods for positional (indexed) * access to list elements. Lists (like Java arrays) are zero based. Note that * these operations may execute in time proportional to the index value for some * implementations (the <tt>LinkedList</tt> class, for example). Thus, iterating * over the elements in a list is typically preferable to indexing through it if * the caller does not know the implementation. * <p> * * The <tt>List</tt> interface provides a special iterator, called a * <tt>ListIterator</tt>, that allows element insertion and replacement, and * bidirectional access in addition to the normal operations that the * <tt>Iterator</tt> interface provides. A method is provided to obtain a list * iterator that starts at a specified position in the list. * <p> * * The <tt>List</tt> interface provides two methods to search for a specified * object. From a performance standpoint, these methods should be used with * caution. In many implementations they will perform costly linear searches. * <p> * * The <tt>List</tt> interface provides two methods to efficiently insert and * remove multiple elements at an arbitrary point in the list. * <p> * * Note: While it is permissible for lists to contain themselves as elements, * extreme caution is advised: the <tt>equals</tt> and <tt>hashCode</tt> methods * are no longer well defined on such a list. * * <p> * This interface is a member of the <a href="{@docRoot} * /../technotes/guides/collections/index.html"> Java Collections Framework</a>. * * @param <E> * the type of elements in this list * * @see List */ public interface GenericConvertList<E> extends UnsupportedDefaultList<E>{ // to string conversion //-------------------------------------------------------------------------------------------------- /// To String conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable, aka null) /// /// @returns The converted string, always possible unless null public default String getString(int index, String fallbck) { return GenericConvert.toString(get(index), fallbck); } /// Default null fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string, always possible unless null public default String getString(int index) { return GenericConvert.toString(get(index)); } // to boolean conversion //-------------------------------------------------------------------------------------------------- /// To boolean conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted string, always possible unless null public default boolean getBoolean(int index, boolean fallbck) { return GenericConvert.toBoolean(get(index), fallbck); } /// Default boolean fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string to boolean, always possible public default boolean getBoolean(int index) { return GenericConvert.toBoolean(get(index)); } // to Number conversion //-------------------------------------------------------------------------------------------------- /// To Number conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted string, always possible unless null public default Number getNumber(int index, Number fallbck) { return GenericConvert.toNumber(get(index), fallbck); } /// Default Number fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string, always possible unless null public default Number getNumber(int index) { return GenericConvert.toNumber(get(index)); } // to int conversion //-------------------------------------------------------------------------------------------------- /// To int conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted string, always possible unless null public default int getInt(int index, int fallbck) { return GenericConvert.toInt(get(index), fallbck); } /// Default int fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string, always possible unless null public default int getInt(String string) { return GenericConvert.toInt(get(string)); } // to long conversion //-------------------------------------------------------------------------------------------------- /// To long conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted string, always possible unless null public default long getLong(int index, long fallbck) { return GenericConvert.toLong(get(index), fallbck); } /// Default long fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string, always possible unless null public default long getLong(int index) { return GenericConvert.toLong(get(index)); } // to float conversion //-------------------------------------------------------------------------------------------------- /// To float conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted string, always possible unless null public default float getFloat(int index, float fallbck) { return GenericConvert.toFloat(get(index), fallbck); } /// Default float fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string, always possible unless null public default float getFloat(int index) { return GenericConvert.toFloat(get(index)); } // to double conversion //-------------------------------------------------------------------------------------------------- /// To double conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted string, always possible unless null public default double getDouble(int index, double fallbck) { return GenericConvert.toDouble(get(index), fallbck); } /// Default float fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string, always possible unless null public default double getDouble(int index) { return GenericConvert.toDouble(get(index)); } // to byte conversion //-------------------------------------------------------------------------------------------------- /// To byte conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted string, always possible unless null public default byte getByte(int index, byte fallbck) { return GenericConvert.toByte(get(index), fallbck); } /// Default float fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string, always possible unless null public default byte getByte(int index) { return GenericConvert.toByte(get(index)); } // to short conversion //-------------------------------------------------------------------------------------------------- /// To short conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted string, always possible unless null public default short getShort(int index, short fallbck) { return GenericConvert.toShort(get(index), fallbck); } /// Default short fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string, always possible unless null public default short getShort(int index) { return GenericConvert.toShort(get(index)); } // to UUID / GUID //-------------------------------------------------------------------------------------------------- /// To UUID conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted UUID, always possible unless null public default UUID getUUID(int index, Object fallbck) { return GenericConvert.toUUID(get(index), fallbck); } /// Default Null fallback, To UUID conversion of generic object /// /// @param input The input value to convert /// /// @returns The converted value public default UUID getUUID(int index) { return GenericConvert.toUUID(get(index)); } /// To GUID conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted UUID, always possible unless null public default String getGUID(int index, Object fallbck) { return GenericConvert.toGUID(get(index), fallbck); } /// Default Null fallback, To GUID conversion of generic object /// /// @param input The input value to convert /// /// @returns The converted value public default String getGUID(int index) { return GenericConvert.toGUID(get(index)); } // to list // @TODO generic list conversion //-------------------------------------------------------------------------------------------------- /// To List<Object> conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted Object[], always possible unless null public default List<Object> getObjectList(int index, Object fallbck) { return GenericConvert.toObjectList(get(index), fallbck); } /// Default Null fallback, To List<Object> conversion of generic object /// /// @param input The input value to convert /// /// @default The converted value public default List<Object> getObjectList(int index) { return GenericConvert.toObjectList(index); } // to array // @TODO generic array conversion //-------------------------------------------------------------------------------------------------- // to string array //-------------------------------------------------------------------------------------------------- /// To String[] conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted String[], always possible unless null public default String[] getStringArray(int index, Object fallbck) { return GenericConvert.toStringArray(get(index), fallbck); } /// Default Null fallback, To String[] conversion of generic object /// /// @param input The input value to convert /// /// @returns The converted value public default String[] getStringArray(String string) { return GenericConvert.toStringArray(get(string)); } // to object array //-------------------------------------------------------------------------------------------------- /// To Object[] conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted Object[], always possible unless null public default Object[] getObjectArray(int index, Object fallbck) { return GenericConvert.toObjectArray(index, fallbck); } /// Default Null fallback, To Object[] conversion of generic object /// /// @param input The input value to convert /// /// @default The converted value public default Object[] getObjectArray(int index) { return GenericConvert.toObjectArray(index); } // NESTED object fetch (related to fully qualified indexs handling) //-------------------------------------------------------------------------------------------------- /// /// Gets an object from the List, /// That could very well be, a list inside a list, inside a map, inside a ..... /// /// Note that at each iteration step, it attempts to do a FULL index match first, /// before the next iteration depth /// /// @param index The input index to fetch, possibly nested /// @param fallbck The fallback default (if not convertable) /// /// @returns The fetched object, always possible unless fallbck null public default Object getNestedObject(String index, Object fallbck) { return GenericConvert.fetchNestedObject(this, index, fallbck); } /// /// Default Null fallback, for `getNestedObject(index,fallback)` /// /// @param index The input index to fetch, possibly nested /// /// @returns The fetched object, always possible unless fallbck null public default Object getNestedObject(String index) { return getNestedObject(index,null); } } /** * The <tt>List</tt> interface provides four methods for positional (indexed) * access to list elements. Lists (like Java arrays) are zero based. Note that * these operations may execute in time proportional to the index value for some * implementations (the <tt>LinkedList</tt> class, for example). Thus, iterating * over the elements in a list is typically preferable to indexing through it if * the caller does not know the implementation. * <p> * * The <tt>List</tt> interface provides a special iterator, called a * <tt>ListIterator</tt>, that allows element insertion and replacement, and * bidirectional access in addition to the normal operations that the * <tt>Iterator</tt> interface provides. A method is provided to obtain a list * iterator that starts at a specified position in the list. * <p> * * The <tt>List</tt> interface provides two methods to search for a specified * object. From a performance standpoint, these methods should be used with * caution. In many implementations they will perform costly linear searches. * <p> * * The <tt>List</tt> interface provides two methods to efficiently insert and * remove multiple elements at an arbitrary point in the list. * <p> * * Note: While it is permissible for lists to contain themselves as elements, * extreme caution is advised: the <tt>equals</tt> and <tt>hashCode</tt> methods * are no longer well defined on such a list. * * <p> * This interface is a member of the <a href="{@docRoot} * /../technotes/guides/collections/index.html"> Java Collections Framework</a>. * * @param <E> * the type of elements in this list * * @see List */ public interface GenericConvertList<E> extends UnsupportedDefaultList<E>{ // to string conversion //-------------------------------------------------------------------------------------------------- /// To String conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable, aka null) /// /// @returns The converted string, always possible unless null public default String getString(int index, String fallbck) { return GenericConvert.toString(get(index), fallbck); } /// Default null fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string, always possible unless null public default String getString(int index) { return GenericConvert.toString(get(index)); } // to boolean conversion //-------------------------------------------------------------------------------------------------- /// To boolean conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted string, always possible unless null public default boolean getBoolean(int index, boolean fallbck) { return GenericConvert.toBoolean(get(index), fallbck); } /// Default boolean fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string, always possible unless null public default boolean getBoolean(int index) { return GenericConvert.toBoolean(get(index)); } // to Number conversion //-------------------------------------------------------------------------------------------------- /// To Number conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted string, always possible unless null public default Number getNumber(int index, Number fallbck) { return GenericConvert.toNumber(get(index), fallbck); } /// Default Number fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string, always possible unless null public default Number getNumber(int index) { return GenericConvert.toNumber(get(index)); } // to int conversion //-------------------------------------------------------------------------------------------------- /// To int conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted string, always possible unless null public default int getInt(int index, int fallbck) { return GenericConvert.toInt(get(index), fallbck); } /// Default int fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string, always possible unless null public default int getInt(String string) { return GenericConvert.toInt(get(string)); } // to long conversion //-------------------------------------------------------------------------------------------------- /// To long conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted string, always possible unless null public default long getLong(int index, long fallbck) { return GenericConvert.toLong(get(index), fallbck); } /// Default long fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string, always possible unless null public default long getLong(int index) { return GenericConvert.toLong(get(index)); } // to float conversion //-------------------------------------------------------------------------------------------------- /// To float conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted string, always possible unless null public default float getFloat(int index, float fallbck) { return GenericConvert.toFloat(get(index), fallbck); } /// Default float fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string, always possible unless null public default float getFloat(int index) { return GenericConvert.toFloat(get(index)); } // to double conversion //-------------------------------------------------------------------------------------------------- /// To double conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted string, always possible unless null public default double getDouble(int index, double fallbck) { return GenericConvert.toDouble(get(index), fallbck); } /// Default float fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string, always possible unless null public default double getDouble(int index) { return GenericConvert.toDouble(get(index)); } // to byte conversion //-------------------------------------------------------------------------------------------------- /// To byte conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted string, always possible unless null public default byte getByte(int index, byte fallbck) { return GenericConvert.toByte(get(index), fallbck); } /// Default float fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string, always possible unless null public default byte getByte(int index) { return GenericConvert.toByte(get(index)); } // to short conversion //-------------------------------------------------------------------------------------------------- /// To short conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted string, always possible unless null public default short getShort(int index, short fallbck) { return GenericConvert.toShort(get(index), fallbck); } /// Default short fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string, always possible unless null public default short getShort(int index) { return GenericConvert.toShort(get(index)); } // to UUID / GUID //-------------------------------------------------------------------------------------------------- /// To UUID conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted UUID, always possible unless null public default UUID getUUID(int index, Object fallbck) { return GenericConvert.toUUID(get(index), fallbck); } /// Default Null fallback, To UUID conversion of generic object /// /// @param input The input value to convert /// /// @returns The converted value public default UUID getUUID(int index) { return GenericConvert.toUUID(get(index)); } /// To GUID conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted UUID, always possible unless null public default String getGUID(int index, Object fallbck) { return GenericConvert.toGUID(get(index), fallbck); } /// Default Null fallback, To GUID conversion of generic object /// /// @param input The input value to convert /// /// @returns The converted value public default String getGUID(int index) { return GenericConvert.toGUID(get(index)); } // to list // @TODO generic list conversion //-------------------------------------------------------------------------------------------------- /// To List<Object> conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted Object[], always possible unless null public default List<Object> getObjectList(int index, Object fallbck) { return GenericConvert.toObjectList(get(index), fallbck); } /// Default Null fallback, To List<Object> conversion of generic object /// /// @param input The input value to convert /// /// @default The converted value public default List<Object> getObjectList(int index) { return GenericConvert.toObjectList(index); } // to array // @TODO generic array conversion //-------------------------------------------------------------------------------------------------- // to string array //-------------------------------------------------------------------------------------------------- /// To String[] conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted String[], always possible unless null public default String[] getStringArray(int index, Object fallbck) { return GenericConvert.toStringArray(get(index), fallbck); } /// Default Null fallback, To String[] conversion of generic object /// /// @param input The input value to convert /// /// @returns The converted value public default String[] getStringArray(String string) { return GenericConvert.toStringArray(get(string)); } // to object array //-------------------------------------------------------------------------------------------------- /// To Object[] conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted Object[], always possible unless null public default Object[] getObjectArray(int index, Object fallbck) { return GenericConvert.toObjectArray(index, fallbck); } /// Default Null fallback, To Object[] conversion of generic object /// /// @param input The input value to convert /// /// @default The converted value public default Object[] getObjectArray(int index) { return GenericConvert.toObjectArray(index); } // NESTED object fetch (related to fully qualified indexs handling) //-------------------------------------------------------------------------------------------------- /// /// Gets an object from the map, /// That could very well be, a map inside a list, inside a map, inside a ..... /// /// Note that at each iteration step, it attempts to do a FULL index match first, /// before the next iteration depth /// /// @param base Map / List to manipulate from /// @param index The input index to fetch, possibly nested /// @param fallbck The fallback default (if not convertable) /// /// @returns The fetched object, always possible unless fallbck null public default Object getNestedObject(String index, Object fallbck) { return GenericConvert.fetchNestedObject(this, index, fallbck); } /// /// Default Null fallback, for `getNestedObject(index,fallback)` /// /// @param base Map / List to manipulate from /// @param index The input index to fetch, possibly nested /// /// @returns The fetched object, always possible unless fallbck null public default Object getNestedObject(String index) { return getNestedObject(index,null); } }
src/picoded/struct/GenericConvertList.java
package picoded.struct; import java.util.List; import java.util.UUID; import picoded.conv.GenericConvert; /** * The <tt>List</tt> interface provides four methods for positional (indexed) * access to list elements. Lists (like Java arrays) are zero based. Note that * these operations may execute in time proportional to the index value for some * implementations (the <tt>LinkedList</tt> class, for example). Thus, iterating * over the elements in a list is typically preferable to indexing through it if * the caller does not know the implementation. * <p> * * The <tt>List</tt> interface provides a special iterator, called a * <tt>ListIterator</tt>, that allows element insertion and replacement, and * bidirectional access in addition to the normal operations that the * <tt>Iterator</tt> interface provides. A method is provided to obtain a list * iterator that starts at a specified position in the list. * <p> * * The <tt>List</tt> interface provides two methods to search for a specified * object. From a performance standpoint, these methods should be used with * caution. In many implementations they will perform costly linear searches. * <p> * * The <tt>List</tt> interface provides two methods to efficiently insert and * remove multiple elements at an arbitrary point in the list. * <p> * * Note: While it is permissible for lists to contain themselves as elements, * extreme caution is advised: the <tt>equals</tt> and <tt>hashCode</tt> methods * are no longer well defined on such a list. * * <p> * This interface is a member of the <a href="{@docRoot} * /../technotes/guides/collections/index.html"> Java Collections Framework</a>. * * @param <E> * the type of elements in this list * * @see List */ public interface GenericConvertList<E> extends UnsupportedDefaultList<E>{ // to string conversion //-------------------------------------------------------------------------------------------------- /// To String conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable, aka null) /// /// @returns The converted string, always possible unless null public default String getString(int index, String fallbck) { return GenericConvert.toString(get(index), fallbck); } /// Default null fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string, always possible unless null public default String getString(int index) { return GenericConvert.toString(get(index)); } // to boolean conversion //-------------------------------------------------------------------------------------------------- /// To boolean conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted string, always possible unless null public default boolean getBoolean(int index, boolean fallbck) { return GenericConvert.toBoolean(get(index), fallbck); } /// Default boolean fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string, always possible unless null public default boolean getBoolean(int index) { return GenericConvert.toBoolean(get(index)); } // to Number conversion //-------------------------------------------------------------------------------------------------- /// To Number conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted string, always possible unless null public default Number getNumber(int index, Number fallbck) { return GenericConvert.toNumber(get(index), fallbck); } /// Default Number fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string, always possible unless null public default Number getNumber(int index) { return GenericConvert.toNumber(get(index)); } // to int conversion //-------------------------------------------------------------------------------------------------- /// To int conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted string, always possible unless null public default int getInt(int index, int fallbck) { return GenericConvert.toInt(get(index), fallbck); } /// Default int fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string, always possible unless null public default int getInt(String string) { return GenericConvert.toInt(get(string)); } // to long conversion //-------------------------------------------------------------------------------------------------- /// To long conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted string, always possible unless null public default long getLong(int index, long fallbck) { return GenericConvert.toLong(get(index), fallbck); } /// Default long fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string, always possible unless null public default long getLong(int index) { return GenericConvert.toLong(get(index)); } // to float conversion //-------------------------------------------------------------------------------------------------- /// To float conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted string, always possible unless null public default float getFloat(int index, float fallbck) { return GenericConvert.toFloat(get(index), fallbck); } /// Default float fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string, always possible unless null public default float getFloat(int index) { return GenericConvert.toFloat(get(index)); } // to double conversion //-------------------------------------------------------------------------------------------------- /// To double conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted string, always possible unless null public default double getDouble(int index, double fallbck) { return GenericConvert.toDouble(get(index), fallbck); } /// Default float fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string, always possible unless null public default double getDouble(int index) { return GenericConvert.toDouble(get(index)); } // to byte conversion //-------------------------------------------------------------------------------------------------- /// To byte conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted string, always possible unless null public default byte getByte(int index, byte fallbck) { return GenericConvert.toByte(get(index), fallbck); } /// Default float fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string, always possible unless null public default byte getByte(int index) { return GenericConvert.toByte(get(index)); } // to short conversion //-------------------------------------------------------------------------------------------------- /// To short conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted string, always possible unless null public default short getShort(int index, short fallbck) { return GenericConvert.toShort(get(index), fallbck); } /// Default short fallback, To String conversion of generic object /// /// @param index The input value index to convert /// /// @returns The converted string, always possible unless null public default short getShort(int index) { return GenericConvert.toShort(get(index)); } // to UUID / GUID //-------------------------------------------------------------------------------------------------- /// To UUID conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted UUID, always possible unless null public default UUID getUUID(int index, Object fallbck) { return GenericConvert.toUUID(get(index), fallbck); } /// Default Null fallback, To UUID conversion of generic object /// /// @param input The input value to convert /// /// @returns The converted value public default UUID getUUID(int index) { return GenericConvert.toUUID(get(index)); } /// To GUID conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted UUID, always possible unless null public default String getGUID(int index, Object fallbck) { return GenericConvert.toGUID(get(index), fallbck); } /// Default Null fallback, To GUID conversion of generic object /// /// @param input The input value to convert /// /// @returns The converted value public default String getGUID(int index) { return GenericConvert.toGUID(get(index)); } // to list // @TODO generic list conversion //-------------------------------------------------------------------------------------------------- /// To List<Object> conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted Object[], always possible unless null public default List<Object> getObjectList(int index, Object fallbck) { return GenericConvert.toObjectList(get(index), fallbck); } /// Default Null fallback, To List<Object> conversion of generic object /// /// @param input The input value to convert /// /// @default The converted value public default List<Object> getObjectList(int index) { return GenericConvert.toObjectList(index); } // to array // @TODO generic array conversion //-------------------------------------------------------------------------------------------------- // to string array //-------------------------------------------------------------------------------------------------- /// To String[] conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted String[], always possible unless null public default String[] getStringArray(int index, Object fallbck) { return GenericConvert.toStringArray(get(index), fallbck); } /// Default Null fallback, To String[] conversion of generic object /// /// @param input The input value to convert /// /// @returns The converted value public default String[] getStringArray(String string) { return GenericConvert.toStringArray(get(string)); } // to object array //-------------------------------------------------------------------------------------------------- /// To Object[] conversion of generic object /// /// @param index The input value index to convert /// @param fallbck The fallback default (if not convertable) /// /// @returns The converted Object[], always possible unless null public default Object[] getObjectArray(int index, Object fallbck) { return GenericConvert.toObjectArray(index, fallbck); } /// Default Null fallback, To Object[] conversion of generic object /// /// @param input The input value to convert /// /// @default The converted value public default Object[] getObjectArray(int index) { return GenericConvert.toObjectArray(index); } // NESTED object fetch (related to fully qualified indexs handling) //-------------------------------------------------------------------------------------------------- /// /// Gets an object from the map, /// That could very well be, a map inside a list, inside a map, inside a ..... /// /// Note that at each iteration step, it attempts to do a FULL index match first, /// before the next iteration depth /// /// @param base Map / List to manipulate from /// @param index The input index to fetch, possibly nested /// @param fallbck The fallback default (if not convertable) /// /// @returns The fetched object, always possible unless fallbck null public default Object getNestedObject(String index, Object fallbck) { return GenericConvert.fetchNestedObject(this, index, fallbck); } /// /// Default Null fallback, for `getNestedObject(index,fallback)` /// /// @param base Map / List to manipulate from /// @param index The input index to fetch, possibly nested /// /// @returns The fetched object, always possible unless fallbck null public default Object getNestedObject(String index) { return getNestedObject(index,null); } }
changes for documentation
src/picoded/struct/GenericConvertList.java
changes for documentation
Java
lgpl-2.1
ae70b93d7402d710581dffb9b32eb893fe411ac2
0
alkacon/opencms-core,gallardo/opencms-core,alkacon/opencms-core,gallardo/opencms-core,gallardo/opencms-core,gallardo/opencms-core,alkacon/opencms-core,alkacon/opencms-core
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.jsp.util; import org.opencms.ade.configuration.CmsADEConfigData; import org.opencms.ade.configuration.CmsADEManager; import org.opencms.ade.configuration.CmsFunctionReference; import org.opencms.ade.containerpage.CmsContainerpageService; import org.opencms.ade.containerpage.CmsModelGroupHelper; import org.opencms.ade.containerpage.shared.CmsFormatterConfig; import org.opencms.ade.containerpage.shared.CmsInheritanceInfo; import org.opencms.ade.detailpage.CmsDetailPageInfo; import org.opencms.ade.detailpage.CmsDetailPageResourceHandler; import org.opencms.file.CmsFile; import org.opencms.file.CmsObject; import org.opencms.file.CmsPropertyDefinition; import org.opencms.file.CmsRequestContext; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.file.history.CmsHistoryResourceHandler; import org.opencms.flex.CmsFlexController; import org.opencms.flex.CmsFlexRequest; import org.opencms.gwt.shared.CmsGwtConstants; import org.opencms.i18n.CmsLocaleGroupService; import org.opencms.jsp.CmsJspBean; import org.opencms.jsp.CmsJspResourceWrapper; import org.opencms.jsp.CmsJspTagContainer; import org.opencms.jsp.CmsJspTagEditable; import org.opencms.jsp.Messages; import org.opencms.jsp.jsonpart.CmsJsonPartFilter; import org.opencms.loader.CmsTemplateContextManager; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.main.CmsRuntimeException; import org.opencms.main.CmsSystemInfo; import org.opencms.main.OpenCms; import org.opencms.relations.CmsCategory; import org.opencms.relations.CmsCategoryService; import org.opencms.site.CmsSite; import org.opencms.util.CmsCollectionsGenericWrapper; import org.opencms.util.CmsMacroResolver; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import org.opencms.xml.containerpage.CmsADESessionCache; import org.opencms.xml.containerpage.CmsContainerBean; import org.opencms.xml.containerpage.CmsContainerElementBean; import org.opencms.xml.containerpage.CmsContainerPageBean; import org.opencms.xml.containerpage.CmsDynamicFunctionBean; import org.opencms.xml.containerpage.CmsDynamicFunctionParser; import org.opencms.xml.containerpage.CmsFormatterConfiguration; import org.opencms.xml.containerpage.CmsMetaMapping; import org.opencms.xml.containerpage.CmsXmlContainerPage; import org.opencms.xml.containerpage.CmsXmlContainerPageFactory; import org.opencms.xml.containerpage.I_CmsFormatterBean; import org.opencms.xml.content.CmsXmlContent; import org.opencms.xml.content.CmsXmlContentFactory; import org.opencms.xml.types.I_CmsXmlContentValue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import org.apache.commons.collections.Transformer; import org.apache.commons.lang3.LocaleUtils; import org.apache.commons.logging.Log; /** * Allows convenient access to the most important OpenCms functions on a JSP page, * indented to be used from a JSP with the JSTL or EL.<p> * * This bean is available by default in the context of an OpenCms managed JSP.<p> * * @since 8.0 */ public final class CmsJspStandardContextBean { /** * Container element wrapper to add some API methods.<p> */ public class CmsContainerElementWrapper extends CmsContainerElementBean { /** The wrapped element instance. */ private CmsContainerElementBean m_wrappedElement; /** * Constructor.<p> * * @param element the element to wrap */ protected CmsContainerElementWrapper(CmsContainerElementBean element) { m_wrappedElement = element; } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#clone() */ @Override public CmsContainerElementBean clone() { return m_wrappedElement.clone(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#editorHash() */ @Override public String editorHash() { return m_wrappedElement.editorHash(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { return m_wrappedElement.equals(obj); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#getFormatterId() */ @Override public CmsUUID getFormatterId() { return m_wrappedElement.getFormatterId(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#getId() */ @Override public CmsUUID getId() { return m_wrappedElement.getId(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#getIndividualSettings() */ @Override public Map<String, String> getIndividualSettings() { return m_wrappedElement.getIndividualSettings(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#getInheritanceInfo() */ @Override public CmsInheritanceInfo getInheritanceInfo() { return m_wrappedElement.getInheritanceInfo(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#getInstanceId() */ @Override public String getInstanceId() { return m_wrappedElement.getInstanceId(); } /** * Returns the parent element if present.<p> * * @return the parent element or <code>null</code> if not available */ public CmsContainerElementWrapper getParent() { CmsContainerElementBean parent = getParentElement(m_wrappedElement); return parent != null ? new CmsContainerElementWrapper(getParentElement(m_wrappedElement)) : null; } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#getResource() */ @Override public CmsResource getResource() { return m_wrappedElement.getResource(); } /** * Returns the resource type name of the element resource.<p> * * @return the resource type name */ public String getResourceTypeName() { String result = ""; try { result = OpenCms.getResourceManager().getResourceType(m_wrappedElement.getResource()).getTypeName(); } catch (Exception e) { CmsJspStandardContextBean.LOG.error(e.getLocalizedMessage(), e); } return result; } /** * Returns a lazy initialized setting map.<p> * * @return the settings */ public Map<String, ElementSettingWrapper> getSetting() { return CmsCollectionsGenericWrapper.createLazyMap(new SettingsTransformer(m_wrappedElement)); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#getSettings() */ @Override public Map<String, String> getSettings() { return m_wrappedElement.getSettings(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#getSitePath() */ @Override public String getSitePath() { return m_wrappedElement.getSitePath(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#hashCode() */ @Override public int hashCode() { return m_wrappedElement.hashCode(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#initResource(org.opencms.file.CmsObject) */ @Override public void initResource(CmsObject cms) throws CmsException { m_wrappedElement.initResource(cms); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#initSettings(org.opencms.file.CmsObject, org.opencms.xml.containerpage.I_CmsFormatterBean) */ @Override public void initSettings(CmsObject cms, I_CmsFormatterBean formatterBean) { m_wrappedElement.initSettings(cms, formatterBean); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#isCreateNew() */ @Override public boolean isCreateNew() { return m_wrappedElement.isCreateNew(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#isGroupContainer(org.opencms.file.CmsObject) */ @Override public boolean isGroupContainer(CmsObject cms) throws CmsException { return m_wrappedElement.isGroupContainer(cms); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#isInheritedContainer(org.opencms.file.CmsObject) */ @Override public boolean isInheritedContainer(CmsObject cms) throws CmsException { return m_wrappedElement.isInheritedContainer(cms); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#isInMemoryOnly() */ @Override public boolean isInMemoryOnly() { return m_wrappedElement.isInMemoryOnly(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#isReleasedAndNotExpired() */ @Override public boolean isReleasedAndNotExpired() { return m_wrappedElement.isReleasedAndNotExpired(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#isTemporaryContent() */ @Override public boolean isTemporaryContent() { return m_wrappedElement.isTemporaryContent(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#removeInstanceId() */ @Override public void removeInstanceId() { m_wrappedElement.removeInstanceId(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#setFormatterId(org.opencms.util.CmsUUID) */ @Override public void setFormatterId(CmsUUID formatterId) { m_wrappedElement.setFormatterId(formatterId); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#setHistoryFile(org.opencms.file.CmsFile) */ @Override public void setHistoryFile(CmsFile file) { m_wrappedElement.setHistoryFile(file); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#setInheritanceInfo(org.opencms.ade.containerpage.shared.CmsInheritanceInfo) */ @Override public void setInheritanceInfo(CmsInheritanceInfo inheritanceInfo) { m_wrappedElement.setInheritanceInfo(inheritanceInfo); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#setTemporaryFile(org.opencms.file.CmsFile) */ @Override public void setTemporaryFile(CmsFile elementFile) { m_wrappedElement.setTemporaryFile(elementFile); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#toString() */ @Override public String toString() { return m_wrappedElement.toString(); } } /** * Provides a lazy initialized Map that provides the detail page link as a value when given the name of a * (named) dynamic function or resource type as a key.<p> */ public class CmsDetailLookupTransformer implements Transformer { /** The selected prefix. */ private String m_prefix; /** * Constructor with a prefix.<p> * * The prefix is used to distinguish between type detail pages and function detail pages.<p> * * @param prefix the prefix to use */ public CmsDetailLookupTransformer(String prefix) { m_prefix = prefix; } /** * @see org.apache.commons.collections.Transformer#transform(java.lang.Object) */ @Override public Object transform(Object input) { String type = m_prefix + String.valueOf(input); CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration( m_cms, m_cms.addSiteRoot(m_cms.getRequestContext().getUri())); List<CmsDetailPageInfo> detailPages = config.getDetailPagesForType(type); if ((detailPages == null) || (detailPages.size() == 0)) { return "[No detail page configured for type =" + type + "=]"; } CmsDetailPageInfo mainDetailPage = detailPages.get(0); CmsUUID id = mainDetailPage.getId(); try { CmsResource r = m_cms.readResource(id); return OpenCms.getLinkManager().substituteLink(m_cms, r); } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); return "[Error reading detail page for type =" + type + "=]"; } } } /** * Element setting value wrapper.<p> */ public class ElementSettingWrapper extends A_CmsJspValueWrapper { /** Flag indicating the setting has been configured. */ private boolean m_exists; /** The wrapped value. */ private String m_value; /** * Constructor.<p> * * @param value the wrapped value * @param exists flag indicating the setting has been configured */ ElementSettingWrapper(String value, boolean exists) { m_value = value; m_exists = exists; } /** * Returns if the setting has been configured.<p> * * @return <code>true</code> if the setting has been configured */ @Override public boolean getExists() { return m_exists; } /** * Returns if the setting value is null or empty.<p> * * @return <code>true</code> if the setting value is null or empty */ @Override public boolean getIsEmpty() { return CmsStringUtil.isEmpty(m_value); } /** * Returns if the setting value is null or white space only.<p> * * @return <code>true</code> if the setting value is null or white space only */ @Override public boolean getIsEmptyOrWhitespaceOnly() { return CmsStringUtil.isEmptyOrWhitespaceOnly(m_value); } /** * @see org.opencms.jsp.util.A_CmsJspValueWrapper#getIsSet() */ @Override public boolean getIsSet() { return getExists() && !getIsEmpty(); } /** * Returns the value.<p> * * @return the value */ public String getValue() { return m_value; } /** * Returns the string value.<p> * * @return the string value */ @Override public String toString() { return m_value != null ? m_value : ""; } } /** * The element setting transformer.<p> */ public class SettingsTransformer implements Transformer { /** The element formatter config. */ private I_CmsFormatterBean m_formatter; /** The element. */ private CmsContainerElementBean m_transformElement; /** * Constructor.<p> * * @param element the element */ SettingsTransformer(CmsContainerElementBean element) { m_transformElement = element; m_formatter = getElementFormatter(element); } /** * @see org.apache.commons.collections.Transformer#transform(java.lang.Object) */ @Override public Object transform(Object arg0) { return new ElementSettingWrapper( m_transformElement.getSettings().get(arg0), m_formatter != null ? m_formatter.getSettings().get(arg0) != null : m_transformElement.getSettings().get(arg0) != null); } } /** * Bean containing a template name and URI.<p> */ public static class TemplateBean { /** True if the template context was manually selected. */ private boolean m_forced; /** The template name. */ private String m_name; /** The template resource. */ private CmsResource m_resource; /** The template uri, if no resource is set. */ private String m_uri; /** * Creates a new instance.<p> * * @param name the template name * @param resource the template resource */ public TemplateBean(String name, CmsResource resource) { m_resource = resource; m_name = name; } /** * Creates a new instance with an URI instead of a resoure.<p> * * @param name the template name * @param uri the template uri */ public TemplateBean(String name, String uri) { m_name = name; m_uri = uri; } /** * Gets the template name.<p> * * @return the template name */ public String getName() { return m_name; } /** * Gets the template resource.<p> * * @return the template resource */ public CmsResource getResource() { return m_resource; } /** * Gets the template uri.<p> * * @return the template URI. */ public String getUri() { if (m_resource != null) { return m_resource.getRootPath(); } else { return m_uri; } } /** * Returns true if the template context was manually selected.<p> * * @return true if the template context was manually selected */ public boolean isForced() { return m_forced; } /** * Sets the 'forced' flag to a new value.<p> * * @param forced the new value */ public void setForced(boolean forced) { m_forced = forced; } } /** * The meta mappings transformer.<p> */ class MetaLookupTranformer implements Transformer { /** * @see org.apache.commons.collections.Transformer#transform(java.lang.Object) */ public Object transform(Object arg0) { String result = null; if (m_metaMappings.containsKey(arg0)) { MetaMapping mapping = m_metaMappings.get(arg0); try { CmsResourceFilter filter = getIsEditMode() ? CmsResourceFilter.IGNORE_EXPIRATION : CmsResourceFilter.DEFAULT; CmsResource res = m_cms.readResource(mapping.m_contentId, filter); CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, res, m_request); if (content.hasLocale(getLocale())) { I_CmsXmlContentValue val = content.getValue(mapping.m_elementXPath, getLocale()); if (val != null) { result = val.getStringValue(m_cms); } } } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); } if (result == null) { result = mapping.m_defaultValue; } } return result; } } /** The meta mapping data. */ class MetaMapping { /** The mapping key. */ String m_key; /** The mapping value xpath. */ String m_elementXPath; /** The mapping order. */ int m_order; /** The mapping content structure id. */ CmsUUID m_contentId; /** The default value. */ String m_defaultValue; } /** The attribute name of the cms object.*/ public static final String ATTRIBUTE_CMS_OBJECT = "__cmsObject"; /** The attribute name of the standard JSP context bean. */ public static final String ATTRIBUTE_NAME = "cms"; /** The logger instance for this class. */ protected static final Log LOG = CmsLog.getLog(CmsJspStandardContextBean.class); /** OpenCms user context. */ protected CmsObject m_cms; /** Lazily initialized map from a category path to all sub-categories of that category. */ private Map<String, CmsJspCategoryAccessBean> m_allSubCategories; /** Lazily initialized map from a category path to the path's category object. */ private Map<String, CmsCategory> m_categories; /** The container the currently rendered element is part of. */ private CmsContainerBean m_container; /** The current detail content resource if available. */ private CmsResource m_detailContentResource; /** The detail only page references containers that are only displayed in detail view. */ private CmsContainerPageBean m_detailOnlyPage; /** Flag to indicate if element was just edited. */ private boolean m_edited; /** The currently rendered element. */ private CmsContainerElementBean m_element; /** The elements of the current page. */ private Map<String, CmsContainerElementBean> m_elementInstances; /** The lazy initialized map which allows access to the dynamic function beans. */ private Map<String, CmsDynamicFunctionBeanWrapper> m_function; /** The lazy initialized map for the function detail pages. */ private Map<String, String> m_functionDetailPage; /** Indicates if in drag mode. */ private boolean m_isDragMode; /** Stores the edit mode info. */ private Boolean m_isEditMode; /** Lazily initialized map from the locale to the localized title property. */ private Map<String, String> m_localeTitles; /** The currently displayed container page. */ private CmsContainerPageBean m_page; /** The current container page resource, lazy initialized. */ private CmsResource m_pageResource; /** The parent containers to the given element instance ids. */ private Map<String, CmsContainerBean> m_parentContainers; /** Lazily initialized map from a category path to all categories on that path. */ private Map<String, List<CmsCategory>> m_pathCategories; /** The current request. */ ServletRequest m_request; /** Lazily initialized map from the root path of a resource to all categories assigned to the resource. */ private Map<String, CmsJspCategoryAccessBean> m_resourceCategories; /** The resource wrapper for the current page. */ private CmsJspResourceWrapper m_resourceWrapper; /** The lazy initialized map for the detail pages. */ private Map<String, String> m_typeDetailPage; /** The VFS content access bean. */ private CmsJspVfsAccessBean m_vfsBean; /** The meta mapping configuration. */ Map<String, MetaMapping> m_metaMappings; /** Map from root paths to site relative paths. */ private Map<String, String> m_sitePaths; /** * Creates an empty instance.<p> */ private CmsJspStandardContextBean() { // NOOP } /** * Creates a new standard JSP context bean. * * @param req the current servlet request */ private CmsJspStandardContextBean(ServletRequest req) { CmsFlexController controller = CmsFlexController.getController(req); m_request = req; CmsObject cms; if (controller != null) { cms = controller.getCmsObject(); } else { cms = (CmsObject)req.getAttribute(ATTRIBUTE_CMS_OBJECT); } if (cms == null) { // cms object unavailable - this request was not initialized properly throw new CmsRuntimeException( Messages.get().container(Messages.ERR_MISSING_CMS_CONTROLLER_1, CmsJspBean.class.getName())); } updateCmsObject(cms); m_detailContentResource = CmsDetailPageResourceHandler.getDetailResource(req); } /** * Creates a new instance of the standard JSP context bean.<p> * * To prevent multiple creations of the bean during a request, the OpenCms request context * attributes are used to cache the created VFS access utility bean.<p> * * @param req the current servlet request * * @return a new instance of the standard JSP context bean */ public static CmsJspStandardContextBean getInstance(ServletRequest req) { Object attribute = req.getAttribute(ATTRIBUTE_NAME); CmsJspStandardContextBean result; if ((attribute != null) && (attribute instanceof CmsJspStandardContextBean)) { result = (CmsJspStandardContextBean)attribute; } else { result = new CmsJspStandardContextBean(req); req.setAttribute(ATTRIBUTE_NAME, result); } return result; } /** * Returns a copy of this JSP context bean.<p> * * @return a copy of this JSP context bean */ public CmsJspStandardContextBean createCopy() { CmsJspStandardContextBean result = new CmsJspStandardContextBean(); result.m_container = m_container; if (m_detailContentResource != null) { result.m_detailContentResource = m_detailContentResource.getCopy(); } result.m_element = m_element; result.setPage(m_page); return result; } /** * Returns a caching hash specific to the element, it's properties and the current container width.<p> * * @return the caching hash */ public String elementCachingHash() { String result = ""; if (m_element != null) { result = m_element.editorHash(); if (m_container != null) { result += "w:" + m_container.getWidth() + "cName:" + m_container.getName() + "cType:" + m_container.getType(); } } return result; } /** * Returns the locales available for the currently requested URI. * * @return the locales available for the currently requested URI. */ public List<Locale> getAvailableLocales() { return OpenCms.getLocaleManager().getAvailableLocales(m_cms, getRequestContext().getUri()); } /** * Returns the container the currently rendered element is part of.<p> * * @return the currently the currently rendered element is part of */ public CmsContainerBean getContainer() { return m_container; } /** * Returns the current detail content, or <code>null</code> if no detail content is requested.<p> * * @return the current detail content, or <code>null</code> if no detail content is requested.<p> */ public CmsResource getDetailContent() { return m_detailContentResource; } /** * Returns the structure id of the current detail content, or <code>null</code> if no detail content is requested.<p> * * @return the structure id of the current detail content, or <code>null</code> if no detail content is requested.<p> */ public CmsUUID getDetailContentId() { return m_detailContentResource == null ? null : m_detailContentResource.getStructureId(); } /** * Returns the detail content site path, or <code>null</code> if not available.<p> * * @return the detail content site path */ public String getDetailContentSitePath() { return ((m_cms == null) || (m_detailContentResource == null)) ? null : m_cms.getSitePath(m_detailContentResource); } /** * Returns the detail only page.<p> * * @return the detail only page */ public CmsContainerPageBean getDetailOnlyPage() { return m_detailOnlyPage; } /** * Returns the currently rendered element.<p> * * @return the currently rendered element */ public CmsContainerElementWrapper getElement() { return m_element != null ? new CmsContainerElementWrapper(m_element) : null; } /** * Alternative method name for getReloadMarker(). * * @see org.opencms.jsp.util.CmsJspStandardContextBean#getReloadMarker() * * @return the reload marker */ public String getEnableReload() { return getReloadMarker(); } /** * Returns a lazy initialized Map which allows access to the dynamic function beans using the JSP EL.<p> * * When given a key, the returned map will look up the corresponding dynamic function bean in the module configuration.<p> * * @return a lazy initialized Map which allows access to the dynamic function beans using the JSP EL */ public Map<String, CmsDynamicFunctionBeanWrapper> getFunction() { if (m_function == null) { Transformer transformer = new Transformer() { @Override public Object transform(Object input) { try { CmsDynamicFunctionBean dynamicFunction = readDynamicFunctionBean((String)input); CmsDynamicFunctionBeanWrapper wrapper = new CmsDynamicFunctionBeanWrapper( m_cms, dynamicFunction); return wrapper; } catch (CmsException e) { LOG.debug(e.getLocalizedMessage(), e); return new CmsDynamicFunctionBeanWrapper(m_cms, null); } } }; m_function = CmsCollectionsGenericWrapper.createLazyMap(transformer); } return m_function; } /** * Deprecated method to access function detail pages using the EL.<p> * * @return a lazy initialized Map that provides the detail page link as a value when given the name of a * (named) dynamic function as a key * * @deprecated use {@link #getFunctionDetailPage()} instead */ @Deprecated public Map<String, String> getFunctionDetail() { return getFunctionDetailPage(); } /** * Returns a lazy initialized Map that provides the detail page link as a value when given the name of a * (named) dynamic function as a key.<p> * * The provided Map key is assumed to be a String that represents a named dynamic function.<p> * * Usage example on a JSP with the JSTL:<pre> * &lt;a href=${cms.functionDetailPage['search']} /&gt * </pre> * * @return a lazy initialized Map that provides the detail page link as a value when given the name of a * (named) dynamic function as a key * * @see #getTypeDetailPage() */ public Map<String, String> getFunctionDetailPage() { if (m_functionDetailPage == null) { m_functionDetailPage = CmsCollectionsGenericWrapper.createLazyMap( new CmsDetailLookupTransformer(CmsDetailPageInfo.FUNCTION_PREFIX)); } return m_functionDetailPage; } /** * Returns a lazy map which creates a wrapper object for a dynamic function format when given an XML content * as a key.<p> * * @return a lazy map for accessing function formats for a content */ public Map<CmsJspContentAccessBean, CmsDynamicFunctionFormatWrapper> getFunctionFormatFromContent() { Transformer transformer = new Transformer() { @Override public Object transform(Object contentAccess) { CmsXmlContent content = (CmsXmlContent)(((CmsJspContentAccessBean)contentAccess).getRawContent()); CmsDynamicFunctionParser parser = new CmsDynamicFunctionParser(); CmsDynamicFunctionBean functionBean = null; try { functionBean = parser.parseFunctionBean(m_cms, content); } catch (CmsException e) { LOG.debug(e.getLocalizedMessage(), e); return new CmsDynamicFunctionFormatWrapper(m_cms, null); } String type = getContainer().getType(); String width = getContainer().getWidth(); int widthNum = -1; try { widthNum = Integer.parseInt(width); } catch (NumberFormatException e) { LOG.debug(e.getLocalizedMessage(), e); } CmsDynamicFunctionBean.Format format = functionBean.getFormatForContainer(m_cms, type, widthNum); CmsDynamicFunctionFormatWrapper wrapper = new CmsDynamicFunctionFormatWrapper(m_cms, format); return wrapper; } }; return CmsCollectionsGenericWrapper.createLazyMap(transformer); } /** * Checks if the current request should be direct edit enabled. * Online-, history-requests, previews and temporary files will not be editable.<p> * * @return <code>true</code> if the current request should be direct edit enabled */ public boolean getIsEditMode() { if (m_isEditMode == null) { m_isEditMode = Boolean.valueOf(CmsJspTagEditable.isEditableRequest(m_request)); } return m_isEditMode.booleanValue(); } /** * Returns true if the current request is a JSON request.<p> * * @return true if we are in a JSON request */ public boolean getIsJSONRequest() { return CmsJsonPartFilter.isJsonRequest(m_request); } /** * Returns if the current project is the online project.<p> * * @return <code>true</code> if the current project is the online project */ public boolean getIsOnlineProject() { return m_cms.getRequestContext().getCurrentProject().isOnlineProject(); } /** * Returns the current locale.<p> * * @return the current locale */ public Locale getLocale() { return getRequestContext().getLocale(); } /** * Gets a map providing access to the locale variants of the current page.<p> * * Note that all available locales for the site / subsite are used as keys, not just the ones for which a locale * variant actually exists. * * Usage in JSPs: ${cms.localeResource['de']] * * @return the map from locale strings to locale variant resources */ public Map<String, CmsJspResourceWrapper> getLocaleResource() { Map<String, CmsJspResourceWrapper> result = getResourceWrapperForPage().getLocaleResource(); List<Locale> locales = CmsLocaleGroupService.getPossibleLocales(m_cms, getContainerPage()); for (Locale locale : locales) { if (!result.containsKey(locale.toString())) { result.put(locale.toString(), null); } } return result; } /** * Gets the main locale for the current page's locale group.<p> * * @return the main locale for the current page's locale group */ public Locale getMainLocale() { return getResourceWrapperForPage().getMainLocale(); } /** * Returns the meta mappings map.<p> * * @return the meta mappings */ public Map<String, String> getMeta() { initMetaMappings(); return CmsCollectionsGenericWrapper.createLazyMap(new MetaLookupTranformer()); } /** * Returns the currently displayed container page.<p> * * @return the currently displayed container page */ public CmsContainerPageBean getPage() { return m_page; } /** * Returns the parent container to the current container if available.<p> * * @return the parent container */ public CmsContainerBean getParentContainer() { CmsContainerBean result = null; if ((getContainer() != null) && (getContainer().getParentInstanceId() != null)) { result = m_parentContainers.get(getContainer().getParentInstanceId()); } return result; } /** * Returns the instance id parent container mapping.<p> * * @return the instance id parent container mapping */ public Map<String, CmsContainerBean> getParentContainers() { if (m_parentContainers == null) { initPageData(); } return Collections.unmodifiableMap(m_parentContainers); } /** * Returns the parent element to the current element if available.<p> * * @return the parent element or null */ public CmsContainerElementBean getParentElement() { return getParentElement(getElement()); } /** * JSP EL accessor method for retrieving the preview formatters.<p> * * @return a lazy map for accessing preview formatters */ public Map<String, String> getPreviewFormatter() { Transformer transformer = new Transformer() { @Override public Object transform(Object uri) { try { String rootPath = m_cms.getRequestContext().addSiteRoot((String)uri); CmsResource resource = m_cms.readResource((String)uri); CmsADEManager adeManager = OpenCms.getADEManager(); CmsADEConfigData configData = adeManager.lookupConfiguration(m_cms, rootPath); CmsFormatterConfiguration formatterConfig = configData.getFormatters(m_cms, resource); if (formatterConfig == null) { return ""; } I_CmsFormatterBean previewFormatter = formatterConfig.getPreviewFormatter(); if (previewFormatter == null) { return ""; } CmsUUID structureId = previewFormatter.getJspStructureId(); m_cms.readResource(structureId); CmsResource formatterResource = m_cms.readResource(structureId); String formatterSitePath = m_cms.getRequestContext().removeSiteRoot( formatterResource.getRootPath()); return formatterSitePath; } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); return ""; } } }; return CmsCollectionsGenericWrapper.createLazyMap(transformer); } /** * Reads all sub-categories below the provided category. * @return The map from the provided category to it's sub-categories in a {@link CmsJspCategoryAccessBean}. */ public Map<String, CmsJspCategoryAccessBean> getReadAllSubCategories() { if (null == m_allSubCategories) { m_allSubCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() { @Override public Object transform(Object categoryPath) { try { List<CmsCategory> categories = CmsCategoryService.getInstance().readCategories( m_cms, (String)categoryPath, true, m_cms.getRequestContext().getUri()); CmsJspCategoryAccessBean result = new CmsJspCategoryAccessBean( m_cms, categories, (String)categoryPath); return result; } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); return null; } } }); } return m_allSubCategories; } /** * Reads the categories assigned to the currently requested URI. * @return the categories assigned to the currently requested URI. */ public CmsJspCategoryAccessBean getReadCategories() { return m_resourceCategories.get(getRequestContext().getUri()); } /** * Transforms the category path of a category to the category. * @return a map from root or site path to category. */ public Map<String, CmsCategory> getReadCategory() { if (null == m_categories) { m_categories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() { public Object transform(Object categoryPath) { try { CmsCategoryService catService = CmsCategoryService.getInstance(); return catService.localizeCategory( m_cms, catService.readCategory(m_cms, (String)categoryPath, getRequestContext().getUri()), m_cms.getRequestContext().getLocale()); } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); return null; } } }); } return m_categories; } /** * Transforms the category path to the list of all categories on that path.<p> * * Example: For path <code>"location/europe/"</code> * the list <code>[getReadCategory.get("location/"),getReadCategory.get("location/europe/")]</code> * is returned. * @return a map from a category path to list of categories on that path. */ public Map<String, List<CmsCategory>> getReadPathCategories() { if (null == m_pathCategories) { m_pathCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() { public Object transform(Object categoryPath) { List<CmsCategory> result = new ArrayList<CmsCategory>(); String path = (String)categoryPath; if ((null == path) || (path.length() <= 1)) { return result; } //cut last slash path = path.substring(0, path.length() - 1); List<String> pathParts = Arrays.asList(path.split("/")); String currentPath = ""; for (String part : pathParts) { currentPath += part + "/"; CmsCategory category = getReadCategory().get(currentPath); if (null != category) { result.add(category); } } return CmsCategoryService.getInstance().localizeCategories( m_cms, result, m_cms.getRequestContext().getLocale()); } }); } return m_pathCategories; } /** * Reads the categories assigned to a resource. * * @return map from the resource path (root path) to the assigned categories */ public Map<String, CmsJspCategoryAccessBean> getReadResourceCategories() { if (null == m_resourceCategories) { m_resourceCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() { public Object transform(Object resourceName) { try { CmsResource resource = m_cms.readResource( getRequestContext().removeSiteRoot((String)resourceName)); return new CmsJspCategoryAccessBean(m_cms, resource); } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); return null; } } }); } return m_resourceCategories; } /** * Returns a HTML comment string that will cause the container page editor to reload the page if the element or its settings * were edited.<p> * * @return the reload marker */ public String getReloadMarker() { if (m_cms.getRequestContext().getCurrentProject().isOnlineProject()) { return ""; // reload marker is not needed in Online mode } else { return CmsGwtConstants.FORMATTER_RELOAD_MARKER; } } /** * Returns the request context.<p> * * @return the request context */ public CmsRequestContext getRequestContext() { return m_cms.getRequestContext(); } /** * Returns the current site.<p> * * @return the current site */ public CmsSite getSite() { return OpenCms.getSiteManager().getSiteForSiteRoot(m_cms.getRequestContext().getSiteRoot()); } /** * Transforms root paths to site paths. * * @return lazy map from root paths to site paths. * * @see CmsRequestContext#removeSiteRoot(String) */ public Map<String, String> getSitePath() { if (m_sitePaths == null) { m_sitePaths = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() { public Object transform(Object rootPath) { if (rootPath instanceof String) { return getRequestContext().removeSiteRoot((String)rootPath); } return null; } }); } return m_sitePaths; } /** * Returns the subsite path for the currently requested URI.<p> * * @return the subsite path */ public String getSubSitePath() { return m_cms.getRequestContext().removeSiteRoot( OpenCms.getADEManager().getSubSiteRoot(m_cms, m_cms.getRequestContext().getRootUri())); } /** * Returns the system information.<p> * * @return the system information */ public CmsSystemInfo getSystemInfo() { return OpenCms.getSystemInfo(); } /** * Gets a bean containing information about the current template.<p> * * @return the template information bean */ public TemplateBean getTemplate() { TemplateBean templateBean = getRequestAttribute(CmsTemplateContextManager.ATTR_TEMPLATE_BEAN); if (templateBean == null) { templateBean = new TemplateBean("", ""); } return templateBean; } /** * Returns the title of a page delivered from OpenCms, usually used for the <code>&lt;title&gt;</code> tag of * a HTML page.<p> * * If no title information has been found, the empty String "" is returned.<p> * * @return the title of the current page */ public String getTitle() { return getLocaleSpecificTitle(null); } /** * Get the title and read the Title property according the provided locale. * @return The map from locales to the locale specific titles. */ public Map<String, String> getTitleLocale() { if (m_localeTitles == null) { m_localeTitles = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() { public Object transform(Object inputLocale) { Locale locale = null; if (null != inputLocale) { if (inputLocale instanceof Locale) { locale = (Locale)inputLocale; } else if (inputLocale instanceof String) { try { locale = LocaleUtils.toLocale((String)inputLocale); } catch (IllegalArgumentException | NullPointerException e) { // do nothing, just go on without locale } } } return getLocaleSpecificTitle(locale); } }); } return m_localeTitles; } /** * Returns a lazy initialized Map that provides the detail page link as a value when given the name of a * resource type as a key.<p> * * The provided Map key is assumed to be the name of a resource type that has a detail page configured.<p> * * Usage example on a JSP with the JSTL:<pre> * &lt;a href=${cms.typeDetailPage['bs-blog']} /&gt * </pre> * * @return a lazy initialized Map that provides the detail page link as a value when given the name of a * resource type as a key * * @see #getFunctionDetailPage() */ public Map<String, String> getTypeDetailPage() { if (m_typeDetailPage == null) { m_typeDetailPage = CmsCollectionsGenericWrapper.createLazyMap(new CmsDetailLookupTransformer("")); } return m_typeDetailPage; } /** * Returns an initialized VFS access bean.<p> * * @return an initialized VFS access bean */ public CmsJspVfsAccessBean getVfs() { if (m_vfsBean == null) { // create a new VVFS access bean m_vfsBean = CmsJspVfsAccessBean.create(m_cms); } return m_vfsBean; } /** * Returns the workplace locale from the current user's settings.<p> * * @return returns the workplace locale from the current user's settings */ public Locale getWorkplaceLocale() { return OpenCms.getWorkplaceManager().getWorkplaceLocale(m_cms); } /** * Initializes the requested container page.<p> * * @param cms the cms context * @param req the current request * * @throws CmsException in case reading the requested resource fails */ public void initPage(CmsObject cms, HttpServletRequest req) throws CmsException { if (m_page == null) { String requestUri = cms.getRequestContext().getUri(); // get the container page itself, checking the history first CmsResource pageResource = (CmsResource)CmsHistoryResourceHandler.getHistoryResource(req); if (pageResource == null) { pageResource = cms.readResource(requestUri); } CmsXmlContainerPage xmlContainerPage = CmsXmlContainerPageFactory.unmarshal(cms, pageResource, req); m_page = xmlContainerPage.getContainerPage(cms); CmsModelGroupHelper modelHelper = new CmsModelGroupHelper( cms, OpenCms.getADEManager().lookupConfiguration(cms, cms.getRequestContext().getRootUri()), CmsJspTagEditable.isEditableRequest(req) ? CmsADESessionCache.getCache(req, cms) : null, CmsContainerpageService.isEditingModelGroups(cms, pageResource)); m_page = modelHelper.readModelGroups(xmlContainerPage.getContainerPage(cms)); } } /** * Returns <code>true</code in case a detail page is available for the current element.<p> * * @return <code>true</code in case a detail page is available for the current element */ public boolean isDetailPageAvailable() { boolean result = false; if ((m_cms != null) && (m_element != null) && !m_element.isInMemoryOnly() && (m_element.getResource() != null)) { try { String detailPage = OpenCms.getADEManager().getDetailPageFinder().getDetailPage( m_cms, m_element.getResource().getRootPath(), m_cms.getRequestContext().getUri(), null); result = detailPage != null; } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); } } return result; } /** * Returns <code>true</code> if this is a request to a detail resource, <code>false</code> otherwise.<p> * * Same as to check if {@link #getDetailContent()} is <code>null</code>.<p> * * @return <code>true</code> if this is a request to a detail resource, <code>false</code> otherwise */ public boolean isDetailRequest() { return m_detailContentResource != null; } /** * Returns if the page is in drag mode.<p> * * @return if the page is in drag mode */ public boolean isDragMode() { return m_isDragMode; } /** * Returns the flag to indicate if in drag and drop mode.<p> * * @return <code>true</code> if in drag and drop mode */ public boolean isEdited() { return m_edited; } /** * Returns if the current element is a model group.<p> * * @return <code>true</code> if the current element is a model group */ public boolean isModelGroupElement() { return (m_element != null) && !m_element.isInMemoryOnly() && isModelGroupPage() && m_element.isModelGroup(); } /** * Returns if the current page is used to manage model groups.<p> * * @return <code>true</code> if the current page is used to manage model groups */ public boolean isModelGroupPage() { CmsResource page = getContainerPage(); return (page != null) && CmsContainerpageService.isEditingModelGroups(m_cms, page); } /** * Sets the container the currently rendered element is part of.<p> * * @param container the container the currently rendered element is part of */ public void setContainer(CmsContainerBean container) { m_container = container; } /** * Sets the detail only page.<p> * * @param detailOnlyPage the detail only page to set */ public void setDetailOnlyPage(CmsContainerPageBean detailOnlyPage) { m_detailOnlyPage = detailOnlyPage; clearPageData(); } /** * Sets if the page is in drag mode.<p> * * @param isDragMode if the page is in drag mode */ public void setDragMode(boolean isDragMode) { m_isDragMode = isDragMode; } /** * Sets the flag to indicate if in drag and drop mode.<p> * * @param edited <code>true</code> if in drag and drop mode */ public void setEdited(boolean edited) { m_edited = edited; } /** * Sets the currently rendered element.<p> * * @param element the currently rendered element to set */ public void setElement(CmsContainerElementBean element) { m_element = element; } /** * Sets the currently displayed container page.<p> * * @param page the currently displayed container page to set */ public void setPage(CmsContainerPageBean page) { m_page = page; clearPageData(); } /** * Updates the internally stored OpenCms user context.<p> * * @param cms the new OpenCms user context */ public void updateCmsObject(CmsObject cms) { try { m_cms = OpenCms.initCmsObject(cms); } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); m_cms = cms; } } /** * Updates the standard context bean from the request.<p> * * @param cmsFlexRequest the request from which to update the data */ public void updateRequestData(CmsFlexRequest cmsFlexRequest) { CmsResource detailRes = CmsDetailPageResourceHandler.getDetailResource(cmsFlexRequest); m_detailContentResource = detailRes; m_request = cmsFlexRequest; } /** * Returns the formatter configuration to the given element.<p> * * @param element the element * * @return the formatter configuration */ protected I_CmsFormatterBean getElementFormatter(CmsContainerElementBean element) { if (m_elementInstances == null) { initPageData(); } I_CmsFormatterBean formatter = null; CmsContainerBean container = m_parentContainers.get(element.getInstanceId()); if (container == null) { // use the current container container = getContainer(); } String containerName = container.getName(); Map<String, String> settings = element.getSettings(); if (settings != null) { String formatterConfigId = settings.get(CmsFormatterConfig.getSettingsKeyForContainer(containerName)); if (CmsUUID.isValidUUID(formatterConfigId)) { formatter = OpenCms.getADEManager().getCachedFormatters(false).getFormatters().get( new CmsUUID(formatterConfigId)); } } if (formatter == null) { try { CmsResource resource = m_cms.readResource(m_cms.getRequestContext().getUri()); CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration(m_cms, resource.getRootPath()); CmsFormatterConfiguration formatters = config.getFormatters(m_cms, resource); int width = -2; try { width = Integer.parseInt(container.getWidth()); } catch (Exception e) { LOG.debug(e.getLocalizedMessage(), e); } formatter = formatters.getDefaultSchemaFormatter(container.getType(), width); } catch (CmsException e1) { LOG.error(e1.getLocalizedMessage(), e1); } } return formatter; } /** * Returns the title according to the given locale. * @param locale the locale for which the title should be read. * @return the title according to the given locale */ protected String getLocaleSpecificTitle(Locale locale) { String result = null; try { if (isDetailRequest()) { // this is a request to a detail page CmsResource res = getDetailContent(); CmsFile file = m_cms.readFile(res); CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, file); result = content.getHandler().getTitleMapping(m_cms, content, m_cms.getRequestContext().getLocale()); if (result == null) { // title not found, maybe no mapping OR not available in the current locale // read the title of the detail resource as fall back (may contain mapping from another locale) result = m_cms.readPropertyObject( res, CmsPropertyDefinition.PROPERTY_TITLE, false, locale).getValue(); } } if (result == null) { // read the title of the requested resource as fall back result = m_cms.readPropertyObject( m_cms.getRequestContext().getUri(), CmsPropertyDefinition.PROPERTY_TITLE, true, locale).getValue(); } } catch (CmsException e) { LOG.debug(e.getLocalizedMessage(), e); } if (CmsStringUtil.isEmptyOrWhitespaceOnly(result)) { result = ""; } return result; } /** * Returns the parent element if available.<p> * * @param element the element * * @return the parent element or null */ protected CmsContainerElementBean getParentElement(CmsContainerElementBean element) { if (m_elementInstances == null) { initPageData(); } CmsContainerElementBean parent = null; CmsContainerBean cont = m_parentContainers.get(element.getInstanceId()); if ((cont != null) && cont.isNestedContainer()) { parent = m_elementInstances.get(cont.getParentInstanceId()); } return parent; } /** * Reads a dynamic function bean, given its name in the module configuration.<p> * * @param configuredName the name of the dynamic function in the module configuration * @return the dynamic function bean for the dynamic function configured under that name * * @throws CmsException if something goes wrong */ protected CmsDynamicFunctionBean readDynamicFunctionBean(String configuredName) throws CmsException { CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration( m_cms, m_cms.addSiteRoot(m_cms.getRequestContext().getUri())); CmsFunctionReference functionRef = config.getFunctionReference(configuredName); if (functionRef == null) { return null; } CmsDynamicFunctionParser parser = new CmsDynamicFunctionParser(); CmsResource functionResource = m_cms.readResource(functionRef.getStructureId()); CmsDynamicFunctionBean result = parser.parseFunctionBean(m_cms, functionResource); return result; } /** * Adds the mappings of the given formatter configuration.<p> * * @param formatterBean the formatter bean * @param elementId the element content structure id * @param resolver The macro resolver used on key and default value of the mappings * @param isDetailContent in case of a detail content */ private void addMappingsForFormatter( I_CmsFormatterBean formatterBean, CmsUUID elementId, CmsMacroResolver resolver, boolean isDetailContent) { if ((formatterBean != null) && (formatterBean.getMetaMappings() != null)) { for (CmsMetaMapping map : formatterBean.getMetaMappings()) { String key = map.getKey(); key = resolver.resolveMacros(key); // the detail content mapping overrides other mappings if (isDetailContent || !m_metaMappings.containsKey(key) || (m_metaMappings.get(key).m_order <= map.getOrder())) { MetaMapping mapping = new MetaMapping(); mapping.m_key = key; mapping.m_elementXPath = map.getElement(); mapping.m_defaultValue = resolver.resolveMacros(map.getDefaultValue()); mapping.m_order = map.getOrder(); mapping.m_contentId = elementId; m_metaMappings.put(key, mapping); } } } } /** * Clears the page element data.<p> */ private void clearPageData() { m_elementInstances = null; m_parentContainers = null; } /** * Returns the current container page resource.<p> * * @return the current container page resource */ private CmsResource getContainerPage() { try { if (m_pageResource == null) { // get the container page itself, checking the history first m_pageResource = (CmsResource)CmsHistoryResourceHandler.getHistoryResource(m_request); if (m_pageResource == null) { m_pageResource = m_cms.readResource(m_cms.getRequestContext().getUri()); } } } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); } return m_pageResource; } /** * Convenience method for getting a request attribute without an explicit cast.<p> * * @param name the attribute name * @return the request attribute */ @SuppressWarnings("unchecked") private <A> A getRequestAttribute(String name) { Object attribute = m_request.getAttribute(name); return attribute != null ? (A)attribute : null; } /** * Gets the resource wrapper for the current page, initializing it if necessary.<p> * * @return the resource wrapper for the current page */ private CmsJspResourceWrapper getResourceWrapperForPage() { if (m_resourceWrapper != null) { return m_resourceWrapper; } m_resourceWrapper = new CmsJspResourceWrapper(m_cms, getContainerPage()); return m_resourceWrapper; } /** * Initializes the mapping configuration.<p> */ private void initMetaMappings() { if (m_metaMappings == null) { try { initPage(m_cms, (HttpServletRequest)m_request); CmsMacroResolver resolver = new CmsMacroResolver(); resolver.setCmsObject(m_cms); resolver.setMessages(OpenCms.getWorkplaceManager().getMessages(getLocale())); CmsResourceFilter filter = getIsEditMode() ? CmsResourceFilter.IGNORE_EXPIRATION : CmsResourceFilter.DEFAULT; m_metaMappings = new HashMap<String, MetaMapping>(); for (CmsContainerBean container : m_page.getContainers().values()) { for (CmsContainerElementBean element : container.getElements()) { String settingsKey = CmsFormatterConfig.getSettingsKeyForContainer(container.getName()); String formatterConfigId = element.getSettings() != null ? element.getSettings().get(settingsKey) : null; I_CmsFormatterBean formatterBean = null; if (CmsUUID.isValidUUID(formatterConfigId)) { formatterBean = OpenCms.getADEManager().getCachedFormatters( m_cms.getRequestContext().getCurrentProject().isOnlineProject()).getFormatters().get( new CmsUUID(formatterConfigId)); } if ((formatterBean != null) && m_cms.existsResource(element.getId(), filter)) { addMappingsForFormatter(formatterBean, element.getId(), resolver, false); } } } if (getDetailContentId() != null) { try { CmsResource detailContent = m_cms.readResource( getDetailContentId(), CmsResourceFilter.ignoreExpirationOffline(m_cms)); CmsFormatterConfiguration config = OpenCms.getADEManager().lookupConfiguration( m_cms, m_cms.getRequestContext().getRootUri()).getFormatters(m_cms, detailContent); for (I_CmsFormatterBean formatter : config.getDetailFormatters()) { addMappingsForFormatter(formatter, getDetailContentId(), resolver, true); } } catch (CmsException e) { LOG.error( Messages.get().getBundle().key( Messages.ERR_READING_REQUIRED_RESOURCE_1, getDetailContentId()), e); } } } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); } } } /** * Initializes the page element data.<p> */ private void initPageData() { m_elementInstances = new HashMap<String, CmsContainerElementBean>(); m_parentContainers = new HashMap<String, CmsContainerBean>(); if (m_page != null) { for (CmsContainerBean container : m_page.getContainers().values()) { for (CmsContainerElementBean element : container.getElements()) { m_elementInstances.put(element.getInstanceId(), element); m_parentContainers.put(element.getInstanceId(), container); try { if (element.isGroupContainer(m_cms) || element.isInheritedContainer(m_cms)) { List<CmsContainerElementBean> children; if (element.isGroupContainer(m_cms)) { children = CmsJspTagContainer.getGroupContainerElements( m_cms, element, m_request, container.getType()); } else { children = CmsJspTagContainer.getInheritedContainerElements(m_cms, element); } for (CmsContainerElementBean childElement : children) { m_elementInstances.put(childElement.getInstanceId(), childElement); m_parentContainers.put(childElement.getInstanceId(), container); } } } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); } } } // also add detail only data if (m_detailOnlyPage != null) { for (CmsContainerBean container : m_detailOnlyPage.getContainers().values()) { for (CmsContainerElementBean element : container.getElements()) { m_elementInstances.put(element.getInstanceId(), element); m_parentContainers.put(element.getInstanceId(), container); } } } } } }
src/org/opencms/jsp/util/CmsJspStandardContextBean.java
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.jsp.util; import org.opencms.ade.configuration.CmsADEConfigData; import org.opencms.ade.configuration.CmsADEManager; import org.opencms.ade.configuration.CmsFunctionReference; import org.opencms.ade.containerpage.CmsContainerpageService; import org.opencms.ade.containerpage.CmsModelGroupHelper; import org.opencms.ade.containerpage.shared.CmsFormatterConfig; import org.opencms.ade.containerpage.shared.CmsInheritanceInfo; import org.opencms.ade.detailpage.CmsDetailPageInfo; import org.opencms.ade.detailpage.CmsDetailPageResourceHandler; import org.opencms.file.CmsFile; import org.opencms.file.CmsObject; import org.opencms.file.CmsPropertyDefinition; import org.opencms.file.CmsRequestContext; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.file.history.CmsHistoryResourceHandler; import org.opencms.flex.CmsFlexController; import org.opencms.flex.CmsFlexRequest; import org.opencms.gwt.shared.CmsGwtConstants; import org.opencms.i18n.CmsLocaleGroupService; import org.opencms.jsp.CmsJspBean; import org.opencms.jsp.CmsJspResourceWrapper; import org.opencms.jsp.CmsJspTagContainer; import org.opencms.jsp.CmsJspTagEditable; import org.opencms.jsp.Messages; import org.opencms.jsp.jsonpart.CmsJsonPartFilter; import org.opencms.loader.CmsTemplateContextManager; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.main.CmsRuntimeException; import org.opencms.main.CmsSystemInfo; import org.opencms.main.OpenCms; import org.opencms.relations.CmsCategory; import org.opencms.relations.CmsCategoryService; import org.opencms.site.CmsSite; import org.opencms.util.CmsCollectionsGenericWrapper; import org.opencms.util.CmsMacroResolver; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import org.opencms.xml.containerpage.CmsADESessionCache; import org.opencms.xml.containerpage.CmsContainerBean; import org.opencms.xml.containerpage.CmsContainerElementBean; import org.opencms.xml.containerpage.CmsContainerPageBean; import org.opencms.xml.containerpage.CmsDynamicFunctionBean; import org.opencms.xml.containerpage.CmsDynamicFunctionParser; import org.opencms.xml.containerpage.CmsFormatterConfiguration; import org.opencms.xml.containerpage.CmsMetaMapping; import org.opencms.xml.containerpage.CmsXmlContainerPage; import org.opencms.xml.containerpage.CmsXmlContainerPageFactory; import org.opencms.xml.containerpage.I_CmsFormatterBean; import org.opencms.xml.content.CmsXmlContent; import org.opencms.xml.content.CmsXmlContentFactory; import org.opencms.xml.types.I_CmsXmlContentValue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import org.apache.commons.collections.Transformer; import org.apache.commons.lang3.LocaleUtils; import org.apache.commons.logging.Log; /** * Allows convenient access to the most important OpenCms functions on a JSP page, * indented to be used from a JSP with the JSTL or EL.<p> * * This bean is available by default in the context of an OpenCms managed JSP.<p> * * @since 8.0 */ public final class CmsJspStandardContextBean { /** * Container element wrapper to add some API methods.<p> */ public class CmsContainerElementWrapper extends CmsContainerElementBean { /** The wrapped element instance. */ private CmsContainerElementBean m_wrappedElement; /** * Constructor.<p> * * @param element the element to wrap */ protected CmsContainerElementWrapper(CmsContainerElementBean element) { m_wrappedElement = element; } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#clone() */ @Override public CmsContainerElementBean clone() { return m_wrappedElement.clone(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#editorHash() */ @Override public String editorHash() { return m_wrappedElement.editorHash(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { return m_wrappedElement.equals(obj); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#getFormatterId() */ @Override public CmsUUID getFormatterId() { return m_wrappedElement.getFormatterId(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#getId() */ @Override public CmsUUID getId() { return m_wrappedElement.getId(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#getIndividualSettings() */ @Override public Map<String, String> getIndividualSettings() { return m_wrappedElement.getIndividualSettings(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#getInheritanceInfo() */ @Override public CmsInheritanceInfo getInheritanceInfo() { return m_wrappedElement.getInheritanceInfo(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#getInstanceId() */ @Override public String getInstanceId() { return m_wrappedElement.getInstanceId(); } /** * Returns the parent element if present.<p> * * @return the parent element or <code>null</code> if not available */ public CmsContainerElementWrapper getParent() { CmsContainerElementBean parent = getParentElement(m_wrappedElement); return parent != null ? new CmsContainerElementWrapper(getParentElement(m_wrappedElement)) : null; } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#getResource() */ @Override public CmsResource getResource() { return m_wrappedElement.getResource(); } /** * Returns the resource type name of the element resource.<p> * * @return the resource type name */ public String getResourceTypeName() { String result = ""; try { result = OpenCms.getResourceManager().getResourceType(m_wrappedElement.getResource()).getTypeName(); } catch (Exception e) { CmsJspStandardContextBean.LOG.error(e.getLocalizedMessage(), e); } return result; } /** * Returns a lazy initialized setting map.<p> * * @return the settings */ public Map<String, ElementSettingWrapper> getSetting() { return CmsCollectionsGenericWrapper.createLazyMap(new SettingsTransformer(m_wrappedElement)); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#getSettings() */ @Override public Map<String, String> getSettings() { return m_wrappedElement.getSettings(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#getSitePath() */ @Override public String getSitePath() { return m_wrappedElement.getSitePath(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#hashCode() */ @Override public int hashCode() { return m_wrappedElement.hashCode(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#initResource(org.opencms.file.CmsObject) */ @Override public void initResource(CmsObject cms) throws CmsException { m_wrappedElement.initResource(cms); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#initSettings(org.opencms.file.CmsObject, org.opencms.xml.containerpage.I_CmsFormatterBean) */ @Override public void initSettings(CmsObject cms, I_CmsFormatterBean formatterBean) { m_wrappedElement.initSettings(cms, formatterBean); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#isCreateNew() */ @Override public boolean isCreateNew() { return m_wrappedElement.isCreateNew(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#isGroupContainer(org.opencms.file.CmsObject) */ @Override public boolean isGroupContainer(CmsObject cms) throws CmsException { return m_wrappedElement.isGroupContainer(cms); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#isInheritedContainer(org.opencms.file.CmsObject) */ @Override public boolean isInheritedContainer(CmsObject cms) throws CmsException { return m_wrappedElement.isInheritedContainer(cms); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#isInMemoryOnly() */ @Override public boolean isInMemoryOnly() { return m_wrappedElement.isInMemoryOnly(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#isReleasedAndNotExpired() */ @Override public boolean isReleasedAndNotExpired() { return m_wrappedElement.isReleasedAndNotExpired(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#isTemporaryContent() */ @Override public boolean isTemporaryContent() { return m_wrappedElement.isTemporaryContent(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#removeInstanceId() */ @Override public void removeInstanceId() { m_wrappedElement.removeInstanceId(); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#setFormatterId(org.opencms.util.CmsUUID) */ @Override public void setFormatterId(CmsUUID formatterId) { m_wrappedElement.setFormatterId(formatterId); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#setHistoryFile(org.opencms.file.CmsFile) */ @Override public void setHistoryFile(CmsFile file) { m_wrappedElement.setHistoryFile(file); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#setInheritanceInfo(org.opencms.ade.containerpage.shared.CmsInheritanceInfo) */ @Override public void setInheritanceInfo(CmsInheritanceInfo inheritanceInfo) { m_wrappedElement.setInheritanceInfo(inheritanceInfo); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#setTemporaryFile(org.opencms.file.CmsFile) */ @Override public void setTemporaryFile(CmsFile elementFile) { m_wrappedElement.setTemporaryFile(elementFile); } /** * @see org.opencms.xml.containerpage.CmsContainerElementBean#toString() */ @Override public String toString() { return m_wrappedElement.toString(); } } /** * Provides a lazy initialized Map that provides the detail page link as a value when given the name of a * (named) dynamic function or resource type as a key.<p> */ public class CmsDetailLookupTransformer implements Transformer { /** The selected prefix. */ private String m_prefix; /** * Constructor with a prefix.<p> * * The prefix is used to distinguish between type detail pages and function detail pages.<p> * * @param prefix the prefix to use */ public CmsDetailLookupTransformer(String prefix) { m_prefix = prefix; } /** * @see org.apache.commons.collections.Transformer#transform(java.lang.Object) */ @Override public Object transform(Object input) { String type = m_prefix + String.valueOf(input); CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration( m_cms, m_cms.addSiteRoot(m_cms.getRequestContext().getUri())); List<CmsDetailPageInfo> detailPages = config.getDetailPagesForType(type); if ((detailPages == null) || (detailPages.size() == 0)) { return "[No detail page configured for type =" + type + "=]"; } CmsDetailPageInfo mainDetailPage = detailPages.get(0); CmsUUID id = mainDetailPage.getId(); try { CmsResource r = m_cms.readResource(id); return OpenCms.getLinkManager().substituteLink(m_cms, r); } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); return "[Error reading detail page for type =" + type + "=]"; } } } /** * Element setting value wrapper.<p> */ public class ElementSettingWrapper extends A_CmsJspValueWrapper { /** Flag indicating the setting has been configured. */ private boolean m_exists; /** The wrapped value. */ private String m_value; /** * Constructor.<p> * * @param value the wrapped value * @param exists flag indicating the setting has been configured */ ElementSettingWrapper(String value, boolean exists) { m_value = value; m_exists = exists; } /** * Returns if the setting has been configured.<p> * * @return <code>true</code> if the setting has been configured */ @Override public boolean getExists() { return m_exists; } /** * Returns if the setting value is null or empty.<p> * * @return <code>true</code> if the setting value is null or empty */ @Override public boolean getIsEmpty() { return CmsStringUtil.isEmpty(m_value); } /** * Returns if the setting value is null or white space only.<p> * * @return <code>true</code> if the setting value is null or white space only */ @Override public boolean getIsEmptyOrWhitespaceOnly() { return CmsStringUtil.isEmptyOrWhitespaceOnly(m_value); } /** * @see org.opencms.jsp.util.A_CmsJspValueWrapper#getIsSet() */ @Override public boolean getIsSet() { return getExists() && !getIsEmpty(); } /** * Returns the value.<p> * * @return the value */ public String getValue() { return m_value; } /** * Returns the string value.<p> * * @return the string value */ @Override public String toString() { return m_value != null ? m_value : ""; } } /** * The element setting transformer.<p> */ public class SettingsTransformer implements Transformer { /** The element formatter config. */ private I_CmsFormatterBean m_formatter; /** The element. */ private CmsContainerElementBean m_transformElement; /** * Constructor.<p> * * @param element the element */ SettingsTransformer(CmsContainerElementBean element) { m_transformElement = element; m_formatter = getElementFormatter(element); } /** * @see org.apache.commons.collections.Transformer#transform(java.lang.Object) */ @Override public Object transform(Object arg0) { return new ElementSettingWrapper( m_transformElement.getSettings().get(arg0), m_formatter != null ? m_formatter.getSettings().get(arg0) != null : m_transformElement.getSettings().get(arg0) != null); } } /** * Bean containing a template name and URI.<p> */ public static class TemplateBean { /** True if the template context was manually selected. */ private boolean m_forced; /** The template name. */ private String m_name; /** The template resource. */ private CmsResource m_resource; /** The template uri, if no resource is set. */ private String m_uri; /** * Creates a new instance.<p> * * @param name the template name * @param resource the template resource */ public TemplateBean(String name, CmsResource resource) { m_resource = resource; m_name = name; } /** * Creates a new instance with an URI instead of a resoure.<p> * * @param name the template name * @param uri the template uri */ public TemplateBean(String name, String uri) { m_name = name; m_uri = uri; } /** * Gets the template name.<p> * * @return the template name */ public String getName() { return m_name; } /** * Gets the template resource.<p> * * @return the template resource */ public CmsResource getResource() { return m_resource; } /** * Gets the template uri.<p> * * @return the template URI. */ public String getUri() { if (m_resource != null) { return m_resource.getRootPath(); } else { return m_uri; } } /** * Returns true if the template context was manually selected.<p> * * @return true if the template context was manually selected */ public boolean isForced() { return m_forced; } /** * Sets the 'forced' flag to a new value.<p> * * @param forced the new value */ public void setForced(boolean forced) { m_forced = forced; } } /** * The meta mappings transformer.<p> */ class MetaLookupTranformer implements Transformer { /** * @see org.apache.commons.collections.Transformer#transform(java.lang.Object) */ public Object transform(Object arg0) { String result = null; if (m_metaMappings.containsKey(arg0)) { MetaMapping mapping = m_metaMappings.get(arg0); try { CmsResourceFilter filter = getIsEditMode() ? CmsResourceFilter.IGNORE_EXPIRATION : CmsResourceFilter.DEFAULT; CmsResource res = m_cms.readResource(mapping.m_contentId, filter); CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, res, m_request); if (content.hasLocale(getLocale())) { I_CmsXmlContentValue val = content.getValue(mapping.m_elementXPath, getLocale()); if (val != null) { result = val.getStringValue(m_cms); } } } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); } if (result == null) { result = mapping.m_defaultValue; } } return result; } } /** The meta mapping data. */ class MetaMapping { /** The mapping key. */ String m_key; /** The mapping value xpath. */ String m_elementXPath; /** The mapping order. */ int m_order; /** The mapping content structure id. */ CmsUUID m_contentId; /** The default value. */ String m_defaultValue; } /** The attribute name of the cms object.*/ public static final String ATTRIBUTE_CMS_OBJECT = "__cmsObject"; /** The attribute name of the standard JSP context bean. */ public static final String ATTRIBUTE_NAME = "cms"; /** The logger instance for this class. */ protected static final Log LOG = CmsLog.getLog(CmsJspStandardContextBean.class); /** OpenCms user context. */ protected CmsObject m_cms; /** Lazily initialized map from a category path to all sub-categories of that category. */ private Map<String, CmsJspCategoryAccessBean> m_allSubCategories; /** Lazily initialized map from a category path to the path's category object. */ private Map<String, CmsCategory> m_categories; /** The container the currently rendered element is part of. */ private CmsContainerBean m_container; /** The current detail content resource if available. */ private CmsResource m_detailContentResource; /** The detail only page references containers that are only displayed in detail view. */ private CmsContainerPageBean m_detailOnlyPage; /** Flag to indicate if element was just edited. */ private boolean m_edited; /** The currently rendered element. */ private CmsContainerElementBean m_element; /** The elements of the current page. */ private Map<String, CmsContainerElementBean> m_elementInstances; /** The lazy initialized map which allows access to the dynamic function beans. */ private Map<String, CmsDynamicFunctionBeanWrapper> m_function; /** The lazy initialized map for the function detail pages. */ private Map<String, String> m_functionDetailPage; /** Indicates if in drag mode. */ private boolean m_isDragMode; /** Stores the edit mode info. */ private Boolean m_isEditMode; /** Lazily initialized map from the locale to the localized title property. */ private Map<String, String> m_localeTitles; /** The currently displayed container page. */ private CmsContainerPageBean m_page; /** The current container page resource, lazy initialized. */ private CmsResource m_pageResource; /** The parent containers to the given element instance ids. */ private Map<String, CmsContainerBean> m_parentContainers; /** Lazily initialized map from a category path to all categories on that path. */ private Map<String, List<CmsCategory>> m_pathCategories; /** The current request. */ ServletRequest m_request; /** Lazily initialized map from the root path of a resource to all categories assigned to the resource. */ private Map<String, CmsJspCategoryAccessBean> m_resourceCategories; /** The resource wrapper for the current page. */ private CmsJspResourceWrapper m_resourceWrapper; /** The lazy initialized map for the detail pages. */ private Map<String, String> m_typeDetailPage; /** The VFS content access bean. */ private CmsJspVfsAccessBean m_vfsBean; /** The meta mapping configuration. */ Map<String, MetaMapping> m_metaMappings; /** * Creates an empty instance.<p> */ private CmsJspStandardContextBean() { // NOOP } /** * Creates a new standard JSP context bean. * * @param req the current servlet request */ private CmsJspStandardContextBean(ServletRequest req) { CmsFlexController controller = CmsFlexController.getController(req); m_request = req; CmsObject cms; if (controller != null) { cms = controller.getCmsObject(); } else { cms = (CmsObject)req.getAttribute(ATTRIBUTE_CMS_OBJECT); } if (cms == null) { // cms object unavailable - this request was not initialized properly throw new CmsRuntimeException( Messages.get().container(Messages.ERR_MISSING_CMS_CONTROLLER_1, CmsJspBean.class.getName())); } updateCmsObject(cms); m_detailContentResource = CmsDetailPageResourceHandler.getDetailResource(req); } /** * Creates a new instance of the standard JSP context bean.<p> * * To prevent multiple creations of the bean during a request, the OpenCms request context * attributes are used to cache the created VFS access utility bean.<p> * * @param req the current servlet request * * @return a new instance of the standard JSP context bean */ public static CmsJspStandardContextBean getInstance(ServletRequest req) { Object attribute = req.getAttribute(ATTRIBUTE_NAME); CmsJspStandardContextBean result; if ((attribute != null) && (attribute instanceof CmsJspStandardContextBean)) { result = (CmsJspStandardContextBean)attribute; } else { result = new CmsJspStandardContextBean(req); req.setAttribute(ATTRIBUTE_NAME, result); } return result; } /** * Returns a copy of this JSP context bean.<p> * * @return a copy of this JSP context bean */ public CmsJspStandardContextBean createCopy() { CmsJspStandardContextBean result = new CmsJspStandardContextBean(); result.m_container = m_container; if (m_detailContentResource != null) { result.m_detailContentResource = m_detailContentResource.getCopy(); } result.m_element = m_element; result.setPage(m_page); return result; } /** * Returns a caching hash specific to the element, it's properties and the current container width.<p> * * @return the caching hash */ public String elementCachingHash() { String result = ""; if (m_element != null) { result = m_element.editorHash(); if (m_container != null) { result += "w:" + m_container.getWidth() + "cName:" + m_container.getName() + "cType:" + m_container.getType(); } } return result; } /** * Returns the locales available for the currently requested URI. * * @return the locales available for the currently requested URI. */ public List<Locale> getAvailableLocales() { return OpenCms.getLocaleManager().getAvailableLocales(m_cms, getRequestContext().getUri()); } /** * Returns the container the currently rendered element is part of.<p> * * @return the currently the currently rendered element is part of */ public CmsContainerBean getContainer() { return m_container; } /** * Returns the current detail content, or <code>null</code> if no detail content is requested.<p> * * @return the current detail content, or <code>null</code> if no detail content is requested.<p> */ public CmsResource getDetailContent() { return m_detailContentResource; } /** * Returns the structure id of the current detail content, or <code>null</code> if no detail content is requested.<p> * * @return the structure id of the current detail content, or <code>null</code> if no detail content is requested.<p> */ public CmsUUID getDetailContentId() { return m_detailContentResource == null ? null : m_detailContentResource.getStructureId(); } /** * Returns the detail content site path, or <code>null</code> if not available.<p> * * @return the detail content site path */ public String getDetailContentSitePath() { return ((m_cms == null) || (m_detailContentResource == null)) ? null : m_cms.getSitePath(m_detailContentResource); } /** * Returns the detail only page.<p> * * @return the detail only page */ public CmsContainerPageBean getDetailOnlyPage() { return m_detailOnlyPage; } /** * Returns the currently rendered element.<p> * * @return the currently rendered element */ public CmsContainerElementWrapper getElement() { return m_element != null ? new CmsContainerElementWrapper(m_element) : null; } /** * Alternative method name for getReloadMarker(). * * @see org.opencms.jsp.util.CmsJspStandardContextBean#getReloadMarker() * * @return the reload marker */ public String getEnableReload() { return getReloadMarker(); } /** * Returns a lazy initialized Map which allows access to the dynamic function beans using the JSP EL.<p> * * When given a key, the returned map will look up the corresponding dynamic function bean in the module configuration.<p> * * @return a lazy initialized Map which allows access to the dynamic function beans using the JSP EL */ public Map<String, CmsDynamicFunctionBeanWrapper> getFunction() { if (m_function == null) { Transformer transformer = new Transformer() { @Override public Object transform(Object input) { try { CmsDynamicFunctionBean dynamicFunction = readDynamicFunctionBean((String)input); CmsDynamicFunctionBeanWrapper wrapper = new CmsDynamicFunctionBeanWrapper( m_cms, dynamicFunction); return wrapper; } catch (CmsException e) { LOG.debug(e.getLocalizedMessage(), e); return new CmsDynamicFunctionBeanWrapper(m_cms, null); } } }; m_function = CmsCollectionsGenericWrapper.createLazyMap(transformer); } return m_function; } /** * Deprecated method to access function detail pages using the EL.<p> * * @return a lazy initialized Map that provides the detail page link as a value when given the name of a * (named) dynamic function as a key * * @deprecated use {@link #getFunctionDetailPage()} instead */ @Deprecated public Map<String, String> getFunctionDetail() { return getFunctionDetailPage(); } /** * Returns a lazy initialized Map that provides the detail page link as a value when given the name of a * (named) dynamic function as a key.<p> * * The provided Map key is assumed to be a String that represents a named dynamic function.<p> * * Usage example on a JSP with the JSTL:<pre> * &lt;a href=${cms.functionDetailPage['search']} /&gt * </pre> * * @return a lazy initialized Map that provides the detail page link as a value when given the name of a * (named) dynamic function as a key * * @see #getTypeDetailPage() */ public Map<String, String> getFunctionDetailPage() { if (m_functionDetailPage == null) { m_functionDetailPage = CmsCollectionsGenericWrapper.createLazyMap( new CmsDetailLookupTransformer(CmsDetailPageInfo.FUNCTION_PREFIX)); } return m_functionDetailPage; } /** * Returns a lazy map which creates a wrapper object for a dynamic function format when given an XML content * as a key.<p> * * @return a lazy map for accessing function formats for a content */ public Map<CmsJspContentAccessBean, CmsDynamicFunctionFormatWrapper> getFunctionFormatFromContent() { Transformer transformer = new Transformer() { @Override public Object transform(Object contentAccess) { CmsXmlContent content = (CmsXmlContent)(((CmsJspContentAccessBean)contentAccess).getRawContent()); CmsDynamicFunctionParser parser = new CmsDynamicFunctionParser(); CmsDynamicFunctionBean functionBean = null; try { functionBean = parser.parseFunctionBean(m_cms, content); } catch (CmsException e) { LOG.debug(e.getLocalizedMessage(), e); return new CmsDynamicFunctionFormatWrapper(m_cms, null); } String type = getContainer().getType(); String width = getContainer().getWidth(); int widthNum = -1; try { widthNum = Integer.parseInt(width); } catch (NumberFormatException e) { LOG.debug(e.getLocalizedMessage(), e); } CmsDynamicFunctionBean.Format format = functionBean.getFormatForContainer(m_cms, type, widthNum); CmsDynamicFunctionFormatWrapper wrapper = new CmsDynamicFunctionFormatWrapper(m_cms, format); return wrapper; } }; return CmsCollectionsGenericWrapper.createLazyMap(transformer); } /** * Checks if the current request should be direct edit enabled. * Online-, history-requests, previews and temporary files will not be editable.<p> * * @return <code>true</code> if the current request should be direct edit enabled */ public boolean getIsEditMode() { if (m_isEditMode == null) { m_isEditMode = Boolean.valueOf(CmsJspTagEditable.isEditableRequest(m_request)); } return m_isEditMode.booleanValue(); } /** * Returns true if the current request is a JSON request.<p> * * @return true if we are in a JSON request */ public boolean getIsJSONRequest() { return CmsJsonPartFilter.isJsonRequest(m_request); } /** * Returns if the current project is the online project.<p> * * @return <code>true</code> if the current project is the online project */ public boolean getIsOnlineProject() { return m_cms.getRequestContext().getCurrentProject().isOnlineProject(); } /** * Returns the current locale.<p> * * @return the current locale */ public Locale getLocale() { return getRequestContext().getLocale(); } /** * Gets a map providing access to the locale variants of the current page.<p> * * Note that all available locales for the site / subsite are used as keys, not just the ones for which a locale * variant actually exists. * * Usage in JSPs: ${cms.localeResource['de']] * * @return the map from locale strings to locale variant resources */ public Map<String, CmsJspResourceWrapper> getLocaleResource() { Map<String, CmsJspResourceWrapper> result = getResourceWrapperForPage().getLocaleResource(); List<Locale> locales = CmsLocaleGroupService.getPossibleLocales(m_cms, getContainerPage()); for (Locale locale : locales) { if (!result.containsKey(locale.toString())) { result.put(locale.toString(), null); } } return result; } /** * Gets the main locale for the current page's locale group.<p> * * @return the main locale for the current page's locale group */ public Locale getMainLocale() { return getResourceWrapperForPage().getMainLocale(); } /** * Returns the meta mappings map.<p> * * @return the meta mappings */ public Map<String, String> getMeta() { initMetaMappings(); return CmsCollectionsGenericWrapper.createLazyMap(new MetaLookupTranformer()); } /** * Returns the currently displayed container page.<p> * * @return the currently displayed container page */ public CmsContainerPageBean getPage() { return m_page; } /** * Returns the parent container to the current container if available.<p> * * @return the parent container */ public CmsContainerBean getParentContainer() { CmsContainerBean result = null; if ((getContainer() != null) && (getContainer().getParentInstanceId() != null)) { result = m_parentContainers.get(getContainer().getParentInstanceId()); } return result; } /** * Returns the instance id parent container mapping.<p> * * @return the instance id parent container mapping */ public Map<String, CmsContainerBean> getParentContainers() { if (m_parentContainers == null) { initPageData(); } return Collections.unmodifiableMap(m_parentContainers); } /** * Returns the parent element to the current element if available.<p> * * @return the parent element or null */ public CmsContainerElementBean getParentElement() { return getParentElement(getElement()); } /** * JSP EL accessor method for retrieving the preview formatters.<p> * * @return a lazy map for accessing preview formatters */ public Map<String, String> getPreviewFormatter() { Transformer transformer = new Transformer() { @Override public Object transform(Object uri) { try { String rootPath = m_cms.getRequestContext().addSiteRoot((String)uri); CmsResource resource = m_cms.readResource((String)uri); CmsADEManager adeManager = OpenCms.getADEManager(); CmsADEConfigData configData = adeManager.lookupConfiguration(m_cms, rootPath); CmsFormatterConfiguration formatterConfig = configData.getFormatters(m_cms, resource); if (formatterConfig == null) { return ""; } I_CmsFormatterBean previewFormatter = formatterConfig.getPreviewFormatter(); if (previewFormatter == null) { return ""; } CmsUUID structureId = previewFormatter.getJspStructureId(); m_cms.readResource(structureId); CmsResource formatterResource = m_cms.readResource(structureId); String formatterSitePath = m_cms.getRequestContext().removeSiteRoot( formatterResource.getRootPath()); return formatterSitePath; } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); return ""; } } }; return CmsCollectionsGenericWrapper.createLazyMap(transformer); } /** * Reads all sub-categories below the provided category. * @return The map from the provided category to it's sub-categories in a {@link CmsJspCategoryAccessBean}. */ public Map<String, CmsJspCategoryAccessBean> getReadAllSubCategories() { if (null == m_allSubCategories) { m_allSubCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() { @Override public Object transform(Object categoryPath) { try { List<CmsCategory> categories = CmsCategoryService.getInstance().readCategories( m_cms, (String)categoryPath, true, m_cms.getRequestContext().getUri()); CmsJspCategoryAccessBean result = new CmsJspCategoryAccessBean( m_cms, categories, (String)categoryPath); return result; } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); return null; } } }); } return m_allSubCategories; } /** * Reads the categories assigned to the currently requested URI. * @return the categories assigned to the currently requested URI. */ public CmsJspCategoryAccessBean getReadCategories() { return m_resourceCategories.get(getRequestContext().getUri()); } /** * Transforms the category path of a category to the category. * @return a map from root or site path to category. */ public Map<String, CmsCategory> getReadCategory() { if (null == m_categories) { m_categories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() { public Object transform(Object categoryPath) { try { CmsCategoryService catService = CmsCategoryService.getInstance(); return catService.localizeCategory( m_cms, catService.readCategory(m_cms, (String)categoryPath, getRequestContext().getUri()), m_cms.getRequestContext().getLocale()); } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); return null; } } }); } return m_categories; } /** * Transforms the category path to the list of all categories on that path.<p> * * Example: For path <code>"location/europe/"</code> * the list <code>[getReadCategory.get("location/"),getReadCategory.get("location/europe/")]</code> * is returned. * @return a map from a category path to list of categories on that path. */ public Map<String, List<CmsCategory>> getReadPathCategories() { if (null == m_pathCategories) { m_pathCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() { public Object transform(Object categoryPath) { List<CmsCategory> result = new ArrayList<CmsCategory>(); String path = (String)categoryPath; if ((null == path) || (path.length() <= 1)) { return result; } //cut last slash path = path.substring(0, path.length() - 1); List<String> pathParts = Arrays.asList(path.split("/")); String currentPath = ""; for (String part : pathParts) { currentPath += part + "/"; CmsCategory category = getReadCategory().get(currentPath); if (null != category) { result.add(category); } } return CmsCategoryService.getInstance().localizeCategories( m_cms, result, m_cms.getRequestContext().getLocale()); } }); } return m_pathCategories; } /** * Reads the categories assigned to a resource. * * @return map from the resource path (root path) to the assigned categories */ public Map<String, CmsJspCategoryAccessBean> getReadResourceCategories() { if (null == m_resourceCategories) { m_resourceCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() { public Object transform(Object resourceName) { try { CmsResource resource = m_cms.readResource( getRequestContext().removeSiteRoot((String)resourceName)); return new CmsJspCategoryAccessBean(m_cms, resource); } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); return null; } } }); } return m_resourceCategories; } /** * Returns a HTML comment string that will cause the container page editor to reload the page if the element or its settings * were edited.<p> * * @return the reload marker */ public String getReloadMarker() { if (m_cms.getRequestContext().getCurrentProject().isOnlineProject()) { return ""; // reload marker is not needed in Online mode } else { return CmsGwtConstants.FORMATTER_RELOAD_MARKER; } } /** * Returns the request context.<p> * * @return the request context */ public CmsRequestContext getRequestContext() { return m_cms.getRequestContext(); } /** * Returns the current site.<p> * * @return the current site */ public CmsSite getSite() { return OpenCms.getSiteManager().getSiteForSiteRoot(m_cms.getRequestContext().getSiteRoot()); } /** * Returns the subsite path for the currently requested URI.<p> * * @return the subsite path */ public String getSubSitePath() { return m_cms.getRequestContext().removeSiteRoot( OpenCms.getADEManager().getSubSiteRoot(m_cms, m_cms.getRequestContext().getRootUri())); } /** * Returns the system information.<p> * * @return the system information */ public CmsSystemInfo getSystemInfo() { return OpenCms.getSystemInfo(); } /** * Gets a bean containing information about the current template.<p> * * @return the template information bean */ public TemplateBean getTemplate() { TemplateBean templateBean = getRequestAttribute(CmsTemplateContextManager.ATTR_TEMPLATE_BEAN); if (templateBean == null) { templateBean = new TemplateBean("", ""); } return templateBean; } /** * Returns the title of a page delivered from OpenCms, usually used for the <code>&lt;title&gt;</code> tag of * a HTML page.<p> * * If no title information has been found, the empty String "" is returned.<p> * * @return the title of the current page */ public String getTitle() { return getLocaleSpecificTitle(null); } /** * Get the title and read the Title property according the provided locale. * @return The map from locales to the locale specific titles. */ public Map<String, String> getTitleLocale() { if (m_localeTitles == null) { m_localeTitles = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() { public Object transform(Object inputLocale) { Locale locale = null; if (null != inputLocale) { if (inputLocale instanceof Locale) { locale = (Locale)inputLocale; } else if (inputLocale instanceof String) { try { locale = LocaleUtils.toLocale((String)inputLocale); } catch (IllegalArgumentException | NullPointerException e) { // do nothing, just go on without locale } } } return getLocaleSpecificTitle(locale); } }); } return m_localeTitles; } /** * Returns a lazy initialized Map that provides the detail page link as a value when given the name of a * resource type as a key.<p> * * The provided Map key is assumed to be the name of a resource type that has a detail page configured.<p> * * Usage example on a JSP with the JSTL:<pre> * &lt;a href=${cms.typeDetailPage['bs-blog']} /&gt * </pre> * * @return a lazy initialized Map that provides the detail page link as a value when given the name of a * resource type as a key * * @see #getFunctionDetailPage() */ public Map<String, String> getTypeDetailPage() { if (m_typeDetailPage == null) { m_typeDetailPage = CmsCollectionsGenericWrapper.createLazyMap(new CmsDetailLookupTransformer("")); } return m_typeDetailPage; } /** * Returns an initialized VFS access bean.<p> * * @return an initialized VFS access bean */ public CmsJspVfsAccessBean getVfs() { if (m_vfsBean == null) { // create a new VVFS access bean m_vfsBean = CmsJspVfsAccessBean.create(m_cms); } return m_vfsBean; } /** * Returns the workplace locale from the current user's settings.<p> * * @return returns the workplace locale from the current user's settings */ public Locale getWorkplaceLocale() { return OpenCms.getWorkplaceManager().getWorkplaceLocale(m_cms); } /** * Initializes the requested container page.<p> * * @param cms the cms context * @param req the current request * * @throws CmsException in case reading the requested resource fails */ public void initPage(CmsObject cms, HttpServletRequest req) throws CmsException { if (m_page == null) { String requestUri = cms.getRequestContext().getUri(); // get the container page itself, checking the history first CmsResource pageResource = (CmsResource)CmsHistoryResourceHandler.getHistoryResource(req); if (pageResource == null) { pageResource = cms.readResource(requestUri); } CmsXmlContainerPage xmlContainerPage = CmsXmlContainerPageFactory.unmarshal(cms, pageResource, req); m_page = xmlContainerPage.getContainerPage(cms); CmsModelGroupHelper modelHelper = new CmsModelGroupHelper( cms, OpenCms.getADEManager().lookupConfiguration(cms, cms.getRequestContext().getRootUri()), CmsJspTagEditable.isEditableRequest(req) ? CmsADESessionCache.getCache(req, cms) : null, CmsContainerpageService.isEditingModelGroups(cms, pageResource)); m_page = modelHelper.readModelGroups(xmlContainerPage.getContainerPage(cms)); } } /** * Returns <code>true</code in case a detail page is available for the current element.<p> * * @return <code>true</code in case a detail page is available for the current element */ public boolean isDetailPageAvailable() { boolean result = false; if ((m_cms != null) && (m_element != null) && !m_element.isInMemoryOnly() && (m_element.getResource() != null)) { try { String detailPage = OpenCms.getADEManager().getDetailPageFinder().getDetailPage( m_cms, m_element.getResource().getRootPath(), m_cms.getRequestContext().getUri(), null); result = detailPage != null; } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); } } return result; } /** * Returns <code>true</code> if this is a request to a detail resource, <code>false</code> otherwise.<p> * * Same as to check if {@link #getDetailContent()} is <code>null</code>.<p> * * @return <code>true</code> if this is a request to a detail resource, <code>false</code> otherwise */ public boolean isDetailRequest() { return m_detailContentResource != null; } /** * Returns if the page is in drag mode.<p> * * @return if the page is in drag mode */ public boolean isDragMode() { return m_isDragMode; } /** * Returns the flag to indicate if in drag and drop mode.<p> * * @return <code>true</code> if in drag and drop mode */ public boolean isEdited() { return m_edited; } /** * Returns if the current element is a model group.<p> * * @return <code>true</code> if the current element is a model group */ public boolean isModelGroupElement() { return (m_element != null) && !m_element.isInMemoryOnly() && isModelGroupPage() && m_element.isModelGroup(); } /** * Returns if the current page is used to manage model groups.<p> * * @return <code>true</code> if the current page is used to manage model groups */ public boolean isModelGroupPage() { CmsResource page = getContainerPage(); return (page != null) && CmsContainerpageService.isEditingModelGroups(m_cms, page); } /** * Sets the container the currently rendered element is part of.<p> * * @param container the container the currently rendered element is part of */ public void setContainer(CmsContainerBean container) { m_container = container; } /** * Sets the detail only page.<p> * * @param detailOnlyPage the detail only page to set */ public void setDetailOnlyPage(CmsContainerPageBean detailOnlyPage) { m_detailOnlyPage = detailOnlyPage; clearPageData(); } /** * Sets if the page is in drag mode.<p> * * @param isDragMode if the page is in drag mode */ public void setDragMode(boolean isDragMode) { m_isDragMode = isDragMode; } /** * Sets the flag to indicate if in drag and drop mode.<p> * * @param edited <code>true</code> if in drag and drop mode */ public void setEdited(boolean edited) { m_edited = edited; } /** * Sets the currently rendered element.<p> * * @param element the currently rendered element to set */ public void setElement(CmsContainerElementBean element) { m_element = element; } /** * Sets the currently displayed container page.<p> * * @param page the currently displayed container page to set */ public void setPage(CmsContainerPageBean page) { m_page = page; clearPageData(); } /** * Updates the internally stored OpenCms user context.<p> * * @param cms the new OpenCms user context */ public void updateCmsObject(CmsObject cms) { try { m_cms = OpenCms.initCmsObject(cms); } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); m_cms = cms; } } /** * Updates the standard context bean from the request.<p> * * @param cmsFlexRequest the request from which to update the data */ public void updateRequestData(CmsFlexRequest cmsFlexRequest) { CmsResource detailRes = CmsDetailPageResourceHandler.getDetailResource(cmsFlexRequest); m_detailContentResource = detailRes; m_request = cmsFlexRequest; } /** * Returns the formatter configuration to the given element.<p> * * @param element the element * * @return the formatter configuration */ protected I_CmsFormatterBean getElementFormatter(CmsContainerElementBean element) { if (m_elementInstances == null) { initPageData(); } I_CmsFormatterBean formatter = null; CmsContainerBean container = m_parentContainers.get(element.getInstanceId()); if (container == null) { // use the current container container = getContainer(); } String containerName = container.getName(); Map<String, String> settings = element.getSettings(); if (settings != null) { String formatterConfigId = settings.get(CmsFormatterConfig.getSettingsKeyForContainer(containerName)); if (CmsUUID.isValidUUID(formatterConfigId)) { formatter = OpenCms.getADEManager().getCachedFormatters(false).getFormatters().get( new CmsUUID(formatterConfigId)); } } if (formatter == null) { try { CmsResource resource = m_cms.readResource(m_cms.getRequestContext().getUri()); CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration(m_cms, resource.getRootPath()); CmsFormatterConfiguration formatters = config.getFormatters(m_cms, resource); int width = -2; try { width = Integer.parseInt(container.getWidth()); } catch (Exception e) { LOG.debug(e.getLocalizedMessage(), e); } formatter = formatters.getDefaultSchemaFormatter(container.getType(), width); } catch (CmsException e1) { LOG.error(e1.getLocalizedMessage(), e1); } } return formatter; } /** * Returns the title according to the given locale. * @param locale the locale for which the title should be read. * @return the title according to the given locale */ protected String getLocaleSpecificTitle(Locale locale) { String result = null; try { if (isDetailRequest()) { // this is a request to a detail page CmsResource res = getDetailContent(); CmsFile file = m_cms.readFile(res); CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, file); result = content.getHandler().getTitleMapping(m_cms, content, m_cms.getRequestContext().getLocale()); if (result == null) { // title not found, maybe no mapping OR not available in the current locale // read the title of the detail resource as fall back (may contain mapping from another locale) result = m_cms.readPropertyObject( res, CmsPropertyDefinition.PROPERTY_TITLE, false, locale).getValue(); } } if (result == null) { // read the title of the requested resource as fall back result = m_cms.readPropertyObject( m_cms.getRequestContext().getUri(), CmsPropertyDefinition.PROPERTY_TITLE, true, locale).getValue(); } } catch (CmsException e) { LOG.debug(e.getLocalizedMessage(), e); } if (CmsStringUtil.isEmptyOrWhitespaceOnly(result)) { result = ""; } return result; } /** * Returns the parent element if available.<p> * * @param element the element * * @return the parent element or null */ protected CmsContainerElementBean getParentElement(CmsContainerElementBean element) { if (m_elementInstances == null) { initPageData(); } CmsContainerElementBean parent = null; CmsContainerBean cont = m_parentContainers.get(element.getInstanceId()); if ((cont != null) && cont.isNestedContainer()) { parent = m_elementInstances.get(cont.getParentInstanceId()); } return parent; } /** * Reads a dynamic function bean, given its name in the module configuration.<p> * * @param configuredName the name of the dynamic function in the module configuration * @return the dynamic function bean for the dynamic function configured under that name * * @throws CmsException if something goes wrong */ protected CmsDynamicFunctionBean readDynamicFunctionBean(String configuredName) throws CmsException { CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration( m_cms, m_cms.addSiteRoot(m_cms.getRequestContext().getUri())); CmsFunctionReference functionRef = config.getFunctionReference(configuredName); if (functionRef == null) { return null; } CmsDynamicFunctionParser parser = new CmsDynamicFunctionParser(); CmsResource functionResource = m_cms.readResource(functionRef.getStructureId()); CmsDynamicFunctionBean result = parser.parseFunctionBean(m_cms, functionResource); return result; } /** * Adds the mappings of the given formatter configuration.<p> * * @param formatterBean the formatter bean * @param elementId the element content structure id * @param resolver The macro resolver used on key and default value of the mappings * @param isDetailContent in case of a detail content */ private void addMappingsForFormatter( I_CmsFormatterBean formatterBean, CmsUUID elementId, CmsMacroResolver resolver, boolean isDetailContent) { if ((formatterBean != null) && (formatterBean.getMetaMappings() != null)) { for (CmsMetaMapping map : formatterBean.getMetaMappings()) { String key = map.getKey(); key = resolver.resolveMacros(key); // the detail content mapping overrides other mappings if (isDetailContent || !m_metaMappings.containsKey(key) || (m_metaMappings.get(key).m_order <= map.getOrder())) { MetaMapping mapping = new MetaMapping(); mapping.m_key = key; mapping.m_elementXPath = map.getElement(); mapping.m_defaultValue = resolver.resolveMacros(map.getDefaultValue()); mapping.m_order = map.getOrder(); mapping.m_contentId = elementId; m_metaMappings.put(key, mapping); } } } } /** * Clears the page element data.<p> */ private void clearPageData() { m_elementInstances = null; m_parentContainers = null; } /** * Returns the current container page resource.<p> * * @return the current container page resource */ private CmsResource getContainerPage() { try { if (m_pageResource == null) { // get the container page itself, checking the history first m_pageResource = (CmsResource)CmsHistoryResourceHandler.getHistoryResource(m_request); if (m_pageResource == null) { m_pageResource = m_cms.readResource(m_cms.getRequestContext().getUri()); } } } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); } return m_pageResource; } /** * Convenience method for getting a request attribute without an explicit cast.<p> * * @param name the attribute name * @return the request attribute */ @SuppressWarnings("unchecked") private <A> A getRequestAttribute(String name) { Object attribute = m_request.getAttribute(name); return attribute != null ? (A)attribute : null; } /** * Gets the resource wrapper for the current page, initializing it if necessary.<p> * * @return the resource wrapper for the current page */ private CmsJspResourceWrapper getResourceWrapperForPage() { if (m_resourceWrapper != null) { return m_resourceWrapper; } m_resourceWrapper = new CmsJspResourceWrapper(m_cms, getContainerPage()); return m_resourceWrapper; } /** * Initializes the mapping configuration.<p> */ private void initMetaMappings() { if (m_metaMappings == null) { try { initPage(m_cms, (HttpServletRequest)m_request); CmsMacroResolver resolver = new CmsMacroResolver(); resolver.setCmsObject(m_cms); resolver.setMessages(OpenCms.getWorkplaceManager().getMessages(getLocale())); CmsResourceFilter filter = getIsEditMode() ? CmsResourceFilter.IGNORE_EXPIRATION : CmsResourceFilter.DEFAULT; m_metaMappings = new HashMap<String, MetaMapping>(); for (CmsContainerBean container : m_page.getContainers().values()) { for (CmsContainerElementBean element : container.getElements()) { String settingsKey = CmsFormatterConfig.getSettingsKeyForContainer(container.getName()); String formatterConfigId = element.getSettings() != null ? element.getSettings().get(settingsKey) : null; I_CmsFormatterBean formatterBean = null; if (CmsUUID.isValidUUID(formatterConfigId)) { formatterBean = OpenCms.getADEManager().getCachedFormatters( m_cms.getRequestContext().getCurrentProject().isOnlineProject()).getFormatters().get( new CmsUUID(formatterConfigId)); } if ((formatterBean != null) && m_cms.existsResource(element.getId(), filter)) { addMappingsForFormatter(formatterBean, element.getId(), resolver, false); } } } if (getDetailContentId() != null) { try { CmsResource detailContent = m_cms.readResource( getDetailContentId(), CmsResourceFilter.ignoreExpirationOffline(m_cms)); CmsFormatterConfiguration config = OpenCms.getADEManager().lookupConfiguration( m_cms, m_cms.getRequestContext().getRootUri()).getFormatters(m_cms, detailContent); for (I_CmsFormatterBean formatter : config.getDetailFormatters()) { addMappingsForFormatter(formatter, getDetailContentId(), resolver, true); } } catch (CmsException e) { LOG.error( Messages.get().getBundle().key( Messages.ERR_READING_REQUIRED_RESOURCE_1, getDetailContentId()), e); } } } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); } } } /** * Initializes the page element data.<p> */ private void initPageData() { m_elementInstances = new HashMap<String, CmsContainerElementBean>(); m_parentContainers = new HashMap<String, CmsContainerBean>(); if (m_page != null) { for (CmsContainerBean container : m_page.getContainers().values()) { for (CmsContainerElementBean element : container.getElements()) { m_elementInstances.put(element.getInstanceId(), element); m_parentContainers.put(element.getInstanceId(), container); try { if (element.isGroupContainer(m_cms) || element.isInheritedContainer(m_cms)) { List<CmsContainerElementBean> children; if (element.isGroupContainer(m_cms)) { children = CmsJspTagContainer.getGroupContainerElements( m_cms, element, m_request, container.getType()); } else { children = CmsJspTagContainer.getInheritedContainerElements(m_cms, element); } for (CmsContainerElementBean childElement : children) { m_elementInstances.put(childElement.getInstanceId(), childElement); m_parentContainers.put(childElement.getInstanceId(), container); } } } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); } } } // also add detail only data if (m_detailOnlyPage != null) { for (CmsContainerBean container : m_detailOnlyPage.getContainers().values()) { for (CmsContainerElementBean element : container.getElements()) { m_elementInstances.put(element.getInstanceId(), element); m_parentContainers.put(element.getInstanceId(), container); } } } } } }
Added CmsJspStandardContextBean#getSitePath to convert root paths to site paths in EL.
src/org/opencms/jsp/util/CmsJspStandardContextBean.java
Added CmsJspStandardContextBean#getSitePath to convert root paths to site paths in EL.
Java
lgpl-2.1
e09429341b71ac925427f187c22a7da7cc65fc77
0
nhochberger/Utilities
package hochberger.utilities.text; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import com.google.common.collect.Iterables; public final class Text { private Text() { super(); } public static String empty() { return ""; } public static String space() { return " "; } public static String space(final int n) { String result = ""; for (int i = 0; i < n; i++) { result += Text.space(); } return result; } public static String newLine() { return "\n"; } public static String emptyIfNull(final String text) { if (null == text) { return Text.empty(); } return text; } public static String fromIterable(final Iterable<?> iterable) { return fromIterable(iterable, Text.empty()); } public static String fromIterable(final Iterable<?> iterable, final String separator) { final StringBuilder result = new StringBuilder(); if (Iterables.isEmpty(iterable)) { return Text.empty(); } for (final Object object : iterable) { result.append(object.toString()); result.append(separator); } final int end = result.length(); result.delete(end - separator.length(), end); return result.toString(); } public static Iterable<String> toIterable(final String source, final String separator) { return Arrays.asList( Text.emptyIfNull(source).split(Text.emptyIfNull(separator))); } public static String trim(final String source) { return Text.emptyIfNull(source).trim(); } public static Iterable<String> trimAll(final Iterable<String> source) { final List<String> result = new LinkedList<>(); for (final String string : source) { result.add(Text.trim(string)); } return result; } }
src/hochberger/utilities/text/Text.java
package hochberger.utilities.text; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import com.google.common.collect.Iterables; public final class Text { private Text() { super(); } public static String empty() { return ""; } public static String space() { return " "; } public static String newLine() { return "\n"; } public static String emptyIfNull(final String text) { if (null == text) { return Text.empty(); } return text; } public static String fromIterable(final Iterable<?> iterable) { return fromIterable(iterable, Text.empty()); } public static String fromIterable(final Iterable<?> iterable, final String separator) { StringBuilder result = new StringBuilder(); if (Iterables.isEmpty(iterable)) { return Text.empty(); } for (Object object : iterable) { result.append(object.toString()); result.append(separator); } int end = result.length(); result.delete(end - separator.length(), end); return result.toString(); } public static Iterable<String> toIterable(final String source, final String separator) { return Arrays.asList(Text.emptyIfNull(source).split( Text.emptyIfNull(separator))); } public static String trim(final String source) { return Text.emptyIfNull(source).trim(); } public static Iterable<String> trimAll(final Iterable<String> source) { List<String> result = new LinkedList<>(); for (String string : source) { result.add(Text.trim(string)); } return result; } }
added space(int n) to Text
src/hochberger/utilities/text/Text.java
added space(int n) to Text
Java
apache-2.0
5abd05c4793e2f49dcb6f8014f8dd307c6101d81
0
micrometer-metrics/micrometer,micrometer-metrics/micrometer,micrometer-metrics/micrometer
/** * Copyright 2017 Pivotal Software, Inc. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.micrometer.spring.autoconfigure; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.Clock; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.binder.hystrix.HystrixMetricsBinder; import io.micrometer.spring.PropertiesMeterFilter; import io.micrometer.spring.autoconfigure.jersey2.server.JerseyServerMetricsConfiguration; import io.micrometer.spring.autoconfigure.web.client.RestTemplateMetricsConfiguration; import io.micrometer.spring.autoconfigure.web.servlet.ServletMetricsConfiguration; import io.micrometer.spring.autoconfigure.web.tomcat.TomcatMetricsConfiguration; import io.micrometer.spring.integration.SpringIntegrationMetrics; import io.micrometer.spring.scheduling.ScheduledMethodMetrics; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration; import org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.SearchStrategy; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.core.annotation.Order; import org.springframework.integration.config.EnableIntegrationManagement; import org.springframework.integration.support.management.IntegrationManagementConfigurer; /** * {@link EnableAutoConfiguration} for Micrometer-based metrics. * * @author Jon Schneider */ @Configuration @ConditionalOnClass(Timed.class) @EnableConfigurationProperties(MetricsProperties.class) @Import({ // default binders MeterBindersConfiguration.class, // default instrumentation ServletMetricsConfiguration.class, RestTemplateMetricsConfiguration.class, TomcatMetricsConfiguration.class, JerseyServerMetricsConfiguration.class, }) @AutoConfigureAfter({ DataSourceAutoConfiguration.class, RabbitAutoConfiguration.class, CacheAutoConfiguration.class }) @AutoConfigureBefore(CompositeMeterRegistryAutoConfiguration.class) public class MetricsAutoConfiguration { @Bean @ConditionalOnMissingBean public Clock micrometerClock() { return Clock.SYSTEM; } @Bean public static MeterRegistryPostProcessor meterRegistryPostProcessor(ApplicationContext context) { return new MeterRegistryPostProcessor(context); } @Bean @Order(0) public MeterRegistryCustomizer<MeterRegistry> propertyBasedFilter(MetricsProperties props) { return r -> r.config().meterFilter(new PropertiesMeterFilter(props)); } // If AOP is not enabled, scheduled interception will not work. @Bean @ConditionalOnClass(name = "org.aspectj.lang.ProceedingJoinPoint") @ConditionalOnProperty(value = "spring.aop.enabled", havingValue = "true", matchIfMissing = true) public ScheduledMethodMetrics metricsSchedulingAspect(MeterRegistry registry) { return new ScheduledMethodMetrics(registry); } @Bean @ConditionalOnClass(name = "com.netflix.hystrix.strategy.HystrixPlugins") @ConditionalOnProperty(value = "management.metrics.binders.hystrix.enabled", matchIfMissing = true) public HystrixMetricsBinder hystrixMetricsBinder() { return new HystrixMetricsBinder(); } /** * Replaced by built-in Micrometer integration starting in Spring Integration 5.0.2. */ @Configuration @ConditionalOnClass(EnableIntegrationManagement.class) static class MetricsIntegrationConfiguration { @Bean(name = IntegrationManagementConfigurer.MANAGEMENT_CONFIGURER_NAME) @ConditionalOnMissingBean(value = IntegrationManagementConfigurer.class, name = IntegrationManagementConfigurer.MANAGEMENT_CONFIGURER_NAME, search = SearchStrategy.CURRENT) public IntegrationManagementConfigurer integrationManagementConfigurer() { IntegrationManagementConfigurer configurer = new IntegrationManagementConfigurer(); configurer.setDefaultCountsEnabled(true); configurer.setDefaultStatsEnabled(true); return configurer; } @Bean public SpringIntegrationMetrics springIntegrationMetrics( IntegrationManagementConfigurer configurer) { return new SpringIntegrationMetrics(configurer); } } }
micrometer-spring-legacy/src/main/java/io/micrometer/spring/autoconfigure/MetricsAutoConfiguration.java
/** * Copyright 2017 Pivotal Software, Inc. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.micrometer.spring.autoconfigure; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.Clock; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.binder.hystrix.HystrixMetricsBinder; import io.micrometer.spring.PropertiesMeterFilter; import io.micrometer.spring.autoconfigure.jersey2.server.JerseyServerMetricsConfiguration; import io.micrometer.spring.autoconfigure.web.client.RestTemplateMetricsConfiguration; import io.micrometer.spring.autoconfigure.web.servlet.ServletMetricsConfiguration; import io.micrometer.spring.autoconfigure.web.tomcat.TomcatMetricsConfiguration; import io.micrometer.spring.integration.SpringIntegrationMetrics; import io.micrometer.spring.scheduling.ScheduledMethodMetrics; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration; import org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.SearchStrategy; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.core.annotation.Order; import org.springframework.integration.config.EnableIntegrationManagement; import org.springframework.integration.support.management.IntegrationManagementConfigurer; /** * {@link EnableAutoConfiguration} for Micrometer-based metrics. * * @author Jon Schneider */ @Configuration @ConditionalOnClass(Timed.class) @EnableConfigurationProperties(MetricsProperties.class) @Import({ // default binders MeterBindersConfiguration.class, // default instrumentation ServletMetricsConfiguration.class, RestTemplateMetricsConfiguration.class, TomcatMetricsConfiguration.class, JerseyServerMetricsConfiguration.class, }) @AutoConfigureAfter({ DataSourceAutoConfiguration.class, RabbitAutoConfiguration.class, CacheAutoConfiguration.class }) @AutoConfigureBefore(CompositeMeterRegistryAutoConfiguration.class) public class MetricsAutoConfiguration { @Bean @ConditionalOnMissingBean public Clock micrometerClock() { return Clock.SYSTEM; } @Bean public static MeterRegistryPostProcessor meterRegistryPostProcessor(ApplicationContext context) { return new MeterRegistryPostProcessor(context); } @Bean @Order(0) public MeterRegistryCustomizer<MeterRegistry> propertyBasedFilter(MetricsProperties props) { return r -> r.config().meterFilter(new PropertiesMeterFilter(props)); } // If AOP is not enabled, scheduled interception will not work. @Bean @ConditionalOnClass(name = "org.aspectj.lang.ProceedingJoinPoint") @ConditionalOnProperty(value = "spring.aop.enabled", havingValue = "true", matchIfMissing = true) public ScheduledMethodMetrics metricsSchedulingAspect(MeterRegistry registry) { return new ScheduledMethodMetrics(registry); } @Bean @ConditionalOnClass(name = "com.netflix.hystrix.strategy.HystrixPlugins") @ConditionalOnProperty(value = "management.metrics.export.hystrix.enabled", matchIfMissing = true) public HystrixMetricsBinder hystrixMetricsBinder() { return new HystrixMetricsBinder(); } /** * Replaced by built-in Micrometer integration starting in Spring Integration 5.0.2. */ @Configuration @ConditionalOnClass(EnableIntegrationManagement.class) static class MetricsIntegrationConfiguration { @Bean(name = IntegrationManagementConfigurer.MANAGEMENT_CONFIGURER_NAME) @ConditionalOnMissingBean(value = IntegrationManagementConfigurer.class, name = IntegrationManagementConfigurer.MANAGEMENT_CONFIGURER_NAME, search = SearchStrategy.CURRENT) public IntegrationManagementConfigurer integrationManagementConfigurer() { IntegrationManagementConfigurer configurer = new IntegrationManagementConfigurer(); configurer.setDefaultCountsEnabled(true); configurer.setDefaultStatsEnabled(true); return configurer; } @Bean public SpringIntegrationMetrics springIntegrationMetrics( IntegrationManagementConfigurer configurer) { return new SpringIntegrationMetrics(configurer); } } }
Fixed typo in hystrix binding conditional
micrometer-spring-legacy/src/main/java/io/micrometer/spring/autoconfigure/MetricsAutoConfiguration.java
Fixed typo in hystrix binding conditional
Java
apache-2.0
50c9a8c7c5015a23a18756cc355f5e27667b85cd
0
freme-project/Broker,freme-project/Broker,freme-project/Broker
/** * Copyright (C) 2015 Agro-Know, Deutsches Forschungszentrum für Künstliche Intelligenz, iMinds, * Institut für Angewandte Informatik e. V. an der Universität Leipzig, * Istituto Superiore Mario Boella, Tilde, Vistatec, WRIPL (http://freme-project.eu) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.freme.broker.eservices; import com.google.gson.JsonSyntaxException; import com.mashape.unirest.http.exceptions.UnirestException; import eu.freme.broker.exception.AccessDeniedException; import eu.freme.broker.exception.BadRequestException; import eu.freme.broker.exception.InternalServerErrorException; import eu.freme.broker.exception.NotAcceptableException; import eu.freme.common.conversion.rdf.RDFConstants; import eu.freme.common.persistence.dao.PipelineDAO; import eu.freme.common.persistence.model.OwnedResource; import eu.freme.common.persistence.model.Pipeline; import eu.freme.eservices.pipelines.core.PipelineResponse; import eu.freme.eservices.pipelines.core.PipelineService; import eu.freme.eservices.pipelines.core.ServiceException; import eu.freme.eservices.pipelines.requests.RequestBuilder; import eu.freme.eservices.pipelines.requests.RequestFactory; import eu.freme.eservices.pipelines.requests.SerializedRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.annotation.Secured; import org.springframework.security.authentication.InsufficientAuthenticationException; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.*; import java.util.List; /** * @author Gerald Haesendonck */ @RestController @SuppressWarnings("unused") @Profile("broker") public class Pipelines extends BaseRestController { @Autowired PipelineService pipelineAPI; @Autowired PipelineDAO pipelineDAO; /** * <p>Calls the pipelining service.</p> * <p>Some predefined Requests can be formed using the class {@link RequestFactory}. It also converts request objects * from and to JSON.</p> * <p><To create custom requests, use the {@link RequestBuilder}.</p> * <p>Examples can be found in the unit tests in the Pipelines repository.</p> * @param requests The requests to send to the service. * @return The response of the last request. * @throws InternalServerErrorException Something goes wrong that shouldn't go wrong. */ @RequestMapping(value = "/pipelining/chain", method = RequestMethod.POST, consumes = "application/json", produces = {"text/turtle", "application/json", "application/ld+json", "application/n-triples", "application/rdf+xml", "text/n3"} ) public ResponseEntity<String> pipeline(@RequestBody String requests) { try { List<SerializedRequest> serializedRequests = RequestFactory.fromJson(requests); PipelineResponse pipelineResult = pipelineAPI.chain(serializedRequests); MultiValueMap<String, String> headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_TYPE, pipelineResult.getContentType()); return new ResponseEntity<>(pipelineResult.getBody(), headers, HttpStatus.OK); } catch (ServiceException serviceError) { logger.error(serviceError.getMessage(), serviceError); MultiValueMap<String, String> headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_TYPE, serviceError.getResponse().getContentType()); return new ResponseEntity<>(serviceError.getMessage(), headers, serviceError.getStatus()); } catch (JsonSyntaxException jsonException) { logger.error(jsonException.getMessage(), jsonException); String errormsg = jsonException.getCause() != null ? jsonException.getCause().getMessage() : jsonException.getMessage(); throw new NotAcceptableException("Error detected in the JSON body contents: " + errormsg); } catch (UnirestException unirestException) { logger.error(unirestException.getMessage(), unirestException); throw new BadRequestException(unirestException.getMessage()); } catch (Throwable t) { logger.error(t.getMessage(), t); // throw an Internal Server exception if anything goes really wrong... throw new InternalServerErrorException(t.getMessage()); } } // TODO: comments @RequestMapping(value = "/pipelining/templates", method = RequestMethod.POST, consumes = "application/json", produces = "application/json" ) @Secured({"ROLE_USER", "ROLE_ADMIN"}) public ResponseEntity<String> create( @RequestBody String requests, @RequestParam(value = "visibility", required = false) String visibility, @RequestParam (value = "persist", defaultValue = "false", required = false) String persist ) { try { // just to perform a first validation of the pipeline... List<SerializedRequest> serializedRequests = RequestFactory.fromJson(requests); boolean toPersist = Boolean.parseBoolean(persist); Pipeline pipeline = new Pipeline(OwnedResource.Visibility.getByString(visibility), "label", "description", requests, toPersist); pipelineDAO.save(pipeline); // now get the id of the pipeline. String response = "{\"id\": " + pipeline.getId() + ", \"persist\": " + pipeline.isPersistent() + '}'; return createOKJSONResponse(response); } catch (JsonSyntaxException jsonException) { logger.error(jsonException.getMessage(), jsonException); String errormsg = jsonException.getCause() != null ? jsonException.getCause().getMessage() : jsonException.getMessage(); throw new NotAcceptableException("Error detected in the JSON body contents: " + errormsg); } catch (eu.freme.common.exception.BadRequestException e) { logger.error(e.getMessage(), e); throw new BadRequestException(e.getMessage()); } catch (org.springframework.security.access.AccessDeniedException | InsufficientAuthenticationException ex) { logger.error(ex.getMessage(), ex); throw new AccessDeniedException(ex.getMessage()); } catch (Throwable t) { logger.error(t.getMessage(), t); // throw an Internal Server exception if anything goes really wrong... throw new InternalServerErrorException(t.getMessage()); } } @RequestMapping( value = "pipelining/templates/{id}", method = RequestMethod.GET, produces = "application/json" ) @Secured({"ROLE_USER", "ROLE_ADMIN"}) public ResponseEntity<String> read(@PathVariable(value = "id") String id) { try { long idNr = Long.parseLong(id); Pipeline pipeline = pipelineDAO.findOneById(idNr); String serializedPipeline = RequestFactory.toJson(pipeline); return createOKJSONResponse(serializedPipeline); } catch (NumberFormatException ex) { logger.error(ex.getMessage(), ex); throw new BadRequestException("The id has to be an integer number. " + ex.getMessage()); } catch (org.springframework.security.access.AccessDeniedException | InsufficientAuthenticationException ex) { logger.error(ex.getMessage(), ex); throw new AccessDeniedException(ex.getMessage()); } catch (Throwable t) { logger.error(t.getMessage(), t); // throw an Internal Server exception if anything goes really wrong... throw new InternalServerErrorException(t.getMessage()); } } @RequestMapping( value = "pipelining/templates", method = RequestMethod.GET, produces = "application/json" ) @Secured({"ROLE_USER", "ROLE_ADMIN"}) public ResponseEntity<String> read() { List<Pipeline> readablePipelines = pipelineDAO.findAllReadAccessible(); String serializedPipelines = RequestFactory.templatesToJson(readablePipelines); return createOKJSONResponse(serializedPipelines); } private ResponseEntity<String> createOKJSONResponse(final String contents) { MultiValueMap<String, String> headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_TYPE, RDFConstants.RDFSerialization.JSON.getMimeType()); return new ResponseEntity<>(contents, headers, HttpStatus.OK); } }
src/main/java/eu/freme/broker/eservices/Pipelines.java
/** * Copyright (C) 2015 Agro-Know, Deutsches Forschungszentrum für Künstliche Intelligenz, iMinds, * Institut für Angewandte Informatik e. V. an der Universität Leipzig, * Istituto Superiore Mario Boella, Tilde, Vistatec, WRIPL (http://freme-project.eu) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.freme.broker.eservices; import com.google.gson.JsonSyntaxException; import com.mashape.unirest.http.exceptions.UnirestException; import eu.freme.broker.exception.AccessDeniedException; import eu.freme.broker.exception.BadRequestException; import eu.freme.broker.exception.InternalServerErrorException; import eu.freme.broker.exception.NotAcceptableException; import eu.freme.common.conversion.rdf.RDFConstants; import eu.freme.common.persistence.dao.PipelineDAO; import eu.freme.common.persistence.model.OwnedResource; import eu.freme.common.persistence.model.Pipeline; import eu.freme.eservices.pipelines.core.PipelineResponse; import eu.freme.eservices.pipelines.core.PipelineService; import eu.freme.eservices.pipelines.core.ServiceException; import eu.freme.eservices.pipelines.requests.RequestBuilder; import eu.freme.eservices.pipelines.requests.RequestFactory; import eu.freme.eservices.pipelines.requests.SerializedRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.annotation.Secured; import org.springframework.security.authentication.InsufficientAuthenticationException; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.*; import java.util.List; /** * @author Gerald Haesendonck */ @RestController @SuppressWarnings("unused") @Profile("broker") public class Pipelines extends BaseRestController { @Autowired PipelineService pipelineAPI; @Autowired PipelineDAO pipelineDAO; /** * <p>Calls the pipelining service.</p> * <p>Some predefined Requests can be formed using the class {@link RequestFactory}. It also converts request objects * from and to JSON.</p> * <p><To create custom requests, use the {@link RequestBuilder}.</p> * <p>Examples can be found in the unit tests in the Pipelines repository.</p> * @param requests The requests to send to the service. * @return The response of the last request. * @throws InternalServerErrorException Something goes wrong that shouldn't go wrong. */ @RequestMapping(value = "/pipelining/chain", method = RequestMethod.POST, consumes = "application/json", produces = {"text/turtle", "application/json", "application/ld+json", "application/n-triples", "application/rdf+xml", "text/n3"} ) public ResponseEntity<String> pipeline(@RequestBody String requests) { try { List<SerializedRequest> serializedRequests = RequestFactory.fromJson(requests); PipelineResponse pipelineResult = pipelineAPI.chain(serializedRequests); MultiValueMap<String, String> headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_TYPE, pipelineResult.getContentType()); return new ResponseEntity<>(pipelineResult.getBody(), headers, HttpStatus.OK); } catch (ServiceException serviceError) { logger.error(serviceError.getMessage(), serviceError); MultiValueMap<String, String> headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_TYPE, serviceError.getResponse().getContentType()); return new ResponseEntity<>(serviceError.getMessage(), headers, serviceError.getStatus()); } catch (JsonSyntaxException jsonException) { logger.error(jsonException.getMessage(), jsonException); String errormsg = jsonException.getCause() != null ? jsonException.getCause().getMessage() : jsonException.getMessage(); throw new NotAcceptableException("Error detected in the JSON body contents: " + errormsg); } catch (UnirestException unirestException) { logger.error(unirestException.getMessage(), unirestException); throw new BadRequestException(unirestException.getMessage()); } catch (Throwable t) { logger.error(t.getMessage(), t); // throw an Internal Server exception if anything goes really wrong... throw new InternalServerErrorException(t.getMessage()); } } // TODO: comments @RequestMapping(value = "/pipelining/templates", method = RequestMethod.POST, consumes = "application/json", produces = "application/json" ) @Secured({"ROLE_USER", "ROLE_ADMIN"}) public ResponseEntity<String> create( @RequestBody String requests, @RequestParam(value = "visibility", required = false) String visibility, @RequestParam (value = "persist", defaultValue = "false", required = false) String persist ) { try { // just to perform a first validation of the pipeline... List<SerializedRequest> serializedRequests = RequestFactory.fromJson(requests); boolean toPersist = Boolean.parseBoolean(persist); Pipeline pipeline = new Pipeline(OwnedResource.Visibility.getByString(visibility), requests, toPersist); pipelineDAO.save(pipeline); // now get the id of the pipeline. String response = "{\"id\": " + pipeline.getId() + ", \"persist\": " + pipeline.isPersistent() + '}'; return createOKJSONResponse(response); } catch (JsonSyntaxException jsonException) { logger.error(jsonException.getMessage(), jsonException); String errormsg = jsonException.getCause() != null ? jsonException.getCause().getMessage() : jsonException.getMessage(); throw new NotAcceptableException("Error detected in the JSON body contents: " + errormsg); } catch (eu.freme.common.exception.BadRequestException e) { logger.error(e.getMessage(), e); throw new BadRequestException(e.getMessage()); } catch (org.springframework.security.access.AccessDeniedException | InsufficientAuthenticationException ex) { logger.error(ex.getMessage(), ex); throw new AccessDeniedException(ex.getMessage()); } catch (Throwable t) { logger.error(t.getMessage(), t); // throw an Internal Server exception if anything goes really wrong... throw new InternalServerErrorException(t.getMessage()); } } @RequestMapping( value = "pipelining/templates/{id}", method = RequestMethod.GET, produces = "application/json" ) @Secured({"ROLE_USER", "ROLE_ADMIN"}) public ResponseEntity<String> read(@PathVariable(value = "id") String id) { try { long idNr = Long.parseLong(id); Pipeline pipeline = pipelineDAO.findOneById(idNr); String serializedPipeline = RequestFactory.toJson(pipeline); return createOKJSONResponse(serializedPipeline); } catch (NumberFormatException ex) { logger.error(ex.getMessage(), ex); throw new BadRequestException("The id has to be an integer number. " + ex.getMessage()); } catch (org.springframework.security.access.AccessDeniedException | InsufficientAuthenticationException ex) { logger.error(ex.getMessage(), ex); throw new AccessDeniedException(ex.getMessage()); } catch (Throwable t) { logger.error(t.getMessage(), t); // throw an Internal Server exception if anything goes really wrong... throw new InternalServerErrorException(t.getMessage()); } } @RequestMapping( value = "pipelining/templates", method = RequestMethod.GET, produces = "application/json" ) @Secured({"ROLE_USER", "ROLE_ADMIN"}) public ResponseEntity<String> read() { List<Pipeline> readablePipelines = pipelineDAO.findAllReadAccessible(); String serializedPipelines = RequestFactory.templatesToJson(readablePipelines); return createOKJSONResponse(serializedPipelines); } private ResponseEntity<String> createOKJSONResponse(final String contents) { MultiValueMap<String, String> headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_TYPE, RDFConstants.RDFSerialization.JSON.getMimeType()); return new ResponseEntity<>(contents, headers, HttpStatus.OK); } }
temporary workaround. Will be fixed later.
src/main/java/eu/freme/broker/eservices/Pipelines.java
temporary workaround. Will be fixed later.
Java
apache-2.0
b6bed79b46bc0329b3b8fb37817ac36425b73012
0
tonywestonuk/picowf,tonywestonuk/picowf,tonywestonuk/picowf
package org.picojs.ws; import java.io.IOException; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentSkipListMap; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.picojs.PacketReceiver; @WebServlet("/WEB-INF/pico/redirect") public class Pico_redirect extends HttpServlet{ private PacketReceiver pr; @Override public void init(ServletConfig config) throws ServletException { pr=(PacketReceiver) config.getServletContext().getAttribute("packetReceiver"); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String serviceType=req.getAttribute("javax.servlet.forward.request_uri").toString(); serviceType=serviceType.substring(serviceType.lastIndexOf("/")+1,serviceType.length()-14); ConcurrentSkipListMap<String, Map<String, String>> map = pr.getPacketCache(); for (Entry<String, Map<String, String>> e:map.entrySet()){ if (serviceType.equals(e.getValue().get("serviceType"))){ String rootUrl=e.getValue().get("rootUrl"); if (req.getParameter("path")!=null){ if (rootUrl.endsWith("/")) rootUrl+=req.getParameter("path"); else rootUrl+="/"+req.getParameter("path"); } resp.sendRedirect(rootUrl); return; } } } }
PicoCore/src/main/java/org/picojs/ws/Pico_redirect.java
package org.picojs.ws; import java.io.IOException; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentSkipListMap; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.picojs.PacketReceiver; @WebServlet("/WEB-INF/pico/redirect") public class Pico_redirect extends HttpServlet{ private PacketReceiver pr; @Override public void init(ServletConfig config) throws ServletException { pr=(PacketReceiver) config.getServletContext().getAttribute("packetReceiver"); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String serviceType=req.getAttribute("javax.servlet.forward.request_uri").toString(); serviceType=serviceType.substring(serviceType.lastIndexOf("/")+1,serviceType.length()-14); ConcurrentSkipListMap<String, Map<String, String>> map = pr.getPacketCache(); for (Entry<String, Map<String, String>> e:map.entrySet()){ if (serviceType.equals(e.getValue().get("serviceType"))){ String rootUrl=e.getValue().get("rootUrl"); if (req.getParameter("path")!=null){ rootUrl+="/"+req.getParameter("path"); } resp.sendRedirect(rootUrl); return; } } } }
Fixed to work with remote server addresses ending with /
PicoCore/src/main/java/org/picojs/ws/Pico_redirect.java
Fixed to work with remote server addresses ending with /
Java
apache-2.0
d05d995ee20fe51dd0a53fb650bb7e73f9c42bb5
0
bither/bitherj,bither/bitherj,liduanw/bitherj,liduanw/bitherj
/* * Copyright 2014 http://Bither.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.bither.bitherj.core; import com.google.common.util.concurrent.Service; import net.bither.bitherj.db.AbstractDb; import net.bither.bitherj.exception.ProtocolException; import net.bither.bitherj.exception.ScriptException; import net.bither.bitherj.exception.VerificationException; import net.bither.bitherj.message.AlertMessage; import net.bither.bitherj.message.BlockMessage; import net.bither.bitherj.message.FilteredBlockMessage; import net.bither.bitherj.message.GetAddrMessage; import net.bither.bitherj.message.GetBlocksMessage; import net.bither.bitherj.message.GetDataMessage; import net.bither.bitherj.message.GetHeadersMessage; import net.bither.bitherj.message.HeadersMessage; import net.bither.bitherj.message.InventoryMessage; import net.bither.bitherj.message.MemoryPoolMessage; import net.bither.bitherj.message.Message; import net.bither.bitherj.message.NotFoundMessage; import net.bither.bitherj.message.PingMessage; import net.bither.bitherj.message.PongMessage; import net.bither.bitherj.message.RejectMessage; import net.bither.bitherj.message.VersionAck; import net.bither.bitherj.message.VersionMessage; import net.bither.bitherj.net.NioClientManager; import net.bither.bitherj.net.PeerSocketHandler; import net.bither.bitherj.script.Script; import net.bither.bitherj.utils.InventoryItem; import net.bither.bitherj.utils.Sha256Hash; import net.bither.bitherj.utils.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Random; public class Peer extends PeerSocketHandler { private static final int MAX_GETDATA_HASHES = 50000; private static final int MAX_UNRELATED_TX_RELAY_COUNT = 1000; private static final Logger log = LoggerFactory.getLogger(Peer.class); private static final int TimeOutDelay = 5000; public enum State { Disconnected, Connecting, Connected } enum DisconnectReason { Normal, NoneProtocol, Timeout } public State state; protected InetAddress peerAddress; protected int peerTimestamp; protected int peerPort; protected long peerServices; protected int peerConnectedCnt; protected long versionLastBlockHeight; // This may be wrong. Do not rely on it. private int incrementalBlockHeight; protected int version; protected long nonce; protected String userAgent; public long pingTime; private long pingStartTime; private int timestamp; private int filterBlockCount; private boolean sentVerAck, gotVerAck; private final HashSet<Sha256Hash> currentTxHashes, knownTxHashes, requestedBlockHashes; private final LinkedHashSet<Sha256Hash> currentBlockHashes; private final HashMap<Sha256Hash, HashSet<Tx>> needToRequestDependencyDict; private Block currentFilteredBlock; private VersionMessage versionMessage; private boolean bloomFilterSent; private int unrelatedTxRelayCount; private boolean synchronising; private int syncStartBlockNo; private long syncStartPeerBlockNo; private int synchronisingBlockCount; private List<Block> syncBlocks; private List<Sha256Hash> syncBlockHashes; public Peer(InetAddress address) { super(new InetSocketAddress(address, BitherjSettings.port)); this.peerAddress = address; peerPort = BitherjSettings.port; state = State.Disconnected; peerServices = 1; currentTxHashes = new HashSet<Sha256Hash>(); currentBlockHashes = new LinkedHashSet<Sha256Hash>(); knownTxHashes = new HashSet<Sha256Hash>(); requestedBlockHashes = new HashSet<Sha256Hash>(); needToRequestDependencyDict = new HashMap<Sha256Hash, HashSet<Tx>>(); incrementalBlockHeight = 0; unrelatedTxRelayCount = 0; nonce = new Random().nextLong(); peerTimestamp = (int) (new Date().getTime() / 1000 - 24 * 60 * 60 * (3 + new Random() .nextFloat() * 4)); synchronising = false; syncBlocks = new ArrayList<Block>(); syncBlockHashes = new ArrayList<Sha256Hash>(); } public void connect() { if (state != State.Disconnected) { log.info("peer[{}:{}] call connect, but its state is not disconnected", this.peerAddress.getHostAddress(), this.peerPort); return; } else { log.info("peer[{}:{}] call connect", this.peerAddress.getHostAddress(), this.peerPort); state = State.Connecting; if (!NioClientManager.instance().isRunning()) { if (NioClientManager.instance().startAndWait() != Service.State.RUNNING) { NioClientManager.instance().startUpError(); } } setTimeoutEnabled(true); setSocketTimeout(TimeOutDelay); bloomFilterSent = false; NioClientManager.instance().openConnection(new InetSocketAddress(getPeerAddress(), BitherjSettings.port), this); } } public void disconnect() { if (state == State.Disconnected) { return; } else { log.info("peer[{}:{}] call disconnect", this.peerAddress.getHostAddress(), this.peerPort); state = State.Disconnected; close(); } } @Override protected void processMessage(Message m) throws Exception { if (m == null) { return; } if (currentFilteredBlock != null && !(m instanceof Tx)) { currentFilteredBlock = null; currentTxHashes.clear(); exceptionCaught(new ProtocolException("Expect more tx for current filtering block, but got a " + m.getClass().getSimpleName() + " message")); } if (m instanceof NotFoundMessage) { // This is sent to us when we did a getdata on some transactions that aren't in the // peers memory pool. // Because NotFoundMessage is a subclass of InventoryMessage, // the test for it must come before the next. processNotFoundMessage((NotFoundMessage) m); } else if (m instanceof InventoryMessage) { processInv((InventoryMessage) m); } else if (m instanceof BlockMessage) { processBlock((BlockMessage) m); } else if (m instanceof FilteredBlockMessage) { startFilteredBlock((FilteredBlockMessage) m); } else if (m instanceof Tx) { processTransaction((Tx) m); } else if (m instanceof GetDataMessage) { processGetData((GetDataMessage) m); } else if (m instanceof HeadersMessage) { processHeaders((HeadersMessage) m); } else if (m instanceof AlertMessage) { processAlert((AlertMessage) m); } else if (m instanceof VersionMessage) { processVersionMessage((VersionMessage) m); } else if (m instanceof VersionAck) { if (!sentVerAck) { throw new ProtocolException("got a version ack before version"); } else if (gotVerAck) { throw new ProtocolException("got more than one version ack"); } gotVerAck = true; setTimeoutEnabled(false); state = State.Connected; PeerManager.instance().peerConnected(this); ping(); } else if (m instanceof PingMessage) { if (((PingMessage) m).hasNonce()) { sendMessage(new PongMessage(((PingMessage) m).getNonce())); } } else if (m instanceof PongMessage) { processPong((PongMessage) m); } else if (m instanceof RejectMessage) { processReject((RejectMessage) m); } } private void processNotFoundMessage(NotFoundMessage m) { // This is received when we previously did a getdata but the peer couldn't find what we // requested in it's // memory pool. Typically, because we are downloading dependencies of a relevant // transaction and reached // the bottom of the dependency tree (where the unconfirmed transactions connect to // transactions that are // in the chain). // // We go through and cancel the pending getdata futures for the items we were told // weren't found. log.info("peer[{}:{}] receive {} notfound item ", this.peerAddress.getHostAddress(), this.peerPort, m.getItems().size()); for (InventoryItem item : m.getItems()) { if (item.type == InventoryItem.Type.Transaction && item.hash != null && item.hash .length > 0) { checkDependencyWithNotFoundMsg(new Sha256Hash(item.hash)); } } } private void checkDependencyWithNotFoundMsg(Sha256Hash hash) { HashSet<Tx> needCheckDependencyTxs = needToRequestDependencyDict.get(hash); if (needCheckDependencyTxs == null) { return; } else { needToRequestDependencyDict.remove(hash); } HashSet<Tx> checkedTxs = new HashSet<Tx>(); for (Tx eachTx : needCheckDependencyTxs) { boolean stillNeedDependency = false; for (HashSet<Tx> set : needToRequestDependencyDict.values()) { if (set.contains(eachTx)) { stillNeedDependency = true; break; } } if (!stillNeedDependency) { PeerManager.instance().relayedTransaction(this, eachTx); checkedTxs.add(eachTx); } } for (Tx eachTx : checkedTxs) { checkDependencyWith(eachTx); } } private void checkDependencyWith(Tx tx) { HashSet<Tx> needCheckDependencyTxs = needToRequestDependencyDict.get(new Sha256Hash(tx .getTxHash())); if (needCheckDependencyTxs == null) { return; } else { needToRequestDependencyDict.remove(new Sha256Hash(tx.getTxHash())); } HashSet<Tx> invalidTxs = new HashSet<Tx>(); HashSet<Tx> checkedTxs = new HashSet<Tx>(); for (Tx eachTx : needCheckDependencyTxs) { boolean valid = true; for (int i = 0; i < eachTx.getIns().size(); i++) { if (Arrays.equals(eachTx.getIns().get(i).getTxHash(), tx.getTxHash())) { if (eachTx.getIns().get(i).getInSn() < tx.getOuts().size()) { byte[] outScript = tx.getOuts().get(eachTx.getIns().get(i).getInSn()) .getOutScript(); Script pubKeyScript = new Script(outScript); Script script = new Script(eachTx.getIns().get(i).getInSignature()); try { script.correctlySpends(eachTx, i, pubKeyScript, true); valid &= true; } catch (ScriptException e) { valid &= false; } } else { valid = false; } if (!valid) { break; } } } if (valid) { boolean stillNeedDependency = false; for (HashSet<Tx> set : needToRequestDependencyDict.values()) { if (set.contains(eachTx)) { stillNeedDependency = true; break; } } if (!stillNeedDependency) { PeerManager.instance().relayedTransaction(this, eachTx); checkedTxs.add(eachTx); } } else { invalidTxs.add(eachTx); } } for (Tx eachTx : invalidTxs) { log.warn(getPeerAddress().getHostAddress() + "tx:" + Utils.bytesToHexString(eachTx .getTxHash()) + " is invalid"); clearInvalidTxFromDependencyDict(eachTx); } for (Tx eachTx : checkedTxs) { checkDependencyWith(eachTx); } } private void clearInvalidTxFromDependencyDict(Tx tx) { for (HashSet<Tx> set : needToRequestDependencyDict.values()) { if (set.contains(tx)) { set.remove(tx); } } HashSet<Tx> subTxs = needToRequestDependencyDict.get(new Sha256Hash(tx.getTxHash())); if (subTxs != null) { needToRequestDependencyDict.remove(new Sha256Hash(tx.getTxHash())); for (Tx eachTx : subTxs) { clearInvalidTxFromDependencyDict(eachTx); } } } private void processInv(InventoryMessage inv) { ArrayList<InventoryItem> items = new ArrayList<InventoryItem>(inv.getItems()); if (items.size() == 0) { return; } else if (items.size() > MAX_GETDATA_HASHES) { log.info(this.getPeerAddress().getHostAddress() + " dropping inv message, " + "" + items.size() + " is too many items, max is " + MAX_GETDATA_HASHES); return; } if (!bloomFilterSent) { log.info("Peer {} received inv. But we didn't send bloomfilter. Ignore"); return; } ArrayList<Sha256Hash> txHashSha256Hashs = new ArrayList<Sha256Hash>(); ArrayList<Sha256Hash> blockHashSha256Hashs = new ArrayList<Sha256Hash>(); for (InventoryItem item : items) { InventoryItem.Type type = item.type; byte[] hash = item.hash; if (hash == null || hash.length == 0) { continue; } switch (type) { case Transaction: Sha256Hash big = new Sha256Hash(hash); if (!txHashSha256Hashs.contains(big)) { txHashSha256Hashs.add(big); } break; case Block: case FilteredBlock: // if(PeerManager.instance().getDownloadingPeer() == null || getDownloadData()) { Sha256Hash bigBlock = new Sha256Hash(hash); if (!blockHashSha256Hashs.contains(bigBlock)) { blockHashSha256Hashs.add(bigBlock); } // } break; } } log.info(getPeerAddress().getHostAddress() + " got inv with " + items.size() + " items " + txHashSha256Hashs.size() + " tx " + blockHashSha256Hashs.size() + " block"); if (txHashSha256Hashs.size() > 10000) { return; } // to improve chain download performance, if we received 500 block hashes, // we request the next 500 block hashes // immediately before sending the getdata request if (blockHashSha256Hashs.size() >= 500) { sendGetBlocksMessage(Arrays.asList(new Sha256Hash[]{blockHashSha256Hashs.get (blockHashSha256Hashs.size() - 1), blockHashSha256Hashs.get(0)}), null); } txHashSha256Hashs.removeAll(knownTxHashes); knownTxHashes.addAll(txHashSha256Hashs); if (txHashSha256Hashs.size() + blockHashSha256Hashs.size() > 0) { if (PeerManager.instance().getDownloadingPeer() == null || getDownloadData()) { sendGetDataMessageWithTxHashesAndBlockHashes(txHashSha256Hashs, blockHashSha256Hashs); // Each merkle block the remote peer sends us is followed by a set of tx messages for // that block. We send a ping // to get a pong reply after the block and all its tx are sent, // indicating that there are no more tx messages if (blockHashSha256Hashs.size() == 1) { ping(); } } else { sendGetDataMessageWithTxHashesAndBlockHashes(txHashSha256Hashs, new ArrayList<Sha256Hash>()); } } if (blockHashSha256Hashs.size() > 0) { //remember blockHashes in case we need to refetch them with an updated bloom filter currentBlockHashes.addAll(blockHashSha256Hashs); if (currentBlockHashes.size() > MAX_GETDATA_HASHES) { Iterator iterator = currentBlockHashes.iterator(); while (iterator.hasNext() && currentBlockHashes.size() > MAX_GETDATA_HASHES / 2) { iterator.remove(); } } if (this.synchronising) { this.syncBlockHashes.addAll(blockHashSha256Hashs); } this.increaseBlockNo(blockHashSha256Hashs.size()); } // if(blockHashSha256Hashs.size() == 1){ // incrementalBlockHeight ++; // } } private void increaseBlockNo(int blockCount) { if (this.synchronising) { synchronisingBlockCount += blockCount; } else { incrementalBlockHeight += blockCount; } } private void processBlock(BlockMessage m) { // we don't need to process block message after we send our awesome bloom filters. log.info("peer[{}:{}] receive block {}", this.peerAddress.getHostAddress(), this.peerPort, Utils.hashToString(m.getBlock().getBlockHash())); } private void startFilteredBlock(FilteredBlockMessage m) { Block block = m.getBlock(); block.verifyHeader(); log.info("peer[{}:{}] receive filtered block {} with {} tx", this.peerAddress.getHostAddress(), this.peerPort, Utils.hashToString(block.getBlockHash()), block.getTxHashes().size()); currentBlockHashes.remove(new Sha256Hash(block.getBlockHash())); requestedBlockHashes.remove(new Sha256Hash(block.getBlockHash())); if (requestedBlockHashes.contains(new Sha256Hash(block.getBlockHash()))) { return; } ArrayList<Sha256Hash> txHashes = new ArrayList<Sha256Hash>(); for (byte[] txHash : block.getTxHashes()) { txHashes.add(new Sha256Hash(txHash)); log.info("peer[{}:{}] receive filtered block {} tx {}", this.peerAddress.getHostAddress(), this.peerPort, Utils.hashToString(m.getBlock().getBlockHash()), Utils.hashToString(txHash)); } // txHashes.removeAll(knownTxHashes); // wait util we get all the tx messages before processing the block if (txHashes.size() > 0) { currentFilteredBlock = block; currentTxHashes.clear(); currentTxHashes.addAll(txHashes); } else { if (this.synchronising && this.syncBlockHashes.contains(new Sha256Hash(block.getBlockHash()))) { this.syncBlockHashes.remove(new Sha256Hash(block.getBlockHash())); this.syncBlocks.add(block); if (this.syncBlockHashes.size() == 0) { PeerManager.instance().relayedBlocks(this, this.syncBlocks); this.syncBlocks.clear(); } else if (this.syncBlocks.size() >= 100) { PeerManager.instance().relayedBlocks(this, this.syncBlocks); this.syncBlocks.clear(); } } else { PeerManager.instance().relayedBlock(this, block); } } if (currentBlockHashes.size() == 0) { sendGetBlocksMessage(Arrays.asList(new byte[][]{block.getBlockHash(), BlockChain.getInstance().getBlockLocatorArray().get(0)}), null); } } private void processTransaction(Tx tx) throws VerificationException { if (currentFilteredBlock != null) { // we're collecting tx messages for a merkleblock PeerManager.instance().relayedTransaction(this, tx); // we can't we byte array hash or BigInteger as the key. // byte array can't be compared // BigInteger can't be cast back to byte array // so we use Sha256Hash class here as key boolean removed = currentTxHashes.remove(new Sha256Hash(tx.getTxHash())); log.info("peer[{}:{}] receive tx {} filtering block: {}, remaining tx {}, remove {}", this.peerAddress.getHostAddress(), this.peerPort, Utils.hashToString(tx.getTxHash()), Utils.hashToString(currentFilteredBlock .getBlockHash()), currentTxHashes.size(), removed ? "success" : "failed"); if (currentTxHashes.size() == 0) { // we received the entire block including all // matched tx Block block = currentFilteredBlock; currentFilteredBlock = null; currentTxHashes.clear(); if (this.synchronising && this.syncBlockHashes.contains(new Sha256Hash(block.getBlockHash()))) { this.syncBlockHashes.remove(new Sha256Hash(block.getBlockHash())); this.syncBlocks.add(block); if (this.syncBlockHashes.size() == 0) { PeerManager.instance().relayedBlocks(this, this.syncBlocks); this.syncBlocks.clear(); } else if (this.syncBlocks.size() >= 100) { PeerManager.instance().relayedBlocks(this, this.syncBlocks); this.syncBlocks.clear(); } } else { PeerManager.instance().relayedBlock(this, block); } } } else { log.info("peer[{}:{}] receive tx {}", this.peerAddress.getHostAddress(), this.peerPort, Utils.hashToString(tx.getTxHash())); if (AddressManager.getInstance().isTxRelated(tx)) { unrelatedTxRelayCount = 0; } else { unrelatedTxRelayCount++; if (unrelatedTxRelayCount > MAX_UNRELATED_TX_RELAY_COUNT) { exceptionCaught(new Exception("Peer " + getPeerAddress().getHostAddress() + " is junking us. Drop it.")); return; } } boolean valid = true; try { tx.verify(); valid = true; } catch (VerificationException e) { valid = false; } if (valid) { PeerManager.instance().relayedTransaction(this, tx); } /* log.info("peer[{}:{}] receive tx {}", this.peerAddress.getHostAddress(), this.peerPort, Utils.hashToString(tx.getTxHash())); if (needToRequestDependencyDict.get(new Sha256Hash(tx.getTxHash())) == null || needToRequestDependencyDict.get(new Sha256Hash(tx.getTxHash())).size() == 0) { if (AddressManager.getInstance().isTxRelated(tx)) { unrelatedTxRelayCount = 0; } else { unrelatedTxRelayCount++; if (unrelatedTxRelayCount > MAX_UNRELATED_TX_RELAY_COUNT) { exceptionCaught(new Exception("Peer " + getPeerAddress().getHostAddress() + " is junking us. Drop it.")); return; } } } // check dependency HashMap<Sha256Hash, Tx> dependency = AbstractDb.txProvider.getTxDependencies(tx); HashSet<Sha256Hash> needToRequest = new HashSet<Sha256Hash>(); boolean valid = true; for (int i = 0; i < tx.getIns().size(); i++) { Tx prevTx = dependency.get(new Sha256Hash(tx.getIns().get(i).getPrevTxHash())); if (prevTx == null) { needToRequest.add(new Sha256Hash(tx.getIns().get(i).getPrevTxHash())); } else { if (prevTx.getOuts().size() <= tx.getIns().get(i).getInSn()) { valid = false; break; } byte[] outScript = prevTx.getOuts().get(tx.getIns().get(i).getInSn()) .getOutScript(); Script pubKeyScript = new Script(outScript); Script script = new Script(tx.getIns().get(i).getInSignature()); try { script.correctlySpends(tx, i, pubKeyScript, true); valid &= true; } catch (ScriptException e) { valid &= false; } if (!valid) { break; } } } try { tx.verify(); valid &= true; } catch (VerificationException e) { valid &= false; } if (valid && needToRequest.size() == 0) { PeerManager.instance().relayedTransaction(this, tx); checkDependencyWith(tx); } else if (valid && needToRequest.size() > 0) { for (Sha256Hash txHash : needToRequest) { if (needToRequestDependencyDict.get(txHash) == null) { HashSet<Tx> txs = new HashSet<Tx>(); txs.add(tx); needToRequestDependencyDict.put(txHash, txs); } else { HashSet<Tx> txs = needToRequestDependencyDict.get(txHash); txs.add(tx); } } sendGetDataMessageWithTxHashesAndBlockHashes(new ArrayList<Sha256Hash> (needToRequest), null); } */ } } private void processGetData(GetDataMessage getdata) { log.info("{}: Received getdata message with {} items", getAddress(), getdata.getItems().size()); ArrayList<InventoryItem> notFound = new ArrayList<InventoryItem>(); for (InventoryItem item : getdata.getItems()) { if (item.type == InventoryItem.Type.Transaction) { Tx tx = PeerManager.instance().requestedTransaction(this, item.hash); if (tx != null) { sendMessage(tx); log.info("Peer {} asked for tx: {} , found {}", getPeerAddress() .getHostAddress(), Utils.hashToString(item.hash), "hash: " + Utils.hashToString(tx.getTxHash()) + ", " + "content: " + Utils.bytesToHexString(tx.bitcoinSerialize())); continue; } else { log.info("Peer {} asked for tx: {} , not found", getPeerAddress().getHostAddress(), Utils.hashToString(item.hash)); } } notFound.add(item); } if (notFound.size() > 0) { sendMessage(new NotFoundMessage(notFound)); } } private void processHeaders(HeadersMessage m) throws ProtocolException { // Runs in network loop thread for this peer. // // This method can run if a peer just randomly sends us a "headers" message (should never // happen), or more // likely when we've requested them as part of chain download using fast catchup. We need // to add each block to // the chain if it pre-dates the fast catchup time. If we go past it, // we can stop processing the headers and // request the full blocks from that point on instead. log.info("peer[{}:{}] receive {} headers", this.peerAddress.getHostAddress(), this.peerPort, m.getBlockHeaders().size()); if (BlockChain.getInstance() == null) { // Can happen if we are receiving unrequested data, or due to programmer error. log.warn("Received headers when Peer is not configured with a chain."); return; } if (m.getBlockHeaders() == null || m.getBlockHeaders().size() == 0) { return; } try { int lastBlockTime = 0; byte[] firstHash = m.getBlockHeaders().get(0).getBlockHash(); byte[] lastHash = m.getBlockHeaders().get(m.getBlockHeaders().size() - 1).getBlockHash(); // ArrayList<Block> blocksToRelay = new ArrayList<Block>(); // for (int i = 0; i < m.getBlockHeaders().size(); i++) { // blocksToRelay.add(m.getBlockHeaders().get(i)); // } // for (int i = 0; i < m.getBlockHeaders().size(); i++) { // BlockMessage header = m.getBlockHeaders().get(i); // // Process headers until we pass the fast catchup time, // // or are about to catch up with the head // // of the chain - always process the last block as a full/filtered block to kick // // us out of the // // fast catchup mode (in which we ignore new blocks). // // boolean passedTime = header.getBlock().getBlockTime() >= PeerManager.instance() // .earliestKeyTime; // boolean reachedTop = PeerManager.instance().getLastBlockHeight() >= this // .versionLastBlockHeight; // if (!passedTime && !reachedTop) { // if (header.getBlock().getBlockTime() > lastBlockTime) { // lastBlockTime = header.getBlock().getBlockTime(); // if (lastBlockTime + 7 * 24 * 60 * 60 >= PeerManager.instance() // .earliestKeyTime - 2 * 60 * 60) { // lastHash = header.getBlock().getBlockHash(); // } // } // if(!blocksToRelay.contains(header.getBlock())){ // blocksToRelay.add(header.getBlock()); // } // } // } PeerManager.instance().relayedBlockHeadersForMainChain(this, m.getBlockHeaders()); // if (lastBlockTime + 7 * 24 * 60 * 60 >= PeerManager.instance().earliestKeyTime - 2 * // 60 * 60) { // sendGetBlocksMessage(Arrays.asList(new byte[][]{lastHash, firstHash}), null); // } else { sendGetHeadersMessage(Arrays.asList(new byte[][]{lastHash, firstHash}), null); // } } catch (VerificationException e) { log.warn("Block header verification failed", e); } } private void processVersionMessage(VersionMessage version) { this.versionMessage = version; this.version = version.clientVersion; if (this.version < BitherjSettings.MIN_PROTO_VERSION) { close(); return; } peerServices = version.localServices; peerTimestamp = (int) version.time; userAgent = version.subVer; versionLastBlockHeight = version.bestHeight; sendMessage(new VersionAck()); } public boolean getDownloadData() { if (PeerManager.instance().getDownloadingPeer() != null) { return equals(PeerManager.instance().getDownloadingPeer()); } else { return false; } } private void processPong(PongMessage m) { // Iterates over a snapshot of the list, so we can run unlocked here. if (m.getNonce() == nonce) { if (pingStartTime > 0) { if (pingTime > 0) { pingTime = (long) (pingTime * 0.5f + (new Date().getTime() - pingStartTime) * 0.5f); } else { pingTime = new Date().getTime() - pingStartTime; } pingStartTime = 0; } log.info("Peer " + getPeerAddress().getHostAddress() + " receive pong, ping time: " + pingTime); } } private void ping() { if (state != State.Connected) { return; } sendMessage(new PingMessage(nonce)); pingStartTime = new Date().getTime(); } private void sendVersionMessage() { sendMessage(new VersionMessage((int) PeerManager.instance().getLastBlockHeight(), false)); log.info("Send version message to peer {}", getPeerAddress().getHostAddress()); sentVerAck = true; } private void processAlert(AlertMessage m) { try { if (m.isSignatureValid()) { log.info("Received alert from peer {}: {}", toString(), m.getStatusBar()); } else { log.warn("Received alert with invalid signature from peer {}: {}", toString(), m.getStatusBar()); } } catch (Throwable t) { // Signature checking can FAIL on Android platforms before Gingerbread apparently due // to bugs in their // Sha256Hash implementations! See issue 160 for discussion. As alerts are just // optional and not that // useful, we just swallow the error here. log.error("Failed to check signature: bug in platform libraries?", t); } } private void processReject(RejectMessage m) { exceptionCaught(new ProtocolException("Peer " + getPeerAddress().getHostAddress() + " " + "Rejected. \n" + m.toString())); } public void sendFilterLoadMessage(BloomFilter filter) { if (state != State.Connected) { return; } filterBlockCount = 0; log.info("Peer {} send bloom filter", getPeerAddress().getHostAddress()); bloomFilterSent = true; sendMessage(filter); } public void sendMemPoolMessage() { if (state != State.Connected) { return; } sendMessage(new MemoryPoolMessage()); } public void sendGetAddrMessage() { if (state != State.Connected) { return; } sendMessage(new GetAddrMessage()); } public void sendInvMessageWithTxHash(Sha256Hash txHash) { if (state != State.Connected) { return; } InventoryMessage m = new InventoryMessage(); m.addTransaction(AbstractDb.txProvider.getTxDetailByTxHash(txHash.getBytes())); log.info("Peer {} send inv with tx {}", getPeerAddress().getHostAddress(), Utils.hashToString(txHash.getBytes())); sendMessage(m); } public void refetchBlocksFrom(Sha256Hash blockHash) { if (!currentBlockHashes.contains(blockHash)) { return; } Iterator<Sha256Hash> iterator = currentBlockHashes.iterator(); while (iterator.hasNext()) { Sha256Hash hash = iterator.next(); iterator.remove(); if (blockHash.equals(hash)) { break; } } log.info("Peer {} refetch {} blocks from {}", getPeerAddress().getHostAddress(), currentBlockHashes.size(), Utils.hashToString(blockHash.getBytes())); sendGetDataMessageWithTxHashesAndBlockHashes(null, new ArrayList<Sha256Hash>(currentBlockHashes)); } public void sendGetHeadersMessage(List<byte[]> locators, byte[] hashStop) { if (state != State.Connected) { return; } GetHeadersMessage m = new GetHeadersMessage(locators, hashStop == null ? Sha256Hash .ZERO_HASH.getBytes() : hashStop); log.info("Peer {} send get header message", getPeerAddress().getHostAddress()); sendMessage(m); } public void sendGetHeadersMessage(List<Sha256Hash> locators, Sha256Hash hashStop) { ArrayList<byte[]> ls = new ArrayList<byte[]>(); for (Sha256Hash i : locators) { ls.add(i.getBytes()); } sendGetHeadersMessage(ls, hashStop == null ? null : hashStop.getBytes()); } public void sendGetBlocksMessage(List<byte[]> locators, byte[] hashStop) { if (state != State.Connected) { return; } GetBlocksMessage m = new GetBlocksMessage(locators, hashStop == null ? Sha256Hash .ZERO_HASH.getBytes() : hashStop); log.info("Peer {} send get blocks message", getPeerAddress().getHostAddress()); sendMessage(m); } public void sendGetBlocksMessage(List<Sha256Hash> locators, Sha256Hash hashStop) { ArrayList<byte[]> ls = new ArrayList<byte[]>(); for (Sha256Hash i : locators) { ls.add(i.getBytes()); } sendGetBlocksMessage(ls, hashStop == null ? null : hashStop.getBytes()); } public void sendGetDataMessageWithTxHashesAndBlockHashes(List<Sha256Hash> txHashes, List<Sha256Hash> blockHashes) { if (state != State.Connected) { return; } GetDataMessage m = new GetDataMessage(); if (blockHashes != null) { for (Sha256Hash hash : blockHashes) { m.addFilteredBlock(hash.getBytes()); } requestedBlockHashes.addAll(blockHashes); } if (txHashes != null) { for (Sha256Hash hash : txHashes) { m.addTransaction(hash.getBytes()); } } int blochHashCount = 0; if (blockHashes != null) { blochHashCount = blockHashes.size(); } if (filterBlockCount + blochHashCount > BitherjSettings.BLOCK_DIFFICULTY_INTERVAL) { log.info("{} rebuilding bloom filter after {} blocks", getPeerAddress().getHostAddress(), filterBlockCount); sendFilterLoadMessage(PeerManager.instance().bloomFilterForPeer(this)); } filterBlockCount += blochHashCount; log.info("Peer {} send get data message with {} tx and & {} block", getPeerAddress().getHostAddress(), txHashes == null ? 0 : txHashes.size(), blochHashCount); sendMessage(m); } public void connectFail() { AbstractDb.peerProvider.conncetFail(getPeerAddress()); } public void connectError() { AbstractDb.peerProvider.removePeer(getPeerAddress()); } public void connectSucceed() { peerConnectedCnt = 1; peerTimestamp = (int) (new Date().getTime() / 1000); AbstractDb.peerProvider.connectSucceed(getPeerAddress()); sendFilterLoadMessage(PeerManager.instance().bloomFilterForPeer(this)); } @Override public void connectionClosed() { state = State.Disconnected; PeerManager.instance().peerDisconnected(this, DisconnectReason.Normal); } @Override protected void timeoutOccurred() { PeerManager.instance().peerDisconnected(this, DisconnectReason.Timeout); super.timeoutOccurred(); } @Override protected void exceptionCaught(Exception e) { super.exceptionCaught(e); if (e instanceof ProtocolException) { PeerManager.instance().peerDisconnected(this, DisconnectReason.NoneProtocol); } else { PeerManager.instance().peerDisconnected(this, DisconnectReason.NoneProtocol); } } @Override public void connectionOpened() { if (state == State.Disconnected) { disconnect(); return; } sendVersionMessage(); } @Override public boolean equals(Object o) { if (o instanceof Peer) { Peer item = (Peer) o; return Arrays.equals(getPeerAddress().getAddress(), item.getPeerAddress().getAddress()); } else { return false; } } @Override public int hashCode() { return getPeerAddress().hashCode(); } public InetAddress getPeerAddress() { return peerAddress; } public void setPeerAddress(InetAddress peerAddress) { this.peerAddress = peerAddress; } public int getPeerTimestamp() { return peerTimestamp; } public void setPeerTimestamp(int peerTimestamp) { this.peerTimestamp = peerTimestamp; } public int getPeerPort() { return peerPort; } public void setPeerPort(int peerPort) { this.peerPort = peerPort; } public long getPeerServices() { return peerServices; } public void setPeerServices(long peerServices) { this.peerServices = peerServices; } public int getPeerConnectedCnt() { return peerConnectedCnt; } public void setPeerConnectedCnt(int peerConnectedCnt) { this.peerConnectedCnt = peerConnectedCnt; } public long getVersionLastBlockHeight() { return versionLastBlockHeight; } // This may be wrong. Do not rely on it. public long getDisplayLastBlockHeight() { return versionLastBlockHeight + incrementalBlockHeight; } public int getClientVersion() { return version; } public String getSubVersion() { return userAgent; } public boolean getSynchronising() { return this.synchronising; } public void setSynchronising(boolean synchronising) { if (synchronising && !this.synchronising) { syncStartBlockNo = BlockChain.getInstance().getLastBlock().getBlockNo(); syncStartPeerBlockNo = this.getDisplayLastBlockHeight(); synchronisingBlockCount = 0; syncBlocks = new ArrayList<Block>(); syncBlockHashes = new ArrayList<Sha256Hash>(); this.synchronising = synchronising; } else if (!synchronising && this.synchronising) { incrementalBlockHeight = BlockChain.getInstance().getLastBlock().getBlockNo() - (int) this.getVersionLastBlockHeight(); synchronisingBlockCount = 0; this.synchronising = synchronising; } } }
bitherj/src/main/java/net/bither/bitherj/core/Peer.java
/* * Copyright 2014 http://Bither.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.bither.bitherj.core; import com.google.common.util.concurrent.Service; import net.bither.bitherj.db.AbstractDb; import net.bither.bitherj.exception.ProtocolException; import net.bither.bitherj.exception.ScriptException; import net.bither.bitherj.exception.VerificationException; import net.bither.bitherj.message.AlertMessage; import net.bither.bitherj.message.BlockMessage; import net.bither.bitherj.message.FilteredBlockMessage; import net.bither.bitherj.message.GetAddrMessage; import net.bither.bitherj.message.GetBlocksMessage; import net.bither.bitherj.message.GetDataMessage; import net.bither.bitherj.message.GetHeadersMessage; import net.bither.bitherj.message.HeadersMessage; import net.bither.bitherj.message.InventoryMessage; import net.bither.bitherj.message.MemoryPoolMessage; import net.bither.bitherj.message.Message; import net.bither.bitherj.message.NotFoundMessage; import net.bither.bitherj.message.PingMessage; import net.bither.bitherj.message.PongMessage; import net.bither.bitherj.message.RejectMessage; import net.bither.bitherj.message.VersionAck; import net.bither.bitherj.message.VersionMessage; import net.bither.bitherj.net.NioClientManager; import net.bither.bitherj.net.PeerSocketHandler; import net.bither.bitherj.script.Script; import net.bither.bitherj.utils.InventoryItem; import net.bither.bitherj.utils.Sha256Hash; import net.bither.bitherj.utils.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Random; public class Peer extends PeerSocketHandler { private static final int MAX_GETDATA_HASHES = 50000; private static final int MAX_UNRELATED_TX_RELAY_COUNT = 1000; private static final Logger log = LoggerFactory.getLogger(Peer.class); private static final int TimeOutDelay = 5000; public enum State { Disconnected, Connecting, Connected } enum DisconnectReason { Normal, NoneProtocol, Timeout } public State state; protected InetAddress peerAddress; protected int peerTimestamp; protected int peerPort; protected long peerServices; protected int peerConnectedCnt; protected long versionLastBlockHeight; // This may be wrong. Do not rely on it. private int incrementalBlockHeight; protected int version; protected long nonce; protected String userAgent; public long pingTime; private long pingStartTime; private int timestamp; private int filterBlockCount; private boolean sentVerAck, gotVerAck; private final HashSet<Sha256Hash> currentTxHashes, knownTxHashes, requestedBlockHashes; private final LinkedHashSet<Sha256Hash> currentBlockHashes; private final HashMap<Sha256Hash, HashSet<Tx>> needToRequestDependencyDict; private Block currentFilteredBlock; private VersionMessage versionMessage; private boolean bloomFilterSent; private int unrelatedTxRelayCount; private boolean synchronising; private int syncStartBlockNo; private long syncStartPeerBlockNo; private int synchronisingBlockCount; private List<Block> syncBlocks; private List<Sha256Hash> syncBlockHashes; public Peer(InetAddress address) { super(new InetSocketAddress(address, BitherjSettings.port)); this.peerAddress = address; peerPort = BitherjSettings.port; state = State.Disconnected; peerServices = 1; currentTxHashes = new HashSet<Sha256Hash>(); currentBlockHashes = new LinkedHashSet<Sha256Hash>(); knownTxHashes = new HashSet<Sha256Hash>(); requestedBlockHashes = new HashSet<Sha256Hash>(); needToRequestDependencyDict = new HashMap<Sha256Hash, HashSet<Tx>>(); incrementalBlockHeight = 0; unrelatedTxRelayCount = 0; nonce = new Random().nextLong(); peerTimestamp = (int) (new Date().getTime() / 1000 - 24 * 60 * 60 * (3 + new Random() .nextFloat() * 4)); synchronising = false; syncBlocks = new ArrayList<Block>(); syncBlockHashes = new ArrayList<Sha256Hash>(); } public void connect() { if (state != State.Disconnected) { log.info("peer[{}:{}] call connect, but its state is not disconnected", this.peerAddress.getHostAddress(), this.peerPort); return; } else { log.info("peer[{}:{}] call connect", this.peerAddress.getHostAddress(), this.peerPort); state = State.Connecting; if (!NioClientManager.instance().isRunning()) { if (NioClientManager.instance().startAndWait() != Service.State.RUNNING) { NioClientManager.instance().startUpError(); } } setTimeoutEnabled(true); setSocketTimeout(TimeOutDelay); bloomFilterSent = false; NioClientManager.instance().openConnection(new InetSocketAddress(getPeerAddress(), BitherjSettings.port), this); } } public void disconnect() { if (state == State.Disconnected) { return; } else { log.info("peer[{}:{}] call disconnect", this.peerAddress.getHostAddress(), this.peerPort); state = State.Disconnected; close(); } } @Override protected void processMessage(Message m) throws Exception { if (m == null) { return; } if (currentFilteredBlock != null && !(m instanceof Tx)) { currentFilteredBlock = null; currentTxHashes.clear(); exceptionCaught(new ProtocolException("Expect more tx for current filtering block, but got a " + m.getClass().getSimpleName() + " message")); } if (m instanceof NotFoundMessage) { // This is sent to us when we did a getdata on some transactions that aren't in the // peers memory pool. // Because NotFoundMessage is a subclass of InventoryMessage, // the test for it must come before the next. processNotFoundMessage((NotFoundMessage) m); } else if (m instanceof InventoryMessage) { processInv((InventoryMessage) m); } else if (m instanceof BlockMessage) { processBlock((BlockMessage) m); } else if (m instanceof FilteredBlockMessage) { startFilteredBlock((FilteredBlockMessage) m); } else if (m instanceof Tx) { processTransaction((Tx) m); } else if (m instanceof GetDataMessage) { processGetData((GetDataMessage) m); } else if (m instanceof HeadersMessage) { processHeaders((HeadersMessage) m); } else if (m instanceof AlertMessage) { processAlert((AlertMessage) m); } else if (m instanceof VersionMessage) { processVersionMessage((VersionMessage) m); } else if (m instanceof VersionAck) { if (!sentVerAck) { throw new ProtocolException("got a version ack before version"); } else if (gotVerAck) { throw new ProtocolException("got more than one version ack"); } gotVerAck = true; setTimeoutEnabled(false); state = State.Connected; PeerManager.instance().peerConnected(this); ping(); } else if (m instanceof PingMessage) { if (((PingMessage) m).hasNonce()) { sendMessage(new PongMessage(((PingMessage) m).getNonce())); } } else if (m instanceof PongMessage) { processPong((PongMessage) m); } else if (m instanceof RejectMessage) { processReject((RejectMessage) m); } } private void processNotFoundMessage(NotFoundMessage m) { // This is received when we previously did a getdata but the peer couldn't find what we // requested in it's // memory pool. Typically, because we are downloading dependencies of a relevant // transaction and reached // the bottom of the dependency tree (where the unconfirmed transactions connect to // transactions that are // in the chain). // // We go through and cancel the pending getdata futures for the items we were told // weren't found. log.info("peer[{}:{}] receive {} notfound item ", this.peerAddress.getHostAddress(), this.peerPort, m.getItems().size()); for (InventoryItem item : m.getItems()) { if (item.type == InventoryItem.Type.Transaction && item.hash != null && item.hash .length > 0) { checkDependencyWithNotFoundMsg(new Sha256Hash(item.hash)); } } } private void checkDependencyWithNotFoundMsg(Sha256Hash hash) { HashSet<Tx> needCheckDependencyTxs = needToRequestDependencyDict.get(hash); if (needCheckDependencyTxs == null) { return; } else { needToRequestDependencyDict.remove(hash); } HashSet<Tx> checkedTxs = new HashSet<Tx>(); for (Tx eachTx : needCheckDependencyTxs) { boolean stillNeedDependency = false; for (HashSet<Tx> set : needToRequestDependencyDict.values()) { if (set.contains(eachTx)) { stillNeedDependency = true; break; } } if (!stillNeedDependency) { PeerManager.instance().relayedTransaction(this, eachTx); checkedTxs.add(eachTx); } } for (Tx eachTx : checkedTxs) { checkDependencyWith(eachTx); } } private void checkDependencyWith(Tx tx) { HashSet<Tx> needCheckDependencyTxs = needToRequestDependencyDict.get(new Sha256Hash(tx .getTxHash())); if (needCheckDependencyTxs == null) { return; } else { needToRequestDependencyDict.remove(new Sha256Hash(tx.getTxHash())); } HashSet<Tx> invalidTxs = new HashSet<Tx>(); HashSet<Tx> checkedTxs = new HashSet<Tx>(); for (Tx eachTx : needCheckDependencyTxs) { boolean valid = true; for (int i = 0; i < eachTx.getIns().size(); i++) { if (Arrays.equals(eachTx.getIns().get(i).getTxHash(), tx.getTxHash())) { if (eachTx.getIns().get(i).getInSn() < tx.getOuts().size()) { byte[] outScript = tx.getOuts().get(eachTx.getIns().get(i).getInSn()) .getOutScript(); Script pubKeyScript = new Script(outScript); Script script = new Script(eachTx.getIns().get(i).getInSignature()); try { script.correctlySpends(eachTx, i, pubKeyScript, true); valid &= true; } catch (ScriptException e) { valid &= false; } } else { valid = false; } if (!valid) { break; } } } if (valid) { boolean stillNeedDependency = false; for (HashSet<Tx> set : needToRequestDependencyDict.values()) { if (set.contains(eachTx)) { stillNeedDependency = true; break; } } if (!stillNeedDependency) { PeerManager.instance().relayedTransaction(this, eachTx); checkedTxs.add(eachTx); } } else { invalidTxs.add(eachTx); } } for (Tx eachTx : invalidTxs) { log.warn(getPeerAddress().getHostAddress() + "tx:" + Utils.bytesToHexString(eachTx .getTxHash()) + " is invalid"); clearInvalidTxFromDependencyDict(eachTx); } for (Tx eachTx : checkedTxs) { checkDependencyWith(eachTx); } } private void clearInvalidTxFromDependencyDict(Tx tx) { for (HashSet<Tx> set : needToRequestDependencyDict.values()) { if (set.contains(tx)) { set.remove(tx); } } HashSet<Tx> subTxs = needToRequestDependencyDict.get(new Sha256Hash(tx.getTxHash())); if (subTxs != null) { needToRequestDependencyDict.remove(new Sha256Hash(tx.getTxHash())); for (Tx eachTx : subTxs) { clearInvalidTxFromDependencyDict(eachTx); } } } private void processInv(InventoryMessage inv) { ArrayList<InventoryItem> items = new ArrayList<InventoryItem>(inv.getItems()); if (items.size() == 0) { return; } else if (items.size() > MAX_GETDATA_HASHES) { log.info(this.getPeerAddress().getHostAddress() + " dropping inv message, " + "" + items.size() + " is too many items, max is " + MAX_GETDATA_HASHES); return; } if (!bloomFilterSent) { log.info("Peer {} received inv. But we didn't send bloomfilter. Ignore"); return; } ArrayList<Sha256Hash> txHashSha256Hashs = new ArrayList<Sha256Hash>(); ArrayList<Sha256Hash> blockHashSha256Hashs = new ArrayList<Sha256Hash>(); for (InventoryItem item : items) { InventoryItem.Type type = item.type; byte[] hash = item.hash; if (hash == null || hash.length == 0) { continue; } switch (type) { case Transaction: Sha256Hash big = new Sha256Hash(hash); if (!txHashSha256Hashs.contains(big)) { txHashSha256Hashs.add(big); } break; case Block: case FilteredBlock: // if(PeerManager.instance().getDownloadingPeer() == null || getDownloadData()) { Sha256Hash bigBlock = new Sha256Hash(hash); if (!blockHashSha256Hashs.contains(bigBlock)) { blockHashSha256Hashs.add(bigBlock); } // } break; } } log.info(getPeerAddress().getHostAddress() + " got inv with " + items.size() + " items " + txHashSha256Hashs.size() + " tx " + blockHashSha256Hashs.size() + " block"); if (txHashSha256Hashs.size() > 10000) { return; } // to improve chain download performance, if we received 500 block hashes, // we request the next 500 block hashes // immediately before sending the getdata request if (blockHashSha256Hashs.size() >= 500) { sendGetBlocksMessage(Arrays.asList(new Sha256Hash[]{blockHashSha256Hashs.get (blockHashSha256Hashs.size() - 1), blockHashSha256Hashs.get(0)}), null); } txHashSha256Hashs.removeAll(knownTxHashes); knownTxHashes.addAll(txHashSha256Hashs); if (txHashSha256Hashs.size() + blockHashSha256Hashs.size() > 0) { if (PeerManager.instance().getDownloadingPeer() == null || getDownloadData()) { sendGetDataMessageWithTxHashesAndBlockHashes(txHashSha256Hashs, blockHashSha256Hashs); // Each merkle block the remote peer sends us is followed by a set of tx messages for // that block. We send a ping // to get a pong reply after the block and all its tx are sent, // indicating that there are no more tx messages if (blockHashSha256Hashs.size() == 1) { ping(); } } else { sendGetDataMessageWithTxHashesAndBlockHashes(txHashSha256Hashs, new ArrayList<Sha256Hash>()); } } if (blockHashSha256Hashs.size() > 0) { //remember blockHashes in case we need to refetch them with an updated bloom filter currentBlockHashes.addAll(blockHashSha256Hashs); if (currentBlockHashes.size() > MAX_GETDATA_HASHES) { Iterator iterator = currentBlockHashes.iterator(); while (iterator.hasNext() && currentBlockHashes.size() > MAX_GETDATA_HASHES / 2) { iterator.remove(); } } if (this.synchronising) { this.syncBlockHashes.addAll(blockHashSha256Hashs); } this.increaseBlockNo(blockHashSha256Hashs.size()); } // if(blockHashSha256Hashs.size() == 1){ // incrementalBlockHeight ++; // } } private void increaseBlockNo(int blockCount) { if (this.synchronising) { synchronisingBlockCount += blockCount; } else { incrementalBlockHeight += blockCount; } } private void processBlock(BlockMessage m) { // we don't need to process block message after we send our awesome bloom filters. log.info("peer[{}:{}] receive block {}", this.peerAddress.getHostAddress(), this.peerPort, Utils.hashToString(m.getBlock().getBlockHash())); } private void startFilteredBlock(FilteredBlockMessage m) { Block block = m.getBlock(); block.verifyHeader(); log.info("peer[{}:{}] receive filtered block {} with {} tx", this.peerAddress.getHostAddress(), this.peerPort, Utils.hashToString(block.getBlockHash()), block.getTxHashes().size()); currentBlockHashes.remove(new Sha256Hash(block.getBlockHash())); requestedBlockHashes.remove(new Sha256Hash(block.getBlockHash())); if (requestedBlockHashes.contains(new Sha256Hash(block.getBlockHash()))) { return; } ArrayList<Sha256Hash> txHashes = new ArrayList<Sha256Hash>(); for (byte[] txHash : block.getTxHashes()) { txHashes.add(new Sha256Hash(txHash)); log.info("peer[{}:{}] receive filtered block {} tx {}", this.peerAddress.getHostAddress(), this.peerPort, Utils.hashToString(m.getBlock().getBlockHash()), Utils.hashToString(txHash)); } // txHashes.removeAll(knownTxHashes); // wait util we get all the tx messages before processing the block if (txHashes.size() > 0) { currentFilteredBlock = block; currentTxHashes.clear(); currentTxHashes.addAll(txHashes); } else { if (this.synchronising && this.syncBlockHashes.contains(new Sha256Hash(block.getBlockHash()))) { this.syncBlockHashes.remove(new Sha256Hash(block.getBlockHash())); this.syncBlocks.add(block); if (this.syncBlockHashes.size() == 0) { PeerManager.instance().relayedBlocks(this, this.syncBlocks); this.syncBlocks.clear(); } else if (this.syncBlocks.size() >= 100) { PeerManager.instance().relayedBlocks(this, this.syncBlocks); this.syncBlocks.clear(); } } else { PeerManager.instance().relayedBlock(this, block); } } if (currentBlockHashes.size() == 0) { sendGetBlocksMessage(Arrays.asList(new byte[][]{block.getBlockHash(), BlockChain.getInstance().getBlockLocatorArray().get(0)}), null); } } private void processTransaction(Tx tx) throws VerificationException { if (currentFilteredBlock != null) { // we're collecting tx messages for a merkleblock PeerManager.instance().relayedTransaction(this, tx); // we can't we byte array hash or BigInteger as the key. // byte array can't be compared // BigInteger can't be cast back to byte array // so we use Sha256Hash class here as key boolean removed = currentTxHashes.remove(new Sha256Hash(tx.getTxHash())); log.info("peer[{}:{}] receive tx {} filtering block: {}, remaining tx {}, remove {}", this.peerAddress.getHostAddress(), this.peerPort, Utils.hashToString(tx.getTxHash()), Utils.hashToString(currentFilteredBlock .getBlockHash()), currentTxHashes.size(), removed ? "success" : "failed"); if (currentTxHashes.size() == 0) { // we received the entire block including all // matched tx Block block = currentFilteredBlock; currentFilteredBlock = null; currentTxHashes.clear(); if (this.synchronising && this.syncBlockHashes.contains(new Sha256Hash(block.getBlockHash()))) { this.syncBlockHashes.remove(new Sha256Hash(block.getBlockHash())); this.syncBlocks.add(block); if (this.syncBlockHashes.size() == 0) { PeerManager.instance().relayedBlocks(this, this.syncBlocks); this.syncBlocks.clear(); } else if (this.syncBlocks.size() >= 100) { PeerManager.instance().relayedBlocks(this, this.syncBlocks); this.syncBlocks.clear(); } } else { PeerManager.instance().relayedBlock(this, block); } } } else { log.info("peer[{}:{}] receive tx {}", this.peerAddress.getHostAddress(), this.peerPort, Utils.hashToString(tx.getTxHash())); if (needToRequestDependencyDict.get(new Sha256Hash(tx.getTxHash())) == null || needToRequestDependencyDict.get(new Sha256Hash(tx.getTxHash())).size() == 0) { if (AddressManager.getInstance().isTxRelated(tx)) { unrelatedTxRelayCount = 0; } else { unrelatedTxRelayCount++; if (unrelatedTxRelayCount > MAX_UNRELATED_TX_RELAY_COUNT) { exceptionCaught(new Exception("Peer " + getPeerAddress().getHostAddress() + " is junking us. Drop it.")); return; } } } // check dependency HashMap<Sha256Hash, Tx> dependency = AbstractDb.txProvider.getTxDependencies(tx); HashSet<Sha256Hash> needToRequest = new HashSet<Sha256Hash>(); boolean valid = true; for (int i = 0; i < tx.getIns().size(); i++) { Tx prevTx = dependency.get(new Sha256Hash(tx.getIns().get(i).getPrevTxHash())); if (prevTx == null) { needToRequest.add(new Sha256Hash(tx.getIns().get(i).getPrevTxHash())); } else { if (prevTx.getOuts().size() <= tx.getIns().get(i).getInSn()) { valid = false; break; } byte[] outScript = prevTx.getOuts().get(tx.getIns().get(i).getInSn()) .getOutScript(); Script pubKeyScript = new Script(outScript); Script script = new Script(tx.getIns().get(i).getInSignature()); try { script.correctlySpends(tx, i, pubKeyScript, true); valid &= true; } catch (ScriptException e) { valid &= false; } if (!valid) { break; } } } try { tx.verify(); valid &= true; } catch (VerificationException e) { valid &= false; } if (valid && needToRequest.size() == 0) { PeerManager.instance().relayedTransaction(this, tx); checkDependencyWith(tx); } else if (valid && needToRequest.size() > 0) { for (Sha256Hash txHash : needToRequest) { if (needToRequestDependencyDict.get(txHash) == null) { HashSet<Tx> txs = new HashSet<Tx>(); txs.add(tx); needToRequestDependencyDict.put(txHash, txs); } else { HashSet<Tx> txs = needToRequestDependencyDict.get(txHash); txs.add(tx); } } sendGetDataMessageWithTxHashesAndBlockHashes(new ArrayList<Sha256Hash> (needToRequest), null); } } } private void processGetData(GetDataMessage getdata) { log.info("{}: Received getdata message with {} items", getAddress(), getdata.getItems().size()); ArrayList<InventoryItem> notFound = new ArrayList<InventoryItem>(); for (InventoryItem item : getdata.getItems()) { if (item.type == InventoryItem.Type.Transaction) { Tx tx = PeerManager.instance().requestedTransaction(this, item.hash); if (tx != null) { sendMessage(tx); log.info("Peer {} asked for tx: {} , found {}", getPeerAddress() .getHostAddress(), Utils.hashToString(item.hash), "hash: " + Utils.hashToString(tx.getTxHash()) + ", " + "content: " + Utils.bytesToHexString(tx.bitcoinSerialize())); continue; } else { log.info("Peer {} asked for tx: {} , not found", getPeerAddress().getHostAddress(), Utils.hashToString(item.hash)); } } notFound.add(item); } if (notFound.size() > 0) { sendMessage(new NotFoundMessage(notFound)); } } private void processHeaders(HeadersMessage m) throws ProtocolException { // Runs in network loop thread for this peer. // // This method can run if a peer just randomly sends us a "headers" message (should never // happen), or more // likely when we've requested them as part of chain download using fast catchup. We need // to add each block to // the chain if it pre-dates the fast catchup time. If we go past it, // we can stop processing the headers and // request the full blocks from that point on instead. log.info("peer[{}:{}] receive {} headers", this.peerAddress.getHostAddress(), this.peerPort, m.getBlockHeaders().size()); if (BlockChain.getInstance() == null) { // Can happen if we are receiving unrequested data, or due to programmer error. log.warn("Received headers when Peer is not configured with a chain."); return; } if (m.getBlockHeaders() == null || m.getBlockHeaders().size() == 0) { return; } try { int lastBlockTime = 0; byte[] firstHash = m.getBlockHeaders().get(0).getBlockHash(); byte[] lastHash = m.getBlockHeaders().get(m.getBlockHeaders().size() - 1).getBlockHash(); // ArrayList<Block> blocksToRelay = new ArrayList<Block>(); // for (int i = 0; i < m.getBlockHeaders().size(); i++) { // blocksToRelay.add(m.getBlockHeaders().get(i)); // } // for (int i = 0; i < m.getBlockHeaders().size(); i++) { // BlockMessage header = m.getBlockHeaders().get(i); // // Process headers until we pass the fast catchup time, // // or are about to catch up with the head // // of the chain - always process the last block as a full/filtered block to kick // // us out of the // // fast catchup mode (in which we ignore new blocks). // // boolean passedTime = header.getBlock().getBlockTime() >= PeerManager.instance() // .earliestKeyTime; // boolean reachedTop = PeerManager.instance().getLastBlockHeight() >= this // .versionLastBlockHeight; // if (!passedTime && !reachedTop) { // if (header.getBlock().getBlockTime() > lastBlockTime) { // lastBlockTime = header.getBlock().getBlockTime(); // if (lastBlockTime + 7 * 24 * 60 * 60 >= PeerManager.instance() // .earliestKeyTime - 2 * 60 * 60) { // lastHash = header.getBlock().getBlockHash(); // } // } // if(!blocksToRelay.contains(header.getBlock())){ // blocksToRelay.add(header.getBlock()); // } // } // } PeerManager.instance().relayedBlockHeadersForMainChain(this, m.getBlockHeaders()); // if (lastBlockTime + 7 * 24 * 60 * 60 >= PeerManager.instance().earliestKeyTime - 2 * // 60 * 60) { // sendGetBlocksMessage(Arrays.asList(new byte[][]{lastHash, firstHash}), null); // } else { sendGetHeadersMessage(Arrays.asList(new byte[][]{lastHash, firstHash}), null); // } } catch (VerificationException e) { log.warn("Block header verification failed", e); } } private void processVersionMessage(VersionMessage version) { this.versionMessage = version; this.version = version.clientVersion; if (this.version < BitherjSettings.MIN_PROTO_VERSION) { close(); return; } peerServices = version.localServices; peerTimestamp = (int) version.time; userAgent = version.subVer; versionLastBlockHeight = version.bestHeight; sendMessage(new VersionAck()); } public boolean getDownloadData() { if (PeerManager.instance().getDownloadingPeer() != null) { return equals(PeerManager.instance().getDownloadingPeer()); } else { return false; } } private void processPong(PongMessage m) { // Iterates over a snapshot of the list, so we can run unlocked here. if (m.getNonce() == nonce) { if (pingStartTime > 0) { if (pingTime > 0) { pingTime = (long) (pingTime * 0.5f + (new Date().getTime() - pingStartTime) * 0.5f); } else { pingTime = new Date().getTime() - pingStartTime; } pingStartTime = 0; } log.info("Peer " + getPeerAddress().getHostAddress() + " receive pong, ping time: " + pingTime); } } private void ping() { if (state != State.Connected) { return; } sendMessage(new PingMessage(nonce)); pingStartTime = new Date().getTime(); } private void sendVersionMessage() { sendMessage(new VersionMessage((int) PeerManager.instance().getLastBlockHeight(), false)); log.info("Send version message to peer {}", getPeerAddress().getHostAddress()); sentVerAck = true; } private void processAlert(AlertMessage m) { try { if (m.isSignatureValid()) { log.info("Received alert from peer {}: {}", toString(), m.getStatusBar()); } else { log.warn("Received alert with invalid signature from peer {}: {}", toString(), m.getStatusBar()); } } catch (Throwable t) { // Signature checking can FAIL on Android platforms before Gingerbread apparently due // to bugs in their // Sha256Hash implementations! See issue 160 for discussion. As alerts are just // optional and not that // useful, we just swallow the error here. log.error("Failed to check signature: bug in platform libraries?", t); } } private void processReject(RejectMessage m) { exceptionCaught(new ProtocolException("Peer " + getPeerAddress().getHostAddress() + " " + "Rejected. \n" + m.toString())); } public void sendFilterLoadMessage(BloomFilter filter) { if (state != State.Connected) { return; } filterBlockCount = 0; log.info("Peer {} send bloom filter", getPeerAddress().getHostAddress()); bloomFilterSent = true; sendMessage(filter); } public void sendMemPoolMessage() { if (state != State.Connected) { return; } sendMessage(new MemoryPoolMessage()); } public void sendGetAddrMessage() { if (state != State.Connected) { return; } sendMessage(new GetAddrMessage()); } public void sendInvMessageWithTxHash(Sha256Hash txHash) { if (state != State.Connected) { return; } InventoryMessage m = new InventoryMessage(); m.addTransaction(AbstractDb.txProvider.getTxDetailByTxHash(txHash.getBytes())); log.info("Peer {} send inv with tx {}", getPeerAddress().getHostAddress(), Utils.hashToString(txHash.getBytes())); sendMessage(m); } public void refetchBlocksFrom(Sha256Hash blockHash) { if (!currentBlockHashes.contains(blockHash)) { return; } Iterator<Sha256Hash> iterator = currentBlockHashes.iterator(); while (iterator.hasNext()) { Sha256Hash hash = iterator.next(); iterator.remove(); if (blockHash.equals(hash)) { break; } } log.info("Peer {} refetch {} blocks from {}", getPeerAddress().getHostAddress(), currentBlockHashes.size(), Utils.hashToString(blockHash.getBytes())); sendGetDataMessageWithTxHashesAndBlockHashes(null, new ArrayList<Sha256Hash>(currentBlockHashes)); } public void sendGetHeadersMessage(List<byte[]> locators, byte[] hashStop) { if (state != State.Connected) { return; } GetHeadersMessage m = new GetHeadersMessage(locators, hashStop == null ? Sha256Hash .ZERO_HASH.getBytes() : hashStop); log.info("Peer {} send get header message", getPeerAddress().getHostAddress()); sendMessage(m); } public void sendGetHeadersMessage(List<Sha256Hash> locators, Sha256Hash hashStop) { ArrayList<byte[]> ls = new ArrayList<byte[]>(); for (Sha256Hash i : locators) { ls.add(i.getBytes()); } sendGetHeadersMessage(ls, hashStop == null ? null : hashStop.getBytes()); } public void sendGetBlocksMessage(List<byte[]> locators, byte[] hashStop) { if (state != State.Connected) { return; } GetBlocksMessage m = new GetBlocksMessage(locators, hashStop == null ? Sha256Hash .ZERO_HASH.getBytes() : hashStop); log.info("Peer {} send get blocks message", getPeerAddress().getHostAddress()); sendMessage(m); } public void sendGetBlocksMessage(List<Sha256Hash> locators, Sha256Hash hashStop) { ArrayList<byte[]> ls = new ArrayList<byte[]>(); for (Sha256Hash i : locators) { ls.add(i.getBytes()); } sendGetBlocksMessage(ls, hashStop == null ? null : hashStop.getBytes()); } public void sendGetDataMessageWithTxHashesAndBlockHashes(List<Sha256Hash> txHashes, List<Sha256Hash> blockHashes) { if (state != State.Connected) { return; } GetDataMessage m = new GetDataMessage(); if (blockHashes != null) { for (Sha256Hash hash : blockHashes) { m.addFilteredBlock(hash.getBytes()); } requestedBlockHashes.addAll(blockHashes); } if (txHashes != null) { for (Sha256Hash hash : txHashes) { m.addTransaction(hash.getBytes()); } } int blochHashCount = 0; if (blockHashes != null) { blochHashCount = blockHashes.size(); } if (filterBlockCount + blochHashCount > BitherjSettings.BLOCK_DIFFICULTY_INTERVAL) { log.info("{} rebuilding bloom filter after {} blocks", getPeerAddress().getHostAddress(), filterBlockCount); sendFilterLoadMessage(PeerManager.instance().bloomFilterForPeer(this)); } filterBlockCount += blochHashCount; log.info("Peer {} send get data message with {} tx and & {} block", getPeerAddress().getHostAddress(), txHashes == null ? 0 : txHashes.size(), blochHashCount); sendMessage(m); } public void connectFail() { AbstractDb.peerProvider.conncetFail(getPeerAddress()); } public void connectError() { AbstractDb.peerProvider.removePeer(getPeerAddress()); } public void connectSucceed() { peerConnectedCnt = 1; peerTimestamp = (int) (new Date().getTime() / 1000); AbstractDb.peerProvider.connectSucceed(getPeerAddress()); sendFilterLoadMessage(PeerManager.instance().bloomFilterForPeer(this)); } @Override public void connectionClosed() { state = State.Disconnected; PeerManager.instance().peerDisconnected(this, DisconnectReason.Normal); } @Override protected void timeoutOccurred() { PeerManager.instance().peerDisconnected(this, DisconnectReason.Timeout); super.timeoutOccurred(); } @Override protected void exceptionCaught(Exception e) { super.exceptionCaught(e); if (e instanceof ProtocolException) { PeerManager.instance().peerDisconnected(this, DisconnectReason.NoneProtocol); } else { PeerManager.instance().peerDisconnected(this, DisconnectReason.NoneProtocol); } } @Override public void connectionOpened() { if (state == State.Disconnected) { disconnect(); return; } sendVersionMessage(); } @Override public boolean equals(Object o) { if (o instanceof Peer) { Peer item = (Peer) o; return Arrays.equals(getPeerAddress().getAddress(), item.getPeerAddress().getAddress()); } else { return false; } } @Override public int hashCode() { return getPeerAddress().hashCode(); } public InetAddress getPeerAddress() { return peerAddress; } public void setPeerAddress(InetAddress peerAddress) { this.peerAddress = peerAddress; } public int getPeerTimestamp() { return peerTimestamp; } public void setPeerTimestamp(int peerTimestamp) { this.peerTimestamp = peerTimestamp; } public int getPeerPort() { return peerPort; } public void setPeerPort(int peerPort) { this.peerPort = peerPort; } public long getPeerServices() { return peerServices; } public void setPeerServices(long peerServices) { this.peerServices = peerServices; } public int getPeerConnectedCnt() { return peerConnectedCnt; } public void setPeerConnectedCnt(int peerConnectedCnt) { this.peerConnectedCnt = peerConnectedCnt; } public long getVersionLastBlockHeight() { return versionLastBlockHeight; } // This may be wrong. Do not rely on it. public long getDisplayLastBlockHeight() { return versionLastBlockHeight + incrementalBlockHeight; } public int getClientVersion() { return version; } public String getSubVersion() { return userAgent; } public boolean getSynchronising() { return this.synchronising; } public void setSynchronising(boolean synchronising) { if (synchronising && !this.synchronising) { syncStartBlockNo = BlockChain.getInstance().getLastBlock().getBlockNo(); syncStartPeerBlockNo = this.getDisplayLastBlockHeight(); synchronisingBlockCount = 0; syncBlocks = new ArrayList<Block>(); syncBlockHashes = new ArrayList<Sha256Hash>(); this.synchronising = synchronising; } else if (!synchronising && this.synchronising) { incrementalBlockHeight = BlockChain.getInstance().getLastBlock().getBlockNo() - (int) this.getVersionLastBlockHeight(); synchronisingBlockCount = 0; this.synchronising = synchronising; } } }
do not check dependency now, may check it in future
bitherj/src/main/java/net/bither/bitherj/core/Peer.java
do not check dependency now, may check it in future
Java
apache-2.0
1aa47c8e871c058fc347541a89c94ca34576834b
0
apache/portals-pluto,apache/portals-pluto,apache/portals-pluto
/* Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.portlet.tck.portlets; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Map; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.ActionURL; import javax.portlet.HeaderPortlet; import javax.portlet.HeaderRequest; import javax.portlet.HeaderResponse; import javax.portlet.Portlet; import javax.portlet.PortletConfig; import javax.portlet.PortletException; import javax.portlet.PortletURL; import javax.portlet.RenderParameters; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import javax.portlet.ResourceRequest; import javax.portlet.ResourceResponse; import javax.portlet.ResourceServingPortlet; import javax.portlet.ResourceURL; import javax.portlet.annotations.PortletApplication; import javax.portlet.annotations.PortletConfiguration; import javax.portlet.annotations.PortletQName; import javax.portlet.annotations.PublicRenderParameterDefinition; import javax.portlet.annotations.Supports; import javax.portlet.tck.beans.TestButton; import javax.portlet.tck.beans.TestResult; import javax.portlet.tck.beans.TestSetupLink; import javax.portlet.tck.util.ModuleTestCaseDetails; import javax.servlet.http.Cookie; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS10; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS15; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE9; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE10; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS13; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS2; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS6; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS15; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS16; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS13A; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_PROPERTIES1; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_PROPERTIES2; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_PROPERTIES3; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_PROPERTIES4; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE11; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_CHARACTERENCODING4; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_CONTENTTYPE5; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE8; import static javax.portlet.tck.constants.Constants.RESULT_ATTR_PREFIX; import static javax.portlet.PortletSession.PORTLET_SCOPE; import static javax.portlet.ResourceURL.PAGE; import static javax.portlet.tck.constants.Constants.THREADID_ATTR; /** * This portlet implements several test cases for the JSR 362 TCK. The test case * names are defined in the /src/main/resources/xml-resources/additionalTCs.xml * file. The build process will integrate the test case names defined in the * additionalTCs.xml file into the complete list of test case names for * execution by the driver. * */ @PortletApplication(publicParams = { @PublicRenderParameterDefinition(identifier = "tckPRP3", qname = @PortletQName(localPart = "tckPRP3", namespaceURI = "")), @PublicRenderParameterDefinition(identifier = "tr1_ready", qname = @PortletQName(localPart = "tr1_ready", namespaceURI = "")) }) @PortletConfiguration(portletName = "HeaderPortletTests_SPEC15_Header", publicParams = { "tckPRP3", "tr1_ready" }, supports = { @Supports(mimeType = "text/html") }) public class HeaderPortletTests_SPEC15_Header implements Portlet, HeaderPortlet, ResourceServingPortlet { @Override public void init(PortletConfig config) throws PortletException { } @Override public void destroy() { } @Override public void processAction(ActionRequest portletReq, ActionResponse portletResp) throws PortletException, IOException { String action = portletReq.getParameter("inputval"); if (action != null) { if (V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS10.equals(action) && portletReq.getParameter("actionURLTr0") != null && portletReq.getParameter("actionURLTr0").equals("true")) { /* TestCase: V2AddlRequestTests_SPEC2_11_Render_parameters10 */ /* Details: "The portlet-container must not propagate parameters */ /* received in an action or event request to subsequent render */ /* requests of the portlet" */ portletResp.setRenderParameter("tr0", "true"); } else if (V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS15 .equals(action) && portletReq.getParameter("tr3a") != null && portletReq.getParameter("tr3a").equals("true")) { /* TestCase: V3HeaderPortletTests_SPEC15_Header_parameters15 */ /* * Details: "Render parameters get automatically cleared if the * portlet receives a processAction or processEvent call" */ portletResp.setRenderParameter("tr3b", "true"); } else if (V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE9.equals(action)) { /* TestCase: V3HeaderPortletTests_SPEC15_Header_cookie9 */ /* * Details: "Cookies set during the Header phase should be available * to the portlet during a subsequent Action phase" */ Cookie[] cookies = portletReq.getCookies(); for (Cookie c : cookies) { if (c.getName().equals("header_tr1_cookie") && c.getValue().equals("true")) { c.setMaxAge(0); c.setValue(""); portletResp.setRenderParameter("trCookie1", "true"); } } } } } @Override public void render(RenderRequest portletReq, RenderResponse portletResp) throws PortletException, IOException { ModuleTestCaseDetails tcd = new ModuleTestCaseDetails(); PrintWriter writer = portletResp.getWriter(); /* TestCase: V3HeaderPortletTests_SPEC15_Header_cookie8 */ /* * Details: "Cookies set during the Header phase should be available to * the portlet during the Resource phase" */ writer.write( "<div id=\"V3HeaderPortletTests_SPEC15_Header\">no resource output.</div>\n"); ResourceURL resurl = portletResp.createResourceURL(); resurl.setCacheability(PAGE); writer.write("<script>\n"); writer.write("(function () {\n"); writer.write(" var xhr = new XMLHttpRequest();\n"); writer.write(" xhr.onreadystatechange=function() {\n"); writer.write(" if (xhr.readyState==4 && xhr.status==200) {\n"); writer.write( " document.getElementById(\"V3HeaderPortletTests_SPEC15_Header\").innerHTML=xhr.responseText;\n"); writer.write(" }\n"); writer.write(" };\n"); writer.write( " xhr.open(\"GET\",\"" + resurl.toString() + "\",true);\n"); writer.write(" xhr.send();\n"); writer.write("})();\n"); writer.write("</script>\n"); /* TestCase: V3HeaderPortletTests_SPEC15_Header_cookie10 */ /* * Details: "Cookies set during the Header phase should be available to * the portlet during a subsequent Render phase" */ Cookie[] cookies = portletReq.getCookies(); StringBuilder txt = new StringBuilder(128); txt.append("<p>Debug info:"); txt.append("<br>"); txt.append("# Cookies: ").append(cookies.length).append("<br>"); TestResult tr2 = tcd .getTestResultFailed(V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE10); for (Cookie c : cookies) { txt.append("Name: ").append(c.getName()); txt.append(", Value: ").append(c.getValue()).append("<br>"); if (c.getName().equals("header_tr2_cookie") && c.getValue().equals("true")) { txt.append("<br>").append("Found my cookie!").append("<br>"); c.setMaxAge(0); c.setValue(""); tr2.setTcSuccess(true); } } tr2.writeTo(writer); txt.append("</p>"); writer.append(txt.toString()); String msg = ((String) portletReq.getPortletSession().getAttribute( RESULT_ATTR_PREFIX + "HeaderPortletTests_SPEC15_Header", PORTLET_SCOPE)); writer.write("<p>" + msg + "</p>"); portletReq.getPortletSession().removeAttribute( RESULT_ATTR_PREFIX + "HeaderPortletTests_SPEC15_Header", PORTLET_SCOPE); } @Override public void renderHeaders(HeaderRequest portletReq, HeaderResponse portletResp) throws PortletException, IOException { ModuleTestCaseDetails tcd = new ModuleTestCaseDetails(); StringWriter writer = new StringWriter(); RenderParameters renderParams = portletReq.getRenderParameters(); String action = portletReq.getParameter("inputval"); Boolean successTr2 = false, successTr5 = false, successTr6 = false; Boolean successTr7 = false, successTr8 = false, successTr13 = false; /* TestCase: V3HeaderPortletTests_SPEC15_Header_parameters10 */ /* * Details: "The portlet-container must not propagate parameters received * in an action or event request to subsequent header requests of the * portlet" */ if (renderParams.getValue("actionURLTr0") == null && renderParams.getValue("tr0") != null && "true".equals(renderParams.getValue("tr0"))) { TestResult tr0 = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS10); tr0.setTcSuccess(true); tr0.writeTo(writer); } else { ActionURL aurl = portletResp.createActionURL(); aurl.setParameter("actionURLTr0", "true"); TestButton tb = new TestButton( V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS10, aurl); tb.writeTo(writer); } if (action != null) { if (action.equals(V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS13)) { /* TestCase: V3HeaderPortletTests_SPEC15_Header_parameters13 */ /* * Details: "If a portlet receives a render request that is the * result of invoking a render URL targeting this portlet the render * parameters received with the render request must be the * parameters set on the render URL" */ TestResult tr2 = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS13); if (portletReq.getParameter("renderURLTr2") != null && portletReq.getParameter("tr2") != null && (portletReq.getParameter("renderURLTr2").contains("tr2:" + portletReq.getParameter("tr2")) || portletReq.getParameter("renderURLTr2").contains("tr2=" + portletReq.getParameter("tr2")))) { tr2.setTcSuccess(true); successTr2 = true; } else { tr2.appendTcDetail( "Parameter renderURLTr2 is missing or does not contain tr2 parameter value."); } tr2.writeTo(writer); } else if (action .equals(V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS2)) { /* TestCase: V3HeaderPortletTests_SPEC15_Header_parameters2 */ /* Details: "The parameters the request object returns must be */ /* \"x-www-form-urlencoded\" decoded" */ TestResult tr5 = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS2); if (portletReq.getParameter("tr5") != null && portletReq.getParameter("tr5").equals("true&<>'")) { tr5.setTcSuccess(true); successTr5 = true; } tr5.writeTo(writer); } else if (action .equals(V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS6)) { /* TestCase: V3HeaderPortletTests_SPEC15_Header_parameters6 */ /* * Details: "The getParameterMap method must return an unmodifiable * Map object" */ TestResult tr6 = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS6); if (portletReq.getParameterMap().containsKey("inputval") && V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS6.equals( portletReq.getParameterMap().get("inputval")[0])) { String tr6TestStringArray[] = { "Modified Value" }; try { portletReq.getParameterMap().put( "inputval", tr6TestStringArray); if (V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS6 .equals( portletReq.getParameterMap().get("inputval")[0])) { tr6.setTcSuccess(true); successTr6 = true; } } catch (UnsupportedOperationException e) { tr6.setTcSuccess(true); successTr6 = true; } } tr6.writeTo(writer); } else if (action.equals( V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS15)) { /* * TestCase: * V3HeaderPortletTests_SPEC15_Header_publicRenderParameters15 */ /* * Details: "A map of private parameters can be obtained through the * getPrivateParameterMap method" */ TestResult tr7 = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS15); Map<String, String[]> privateParamMap = portletReq .getPrivateParameterMap(); if (privateParamMap != null && privateParamMap.containsKey("tr7") && privateParamMap.get("tr7")[0].equals("true")) { tr7.setTcSuccess(true); successTr7 = true; } tr7.writeTo(writer); } else if (action.equals( V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS16)) { /* * TestCase: * V3HeaderPortletTests_SPEC15_Header_publicRenderParameters16 */ /* * Details: "A map of public parameters can be obtained through the * getPublicParameterMap method" */ TestResult tr8 = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS16); if (portletReq.getPublicParameterMap() != null && portletReq .getPublicParameterMap().containsKey("tckPRP3")) { tr8.setTcSuccess(true); successTr8 = true; } else { tr8.appendTcDetail("No public render parameter found."); } tr8.writeTo(writer); } else if (action.equals( V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS13A)) { /* * TestCase: * V3HeaderPortletTests_SPEC15_Header_publicRenderParameters13a */ /* Details: "A public render parameter can be deleted using the */ /* removePublicRenderParameter method on the PortletURL" */ TestResult tr13 = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS13A); if (portletReq.getPublicParameterMap() != null && !portletReq .getPublicParameterMap().containsKey("tckPRP3")) { tr13.setTcSuccess(true); successTr13 = true; } else { tr13.appendTcDetail("Render parameter tckPRP3 is not removed."); } tr13.writeTo(writer); } } if (!successTr2) { /* TestCase: V3HeaderPortletTests_SPEC15_Header_parameters13 */ /* * Details: "If a portlet receives a render request that is the result * of invoking a render URL targeting this portlet the render * parameters received with the render request must be the parameters * set on the render URL" */ PortletURL rurl = portletResp.createRenderURL(); rurl.setParameters(portletReq.getPrivateParameterMap()); rurl.setParameter("tr2", "true"); rurl.setParameter("renderURLTr2", rurl.toString()); TestButton tb = new TestButton( V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS13, rurl); tb.writeTo(writer); } if (!successTr5) { /* TestCase: V3HeaderPortletTests_SPEC15_Header_parameters2 */ /* Details: "The parameters the request object returns must be */ /* \"x-www-form-urlencoded\" decoded" */ PortletURL purl = portletResp.createRenderURL(); purl.setParameter("tr5", "true&<>'"); TestButton tb = new TestButton( V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS2, purl); tb.writeTo(writer); } if (!successTr6) { /* TestCase: V3HeaderPortletTests_SPEC15_Header_parameters6 */ /* * Details: "The getParameterMap method must return an unmodifiable Map * object" */ PortletURL purl = portletResp.createRenderURL(); TestButton tb = new TestButton( V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS6, purl); tb.writeTo(writer); } if (!successTr7) { /* * TestCase: * V3HeaderPortletTests_SPEC15_Header_publicRenderParameters15 */ /* Details: "A map of private parameters can be obtained through the */ /* getPrivateParameterMap method" */ PortletURL purl = portletResp.createRenderURL(); purl.setParameter("tr7", "true"); TestButton tb = new TestButton( V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS15, purl); tb.writeTo(writer); } if (!successTr8) { /* * TestCase: * V3HeaderPortletTests_SPEC15_Header_publicRenderParameters16 */ /* Details: "A map of public parameters can be obtained through the */ /* getPublicParameterMap method" */ if (portletReq.getParameter("tckPRP3") == null) { PortletURL purl = portletResp.createRenderURL(); purl.setParameter("tckPRP3", "true"); TestSetupLink tl = new TestSetupLink( V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS16, purl); tl.writeTo(writer); } else { PortletURL aurl = portletResp.createRenderURL(); aurl.setParameters(portletReq.getPrivateParameterMap()); TestButton tb = new TestButton( V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS16, aurl); tb.writeTo(writer); } } if (!successTr13) { /* * TestCase: * V3HeaderPortletTests_SPEC15_Header_publicRenderParameters13a */ /* Details: "A public render parameter can be deleted using the */ /* removePublicRenderParameter method on the PortletURL" */ if (portletReq.getParameter("tckPRP3") == null) { PortletURL purl = portletResp.createRenderURL(); purl.setParameter("tckPRP3", "true"); TestSetupLink tl = new TestSetupLink( V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS13A, purl); tl.writeTo(writer); } else { PortletURL purl = portletResp.createRenderURL(); purl.setParameters(portletReq.getPrivateParameterMap()); purl.removePublicRenderParameter("tckPRP3"); TestButton tb = new TestButton( V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS13A, purl); tb.writeTo(writer); } } /* TestCase: V3HeaderPortletTests_SPEC15_Header_parameters15 */ /* Details: "Render parameters get automatically cleared if the portlet */ /* receives a processAction or processEvent call" */ if (portletReq.getParameter("tr3a") != null) { PortletURL aurl = portletResp.createActionURL(); aurl.setParameter("tr3a", "true"); TestButton tb = new TestButton( V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS15, aurl); tb.writeTo(writer); } else { if (portletReq.getParameter("tr3b") != null && portletReq.getParameter("tr3b").equals("true")) { TestResult tr3 = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS15); tr3.setTcSuccess(true); tr3.writeTo(writer); } else { PortletURL purl = portletResp.createRenderURL(); purl.setParameter("tr3a", "true"); TestSetupLink tl = new TestSetupLink( V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS15, purl); tl.writeTo(writer); } } /* TestCase: V3HeaderPortletTests_SPEC15_Header_properties1 */ /* * Details: "The portlet can use the getProperty method to access single * portal property and optionally-available HTTP header values" */ { TestResult result = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_PROPERTIES1); if (portletReq.getProperty("Accept") != null) { result.setTcSuccess(true); } else { result.appendTcDetail( "Failed because Accept header is not found in request headers."); } result.writeTo(writer); } /* TestCase: V3HeaderPortletTests_SPEC15_Header_properties2 */ /* * Details: "The portlet can use the getProperties method to access * multiple portal property and optionally-available HTTP header values by * the same property name" */ { TestResult result = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_PROPERTIES2); if (portletReq.getProperties("Accept").hasMoreElements()) { result.setTcSuccess(true); } else { result.appendTcDetail( "Failed because Accept header is not found in request headers."); } result.writeTo(writer); } /* TestCase: V3HeaderPortletTests_SPEC15_Header_properties3 */ /* * Details: "The portlet can use the getPropertyNames method to obtain an * Enumeration of all available property names" */ { TestResult result = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_PROPERTIES3); if (portletReq.getPropertyNames().hasMoreElements()) { result.setTcSuccess(true); } else { result.appendTcDetail( "Failed because no header is not found in request headers."); } result.writeTo(writer); } /* TestCase: V3HeaderPortletTests_SPEC15_Header_properties4 */ /* * Details: "The portlet can access cookies provided by the current * request using the getCookies method" */ { TestResult result = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_PROPERTIES4); if (portletReq.getCookies().length > 0) { result.setTcSuccess(true); } else { result.appendTcDetail( "Failed because no cookies are found in HeaderRequest object"); } result.writeTo(writer); } /* TestCase: V3HeaderPortletTests_SPEC15_Header_cookie8 */ /* * Details: "Cookies set during the Header phase should be available to * the portlet during the Resource phase" */ { Cookie c = new Cookie("header_tr0_cookie", "true"); c.setMaxAge(100); c.setPath("/"); portletResp.addProperty(c); } /* TestCase: V3HeaderPortletTests_SPEC15_Header_cookie9 */ /* * Details: "Cookies set during the Header phase should be available to * the portlet during a subsequent Action phase" */ if (portletReq.getParameter("trCookie1") != null && portletReq.getParameter("trCookie1").equals("true")) { TestResult tr1 = tcd .getTestResultFailed(V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE9); tr1.setTcSuccess(true); tr1.writeTo(writer); } else { Cookie c = new Cookie("header_tr1_cookie", "true"); c.setMaxAge(100); c.setPath("/"); portletResp.addProperty(c); PortletURL aurl = portletResp.createActionURL(); TestButton tb = new TestButton( V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE9, aurl); tb.writeTo(writer); } /* TestCase: V3HeaderPortletTests_SPEC15_Header_cookie10 */ /* * Details: "Cookies set during the Header phase should be available to * the portlet during a subsequent Render phase" */ { Cookie c = new Cookie("header_tr2_cookie", "true"); c.setMaxAge(100); c.setPath("/"); portletResp.addProperty(c); PortletURL rurl = portletResp.createRenderURL(); TestButton tb = new TestButton( V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE10, rurl); tb.writeTo(writer); } /* TestCase: V3HeaderPortletTests_SPEC15_Header_cookie11 */ /* * Details: "Cookies set during the Header phase should be available to * the portlet during a subsequent request triggered by a URL" */ if (portletReq.getParameter("tr3") != null && portletReq.getParameter("tr3").equals("true")) { Cookie[] cookies = portletReq.getCookies(); StringBuilder txt = new StringBuilder(128); txt.append("<p>Debug info:"); txt.append("<br>"); txt.append("# Cookies: ").append(cookies.length).append("<br>"); TestResult tr2 = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE11); for (Cookie c : cookies) { txt.append("Name: ").append(c.getName()); txt.append(", Value: ").append(c.getValue()).append("<br>"); if (c.getName().equals("header_tr3_cookie") && c.getValue().equals("true")) { txt.append("<br>").append("Found my cookie!").append("<br>"); c.setMaxAge(0); c.setValue(""); tr2.setTcSuccess(true); } } tr2.writeTo(writer); txt.append("</p>"); writer.append(txt.toString()); } else { Cookie c = new Cookie("header_tr3_cookie", "true"); c.setMaxAge(100); c.setPath("/"); portletResp.addProperty(c); PortletURL rurl = portletResp.createRenderURL(); rurl.setParameter("tr3", "true"); TestButton tb = new TestButton( V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE11, rurl); tb.writeTo(writer); } /* TestCase: V3HeaderPortletTests_SPEC15_Header_contentType5 */ /* * Details: "If the setContentType method is not called before the * getWriter or getPortletOutputStream method is used, the portlet * container uses the content type returned by getResponseContentType" */ { TestResult result = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_CONTENTTYPE5); if (portletReq.getResponseContentType() != null) { result.setTcSuccess(true); result.appendTcDetail( "Content type is - " + portletReq.getResponseContentType()); } else { result.appendTcDetail( "Failed because getResponseContentType() method returned null"); } result.writeTo(writer); } /* TestCase: V3HeaderPortletTests_SPEC15_Header_characterEncoding4 */ /* * Details: "If the portlet does not set the character encoding, the * portlet container uses UTF-8 as the default character encoding" */ { TestResult result = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_CHARACTERENCODING4); if (portletResp.getCharacterEncoding().equals("UTF-8")) { result.setTcSuccess(true); } else { result.appendTcDetail( "Failed because default character encoding is not UTF-8 but " + portletResp.getCharacterEncoding()); } result.writeTo(writer); } portletReq.getPortletSession().setAttribute( RESULT_ATTR_PREFIX + "HeaderPortletTests_SPEC15_Header", writer.toString(), PORTLET_SCOPE); } @Override public void serveResource(ResourceRequest portletReq, ResourceResponse portletResp) throws PortletException, IOException { ModuleTestCaseDetails tcd = new ModuleTestCaseDetails(); long tid = Thread.currentThread().getId(); portletReq.setAttribute(THREADID_ATTR, tid); PrintWriter writer = portletResp.getWriter(); /* TestCase: V3HeaderPortletTests_SPEC15_Header_cookie8 */ /* * Details: "Cookies set during the Header phase should be available to * the portlet during the Resource phase" */ Cookie[] cookies = portletReq.getCookies(); StringBuilder txt = new StringBuilder(128); txt.append("<p>Debug info:"); txt.append("<br>"); txt.append("# Cookies: ").append(cookies.length).append("<br>"); TestResult tr1 = tcd .getTestResultFailed(V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE8); for (Cookie c : cookies) { txt.append("Name: ").append(c.getName()); txt.append(", Value: ").append(c.getValue()).append("<br>"); if (c.getName().equals("header_tr0_cookie") && c.getValue().equals("true")) { txt.append("<br>").append("Found my cookie!").append("<br>"); c.setMaxAge(0); c.setValue(""); tr1.setTcSuccess(true); } } tr1.writeTo(writer); txt.append("</p>"); writer.append(txt.toString()); } }
portlet-tck_3.0/V3HeaderPortletTests/src/main/java/javax/portlet/tck/portlets/HeaderPortletTests_SPEC15_Header.java
/* Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.portlet.tck.portlets; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Map; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.ActionURL; import javax.portlet.HeaderPortlet; import javax.portlet.HeaderRequest; import javax.portlet.HeaderResponse; import javax.portlet.Portlet; import javax.portlet.PortletConfig; import javax.portlet.PortletException; import javax.portlet.PortletURL; import javax.portlet.RenderParameters; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import javax.portlet.ResourceRequest; import javax.portlet.ResourceResponse; import javax.portlet.ResourceServingPortlet; import javax.portlet.ResourceURL; import javax.portlet.annotations.PortletApplication; import javax.portlet.annotations.PortletConfiguration; import javax.portlet.annotations.PortletQName; import javax.portlet.annotations.PublicRenderParameterDefinition; import javax.portlet.annotations.Supports; import javax.portlet.tck.beans.TestButton; import javax.portlet.tck.beans.TestResult; import javax.portlet.tck.beans.TestSetupLink; import javax.portlet.tck.util.ModuleTestCaseDetails; import javax.servlet.http.Cookie; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS10; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS15; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE9; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE10; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS13; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS2; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS6; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS15; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS16; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS13A; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_PROPERTIES1; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_PROPERTIES2; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_PROPERTIES3; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_PROPERTIES4; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE11; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_CHARACTERENCODING4; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_CONTENTTYPE5; import static javax.portlet.tck.util.ModuleTestCaseDetails.V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE8; import static javax.portlet.tck.constants.Constants.RESULT_ATTR_PREFIX; import static javax.portlet.PortletSession.PORTLET_SCOPE; import static javax.portlet.ResourceURL.PAGE; import static javax.portlet.tck.constants.Constants.THREADID_ATTR; /** * This portlet implements several test cases for the JSR 362 TCK. The test case * names are defined in the /src/main/resources/xml-resources/additionalTCs.xml * file. The build process will integrate the test case names defined in the * additionalTCs.xml file into the complete list of test case names for * execution by the driver. * */ @PortletApplication(publicParams = { @PublicRenderParameterDefinition(identifier = "tckPRP3", qname = @PortletQName(localPart = "tckPRP3", namespaceURI = "")), @PublicRenderParameterDefinition(identifier = "tr1_ready", qname = @PortletQName(localPart = "tr1_ready", namespaceURI = "")) }) @PortletConfiguration(portletName = "HeaderPortletTests_SPEC15_Header", publicParams = { "tckPRP3", "tr1_ready" }, supports = { @Supports(mimeType = "text/html") }) public class HeaderPortletTests_SPEC15_Header implements Portlet, HeaderPortlet, ResourceServingPortlet { @Override public void init(PortletConfig config) throws PortletException { } @Override public void destroy() { } @Override public void processAction(ActionRequest portletReq, ActionResponse portletResp) throws PortletException, IOException { String action = portletReq.getParameter("inputval"); if (action != null) { if (V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS10.equals(action) && portletReq.getParameter("actionURLTr0") != null && portletReq.getParameter("actionURLTr0").equals("true")) { /* TestCase: V2AddlRequestTests_SPEC2_11_Render_parameters10 */ /* Details: "The portlet-container must not propagate parameters */ /* received in an action or event request to subsequent render */ /* requests of the portlet" */ portletResp.setRenderParameter("tr0", "true"); } else if (V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS15 .equals(action) && portletReq.getParameter("tr3a") != null && portletReq.getParameter("tr3a").equals("true")) { /* TestCase: V3HeaderPortletTests_SPEC15_Header_parameters15 */ /* * Details: "Render parameters get automatically cleared if the * portlet receives a processAction or processEvent call" */ portletResp.setRenderParameter("tr3b", "true"); } else if (V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE9.equals(action)) { /* TestCase: V3HeaderPortletTests_SPEC15_Header_cookie9 */ /* * Details: "Cookies set during the Header phase should be available * to the portlet during a subsequent Action phase" */ Cookie[] cookies = portletReq.getCookies(); for (Cookie c : cookies) { if (c.getName().equals("header_tr1_cookie") && c.getValue().equals("true")) { c.setMaxAge(0); c.setValue(""); portletResp.setRenderParameter("trCookie1", "true"); } } } } } @Override public void render(RenderRequest portletReq, RenderResponse portletResp) throws PortletException, IOException { ModuleTestCaseDetails tcd = new ModuleTestCaseDetails(); PrintWriter writer = portletResp.getWriter(); /* TestCase: V3HeaderPortletTests_SPEC15_Header_cookie8 */ /* * Details: "Cookies set during the Header phase should be available to * the portlet during the Resource phase" */ writer.write( "<div id=\"V3HeaderPortletTests_SPEC15_Header\">no resource output.</div>\n"); ResourceURL resurl = portletResp.createResourceURL(); resurl.setCacheability(PAGE); writer.write("<script>\n"); writer.write("(function () {\n"); writer.write(" var xhr = new XMLHttpRequest();\n"); writer.write(" xhr.onreadystatechange=function() {\n"); writer.write(" if (xhr.readyState==4 && xhr.status==200) {\n"); writer.write( " document.getElementById(\"V3HeaderPortletTests_SPEC15_Header\").innerHTML=xhr.responseText;\n"); writer.write(" }\n"); writer.write(" };\n"); writer.write( " xhr.open(\"GET\",\"" + resurl.toString() + "\",true);\n"); writer.write(" xhr.send();\n"); writer.write("})();\n"); writer.write("</script>\n"); /* TestCase: V3HeaderPortletTests_SPEC15_Header_cookie10 */ /* * Details: "Cookies set during the Header phase should be available to * the portlet during a subsequent Render phase" */ Cookie[] cookies = portletReq.getCookies(); StringBuilder txt = new StringBuilder(128); txt.append("<p>Debug info:"); txt.append("<br>"); txt.append("# Cookies: ").append(cookies.length).append("<br>"); TestResult tr2 = tcd .getTestResultFailed(V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE10); for (Cookie c : cookies) { txt.append("Name: ").append(c.getName()); txt.append(", Value: ").append(c.getValue()).append("<br>"); if (c.getName().equals("header_tr2_cookie") && c.getValue().equals("true")) { txt.append("<br>").append("Found my cookie!").append("<br>"); c.setMaxAge(0); c.setValue(""); tr2.setTcSuccess(true); } } tr2.writeTo(writer); txt.append("</p>"); writer.append(txt.toString()); String msg = ((String) portletReq.getPortletSession().getAttribute( RESULT_ATTR_PREFIX + "HeaderPortletTests_SPEC15_Header", PORTLET_SCOPE)); writer.write("<p>" + msg + "</p>"); portletReq.getPortletSession().removeAttribute( RESULT_ATTR_PREFIX + "HeaderPortletTests_SPEC15_Header", PORTLET_SCOPE); } @Override public void renderHeaders(HeaderRequest portletReq, HeaderResponse portletResp) throws PortletException, IOException { ModuleTestCaseDetails tcd = new ModuleTestCaseDetails(); StringWriter writer = new StringWriter(); RenderParameters renderParams = portletReq.getRenderParameters(); String action = portletReq.getParameter("inputval"); Boolean successTr2 = false, successTr5 = false, successTr6 = false; Boolean successTr7 = false, successTr8 = false, successTr13 = false; /* TestCase: V3HeaderPortletTests_SPEC15_Header_parameters10 */ /* * Details: "The portlet-container must not propagate parameters received * in an action or event request to subsequent header requests of the * portlet" */ if (renderParams.getValue("actionURLTr0") == null && renderParams.getValue("tr0") != null && "true".equals(renderParams.getValue("tr0"))) { TestResult tr0 = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS10); tr0.setTcSuccess(true); tr0.writeTo(writer); } else { ActionURL aurl = portletResp.createActionURL(); aurl.setParameter("actionURLTr0", "true"); TestButton tb = new TestButton( V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS10, aurl); tb.writeTo(writer); } if (action != null) { if (action.equals(V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS13)) { /* TestCase: V3HeaderPortletTests_SPEC15_Header_parameters13 */ /* * Details: "If a portlet receives a render request that is the * result of invoking a render URL targeting this portlet the render * parameters received with the render request must be the * parameters set on the render URL" */ TestResult tr2 = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS13); if (portletReq.getParameter("renderURLTr2") != null && portletReq.getParameter("tr2") != null && portletReq.getParameter("renderURLTr2") .contains("tr2:" + portletReq.getParameter("tr2"))) { tr2.setTcSuccess(true); successTr2 = true; } else { tr2.appendTcDetail( "Parameter renderURLTr2 is missing or does not contain tr2 parameter value."); } tr2.writeTo(writer); } else if (action .equals(V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS2)) { /* TestCase: V3HeaderPortletTests_SPEC15_Header_parameters2 */ /* Details: "The parameters the request object returns must be */ /* \"x-www-form-urlencoded\" decoded" */ TestResult tr5 = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS2); if (portletReq.getParameter("tr5") != null && portletReq.getParameter("tr5").equals("true&<>'")) { tr5.setTcSuccess(true); successTr5 = true; } tr5.writeTo(writer); } else if (action .equals(V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS6)) { /* TestCase: V3HeaderPortletTests_SPEC15_Header_parameters6 */ /* * Details: "The getParameterMap method must return an unmodifiable * Map object" */ TestResult tr6 = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS6); if (portletReq.getParameterMap().containsKey("inputval") && V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS6.equals( portletReq.getParameterMap().get("inputval")[0])) { String tr6TestStringArray[] = { "Modified Value" }; try { portletReq.getParameterMap().put( "inputval", tr6TestStringArray); if (V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS6 .equals( portletReq.getParameterMap().get("inputval")[0])) { tr6.setTcSuccess(true); successTr6 = true; } } catch (UnsupportedOperationException e) { tr6.setTcSuccess(true); successTr6 = true; } } tr6.writeTo(writer); } else if (action.equals( V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS15)) { /* * TestCase: * V3HeaderPortletTests_SPEC15_Header_publicRenderParameters15 */ /* * Details: "A map of private parameters can be obtained through the * getPrivateParameterMap method" */ TestResult tr7 = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS15); Map<String, String[]> privateParamMap = portletReq .getPrivateParameterMap(); if (privateParamMap != null && privateParamMap.containsKey("tr7") && privateParamMap.get("tr7")[0].equals("true")) { tr7.setTcSuccess(true); successTr7 = true; } tr7.writeTo(writer); } else if (action.equals( V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS16)) { /* * TestCase: * V3HeaderPortletTests_SPEC15_Header_publicRenderParameters16 */ /* * Details: "A map of public parameters can be obtained through the * getPublicParameterMap method" */ TestResult tr8 = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS16); if (portletReq.getPublicParameterMap() != null && portletReq .getPublicParameterMap().containsKey("tckPRP3")) { tr8.setTcSuccess(true); successTr8 = true; } else { tr8.appendTcDetail("No public render parameter found."); } tr8.writeTo(writer); } else if (action.equals( V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS13A)) { /* * TestCase: * V3HeaderPortletTests_SPEC15_Header_publicRenderParameters13a */ /* Details: "A public render parameter can be deleted using the */ /* removePublicRenderParameter method on the PortletURL" */ TestResult tr13 = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS13A); if (portletReq.getPublicParameterMap() != null && !portletReq .getPublicParameterMap().containsKey("tckPRP3")) { tr13.setTcSuccess(true); successTr13 = true; } else { tr13.appendTcDetail("Render parameter tckPRP3 is not removed."); } tr13.writeTo(writer); } } if (!successTr2) { /* TestCase: V3HeaderPortletTests_SPEC15_Header_parameters13 */ /* * Details: "If a portlet receives a render request that is the result * of invoking a render URL targeting this portlet the render * parameters received with the render request must be the parameters * set on the render URL" */ PortletURL rurl = portletResp.createRenderURL(); rurl.setParameters(portletReq.getPrivateParameterMap()); rurl.setParameter("tr2", "true"); rurl.setParameter("renderURLTr2", rurl.toString()); TestButton tb = new TestButton( V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS13, rurl); tb.writeTo(writer); } if (!successTr5) { /* TestCase: V3HeaderPortletTests_SPEC15_Header_parameters2 */ /* Details: "The parameters the request object returns must be */ /* \"x-www-form-urlencoded\" decoded" */ PortletURL purl = portletResp.createRenderURL(); purl.setParameter("tr5", "true&<>'"); TestButton tb = new TestButton( V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS2, purl); tb.writeTo(writer); } if (!successTr6) { /* TestCase: V3HeaderPortletTests_SPEC15_Header_parameters6 */ /* * Details: "The getParameterMap method must return an unmodifiable Map * object" */ PortletURL purl = portletResp.createRenderURL(); TestButton tb = new TestButton( V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS6, purl); tb.writeTo(writer); } if (!successTr7) { /* * TestCase: * V3HeaderPortletTests_SPEC15_Header_publicRenderParameters15 */ /* Details: "A map of private parameters can be obtained through the */ /* getPrivateParameterMap method" */ PortletURL purl = portletResp.createRenderURL(); purl.setParameter("tr7", "true"); TestButton tb = new TestButton( V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS15, purl); tb.writeTo(writer); } if (!successTr8) { /* * TestCase: * V3HeaderPortletTests_SPEC15_Header_publicRenderParameters16 */ /* Details: "A map of public parameters can be obtained through the */ /* getPublicParameterMap method" */ if (portletReq.getParameter("tckPRP3") == null) { PortletURL purl = portletResp.createRenderURL(); purl.setParameter("tckPRP3", "true"); TestSetupLink tl = new TestSetupLink( V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS16, purl); tl.writeTo(writer); } else { PortletURL aurl = portletResp.createRenderURL(); aurl.setParameters(portletReq.getPrivateParameterMap()); TestButton tb = new TestButton( V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS16, aurl); tb.writeTo(writer); } } if (!successTr13) { /* * TestCase: * V3HeaderPortletTests_SPEC15_Header_publicRenderParameters13a */ /* Details: "A public render parameter can be deleted using the */ /* removePublicRenderParameter method on the PortletURL" */ if (portletReq.getParameter("tckPRP3") == null) { PortletURL purl = portletResp.createRenderURL(); purl.setParameter("tckPRP3", "true"); TestSetupLink tl = new TestSetupLink( V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS13A, purl); tl.writeTo(writer); } else { PortletURL purl = portletResp.createRenderURL(); purl.setParameters(portletReq.getPrivateParameterMap()); purl.removePublicRenderParameter("tckPRP3"); TestButton tb = new TestButton( V3HEADERPORTLETTESTS_SPEC15_HEADER_PUBLICRENDERPARAMETERS13A, purl); tb.writeTo(writer); } } /* TestCase: V3HeaderPortletTests_SPEC15_Header_parameters15 */ /* Details: "Render parameters get automatically cleared if the portlet */ /* receives a processAction or processEvent call" */ if (portletReq.getParameter("tr3a") != null) { PortletURL aurl = portletResp.createActionURL(); aurl.setParameter("tr3a", "true"); TestButton tb = new TestButton( V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS15, aurl); tb.writeTo(writer); } else { if (portletReq.getParameter("tr3b") != null && portletReq.getParameter("tr3b").equals("true")) { TestResult tr3 = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS15); tr3.setTcSuccess(true); tr3.writeTo(writer); } else { PortletURL purl = portletResp.createRenderURL(); purl.setParameter("tr3a", "true"); TestSetupLink tl = new TestSetupLink( V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS15, purl); tl.writeTo(writer); } } /* TestCase: V3HeaderPortletTests_SPEC15_Header_properties1 */ /* * Details: "The portlet can use the getProperty method to access single * portal property and optionally-available HTTP header values" */ { TestResult result = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_PROPERTIES1); if (portletReq.getProperty("Accept") != null) { result.setTcSuccess(true); } else { result.appendTcDetail( "Failed because Accept header is not found in request headers."); } result.writeTo(writer); } /* TestCase: V3HeaderPortletTests_SPEC15_Header_properties2 */ /* * Details: "The portlet can use the getProperties method to access * multiple portal property and optionally-available HTTP header values by * the same property name" */ { TestResult result = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_PROPERTIES2); if (portletReq.getProperties("Accept").hasMoreElements()) { result.setTcSuccess(true); } else { result.appendTcDetail( "Failed because Accept header is not found in request headers."); } result.writeTo(writer); } /* TestCase: V3HeaderPortletTests_SPEC15_Header_properties3 */ /* * Details: "The portlet can use the getPropertyNames method to obtain an * Enumeration of all available property names" */ { TestResult result = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_PROPERTIES3); if (portletReq.getPropertyNames().hasMoreElements()) { result.setTcSuccess(true); } else { result.appendTcDetail( "Failed because no header is not found in request headers."); } result.writeTo(writer); } /* TestCase: V3HeaderPortletTests_SPEC15_Header_properties4 */ /* * Details: "The portlet can access cookies provided by the current * request using the getCookies method" */ { TestResult result = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_PROPERTIES4); if (portletReq.getCookies().length > 0) { result.setTcSuccess(true); } else { result.appendTcDetail( "Failed because no cookies are found in HeaderRequest object"); } result.writeTo(writer); } /* TestCase: V3HeaderPortletTests_SPEC15_Header_cookie8 */ /* * Details: "Cookies set during the Header phase should be available to * the portlet during the Resource phase" */ { Cookie c = new Cookie("header_tr0_cookie", "true"); c.setMaxAge(100); c.setPath("/"); portletResp.addProperty(c); } /* TestCase: V3HeaderPortletTests_SPEC15_Header_cookie9 */ /* * Details: "Cookies set during the Header phase should be available to * the portlet during a subsequent Action phase" */ if (portletReq.getParameter("trCookie1") != null && portletReq.getParameter("trCookie1").equals("true")) { TestResult tr1 = tcd .getTestResultFailed(V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE9); tr1.setTcSuccess(true); tr1.writeTo(writer); } else { Cookie c = new Cookie("header_tr1_cookie", "true"); c.setMaxAge(100); c.setPath("/"); portletResp.addProperty(c); PortletURL aurl = portletResp.createActionURL(); TestButton tb = new TestButton( V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE9, aurl); tb.writeTo(writer); } /* TestCase: V3HeaderPortletTests_SPEC15_Header_cookie10 */ /* * Details: "Cookies set during the Header phase should be available to * the portlet during a subsequent Render phase" */ { Cookie c = new Cookie("header_tr2_cookie", "true"); c.setMaxAge(100); c.setPath("/"); portletResp.addProperty(c); PortletURL rurl = portletResp.createRenderURL(); TestButton tb = new TestButton( V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE10, rurl); tb.writeTo(writer); } /* TestCase: V3HeaderPortletTests_SPEC15_Header_cookie11 */ /* * Details: "Cookies set during the Header phase should be available to * the portlet during a subsequent request triggered by a URL" */ if (portletReq.getParameter("tr3") != null && portletReq.getParameter("tr3").equals("true")) { Cookie[] cookies = portletReq.getCookies(); StringBuilder txt = new StringBuilder(128); txt.append("<p>Debug info:"); txt.append("<br>"); txt.append("# Cookies: ").append(cookies.length).append("<br>"); TestResult tr2 = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE11); for (Cookie c : cookies) { txt.append("Name: ").append(c.getName()); txt.append(", Value: ").append(c.getValue()).append("<br>"); if (c.getName().equals("header_tr3_cookie") && c.getValue().equals("true")) { txt.append("<br>").append("Found my cookie!").append("<br>"); c.setMaxAge(0); c.setValue(""); tr2.setTcSuccess(true); } } tr2.writeTo(writer); txt.append("</p>"); writer.append(txt.toString()); } else { Cookie c = new Cookie("header_tr3_cookie", "true"); c.setMaxAge(100); c.setPath("/"); portletResp.addProperty(c); PortletURL rurl = portletResp.createRenderURL(); rurl.setParameter("tr3", "true"); TestButton tb = new TestButton( V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE11, rurl); tb.writeTo(writer); } /* TestCase: V3HeaderPortletTests_SPEC15_Header_contentType5 */ /* * Details: "If the setContentType method is not called before the * getWriter or getPortletOutputStream method is used, the portlet * container uses the content type returned by getResponseContentType" */ { TestResult result = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_CONTENTTYPE5); if (portletReq.getResponseContentType() != null) { result.setTcSuccess(true); result.appendTcDetail( "Content type is - " + portletReq.getResponseContentType()); } else { result.appendTcDetail( "Failed because getResponseContentType() method returned null"); } result.writeTo(writer); } /* TestCase: V3HeaderPortletTests_SPEC15_Header_characterEncoding4 */ /* * Details: "If the portlet does not set the character encoding, the * portlet container uses UTF-8 as the default character encoding" */ { TestResult result = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC15_HEADER_CHARACTERENCODING4); if (portletResp.getCharacterEncoding().equals("UTF-8")) { result.setTcSuccess(true); } else { result.appendTcDetail( "Failed because default character encoding is not UTF-8 but " + portletResp.getCharacterEncoding()); } result.writeTo(writer); } portletReq.getPortletSession().setAttribute( RESULT_ATTR_PREFIX + "HeaderPortletTests_SPEC15_Header", writer.toString(), PORTLET_SCOPE); } @Override public void serveResource(ResourceRequest portletReq, ResourceResponse portletResp) throws PortletException, IOException { ModuleTestCaseDetails tcd = new ModuleTestCaseDetails(); long tid = Thread.currentThread().getId(); portletReq.setAttribute(THREADID_ATTR, tid); PrintWriter writer = portletResp.getWriter(); /* TestCase: V3HeaderPortletTests_SPEC15_Header_cookie8 */ /* * Details: "Cookies set during the Header phase should be available to * the portlet during the Resource phase" */ Cookie[] cookies = portletReq.getCookies(); StringBuilder txt = new StringBuilder(128); txt.append("<p>Debug info:"); txt.append("<br>"); txt.append("# Cookies: ").append(cookies.length).append("<br>"); TestResult tr1 = tcd .getTestResultFailed(V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE8); for (Cookie c : cookies) { txt.append("Name: ").append(c.getName()); txt.append(", Value: ").append(c.getValue()).append("<br>"); if (c.getName().equals("header_tr0_cookie") && c.getValue().equals("true")) { txt.append("<br>").append("Found my cookie!").append("<br>"); c.setMaxAge(0); c.setValue(""); tr1.setTcSuccess(true); } } tr1.writeTo(writer); txt.append("</p>"); writer.append(txt.toString()); } }
PLUTO-678 TCK: Contesting V2AddlRequestTests_SPEC2_11_Render_parameters13 and V3HeaderPortletTests_SPEC15_Header_parameters13
portlet-tck_3.0/V3HeaderPortletTests/src/main/java/javax/portlet/tck/portlets/HeaderPortletTests_SPEC15_Header.java
PLUTO-678 TCK: Contesting V2AddlRequestTests_SPEC2_11_Render_parameters13 and V3HeaderPortletTests_SPEC15_Header_parameters13
Java
apache-2.0
57db6842628718d04b616997461836c3f40f9da3
0
cloudsmith/orientdb,cloudsmith/orientdb,cloudsmith/orientdb,cloudsmith/orientdb
/* * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.orient.core.serialization.serializer.record.string; import java.io.IOException; import java.io.StringWriter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.common.parser.OStringParser; import com.orientechnologies.orient.core.db.OUserObject2RecordHandler; import com.orientechnologies.orient.core.db.record.ODatabaseRecord; import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.db.record.ORecordLazyList; import com.orientechnologies.orient.core.db.record.ORecordLazySet; import com.orientechnologies.orient.core.db.record.OTrackedList; import com.orientechnologies.orient.core.db.record.OTrackedSet; import com.orientechnologies.orient.core.exception.OSerializationException; import com.orientechnologies.orient.core.fetch.OFetchHelper; import com.orientechnologies.orient.core.id.ORID; import com.orientechnologies.orient.core.id.ORecordId; import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.OProperty; import com.orientechnologies.orient.core.metadata.schema.OType; import com.orientechnologies.orient.core.record.ORecord; import com.orientechnologies.orient.core.record.ORecordFactory; import com.orientechnologies.orient.core.record.ORecordInternal; import com.orientechnologies.orient.core.record.ORecordSchemaAware; import com.orientechnologies.orient.core.record.ORecordStringable; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.record.impl.ORecordBytes; import com.orientechnologies.orient.core.serialization.OBase64Utils; import com.orientechnologies.orient.core.serialization.serializer.OJSONWriter; import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper; public class ORecordSerializerJSON extends ORecordSerializerStringAbstract { public static final String NAME = "json"; public static final ORecordSerializerJSON INSTANCE = new ORecordSerializerJSON(); public static final String ATTRIBUTE_ID = "@rid"; public static final String ATTRIBUTE_VERSION = "@version"; public static final String ATTRIBUTE_TYPE = "@type"; public static final String ATTRIBUTE_FIELD_TYPES = "@fieldTypes"; public static final String ATTRIBUTE_CLASS = "@class"; public static final String DEF_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss:SSS"; private SimpleDateFormat dateFormat = new SimpleDateFormat(DEF_DATE_FORMAT); @Override public ORecordInternal<?> fromString(final ODatabaseRecord iDatabase, final String iSource) { return fromString(iDatabase, iSource, null); } @Override public ORecordInternal<?> fromString(final ODatabaseRecord iDatabase, String iSource, ORecordInternal<?> iRecord) { if (iSource == null) throw new OSerializationException("Error on unmarshalling JSON content: content is null"); iSource = iSource.trim(); if (!iSource.startsWith("{") || !iSource.endsWith("}")) throw new OSerializationException("Error on unmarshalling JSON content: content must be between { }"); if (iRecord != null) // RESET ALL THE FIELDS iRecord.reset(); iSource = iSource.substring(1, iSource.length() - 1).trim(); String[] fields = OStringParser.getWords(iSource, ":,", true); String fieldName; String fieldValue; String fieldValueAsString; Map<String, Character> fieldTypes = null; // SEARCH FOR FIELD TYPES IF ANY for (int i = 0; i < fields.length; i += 2) { fieldName = fields[i]; fieldName = fieldName.substring(1, fieldName.length() - 1); fieldValue = fields[i + 1]; fieldValueAsString = fieldValue.length() >= 2 ? fieldValue.substring(1, fieldValue.length() - 1) : fieldValue; if (fieldName.equals(ATTRIBUTE_FIELD_TYPES) && iRecord instanceof ODocument) { // LOAD THE FIELD TYPE MAP final String[] fieldTypesParts = fieldValueAsString.split(","); if (fieldTypesParts.length > 0) { fieldTypes = new HashMap<String, Character>(); String[] part; for (String f : fieldTypesParts) { part = f.split("="); if (part.length == 2) fieldTypes.put(part[0], part[1].charAt(0)); } } } } try { if (fields != null && fields.length > 0) { for (int i = 0; i < fields.length; i += 2) { fieldName = fields[i]; fieldName = fieldName.substring(1, fieldName.length() - 1); fieldValue = fields[i + 1].trim(); fieldValueAsString = fieldValue.length() >= 2 ? fieldValue.substring(1, fieldValue.length() - 1) : fieldValue; // RECORD ATTRIBUTES if (fieldName.equals(ATTRIBUTE_ID)) iRecord.setIdentity(new ORecordId(fieldValueAsString)); else if (fieldName.equals(ATTRIBUTE_VERSION)) iRecord.setVersion(Integer.parseInt(fieldValue)); else if (fieldName.equals(ATTRIBUTE_TYPE)) { if (iRecord == null || iRecord.getRecordType() != fieldValueAsString.charAt(0)) { // CREATE THE RIGHT RECORD INSTANCE iRecord = ORecordFactory.newInstance((byte) fieldValueAsString.charAt(0)); iRecord.setDatabase(iDatabase); } } else if (fieldName.equals(ATTRIBUTE_CLASS) && iRecord instanceof ODocument) ((ODocument) iRecord).setClassNameIfExists("null".equals(fieldValueAsString) ? null : fieldValueAsString); else if (fieldName.equals(ATTRIBUTE_FIELD_TYPES) && iRecord instanceof ODocument) // JUMP IT continue; // RECORD VALUE(S) else if (fieldName.equals("value") && !(iRecord instanceof ODocument)) { if ("null".equals(fieldValue)) iRecord.fromStream(new byte[] {}); else if (iRecord instanceof ORecordBytes) { // BYTES iRecord.fromStream(OBase64Utils.decode(fieldValueAsString)); } else if (iRecord instanceof ORecordStringable) { ((ORecordStringable) iRecord).value(fieldValueAsString); } } else { if (iRecord instanceof ODocument) { final Object v = getValue((ODocument) iRecord, fieldName, fieldValue, fieldValueAsString, null, null, fieldTypes); if (v != null) if (v instanceof Collection<?> && ((Collection<?>) v).size() > 0) { if (v instanceof ORecordLazySet) ((ORecordLazySet) v).setAutoConvertToRecord(false); else if (v instanceof ORecordLazyList) ((ORecordLazyList) v).setAutoConvertToRecord(false); // CHECK IF THE COLLECTION IS EMBEDDED Object first = ((Collection<?>) v).iterator().next(); if (first != null && first instanceof ORecord<?> && !((ORecord<?>) first).getIdentity().isValid()) { ((ODocument) iRecord).field(fieldName, v, v instanceof Set<?> ? OType.EMBEDDEDSET : OType.EMBEDDEDLIST); continue; } } else if (v instanceof Map<?, ?> && ((Map<?, ?>) v).size() > 0) { // CHECK IF THE MAP IS EMBEDDED Object first = ((Map<?, ?>) v).values().iterator().next(); if (first != null && first instanceof ORecord<?> && !((ORecord<?>) first).getIdentity().isValid()) { ((ODocument) iRecord).field(fieldName, v, OType.EMBEDDEDMAP); continue; } } ((ODocument) iRecord).field(fieldName, v); } } } } } catch (Exception e) { e.printStackTrace(); throw new OSerializationException("Error on unmarshalling JSON content for record " + iRecord.getIdentity(), e); } return iRecord; } @SuppressWarnings("unchecked") private Object getValue(final ODocument iRecord, String iFieldName, String iFieldValue, String iFieldValueAsString, OType iType, OType iLinkedType, final Map<String, Character> iFieldTypes) { if (iFieldValue.equals("null")) return null; if (iFieldName != null) if (iRecord.getSchemaClass() != null) { final OProperty p = iRecord.getSchemaClass().getProperty(iFieldName); if (p != null) { iType = p.getType(); iLinkedType = p.getLinkedType(); } } if (iFieldValue.startsWith("{") && iFieldValue.endsWith("}")) { // OBJECT OR MAP. CHECK THE TYPE ATTRIBUTE TO KNOW IT String[] fields = OStringParser.getWords(iFieldValueAsString, ":,", true); if (fields == null || fields.length == 0) // EMPTY, RETURN an EMPTY HASHMAP return new HashMap<String, Object>(); if (fields[0].equals("\"@type\"")) // OBJECT return fromString(iRecord.getDatabase(), iFieldValue, null); else { if (fields.length % 2 == 1) throw new OSerializationException("Bad JSON format on map. Expected pairs of field:value but received '" + iFieldValueAsString + "'"); // MAP final Map<String, Object> embeddedMap = new LinkedHashMap<String, Object>(); for (int i = 0; i < fields.length; i += 2) { iFieldName = fields[i]; if (iFieldName.length() >= 2) iFieldName = iFieldName.substring(1, iFieldName.length() - 1); iFieldValue = fields[i + 1]; iFieldValueAsString = iFieldValue.length() >= 2 ? iFieldValue.substring(1, iFieldValue.length() - 1) : iFieldValue; embeddedMap.put(iFieldName, getValue(iRecord, null, iFieldValue, iFieldValueAsString, iLinkedType, null, iFieldTypes)); } return embeddedMap; } } else if (iFieldValue.startsWith("[") && iFieldValue.endsWith("]")) { // EMBEDDED VALUES final Collection<?> embeddedCollection; if (iType == OType.LINKSET) embeddedCollection = new ORecordLazySet(iRecord); else if (iType == OType.EMBEDDEDSET) embeddedCollection = new OTrackedSet<Object>(iRecord); else if (iType == OType.LINKLIST) embeddedCollection = new ORecordLazyList(iRecord); else embeddedCollection = new OTrackedList<Object>(iRecord); iFieldValue = iFieldValue.substring(1, iFieldValue.length() - 1); if (iFieldValue.length() > 0) { // EMBEDDED VALUES List<String> items = OStringSerializerHelper.smartSplit(iFieldValue, ','); Object collectionItem; for (String item : items) { iFieldValue = item.trim(); iFieldValueAsString = iFieldValue.length() >= 2 ? iFieldValue.substring(1, iFieldValue.length() - 1) : iFieldValue; collectionItem = getValue(iRecord, null, iFieldValue, iFieldValueAsString, iLinkedType, null, iFieldTypes); if (collectionItem instanceof ODocument && iRecord instanceof ODocument) // SET THE OWNER ((ODocument) collectionItem).addOwner(iRecord); ((Collection<Object>) embeddedCollection).add(collectionItem); } } return embeddedCollection; } if (iType == null) // TRY TO DETERMINE THE CONTAINED TYPE from THE FIRST VALUE if (iFieldValue.charAt(0) != '\"') { if (iFieldValue.equalsIgnoreCase("false") || iFieldValue.equalsIgnoreCase("true")) iType = OType.BOOLEAN; else { Character c = null; if (iFieldTypes != null) { c = iFieldTypes.get(iFieldName); if (c != null) iType = ORecordSerializerStringAbstract.getType(iFieldValue + c); } if (c == null) // TRY TO AUTODETERMINE THE BEST TYPE if (OStringSerializerHelper.contains(iFieldValue, '.')) iType = OType.FLOAT; else iType = OType.INTEGER; } } else if (iFieldValueAsString.length() >= 4 && iFieldValueAsString.charAt(0) == '#' && iFieldValueAsString.contains(":")) iType = OType.LINK; else if (iFieldValueAsString.startsWith("{") && iFieldValueAsString.endsWith("}")) iType = OType.EMBEDDED; else { if (iFieldValueAsString.length() == DEF_DATE_FORMAT.length()) // TRY TO PARSE AS DATE try { synchronized (dateFormat) { return dateFormat.parseObject(iFieldValueAsString); } } catch (Exception e) { } iType = OType.STRING; } if (iType != null) switch (iType) { case STRING: return iFieldValueAsString; case LINK: final int pos = iFieldValueAsString.indexOf('@'); if (pos > -1) // CREATE DOCUMENT return new ODocument(iRecord.getDatabase(), iFieldValueAsString.substring(1, pos), new ORecordId( iFieldValueAsString.substring(pos + 1))); else // CREATE SIMPLE RID return new ORecordId(iFieldValueAsString.substring(1)); case EMBEDDED: return fromString(iRecord.getDatabase(), iFieldValueAsString); case DATE: try { // TRY TO PARSE AS LONG return Long.parseLong(iFieldValueAsString); } catch (NumberFormatException e) { try { // TRY TO PARSE AS DATE return dateFormat.parseObject(iFieldValueAsString); } catch (ParseException ex) { throw new OSerializationException("Unable to unmarshall date: " + iFieldValueAsString, e); } } default: return OStringSerializerHelper.fieldTypeFromStream(iRecord, iType, iFieldValue); } return iFieldValueAsString; } @Override public String toString(final ORecordInternal<?> iRecord, final String iFormat, final OUserObject2RecordHandler iObjHandler, final Set<Integer> iMarshalledRecords) { try { final StringWriter buffer = new StringWriter(); final OJSONWriter json = new OJSONWriter(buffer, iFormat); final Set<ORID> parsedRecords = new HashSet<ORID>(); boolean includeVer; boolean includeType; boolean includeId; boolean includeClazz; boolean attribSameRow; int indentLevel; String fetchPlan = null; boolean keepTypes; if (iFormat == null) { includeType = true; includeVer = true; includeId = true; includeClazz = true; attribSameRow = true; indentLevel = 0; fetchPlan = ""; keepTypes = false; } else { includeType = false; includeVer = false; includeId = false; includeClazz = false; attribSameRow = false; indentLevel = 0; keepTypes = false; String[] format = iFormat.split(","); for (String f : format) if (f.equals("type")) includeType = true; else if (f.equals("rid")) includeId = true; else if (f.equals("version")) includeVer = true; else if (f.equals("class")) includeClazz = true; else if (f.equals("attribSameRow")) attribSameRow = true; else if (f.startsWith("indent")) indentLevel = Integer.parseInt(f.substring(f.indexOf(':') + 1)); else if (f.startsWith("fetchPlan")) fetchPlan = f.substring(f.indexOf(':') + 1); else if (f.startsWith("keepTypes")) keepTypes = true; } json.beginObject(indentLevel); writeSignature(json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, iRecord); if (iRecord instanceof ORecordSchemaAware<?>) { // SCHEMA AWARE final ORecordSchemaAware<?> record = (ORecordSchemaAware<?>) iRecord; parsedRecords.add(iRecord.getIdentity()); Map<String, Integer> fetchPlanMap = null; if (fetchPlan != null && fetchPlan.length() > 0) fetchPlanMap = OFetchHelper.buildFetchPlan(fetchPlan); processRecord(json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, record, fetchPlanMap, keepTypes, 0, -1, parsedRecords); } else if (iRecord instanceof ORecordStringable) { // STRINGABLE final ORecordStringable record = (ORecordStringable) iRecord; json.writeAttribute(indentLevel + 1, true, "value", record.value()); } else if (iRecord instanceof ORecordBytes) { // BYTES final ORecordBytes record = (ORecordBytes) iRecord; json.writeAttribute(indentLevel + 1, true, "value", OBase64Utils.encodeBytes(record.toStream())); } else throw new OSerializationException("Error on marshalling record of type '" + iRecord.getClass() + "' to JSON. The record type can't be exported to JSON"); json.endObject(indentLevel); parsedRecords.clear(); return buffer.toString(); } catch (IOException e) { throw new OSerializationException("Error on marshalling of record to JSON", e); } } private void processRecord(final OJSONWriter json, int indentLevel, boolean includeType, boolean includeId, boolean includeVer, boolean includeClazz, boolean attribSameRow, final ORecordSchemaAware<?> record, Map<String, Integer> iFetchPlan, boolean keepTypes, final int iCurrentLevel, final int iMaxFetch, final Set<ORID> parsedRecords) throws IOException { Object fieldValue; final StringBuilder types = new StringBuilder(); for (String fieldName : record.fieldNames()) { if (iFetchPlan == null) { final Object v = record.field(fieldName); if (keepTypes) { if (v instanceof Long) appendType(types, fieldName, 'l'); else if (v instanceof Float) appendType(types, fieldName, 'f'); else if (v instanceof Short) appendType(types, fieldName, 's'); else if (v instanceof Double) appendType(types, fieldName, 'd'); else if (v instanceof Date) appendType(types, fieldName, 't'); else if (v instanceof Byte) appendType(types, fieldName, 'b'); } json.writeAttribute(indentLevel + 1, true, fieldName, OJSONWriter.encode(v)); } else { final Integer depthLevel = getDepthLevel(record, iFetchPlan, fieldName); if (depthLevel != null) { if (depthLevel == 0) { // NO FETCH THIS FIELD PLEASE continue; } if (depthLevel > -1 && depthLevel >= iCurrentLevel) { // MAX DEPTH REACHED: STOP TO FETCH THIS FIELD continue; } } fieldValue = record.field(fieldName); if (fieldValue == null || !(fieldValue instanceof OIdentifiable) && (!(fieldValue instanceof Collection<?>) || ((Collection<?>) fieldValue).size() == 0 || !(((Collection<?>) fieldValue) .iterator().next() instanceof OIdentifiable)) && (!(fieldValue instanceof Map<?, ?>) || ((Map<?, ?>) fieldValue).size() == 0 || !(((Map<?, ?>) fieldValue).values() .iterator().next() instanceof OIdentifiable))) { json.writeAttribute(indentLevel + 1, true, fieldName, OJSONWriter.encode(fieldValue)); } else { try { fetch(record, iFetchPlan, fieldValue, fieldName, iCurrentLevel + 1, iMaxFetch, json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, keepTypes, parsedRecords); } catch (Exception e) { e.printStackTrace(); OLogManager.instance().error(null, "Fetching error on record %s", e, record.getIdentity()); } } } } if (keepTypes && types.length() > 0) json.writeAttribute(indentLevel + 1, true, ATTRIBUTE_FIELD_TYPES, types.toString()); } private void appendType(final StringBuilder iBuffer, final String iFieldName, final char iType) { if (iBuffer.length() > 0) iBuffer.append(','); iBuffer.append(iFieldName); iBuffer.append('='); iBuffer.append(iType); } private void writeSignature(final OJSONWriter json, int indentLevel, boolean includeType, boolean includeId, boolean includeVer, boolean includeClazz, boolean attribSameRow, final ORecordInternal<?> record) throws IOException { boolean firstAttribute = true; if (includeType) { json.writeAttribute(firstAttribute ? indentLevel + 1 : 0, firstAttribute, ATTRIBUTE_TYPE, "" + (char) record.getRecordType()); if (attribSameRow) firstAttribute = false; } if (includeId && record.getIdentity() != null && record.getIdentity().isValid()) { json.writeAttribute(!firstAttribute ? indentLevel + 1 : 0, firstAttribute, ATTRIBUTE_ID, record.getIdentity().toString()); if (attribSameRow) firstAttribute = false; } if (includeVer) { json.writeAttribute(firstAttribute ? indentLevel + 1 : 0, firstAttribute, ATTRIBUTE_VERSION, record.getVersion()); if (attribSameRow) firstAttribute = false; } if (includeClazz && record instanceof ORecordSchemaAware<?> && ((ORecordSchemaAware<?>) record).getClassName() != null) { json.writeAttribute(firstAttribute ? indentLevel + 1 : 0, firstAttribute, ATTRIBUTE_CLASS, ((ORecordSchemaAware<?>) record).getClassName()); if (attribSameRow) firstAttribute = false; } } private void fetch(final ORecordSchemaAware<?> iRootRecord, final Map<String, Integer> iFetchPlan, final Object fieldValue, final String fieldName, final int iCurrentLevel, final int iMaxFetch, final OJSONWriter json, int indentLevel, boolean includeType, final boolean includeId, final boolean includeVer, final boolean includeClazz, final boolean attribSameRow, final boolean keepTypes, final Set<ORID> parsedRecords) throws IOException { Integer depthLevel; final Integer anyFieldDepthLevel = iFetchPlan != null ? iFetchPlan.get("*") : -1; depthLevel = getDepthLevel(iRootRecord, iFetchPlan, fieldName); if (depthLevel == null) // NO SPECIFIED: ASSIGN DEFAULT LEVEL TAKEN FROM * WILDCARD IF ANY depthLevel = anyFieldDepthLevel; if (depthLevel == 0) // NO FETCH THIS FIELD PLEASE return; if (depthLevel > -1 && iCurrentLevel >= depthLevel) // MAX DEPTH REACHED: STOP TO FETCH THIS FIELD return; if (fieldValue == null) { json.writeAttribute(indentLevel + 1, true, fieldName, null); } else if (fieldValue instanceof ODocument) { fetchDocument(iFetchPlan, fieldValue, fieldName, iCurrentLevel, iMaxFetch, json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, keepTypes, parsedRecords); } else if (fieldValue instanceof Collection<?>) { fetchCollection(iRootRecord.getDatabase(), iFetchPlan, fieldValue, fieldName, iCurrentLevel, iMaxFetch, json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, keepTypes, parsedRecords); } else if (fieldValue.getClass().isArray()) { fetchArray(iFetchPlan, fieldValue, fieldName, iCurrentLevel, iMaxFetch, json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, keepTypes, parsedRecords); } else if (fieldValue instanceof Map<?, ?>) { fetchMap(iFetchPlan, fieldValue, fieldName, iCurrentLevel, iMaxFetch, json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, keepTypes, parsedRecords); } if (iMaxFetch > -1 && iCurrentLevel >= iMaxFetch) { // MAX FETCH SIZE REACHED: STOP TO FETCH AT ALL return; } } @SuppressWarnings("unchecked") private void fetchMap(Map<String, Integer> iFetchPlan, Object fieldValue, String fieldName, final int iCurrentLevel, final int iMaxFetch, final OJSONWriter json, final int indentLevel, final boolean includeType, final boolean includeId, final boolean includeVer, final boolean includeClazz, final boolean attribSameRow, final boolean keepTypes, final Set<ORID> parsedRecords) throws IOException { final Map<String, ODocument> linked = (Map<String, ODocument>) fieldValue; json.beginObject(indentLevel + 1, true, fieldValue); for (ODocument d : (linked).values()) { // GO RECURSIVELY if (!parsedRecords.contains((d).getIdentity())) { parsedRecords.add((d).getIdentity()); json.beginObject(indentLevel + 1, true, null); writeSignature(json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, d); processRecord(json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, d, iFetchPlan, keepTypes, iCurrentLevel + 1, iMaxFetch, parsedRecords); json.endObject(indentLevel + 1, true); } else { json.writeValue(indentLevel + 1, false, OJSONWriter.encode(d)); } } json.endObject(indentLevel + 1, true); } private void fetchArray(final Map<String, Integer> iFetchPlan, final Object fieldValue, final String fieldName, final int iCurrentLevel, final int iMaxFetch, final OJSONWriter json, final int indentLevel, final boolean includeType, final boolean includeId, final boolean includeVer, final boolean includeClazz, final boolean attribSameRow, final boolean keepTypes, final Set<ORID> parsedRecords) throws IOException { if (fieldValue instanceof ODocument[]) { final ODocument[] linked = (ODocument[]) fieldValue; json.beginCollection(indentLevel + 1, true, fieldName); for (ODocument d : linked) { // GO RECURSIVELY if (!parsedRecords.contains((d).getIdentity())) { parsedRecords.add((d).getIdentity()); json.beginObject(indentLevel + 1, true, null); writeSignature(json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, d); processRecord(json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, d, iFetchPlan, keepTypes, iCurrentLevel + 1, iMaxFetch, parsedRecords); json.endObject(indentLevel + 1, true); } else { json.writeValue(indentLevel + 1, false, OJSONWriter.encode(d)); } } json.endCollection(indentLevel + 1, false); } else { json.writeAttribute(indentLevel + 1, true, fieldName, null); } } @SuppressWarnings("unchecked") private void fetchCollection(final ODatabaseRecord iDatabase, final Map<String, Integer> iFetchPlan, final Object fieldValue, final String fieldName, final int iCurrentLevel, final int iMaxFetch, final OJSONWriter json, final int indentLevel, final boolean includeType, final boolean includeId, final boolean includeVer, final boolean includeClazz, final boolean attribSameRow, final boolean keepTypes, final Set<ORID> parsedRecords) throws IOException { final Collection<ODocument> linked = (Collection<ODocument>) fieldValue; json.beginCollection(indentLevel + 1, true, fieldName); for (OIdentifiable d : linked) { // GO RECURSIVELY if (!parsedRecords.contains((d).getIdentity())) { parsedRecords.add((d).getIdentity()); if (d instanceof ORecordId) { d = iDatabase.load((ORecordId) d); } if (!(d instanceof ODocument)) { json.writeValue(indentLevel + 1, false, OJSONWriter.encode(d)); } else { json.beginObject(indentLevel + 1, true, null); writeSignature(json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, (ODocument) d); processRecord(json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, (ODocument) d, iFetchPlan, keepTypes, iCurrentLevel + 1, iMaxFetch, parsedRecords); json.endObject(indentLevel + 1, true); } } else { json.writeValue(indentLevel + 1, false, OJSONWriter.encode(d)); } } json.endCollection(indentLevel + 1, false); } private void fetchDocument(Map<String, Integer> iFetchPlan, Object fieldValue, String fieldName, final int iCurrentLevel, final int iMaxFetch, final OJSONWriter json, int indentLevel, boolean includeType, boolean includeId, boolean includeVer, boolean includeClazz, boolean attribSameRow, boolean keepTypes, final Set<ORID> parsedRecords) throws IOException { if (!parsedRecords.contains(((ODocument) fieldValue).getIdentity())) { parsedRecords.add(((ODocument) fieldValue).getIdentity()); final ODocument linked = (ODocument) fieldValue; json.beginObject(indentLevel + 1, true, fieldName); writeSignature(json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, linked); processRecord(json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, linked, iFetchPlan, keepTypes, iCurrentLevel + 1, iMaxFetch, parsedRecords); json.endObject(indentLevel + 1, true); } else { json.writeAttribute(indentLevel + 1, true, fieldName, OJSONWriter.encode(fieldValue)); } } private Integer getDepthLevel(final ORecordSchemaAware<?> record, final Map<String, Integer> iFetchPlan, final String iFieldName) { Integer depthLevel; if (iFetchPlan != null) { // GET THE FETCH PLAN FOR THE GENERIC FIELD IF SPECIFIED depthLevel = iFetchPlan.get(iFieldName); if (depthLevel == null) { OClass cls = record.getSchemaClass(); while (cls != null && depthLevel == null) { depthLevel = iFetchPlan.get(cls.getName() + "." + iFieldName); if (depthLevel == null) cls = cls.getSuperClass(); } } } else // INFINITE depthLevel = -1; return depthLevel; } @Override public String toString() { return NAME; } }
core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerJSON.java
/* * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.orient.core.serialization.serializer.record.string; import java.io.IOException; import java.io.StringWriter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.common.parser.OStringParser; import com.orientechnologies.orient.core.db.OUserObject2RecordHandler; import com.orientechnologies.orient.core.db.record.ODatabaseRecord; import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.db.record.ORecordLazyList; import com.orientechnologies.orient.core.db.record.ORecordLazySet; import com.orientechnologies.orient.core.db.record.OTrackedList; import com.orientechnologies.orient.core.db.record.OTrackedSet; import com.orientechnologies.orient.core.exception.OSerializationException; import com.orientechnologies.orient.core.fetch.OFetchHelper; import com.orientechnologies.orient.core.id.ORID; import com.orientechnologies.orient.core.id.ORecordId; import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.OProperty; import com.orientechnologies.orient.core.metadata.schema.OType; import com.orientechnologies.orient.core.record.ORecord; import com.orientechnologies.orient.core.record.ORecordFactory; import com.orientechnologies.orient.core.record.ORecordInternal; import com.orientechnologies.orient.core.record.ORecordSchemaAware; import com.orientechnologies.orient.core.record.ORecordStringable; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.record.impl.ORecordBytes; import com.orientechnologies.orient.core.serialization.OBase64Utils; import com.orientechnologies.orient.core.serialization.serializer.OJSONWriter; import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper; public class ORecordSerializerJSON extends ORecordSerializerStringAbstract { public static final String NAME = "json"; public static final ORecordSerializerJSON INSTANCE = new ORecordSerializerJSON(); public static final String ATTRIBUTE_ID = "@rid"; public static final String ATTRIBUTE_VERSION = "@version"; public static final String ATTRIBUTE_TYPE = "@type"; public static final String ATTRIBUTE_FIELD_TYPES = "@fieldTypes"; public static final String ATTRIBUTE_CLASS = "@class"; public static final String DEF_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss:SSS"; private SimpleDateFormat dateFormat = new SimpleDateFormat(DEF_DATE_FORMAT); @Override public ORecordInternal<?> fromString(final ODatabaseRecord iDatabase, final String iSource) { return fromString(iDatabase, iSource, null); } @Override public ORecordInternal<?> fromString(final ODatabaseRecord iDatabase, String iSource, ORecordInternal<?> iRecord) { if (iSource == null) throw new OSerializationException("Error on unmarshalling JSON content: content is null"); iSource = iSource.trim(); if (!iSource.startsWith("{") || !iSource.endsWith("}")) throw new OSerializationException("Error on unmarshalling JSON content: content must be between { }"); if (iRecord != null) // RESET ALL THE FIELDS iRecord.reset(); iSource = iSource.substring(1, iSource.length() - 1).trim(); String[] fields = OStringParser.getWords(iSource, ":,", true); String fieldName; String fieldValue; String fieldValueAsString; Map<String, Character> fieldTypes = null; // SEARCH FOR FIELD TYPES IF ANY for (int i = 0; i < fields.length; i += 2) { fieldName = fields[i]; fieldName = fieldName.substring(1, fieldName.length() - 1); fieldValue = fields[i + 1]; fieldValueAsString = fieldValue.length() >= 2 ? fieldValue.substring(1, fieldValue.length() - 1) : fieldValue; if (fieldName.equals(ATTRIBUTE_FIELD_TYPES) && iRecord instanceof ODocument) { // LOAD THE FIELD TYPE MAP final String[] fieldTypesParts = fieldValueAsString.split(","); if (fieldTypesParts.length > 0) { fieldTypes = new HashMap<String, Character>(); String[] part; for (String f : fieldTypesParts) { part = f.split("="); if (part.length == 2) fieldTypes.put(part[0], part[1].charAt(0)); } } } } try { if (fields != null && fields.length > 0) { for (int i = 0; i < fields.length; i += 2) { fieldName = fields[i]; fieldName = fieldName.substring(1, fieldName.length() - 1); fieldValue = fields[i + 1].trim(); fieldValueAsString = fieldValue.length() >= 2 ? fieldValue.substring(1, fieldValue.length() - 1) : fieldValue; // RECORD ATTRIBUTES if (fieldName.equals(ATTRIBUTE_ID)) iRecord.setIdentity(new ORecordId(fieldValueAsString)); else if (fieldName.equals(ATTRIBUTE_VERSION)) iRecord.setVersion(Integer.parseInt(fieldValue)); else if (fieldName.equals(ATTRIBUTE_TYPE)) { if (iRecord == null || iRecord.getRecordType() != fieldValueAsString.charAt(0)) { // CREATE THE RIGHT RECORD INSTANCE iRecord = ORecordFactory.newInstance((byte) fieldValueAsString.charAt(0)); iRecord.setDatabase(iDatabase); } } else if (fieldName.equals(ATTRIBUTE_CLASS) && iRecord instanceof ODocument) ((ODocument) iRecord).setClassNameIfExists("null".equals(fieldValueAsString) ? null : fieldValueAsString); else if (fieldName.equals(ATTRIBUTE_FIELD_TYPES) && iRecord instanceof ODocument) // JUMP IT continue; // RECORD VALUE(S) else if (fieldName.equals("value") && !(iRecord instanceof ODocument)) { if ("null".equals(fieldValue)) iRecord.fromStream(new byte[] {}); else if (iRecord instanceof ORecordBytes) { // BYTES iRecord.fromStream(OBase64Utils.decode(fieldValueAsString)); } else if (iRecord instanceof ORecordStringable) { ((ORecordStringable) iRecord).value(fieldValueAsString); } } else { if (iRecord instanceof ODocument) { final Object v = getValue((ODocument) iRecord, fieldName, fieldValue, fieldValueAsString, null, null, fieldTypes); if (v != null) if (v instanceof Collection<?> && ((Collection<?>) v).size() > 0) { if (v instanceof ORecordLazySet) ((ORecordLazySet) v).setAutoConvertToRecord(false); else if (v instanceof ORecordLazyList) ((ORecordLazyList) v).setAutoConvertToRecord(false); // CHECK IF THE COLLECTION IS EMBEDDED Object first = ((Collection<?>) v).iterator().next(); if (first != null && first instanceof ORecord<?> && !((ORecord<?>) first).getIdentity().isValid()) { ((ODocument) iRecord).field(fieldName, v, v instanceof Set<?> ? OType.EMBEDDEDSET : OType.EMBEDDEDLIST); continue; } } else if (v instanceof Map<?, ?> && ((Map<?, ?>) v).size() > 0) { // CHECK IF THE MAP IS EMBEDDED Object first = ((Map<?, ?>) v).values().iterator().next(); if (first != null && first instanceof ORecord<?> && !((ORecord<?>) first).getIdentity().isValid()) { ((ODocument) iRecord).field(fieldName, v, OType.EMBEDDEDMAP); continue; } } ((ODocument) iRecord).field(fieldName, v); } } } } } catch (Exception e) { e.printStackTrace(); throw new OSerializationException("Error on unmarshalling JSON content for record " + iRecord.getIdentity(), e); } return iRecord; } @SuppressWarnings("unchecked") private Object getValue(final ODocument iRecord, String iFieldName, String iFieldValue, String iFieldValueAsString, OType iType, OType iLinkedType, final Map<String, Character> iFieldTypes) { if (iFieldValue.equals("null")) return null; if (iFieldName != null) if (iRecord.getSchemaClass() != null) { final OProperty p = iRecord.getSchemaClass().getProperty(iFieldName); if (p != null) { iType = p.getType(); iLinkedType = p.getLinkedType(); } } if (iFieldValue.startsWith("{") && iFieldValue.endsWith("}")) { // OBJECT OR MAP. CHECK THE TYPE ATTRIBUTE TO KNOW IT String[] fields = OStringParser.getWords(iFieldValueAsString, ":,", true); if (fields == null || fields.length == 0) // EMPTY, RETURN an EMPTY HASHMAP return new HashMap<String, Object>(); if (fields[0].equals("\"@type\"")) // OBJECT return fromString(iRecord.getDatabase(), iFieldValue, null); else { if (fields.length % 2 == 1) throw new OSerializationException("Bad JSON format on map. Expected pairs of field:value but received '" + iFieldValueAsString + "'"); // MAP final Map<String, Object> embeddedMap = new LinkedHashMap<String, Object>(); for (int i = 0; i < fields.length; i += 2) { iFieldName = fields[i]; if (iFieldName.length() >= 2) iFieldName = iFieldName.substring(1, iFieldName.length() - 1); iFieldValue = fields[i + 1]; iFieldValueAsString = iFieldValue.length() >= 2 ? iFieldValue.substring(1, iFieldValue.length() - 1) : iFieldValue; embeddedMap.put(iFieldName, getValue(iRecord, null, iFieldValue, iFieldValueAsString, iLinkedType, null, iFieldTypes)); } return embeddedMap; } } else if (iFieldValue.startsWith("[") && iFieldValue.endsWith("]")) { // EMBEDDED VALUES final Collection<?> embeddedCollection; if (iType == OType.LINKSET) embeddedCollection = new ORecordLazySet(iRecord); else if (iType == OType.EMBEDDEDSET) embeddedCollection = new OTrackedSet<Object>(iRecord); else if (iType == OType.LINKLIST) embeddedCollection = new ORecordLazyList(iRecord); else embeddedCollection = new OTrackedList<Object>(iRecord); iFieldValue = iFieldValue.substring(1, iFieldValue.length() - 1); if (iFieldValue.length() > 0) { // EMBEDDED VALUES List<String> items = OStringSerializerHelper.smartSplit(iFieldValue, ','); Object collectionItem; for (String item : items) { iFieldValue = item.trim(); iFieldValueAsString = iFieldValue.length() >= 2 ? iFieldValue.substring(1, iFieldValue.length() - 1) : iFieldValue; collectionItem = getValue(iRecord, null, iFieldValue, iFieldValueAsString, iLinkedType, null, iFieldTypes); if (collectionItem instanceof ODocument && iRecord instanceof ODocument) // SET THE OWNER ((ODocument) collectionItem).addOwner(iRecord); ((Collection<Object>) embeddedCollection).add(collectionItem); } } return embeddedCollection; } if (iType == null) // TRY TO DETERMINE THE CONTAINED TYPE from THE FIRST VALUE if (iFieldValue.charAt(0) != '\"') { if (iFieldValue.equalsIgnoreCase("false") || iFieldValue.equalsIgnoreCase("true")) iType = OType.BOOLEAN; else { Character c = null; if (iFieldTypes != null) { c = iFieldTypes.get(iFieldName); if (c != null) iType = ORecordSerializerStringAbstract.getType(iFieldValue + c); } if (c == null) // TRY TO AUTODETERMINE THE BEST TYPE if (OStringSerializerHelper.contains(iFieldValue, '.')) iType = OType.FLOAT; else iType = OType.INTEGER; } } else if (iFieldValueAsString.length() >= 4 && iFieldValueAsString.charAt(0) == '#' && iFieldValueAsString.contains(":")) iType = OType.LINK; else if (iFieldValueAsString.startsWith("{") && iFieldValueAsString.endsWith("}")) iType = OType.EMBEDDED; else { if (iFieldValueAsString.length() == DEF_DATE_FORMAT.length()) // TRY TO PARSE AS DATE try { synchronized (dateFormat) { return dateFormat.parseObject(iFieldValueAsString); } } catch (Exception e) { } iType = OType.STRING; } if (iType != null) switch (iType) { case STRING: return iFieldValueAsString; case LINK: final int pos = iFieldValueAsString.indexOf('@'); if (pos > -1) // CREATE DOCUMENT return new ODocument(iRecord.getDatabase(), iFieldValueAsString.substring(1, pos), new ORecordId( iFieldValueAsString.substring(pos + 1))); else // CREATE SIMPLE RID return new ORecordId(iFieldValueAsString.substring(1)); case EMBEDDED: return fromString(iRecord.getDatabase(), iFieldValueAsString); case DATE: try { // TRY TO PARSE AS LONG return Long.parseLong(iFieldValueAsString); } catch (NumberFormatException e) { try { // TRY TO PARSE AS DATE return dateFormat.parseObject(iFieldValueAsString); } catch (ParseException ex) { throw new OSerializationException("Unable to unmarshall date: " + iFieldValueAsString, e); } } default: return OStringSerializerHelper.fieldTypeFromStream(iRecord, iType, iFieldValue); } return iFieldValueAsString; } @Override public String toString(final ORecordInternal<?> iRecord, final String iFormat, final OUserObject2RecordHandler iObjHandler, final Set<Integer> iMarshalledRecords) { try { final StringWriter buffer = new StringWriter(); final OJSONWriter json = new OJSONWriter(buffer, iFormat); final Set<ORID> parsedRecords = new HashSet<ORID>(); boolean includeVer; boolean includeType; boolean includeId; boolean includeClazz; boolean attribSameRow; int indentLevel; String fetchPlan = null; boolean keepTypes; if (iFormat == null) { includeType = true; includeVer = true; includeId = true; includeClazz = true; attribSameRow = true; indentLevel = 0; fetchPlan = ""; keepTypes = false; } else { includeType = false; includeVer = false; includeId = false; includeClazz = false; attribSameRow = false; indentLevel = 0; keepTypes = false; String[] format = iFormat.split(","); for (String f : format) if (f.equals("type")) includeType = true; else if (f.equals("rid")) includeId = true; else if (f.equals("version")) includeVer = true; else if (f.equals("class")) includeClazz = true; else if (f.equals("attribSameRow")) attribSameRow = true; else if (f.startsWith("indent")) indentLevel = Integer.parseInt(f.substring(f.indexOf(':') + 1)); else if (f.startsWith("fetchPlan")) fetchPlan = f.substring(f.indexOf(':') + 1); else if (f.startsWith("keepTypes")) keepTypes = true; } json.beginObject(indentLevel); writeSignature(json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, iRecord); if (iRecord instanceof ORecordSchemaAware<?>) { // SCHEMA AWARE final ORecordSchemaAware<?> record = (ORecordSchemaAware<?>) iRecord; parsedRecords.add(iRecord.getIdentity()); Map<String, Integer> fetchPlanMap = null; if (fetchPlan != null && fetchPlan.length() > 0) fetchPlanMap = OFetchHelper.buildFetchPlan(fetchPlan); processRecord(json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, record, fetchPlanMap, keepTypes, 0, -1, parsedRecords); } else if (iRecord instanceof ORecordStringable) { // STRINGABLE final ORecordStringable record = (ORecordStringable) iRecord; json.writeAttribute(indentLevel + 1, true, "value", record.value()); } else if (iRecord instanceof ORecordBytes) { // BYTES final ORecordBytes record = (ORecordBytes) iRecord; json.writeAttribute(indentLevel + 1, true, "value", OBase64Utils.encodeBytes(record.toStream())); } else throw new OSerializationException("Error on marshalling record of type '" + iRecord.getClass() + "' to JSON. The record type can't be exported to JSON"); json.endObject(indentLevel); parsedRecords.clear(); return buffer.toString(); } catch (IOException e) { throw new OSerializationException("Error on marshalling of record to JSON", e); } } private void processRecord(final OJSONWriter json, int indentLevel, boolean includeType, boolean includeId, boolean includeVer, boolean includeClazz, boolean attribSameRow, final ORecordSchemaAware<?> record, Map<String, Integer> iFetchPlan, boolean keepTypes, final int iCurrentLevel, final int iMaxFetch, final Set<ORID> parsedRecords) throws IOException { Object fieldValue; final StringBuilder types = new StringBuilder(); for (String fieldName : record.fieldNames()) { if (iFetchPlan == null) { final Object v = record.field(fieldName); if (keepTypes) { if (v instanceof Long) appendType(types, fieldName, 'l'); else if (v instanceof Float) appendType(types, fieldName, 'f'); else if (v instanceof Short) appendType(types, fieldName, 's'); else if (v instanceof Double) appendType(types, fieldName, 'd'); else if (v instanceof Date) appendType(types, fieldName, 't'); else if (v instanceof Byte) appendType(types, fieldName, 'b'); } json.writeAttribute(indentLevel + 1, true, fieldName, OJSONWriter.encode(v)); } else { final Integer depthLevel = getDepthLevel(record, iFetchPlan, fieldName); if (depthLevel != null) { if (depthLevel == 0) { // NO FETCH THIS FIELD PLEASE continue; } if (depthLevel > -1 && depthLevel >= iCurrentLevel) { // MAX DEPTH REACHED: STOP TO FETCH THIS FIELD continue; } } fieldValue = record.field(fieldName); if (fieldValue == null || !(fieldValue instanceof OIdentifiable) && (!(fieldValue instanceof Collection<?>) || ((Collection<?>) fieldValue).size() == 0 || !(((Collection<?>) fieldValue) .iterator().next() instanceof OIdentifiable)) && (!(fieldValue instanceof Map<?, ?>) || ((Map<?, ?>) fieldValue).size() == 0 || !(((Map<?, ?>) fieldValue).values() .iterator().next() instanceof OIdentifiable))) { json.writeAttribute(indentLevel + 1, true, fieldName, OJSONWriter.encode(fieldValue)); } else { try { fetch(record, iFetchPlan, fieldValue, fieldName, iCurrentLevel + 1, iMaxFetch, json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, keepTypes, parsedRecords); } catch (Exception e) { e.printStackTrace(); OLogManager.instance().error(null, "Fetching error on record %s", e, record.getIdentity()); } } } } if (keepTypes && types.length() > 0) json.writeAttribute(indentLevel + 1, true, ATTRIBUTE_FIELD_TYPES, types.toString()); } private void appendType(final StringBuilder iBuffer, final String iFieldName, final char iType) { if (iBuffer.length() > 0) iBuffer.append(','); iBuffer.append(iFieldName); iBuffer.append('='); iBuffer.append(iType); } private void writeSignature(final OJSONWriter json, int indentLevel, boolean includeType, boolean includeId, boolean includeVer, boolean includeClazz, boolean attribSameRow, final ORecordInternal<?> record) throws IOException { boolean firstAttribute = true; if (includeType) { json.writeAttribute(firstAttribute ? indentLevel + 1 : 0, firstAttribute, ATTRIBUTE_TYPE, "" + (char) record.getRecordType()); if (attribSameRow) firstAttribute = false; } if (includeId && record.getIdentity() != null && record.getIdentity().isValid()) { json.writeAttribute(!firstAttribute ? indentLevel + 1 : 0, firstAttribute, ATTRIBUTE_ID, record.getIdentity().toString()); if (attribSameRow) firstAttribute = false; } if (includeVer && record.getVersion() > 0) { json.writeAttribute(firstAttribute ? indentLevel + 1 : 0, firstAttribute, ATTRIBUTE_VERSION, record.getVersion()); if (attribSameRow) firstAttribute = false; } if (includeClazz && record instanceof ORecordSchemaAware<?> && ((ORecordSchemaAware<?>) record).getClassName() != null) { json.writeAttribute(firstAttribute ? indentLevel + 1 : 0, firstAttribute, ATTRIBUTE_CLASS, ((ORecordSchemaAware<?>) record).getClassName()); if (attribSameRow) firstAttribute = false; } } private void fetch(final ORecordSchemaAware<?> iRootRecord, final Map<String, Integer> iFetchPlan, final Object fieldValue, final String fieldName, final int iCurrentLevel, final int iMaxFetch, final OJSONWriter json, int indentLevel, boolean includeType, final boolean includeId, final boolean includeVer, final boolean includeClazz, final boolean attribSameRow, final boolean keepTypes, final Set<ORID> parsedRecords) throws IOException { Integer depthLevel; final Integer anyFieldDepthLevel = iFetchPlan != null ? iFetchPlan.get("*") : -1; depthLevel = getDepthLevel(iRootRecord, iFetchPlan, fieldName); if (depthLevel == null) // NO SPECIFIED: ASSIGN DEFAULT LEVEL TAKEN FROM * WILDCARD IF ANY depthLevel = anyFieldDepthLevel; if (depthLevel == 0) // NO FETCH THIS FIELD PLEASE return; if (depthLevel > -1 && iCurrentLevel >= depthLevel) // MAX DEPTH REACHED: STOP TO FETCH THIS FIELD return; if (fieldValue == null) { json.writeAttribute(indentLevel + 1, true, fieldName, null); } else if (fieldValue instanceof ODocument) { fetchDocument(iFetchPlan, fieldValue, fieldName, iCurrentLevel, iMaxFetch, json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, keepTypes, parsedRecords); } else if (fieldValue instanceof Collection<?>) { fetchCollection(iRootRecord.getDatabase(), iFetchPlan, fieldValue, fieldName, iCurrentLevel, iMaxFetch, json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, keepTypes, parsedRecords); } else if (fieldValue.getClass().isArray()) { fetchArray(iFetchPlan, fieldValue, fieldName, iCurrentLevel, iMaxFetch, json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, keepTypes, parsedRecords); } else if (fieldValue instanceof Map<?, ?>) { fetchMap(iFetchPlan, fieldValue, fieldName, iCurrentLevel, iMaxFetch, json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, keepTypes, parsedRecords); } if (iMaxFetch > -1 && iCurrentLevel >= iMaxFetch) { // MAX FETCH SIZE REACHED: STOP TO FETCH AT ALL return; } } @SuppressWarnings("unchecked") private void fetchMap(Map<String, Integer> iFetchPlan, Object fieldValue, String fieldName, final int iCurrentLevel, final int iMaxFetch, final OJSONWriter json, final int indentLevel, final boolean includeType, final boolean includeId, final boolean includeVer, final boolean includeClazz, final boolean attribSameRow, final boolean keepTypes, final Set<ORID> parsedRecords) throws IOException { final Map<String, ODocument> linked = (Map<String, ODocument>) fieldValue; json.beginObject(indentLevel + 1, true, fieldValue); for (ODocument d : (linked).values()) { // GO RECURSIVELY if (!parsedRecords.contains((d).getIdentity())) { parsedRecords.add((d).getIdentity()); json.beginObject(indentLevel + 1, true, null); writeSignature(json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, d); processRecord(json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, d, iFetchPlan, keepTypes, iCurrentLevel + 1, iMaxFetch, parsedRecords); json.endObject(indentLevel + 1, true); } else { json.writeValue(indentLevel + 1, false, OJSONWriter.encode(d)); } } json.endObject(indentLevel + 1, true); } private void fetchArray(final Map<String, Integer> iFetchPlan, final Object fieldValue, final String fieldName, final int iCurrentLevel, final int iMaxFetch, final OJSONWriter json, final int indentLevel, final boolean includeType, final boolean includeId, final boolean includeVer, final boolean includeClazz, final boolean attribSameRow, final boolean keepTypes, final Set<ORID> parsedRecords) throws IOException { if (fieldValue instanceof ODocument[]) { final ODocument[] linked = (ODocument[]) fieldValue; json.beginCollection(indentLevel + 1, true, fieldName); for (ODocument d : linked) { // GO RECURSIVELY if (!parsedRecords.contains((d).getIdentity())) { parsedRecords.add((d).getIdentity()); json.beginObject(indentLevel + 1, true, null); writeSignature(json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, d); processRecord(json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, d, iFetchPlan, keepTypes, iCurrentLevel + 1, iMaxFetch, parsedRecords); json.endObject(indentLevel + 1, true); } else { json.writeValue(indentLevel + 1, false, OJSONWriter.encode(d)); } } json.endCollection(indentLevel + 1, false); } else { json.writeAttribute(indentLevel + 1, true, fieldName, null); } } @SuppressWarnings("unchecked") private void fetchCollection(final ODatabaseRecord iDatabase, final Map<String, Integer> iFetchPlan, final Object fieldValue, final String fieldName, final int iCurrentLevel, final int iMaxFetch, final OJSONWriter json, final int indentLevel, final boolean includeType, final boolean includeId, final boolean includeVer, final boolean includeClazz, final boolean attribSameRow, final boolean keepTypes, final Set<ORID> parsedRecords) throws IOException { final Collection<ODocument> linked = (Collection<ODocument>) fieldValue; json.beginCollection(indentLevel + 1, true, fieldName); for (OIdentifiable d : linked) { // GO RECURSIVELY if (!parsedRecords.contains((d).getIdentity())) { parsedRecords.add((d).getIdentity()); if (d instanceof ORecordId) { d = iDatabase.load((ORecordId) d); } if (!(d instanceof ODocument)) { json.writeValue(indentLevel + 1, false, OJSONWriter.encode(d)); } else { json.beginObject(indentLevel + 1, true, null); writeSignature(json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, (ODocument) d); processRecord(json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, (ODocument) d, iFetchPlan, keepTypes, iCurrentLevel + 1, iMaxFetch, parsedRecords); json.endObject(indentLevel + 1, true); } } else { json.writeValue(indentLevel + 1, false, OJSONWriter.encode(d)); } } json.endCollection(indentLevel + 1, false); } private void fetchDocument(Map<String, Integer> iFetchPlan, Object fieldValue, String fieldName, final int iCurrentLevel, final int iMaxFetch, final OJSONWriter json, int indentLevel, boolean includeType, boolean includeId, boolean includeVer, boolean includeClazz, boolean attribSameRow, boolean keepTypes, final Set<ORID> parsedRecords) throws IOException { if (!parsedRecords.contains(((ODocument) fieldValue).getIdentity())) { parsedRecords.add(((ODocument) fieldValue).getIdentity()); final ODocument linked = (ODocument) fieldValue; json.beginObject(indentLevel + 1, true, fieldName); writeSignature(json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, linked); processRecord(json, indentLevel, includeType, includeId, includeVer, includeClazz, attribSameRow, linked, iFetchPlan, keepTypes, iCurrentLevel + 1, iMaxFetch, parsedRecords); json.endObject(indentLevel + 1, true); } else { json.writeAttribute(indentLevel + 1, true, fieldName, OJSONWriter.encode(fieldValue)); } } private Integer getDepthLevel(final ORecordSchemaAware<?> record, final Map<String, Integer> iFetchPlan, final String iFieldName) { Integer depthLevel; if (iFetchPlan != null) { // GET THE FETCH PLAN FOR THE GENERIC FIELD IF SPECIFIED depthLevel = iFetchPlan.get(iFieldName); if (depthLevel == null) { OClass cls = record.getSchemaClass(); while (cls != null && depthLevel == null) { depthLevel = iFetchPlan.get(cls.getName() + "." + iFieldName); if (depthLevel == null) cls = cls.getSuperClass(); } } } else // INFINITE depthLevel = -1; return depthLevel; } @Override public String toString() { return NAME; } }
Fixed bug on JSON converter. Before now it included the @version only if > 0. Now always.
core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerJSON.java
Fixed bug on JSON converter. Before now it included the @version only if > 0. Now always.
Java
apache-2.0
aaee5a41d8fc02324d232620f253d2b16a49617f
0
icecondor/android,icecondor/android
package com.icecondor.nest; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase.CursorFactory; public class GeoRssSqlite extends SQLiteOpenHelper { public static final String NAME = "name"; public static final String URL = "url"; public static final String SERVICES_TABLE = "services"; public static final String SHOUTS_TABLE = "shouts"; public static final String ID = "_id"; public GeoRssSqlite(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE services (_id integer primary key, name text, url text)"); db.execSQL("CREATE TABLE shouts (_id integer primary key, guid text unique on conflict replace, title text, lat float, long float, date datetime, service_id integer)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub } }
src/com/icecondor/nest/GeoRssSqlite.java
package com.icecondor.nest; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase.CursorFactory; public class GeoRssSqlite extends SQLiteOpenHelper { public static final String NAME = "name"; public static final String URL = "url"; public static final String SERVICES_TABLE = "services"; public static final String SHOUTS_TABLE = "shouts"; public static final String ID = "_id"; public GeoRssSqlite(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE services (_id integer primary key, name text, url text)"); db.execSQL("CREATE TABLE shouts (_id integer primary key, guid text unique on conflict ignore, title text, lat float, long float, date datetime, service_id integer)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub } }
replace shouts instead of ignoring existing shouts (in the db)
src/com/icecondor/nest/GeoRssSqlite.java
replace shouts instead of ignoring existing shouts (in the db)
Java
apache-2.0
d896c931f755dd3b743bf09ad6926fe96ad6bba4
0
lincoln-lil/flink,zentol/flink,tony810430/flink,apache/flink,zentol/flink,twalthr/flink,zjureel/flink,twalthr/flink,xccui/flink,gyfora/flink,apache/flink,zjureel/flink,lincoln-lil/flink,xccui/flink,zjureel/flink,apache/flink,xccui/flink,zjureel/flink,godfreyhe/flink,godfreyhe/flink,zentol/flink,zjureel/flink,wwjiang007/flink,zjureel/flink,gyfora/flink,gyfora/flink,twalthr/flink,tony810430/flink,gyfora/flink,godfreyhe/flink,apache/flink,gyfora/flink,xccui/flink,xccui/flink,wwjiang007/flink,zentol/flink,tony810430/flink,lincoln-lil/flink,twalthr/flink,xccui/flink,zjureel/flink,gyfora/flink,zentol/flink,tony810430/flink,apache/flink,apache/flink,godfreyhe/flink,zentol/flink,godfreyhe/flink,wwjiang007/flink,wwjiang007/flink,tony810430/flink,godfreyhe/flink,wwjiang007/flink,lincoln-lil/flink,lincoln-lil/flink,lincoln-lil/flink,twalthr/flink,lincoln-lil/flink,wwjiang007/flink,twalthr/flink,tony810430/flink,godfreyhe/flink,tony810430/flink,twalthr/flink,gyfora/flink,zentol/flink,wwjiang007/flink,xccui/flink,apache/flink
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.architecture.rules; import org.apache.flink.core.testutils.AllCallbackWrapper; import org.apache.flink.runtime.testutils.MiniClusterExtension; import org.apache.flink.test.util.AbstractTestBase; import org.apache.flink.test.util.MiniClusterWithClientResource; import com.tngtech.archunit.junit.ArchTest; import com.tngtech.archunit.lang.ArchRule; import org.junit.ClassRule; import org.junit.Rule; import org.junit.jupiter.api.extension.RegisterExtension; import static com.tngtech.archunit.core.domain.JavaModifier.ABSTRACT; import static com.tngtech.archunit.library.freeze.FreezingArchRule.freeze; import static org.apache.flink.architecture.common.Conditions.fulfill; import static org.apache.flink.architecture.common.GivenJavaClasses.javaClassesThat; import static org.apache.flink.architecture.common.Predicates.arePublicFinalOfTypeWithAnnotation; import static org.apache.flink.architecture.common.Predicates.arePublicStaticFinalOfType; import static org.apache.flink.architecture.common.Predicates.arePublicStaticFinalOfTypeWithAnnotation; import static org.apache.flink.architecture.common.Predicates.containAnyFieldsInClassHierarchyThat; /** Rules for Integration Tests. */ public class ITCaseRules { @ArchTest public static final ArchRule INTEGRATION_TEST_ENDING_WITH_ITCASE = freeze( javaClassesThat() .areAssignableTo(AbstractTestBase.class) .and() .doNotHaveModifier(ABSTRACT) .should() .haveSimpleNameEndingWith("ITCase")); /** * In order to pass this check, IT cases must fulfill at least one of the following conditions. * * <p>1. For JUnit 5 test, both fields are required like: * * <pre>{@code * public static final MiniClusterExtension MINI_CLUSTER_RESOURCE = * new MiniClusterExtension( * new MiniClusterResourceConfiguration.Builder() * .setConfiguration(getFlinkConfiguration()) * .build()); * * @RegisterExtension * public static AllCallbackWrapper allCallbackWrapper = * new AllCallbackWrapper(MINI_CLUSTER_RESOURCE); * }</pre> * * <p>2. For JUnit 4 test via @Rule like: * * <pre>{@code * @Rule * public final MiniClusterWithClientResource miniClusterResource = * new MiniClusterWithClientResource( * new MiniClusterResourceConfiguration.Builder() * .setNumberTaskManagers(1) * .setNumberSlotsPerTaskManager(PARALLELISM) * .setRpcServiceSharing(RpcServiceSharing.DEDICATED) * .withHaLeadershipControl() * .build()); * }</pre> * * <p>3. For JUnit 4 test via @ClassRule like: * * <pre>{@code * @ClassRule * public static final MiniClusterWithClientResource MINI_CLUSTER = * new MiniClusterWithClientResource( * new MiniClusterResourceConfiguration.Builder() * .setConfiguration(new Configuration()) * .build()); * }</pre> */ @ArchTest public static final ArchRule ITCASE_USE_MINICLUSTER = freeze( javaClassesThat() .haveSimpleNameEndingWith("ITCase") .and() .areTopLevelClasses() .and() .doNotHaveModifier(ABSTRACT) .should( fulfill( // JUnit 5 violation check containAnyFieldsInClassHierarchyThat( arePublicStaticFinalOfType( MiniClusterExtension.class)) .and( containAnyFieldsInClassHierarchyThat( arePublicStaticFinalOfTypeWithAnnotation( AllCallbackWrapper .class, RegisterExtension .class))) // JUnit 4 violation check, which should be // removed // after the JUnit 4->5 migration is closed. // Please refer to FLINK-25858. .or( containAnyFieldsInClassHierarchyThat( arePublicStaticFinalOfTypeWithAnnotation( MiniClusterWithClientResource .class, ClassRule.class))) .or( containAnyFieldsInClassHierarchyThat( arePublicFinalOfTypeWithAnnotation( MiniClusterWithClientResource .class, Rule.class)))))); }
flink-architecture-tests/flink-architecture-tests-test/src/main/java/org/apache/flink/architecture/rules/ITCaseRules.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.architecture.rules; import org.apache.flink.core.testutils.AllCallbackWrapper; import org.apache.flink.runtime.testutils.MiniClusterExtension; import org.apache.flink.test.util.AbstractTestBase; import org.apache.flink.test.util.MiniClusterWithClientResource; import com.tngtech.archunit.junit.ArchTest; import com.tngtech.archunit.lang.ArchRule; import org.junit.ClassRule; import org.junit.Rule; import org.junit.jupiter.api.extension.RegisterExtension; import static com.tngtech.archunit.core.domain.JavaModifier.ABSTRACT; import static com.tngtech.archunit.library.freeze.FreezingArchRule.freeze; import static org.apache.flink.architecture.common.Conditions.fulfill; import static org.apache.flink.architecture.common.GivenJavaClasses.javaClassesThat; import static org.apache.flink.architecture.common.Predicates.arePublicFinalOfTypeWithAnnotation; import static org.apache.flink.architecture.common.Predicates.arePublicStaticFinalOfType; import static org.apache.flink.architecture.common.Predicates.arePublicStaticFinalOfTypeWithAnnotation; import static org.apache.flink.architecture.common.Predicates.containAnyFieldsInClassHierarchyThat; /** Rules for Integration Tests. */ public class ITCaseRules { @ArchTest public static final ArchRule INTEGRATION_TEST_ENDING_WITH_ITCASE = freeze( javaClassesThat() .areAssignableTo(AbstractTestBase.class) .and() .doNotHaveModifier(ABSTRACT) .should() .haveSimpleNameEndingWith("ITCase")); @ArchTest public static final ArchRule ITCASE_USE_MINICLUSTER = freeze( javaClassesThat() .haveSimpleNameEndingWith("ITCase") .and() .areTopLevelClasses() .and() .doNotHaveModifier(ABSTRACT) .should( fulfill( // JUnit 5 violation check containAnyFieldsInClassHierarchyThat( arePublicStaticFinalOfType( MiniClusterExtension.class)) .and( containAnyFieldsInClassHierarchyThat( arePublicStaticFinalOfTypeWithAnnotation( AllCallbackWrapper .class, RegisterExtension .class))) // JUnit 4 violation check, which should be // removed // after the JUnit 4->5 migration is closed. .or( containAnyFieldsInClassHierarchyThat( arePublicStaticFinalOfTypeWithAnnotation( MiniClusterWithClientResource .class, ClassRule.class))) .or( containAnyFieldsInClassHierarchyThat( arePublicFinalOfTypeWithAnnotation( MiniClusterWithClientResource .class, Rule.class)))))); }
[hotfix][docs] Describe how to resolve the ITCASE_USE_MINICLUSTER rule closes #18695
flink-architecture-tests/flink-architecture-tests-test/src/main/java/org/apache/flink/architecture/rules/ITCaseRules.java
[hotfix][docs] Describe how to resolve the ITCASE_USE_MINICLUSTER rule
Java
apache-2.0
0be74594fee335b0fb6e6f5088e48758978b9b59
0
gouravshenoy/airavata,machristie/airavata,jjj117/airavata,hasinitg/airavata,glahiru/airavata,gouravshenoy/airavata,jjj117/airavata,machristie/airavata,apache/airavata,dogless/airavata,anujbhan/airavata,gouravshenoy/airavata,glahiru/airavata,dogless/airavata,apache/airavata,apache/airavata,anujbhan/airavata,glahiru/airavata,anujbhan/airavata,anujbhan/airavata,gouravshenoy/airavata,machristie/airavata,apache/airavata,jjj117/airavata,dogless/airavata,machristie/airavata,glahiru/airavata,dogless/airavata,hasinitg/airavata,gouravshenoy/airavata,anujbhan/airavata,hasinitg/airavata,apache/airavata,machristie/airavata,hasinitg/airavata,jjj117/airavata,gouravshenoy/airavata,machristie/airavata,gouravshenoy/airavata,apache/airavata,jjj117/airavata,anujbhan/airavata,dogless/airavata,hasinitg/airavata,apache/airavata,apache/airavata,jjj117/airavata,glahiru/airavata,hasinitg/airavata,machristie/airavata,anujbhan/airavata,dogless/airavata
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.wsmg.samples.wse; import java.util.Properties; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import org.apache.airavata.wsmg.client.WseMsgBrokerClient; import org.apache.axiom.soap.SOAPEnvelope; import org.apache.axis2.AxisFault; import org.apache.airavata.wsmg.client.ConsumerNotificationHandler; import org.apache.airavata.wsmg.client.MsgBrokerClientException; import org.apache.airavata.wsmg.samples.util.ConfigKeys; public class Consumer extends Thread { class NotificationMsgReciever implements ConsumerNotificationHandler { private BlockingQueue<SOAPEnvelope> queue = new LinkedBlockingQueue<SOAPEnvelope>(); public void handleNotification(SOAPEnvelope msgEnvelope) { queue.add(msgEnvelope); } public BlockingQueue<SOAPEnvelope> getQueue() { return queue; } } private Properties configurations; private int consumerPort; public Consumer(String consumerName, int port, Properties config) { super(consumerName); consumerPort = port; configurations = config; } public void run() { String brokerLocation = configurations .getProperty(ConfigKeys.BROKER_EVENTING_SERVICE_EPR); String xpathExpression = configurations .getProperty(ConfigKeys.TOPIC_XPATH); System.out.println("subscribing with xpath expression: " + xpathExpression); NotificationMsgReciever msgReciever = new NotificationMsgReciever(); String[] consumerEprs = null; String subscriptionId = null; WseMsgBrokerClient client = new WseMsgBrokerClient(); client.init(brokerLocation); try { consumerEprs = client.startConsumerService(consumerPort, msgReciever); } catch (MsgBrokerClientException e) { e.printStackTrace(); System.out.println("unable to start consumer service, exiting"); return; } try { subscriptionId = client.subscribe(consumerEprs[0], null, xpathExpression); System.out.println(getName() + "got the subscription id :" + subscriptionId); } catch (MsgBrokerClientException e) { e.printStackTrace(); System.out .println("unable to subscribe for the xpath consumer exiting"); return; } try { do { SOAPEnvelope env = msgReciever.getQueue().take(); String msg; try { msg = env.getBody().getFirstElement().toStringWithConsume(); System.out.println(String.format( "consumer [%s] recieved: %s", getName(), msg)); } catch (Exception e) { System.err.print("invalid msg recieved"); } } while (true); } catch (InterruptedException ie) { try { // unsubscribe from the topic. client.unSubscribe(subscriptionId); } catch (MsgBrokerClientException e) { e.printStackTrace(); System.out.println("unable to unsubscribe, ignoring"); } // shutdown the consumer service. client.shutdownConsumerService(); System.out.println("interrupted"); } } }
modules/ws-messenger/samples/messagebroker/wse-multiple-producers-consumers/src/org/apache/airavata/wsmg/samples/wse/Consumer.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.wsmg.samples.wse; import java.util.Properties; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import org.apache.airavata.wsmg.client.WseMsgBrokerClient; import com.sun.tools.doclets.internal.toolkit.MethodWriter; import org.apache.axiom.soap.SOAPEnvelope; import org.apache.axis2.AxisFault; import org.apache.airavata.wsmg.client.ConsumerNotificationHandler; import org.apache.airavata.wsmg.client.MsgBrokerClientException; import org.apache.airavata.wsmg.samples.util.ConfigKeys; public class Consumer extends Thread { class NotificationMsgReciever implements ConsumerNotificationHandler { private BlockingQueue<SOAPEnvelope> queue = new LinkedBlockingQueue<SOAPEnvelope>(); public void handleNotification(SOAPEnvelope msgEnvelope) { queue.add(msgEnvelope); } public BlockingQueue<SOAPEnvelope> getQueue() { return queue; } } private Properties configurations; private int consumerPort; public Consumer(String consumerName, int port, Properties config) { super(consumerName); consumerPort = port; configurations = config; } public void run() { String brokerLocation = configurations .getProperty(ConfigKeys.BROKER_EVENTING_SERVICE_EPR); String xpathExpression = configurations .getProperty(ConfigKeys.TOPIC_XPATH); System.out.println("subscribing with xpath expression: " + xpathExpression); NotificationMsgReciever msgReciever = new NotificationMsgReciever(); String[] consumerEprs = null; String subscriptionId = null; WseMsgBrokerClient client = new WseMsgBrokerClient(); client.init(brokerLocation); try { consumerEprs = client.startConsumerService(consumerPort, msgReciever); } catch (MsgBrokerClientException e) { e.printStackTrace(); System.out.println("unable to start consumer service, exiting"); return; } try { subscriptionId = client.subscribe(consumerEprs[0], null, xpathExpression); System.out.println(getName() + "got the subscription id :" + subscriptionId); } catch (MsgBrokerClientException e) { e.printStackTrace(); System.out .println("unable to subscribe for the xpath consumer exiting"); return; } try { do { SOAPEnvelope env = msgReciever.getQueue().take(); String msg; try { msg = env.getBody().getFirstElement().toStringWithConsume(); System.out.println(String.format( "consumer [%s] recieved: %s", getName(), msg)); } catch (Exception e) { System.err.print("invalid msg recieved"); } } while (true); } catch (InterruptedException ie) { try { // unsubscribe from the topic. client.unSubscribe(subscriptionId); } catch (MsgBrokerClientException e) { e.printStackTrace(); System.out.println("unable to unsubscribe, ignoring"); } // shutdown the consumer service. client.shutdownConsumerService(); System.out.println("interrupted"); } } }
Removed the unused import git-svn-id: 64c7115bac0e45f25b6ef7317621bf38f6d5f89e@1367537 13f79535-47bb-0310-9956-ffa450edef68
modules/ws-messenger/samples/messagebroker/wse-multiple-producers-consumers/src/org/apache/airavata/wsmg/samples/wse/Consumer.java
Removed the unused import
Java
apache-2.0
f7202ab26808abe1e54dc2608176238289257c61
0
IHTSDO/snow-owl,IHTSDO/snow-owl,IHTSDO/snow-owl,IHTSDO/snow-owl
/* * Copyright 2011-2015 B2i Healthcare Pte Ltd, http://b2i.sg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.b2international.snowowl.snomed.mrcm.core.widget.bean; import static com.b2international.commons.StringUtils.isEmpty; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Maps.newHashMap; import static com.google.common.collect.Sets.newHashSet; import java.io.Serializable; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; import com.b2international.snowowl.core.ApplicationContext; import com.b2international.snowowl.core.api.IBranchPath; import com.b2international.snowowl.core.api.IComponent; import com.b2international.snowowl.core.api.NullComponent; import com.b2international.snowowl.eventbus.IEventBus; import com.b2international.snowowl.snomed.core.domain.SnomedConcepts; import com.b2international.snowowl.snomed.core.lang.LanguageSetting; import com.b2international.snowowl.snomed.datastore.SnomedDatastoreActivator; import com.b2international.snowowl.snomed.datastore.index.entry.SnomedConceptDocument; import com.b2international.snowowl.snomed.datastore.request.SnomedRequests; import com.b2international.snowowl.snomed.mrcm.core.widget.model.ConceptWidgetModel; import com.google.common.collect.Iterables; /** * Represents the root element of the backing bean tree, forming the simplified representation of a SNOMED CT concept. * */ public class ConceptWidgetBean extends ModeledWidgetBean implements Serializable { private static final long serialVersionUID = 6737791419471322048L; private IBranchPath branchPath; private DescriptionContainerWidgetBean descriptions; private ContainerWidgetBean properties; private ContainerWidgetBean mappings; private String conceptId; private boolean active; /** * Default constructor for serialization. */ protected ConceptWidgetBean() { super(); } public ConceptWidgetBean(final IBranchPath branchPath, final ConceptWidgetModel model, final String conceptId, final boolean active) { super(model); this.branchPath = branchPath; this.conceptId = conceptId; this.active = active; } public IBranchPath getBranchPath() { return branchPath; } @Override public ConceptWidgetModel getModel() { return (ConceptWidgetModel) super.getModel(); } /** * Returns with the unique ID of the SNOMED&nbsp;CT concept. * * @return the SNOMED&nbsp;CT concept. Can have temporary CDO ID and NEW state. */ public String getConceptId() { return conceptId; } /** * Returns with the status of the SNOMED&nbsp;CT concept. * * @return {@code true} if active, otherwise {@code false}. */ public boolean isActive() { return active; } public ContainerWidgetBean getProperties() { return properties; } public void setProperties(final ContainerWidgetBean properties) { this.properties = properties; } public DescriptionContainerWidgetBean getDescriptions() { return descriptions; } public void setDescriptions(final DescriptionContainerWidgetBean descriptions) { this.descriptions = descriptions; } public ContainerWidgetBean getMappings() { return mappings; } public void setMappings(ContainerWidgetBean mappings) { this.mappings = mappings; } /** * Returns all {@link RelationshipWidgetBean} of this {@link ConceptWidgetBean} instance. * * @param concept * @return */ public Iterable<RelationshipWidgetBean> getRelationships() { // all grouped properties final Collection<RelationshipWidgetBean> relationships = newArrayList(); final Iterable<RelationshipGroupWidgetBean> groups = Iterables.filter(getProperties().getElements(), RelationshipGroupWidgetBean.class); for (RelationshipGroupWidgetBean group : groups) { relationships.addAll(newArrayList(Iterables.filter(group.getElements(), RelationshipWidgetBean.class))); } return relationships; } /** * Returns all {@link DataTypeWidgetBean} of this {@link ConceptWidgetBean} instance. * * @param concept * @return */ public Iterable<DataTypeWidgetBean> getDataTypes() { // all grouped properties final Collection<DataTypeWidgetBean> dataTypes = newArrayList(); final Iterable<RelationshipGroupWidgetBean> groups = Iterables.filter(getProperties().getElements(), RelationshipGroupWidgetBean.class); for (RelationshipGroupWidgetBean group : groups) { dataTypes.addAll(newArrayList(Iterables.filter(group.getElements(), DataTypeWidgetBean.class))); } return dataTypes; } /** * Returns all {@link DescriptionWidgetBean} of this {@link ConceptWidgetBean} instance. * * @return */ public Iterable<DescriptionWidgetBean> getDescriptionBeans() { return Iterables.filter(getDescriptions().getElements(), DescriptionWidgetBean.class); } @Override public ConceptWidgetBean getConcept() { return this; } @Override public String toString() { return String.format("ConceptWidgetBean [descriptions=%s, properties=%s, concept ID=%s, active=%s]", descriptions, properties, conceptId, active); } public void add(final String id) { if (!isEmpty(id)) { synchronized (componentMapMutex) { componentMap.put(id, NullComponent.<String> getNullImplementation()); } } } public void add(final IComponent<String> component) { if (!NullComponent.isNullComponent(component) && !isEmpty(component.getId())) { synchronized (componentMapMutex) { componentMap.put(component.getId(), component); } } } public IComponent<String> getComponent(final String id) { if (isEmpty(id)) { return NullComponent.getNullImplementation(); } synchronized (componentMapMutex) { IComponent<String> component = componentMap.get(id); if (NullComponent.isNullComponent(component)) { final Collection<String> unresolvedComponentIds = newHashSet(); for (final Entry<String, IComponent<String>> entry : componentMap.entrySet()) { if (NullComponent.isNullComponent(entry.getValue())) { unresolvedComponentIds.add(entry.getKey()); } } for (final IComponent<String> concept : getConcepts(unresolvedComponentIds)) { componentMap.put(concept.getId(), concept); } return componentMap.get(id); } else { return component; } } } private Collection<SnomedConceptDocument> getConcepts(Collection<String> unresolvedComponentIds) { return SnomedRequests.prepareSearchConcept() .all() .setComponentIds(unresolvedComponentIds) .setLocales(ApplicationContext.getServiceForClass(LanguageSetting.class).getLanguagePreference()) .build(SnomedDatastoreActivator.REPOSITORY_UUID, branchPath.getPath()) .execute(ApplicationContext.getServiceForClass(IEventBus.class)) .then(SnomedConcepts.TO_DOCS) .getSync(); } private final Map<String, IComponent<String>> componentMap = newHashMap(); private final Object componentMapMutex = UUID.randomUUID(); }
snomed/com.b2international.snowowl.snomed.mrcm.core/src/com/b2international/snowowl/snomed/mrcm/core/widget/bean/ConceptWidgetBean.java
/* * Copyright 2011-2015 B2i Healthcare Pte Ltd, http://b2i.sg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.b2international.snowowl.snomed.mrcm.core.widget.bean; import static com.b2international.commons.StringUtils.isEmpty; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Maps.newHashMap; import static com.google.common.collect.Sets.newHashSet; import java.io.Serializable; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; import com.b2international.snowowl.core.ApplicationContext; import com.b2international.snowowl.core.api.IBranchPath; import com.b2international.snowowl.core.api.IComponent; import com.b2international.snowowl.core.api.NullComponent; import com.b2international.snowowl.eventbus.IEventBus; import com.b2international.snowowl.snomed.core.domain.SnomedConcepts; import com.b2international.snowowl.snomed.core.lang.LanguageSetting; import com.b2international.snowowl.snomed.datastore.SnomedDatastoreActivator; import com.b2international.snowowl.snomed.datastore.index.entry.SnomedConceptDocument; import com.b2international.snowowl.snomed.datastore.request.SnomedRequests; import com.b2international.snowowl.snomed.mrcm.core.widget.model.ConceptWidgetModel; import com.google.common.collect.Iterables; /** * Represents the root element of the backing bean tree, forming the simplified representation of a SNOMED CT concept. * */ public class ConceptWidgetBean extends ModeledWidgetBean implements Serializable { private static final long serialVersionUID = 6737791419471322048L; private IBranchPath branchPath; private DescriptionContainerWidgetBean descriptions; private ContainerWidgetBean properties; private ContainerWidgetBean mappings; private String conceptId; private boolean active; /** * Default constructor for serialization. */ protected ConceptWidgetBean() { super(); } public ConceptWidgetBean(final IBranchPath branchPath, final ConceptWidgetModel model, final String conceptId, final boolean active) { super(model); this.branchPath = branchPath; this.conceptId = conceptId; this.active = active; } @Override public ConceptWidgetModel getModel() { return (ConceptWidgetModel) super.getModel(); } /** * Returns with the unique ID of the SNOMED&nbsp;CT concept. * * @return the SNOMED&nbsp;CT concept. Can have temporary CDO ID and NEW state. */ public String getConceptId() { return conceptId; } /** * Returns with the status of the SNOMED&nbsp;CT concept. * * @return {@code true} if active, otherwise {@code false}. */ public boolean isActive() { return active; } public ContainerWidgetBean getProperties() { return properties; } public void setProperties(final ContainerWidgetBean properties) { this.properties = properties; } public DescriptionContainerWidgetBean getDescriptions() { return descriptions; } public void setDescriptions(final DescriptionContainerWidgetBean descriptions) { this.descriptions = descriptions; } public ContainerWidgetBean getMappings() { return mappings; } public void setMappings(ContainerWidgetBean mappings) { this.mappings = mappings; } /** * Returns all {@link RelationshipWidgetBean} of this {@link ConceptWidgetBean} instance. * * @param concept * @return */ public Iterable<RelationshipWidgetBean> getRelationships() { // all grouped properties final Collection<RelationshipWidgetBean> relationships = newArrayList(); final Iterable<RelationshipGroupWidgetBean> groups = Iterables.filter(getProperties().getElements(), RelationshipGroupWidgetBean.class); for (RelationshipGroupWidgetBean group : groups) { relationships.addAll(newArrayList(Iterables.filter(group.getElements(), RelationshipWidgetBean.class))); } return relationships; } /** * Returns all {@link DataTypeWidgetBean} of this {@link ConceptWidgetBean} instance. * * @param concept * @return */ public Iterable<DataTypeWidgetBean> getDataTypes() { // all grouped properties final Collection<DataTypeWidgetBean> dataTypes = newArrayList(); final Iterable<RelationshipGroupWidgetBean> groups = Iterables.filter(getProperties().getElements(), RelationshipGroupWidgetBean.class); for (RelationshipGroupWidgetBean group : groups) { dataTypes.addAll(newArrayList(Iterables.filter(group.getElements(), DataTypeWidgetBean.class))); } return dataTypes; } /** * Returns all {@link DescriptionWidgetBean} of this {@link ConceptWidgetBean} instance. * * @return */ public Iterable<DescriptionWidgetBean> getDescriptionBeans() { return Iterables.filter(getDescriptions().getElements(), DescriptionWidgetBean.class); } @Override public ConceptWidgetBean getConcept() { return this; } @Override public String toString() { return String.format("ConceptWidgetBean [descriptions=%s, properties=%s, concept ID=%s, active=%s]", descriptions, properties, conceptId, active); } public void add(final String id) { if (!isEmpty(id)) { synchronized (componentMapMutex) { componentMap.put(id, NullComponent.<String> getNullImplementation()); } } } public void add(final IComponent<String> component) { if (!NullComponent.isNullComponent(component) && !isEmpty(component.getId())) { synchronized (componentMapMutex) { componentMap.put(component.getId(), component); } } } public IComponent<String> getComponent(final String id) { if (isEmpty(id)) { return NullComponent.getNullImplementation(); } synchronized (componentMapMutex) { IComponent<String> component = componentMap.get(id); if (NullComponent.isNullComponent(component)) { final Collection<String> unresolvedComponentIds = newHashSet(); for (final Entry<String, IComponent<String>> entry : componentMap.entrySet()) { if (NullComponent.isNullComponent(entry.getValue())) { unresolvedComponentIds.add(entry.getKey()); } } for (final IComponent<String> concept : getConcepts(unresolvedComponentIds)) { componentMap.put(concept.getId(), concept); } return componentMap.get(id); } else { return component; } } } private Collection<SnomedConceptDocument> getConcepts(Collection<String> unresolvedComponentIds) { return SnomedRequests.prepareSearchConcept() .all() .setComponentIds(unresolvedComponentIds) .setLocales(ApplicationContext.getServiceForClass(LanguageSetting.class).getLanguagePreference()) .build(SnomedDatastoreActivator.REPOSITORY_UUID, branchPath.getPath()) .execute(ApplicationContext.getServiceForClass(IEventBus.class)) .then(SnomedConcepts.TO_DOCS) .getSync(); } private final Map<String, IComponent<String>> componentMap = newHashMap(); private final Object componentMapMutex = UUID.randomUUID(); }
[mrcm] add branchPath getter to ConceptWidgetBean
snomed/com.b2international.snowowl.snomed.mrcm.core/src/com/b2international/snowowl/snomed/mrcm/core/widget/bean/ConceptWidgetBean.java
[mrcm] add branchPath getter to ConceptWidgetBean
Java
apache-2.0
fec19cdce900d79c4dbfe65dfb1dc3ec40ca640f
0
wso2/carbon-analytics,wso2/carbon-analytics-common,Niveathika92/carbon-analytics,Nethmi-Pathirana/carbon-analytics,tishan89/carbon-analytics,grainier/carbon-analytics-common,erangatl/carbon-analytics,Niveathika92/carbon-analytics,tishan89/carbon-analytics,Anoukh/carbon-analytics,erangatl/carbon-analytics,mohanvive/carbon-analytics,chanikag/carbon-coordinator,wso2/carbon-analytics-common,mohanvive/carbon-analytics,erangatl/carbon-analytics,sajithshn/carbon-analytics-common,ksdperera/carbon-analytics-common,Niveathika92/carbon-analytics,Niveathika92/carbon-analytics,minudika/carbon-analytics,minudika/carbon-analytics,grainier/carbon-analytics,lasanthaS/carbon-analytics-common,tishan89/carbon-analytics,mohanvive/carbon-analytics,grainier/carbon-analytics,Anoukh/carbon-analytics,Anoukh/carbon-analytics,Nethmi-Pathirana/carbon-analytics,wso2/carbon-analytics,wso2/carbon-analytics,tishan89/carbon-analytics,wso2/carbon-analytics,wso2/carbon-analytics,samgregoost/carbon-analytics,grainier/carbon-analytics,Anoukh/carbon-analytics,Nethmi-Pathirana/carbon-analytics,dilini-muthumala/carbon-analytics-common,erangatl/carbon-analytics,ramindu90/carbon-analytics-common,tishan89/carbon-analytics,Nethmi-Pathirana/carbon-analytics,Nethmi-Pathirana/carbon-analytics,grainier/carbon-analytics,mohanvive/carbon-analytics,Niveathika92/carbon-analytics,grainier/carbon-analytics,lasanthaS/carbon-analytics-common,ramindu90/carbon-analytics-common,mohanvive/carbon-analytics,Anoukh/carbon-analytics,ksdperera/carbon-analytics-common,minudika/carbon-analytics,minudika/carbon-analytics,minudika/carbon-analytics,dilini-muthumala/carbon-analytics-common,erangatl/carbon-analytics
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.analytics.data.commons.utils; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; import org.apache.commons.collections.IteratorUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.analytics.data.commons.AnalyticsDataService; import org.wso2.carbon.analytics.data.commons.AnalyticsRecordStore; import org.wso2.carbon.analytics.data.commons.exception.AnalyticsException; import org.wso2.carbon.analytics.data.commons.service.AnalyticsCommonServiceHolder; import org.wso2.carbon.analytics.data.commons.service.AnalyticsDataResponse; import org.wso2.carbon.analytics.data.commons.service.AnalyticsSchema; import org.wso2.carbon.analytics.data.commons.sources.AnalyticsCommonConstants; import org.wso2.carbon.analytics.data.commons.sources.Record; import org.wso2.carbon.analytics.data.commons.sources.RecordGroup; import java.io.*; import java.net.URISyntaxException; import java.net.URL; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import java.security.SecureRandom; import java.util.*; public class AnalyticsCommonUtils { private static final byte BOOLEAN_TRUE = 1; private static final byte BOOLEAN_FALSE = 0; private static final byte DATA_TYPE_NULL = 0x00; private static final byte DATA_TYPE_STRING = 0x01; private static final byte DATA_TYPE_INTEGER = 0x02; private static final byte DATA_TYPE_LONG = 0x03; private static final byte DATA_TYPE_FLOAT = 0x04; private static final byte DATA_TYPE_DOUBLE = 0x05; private static final byte DATA_TYPE_BOOLEAN = 0x06; private static final byte DATA_TYPE_BINARY = 0x07; private static final byte DATA_TYPE_OBJECT = 0x10; private static final String ANALYTICS_USER_TABLE_PREFIX = "ANX"; private static final String CUSTOM_WSO2_CONF_DIR_NAME = "conf"; private static final String ANALYTICS_CONF_DIR_NAME = "analytics"; public static final String WSO2_ANALYTICS_CONF_DIRECTORY_SYS_PROP = "wso2_custom_conf_dir"; public static final String WSO2_CARBON_CONF_DIR_SYS_PROP = "carbon.config.dir.path"; private static final Log LOG = LogFactory.getLog(AnalyticsCommonUtils.class); private static ThreadLocal<Kryo> kryoTL = new ThreadLocal<Kryo>() { protected Kryo initialValue() { return new Kryo(); } }; public static String generateRecordID() { byte[] data = new byte[16]; secureRandom.get().nextBytes(data); ByteBuffer buff = ByteBuffer.wrap(data); return new UUID(buff.getLong(), buff.getLong()).toString(); } private static ThreadLocal<SecureRandom> secureRandom = new ThreadLocal<SecureRandom>() { protected SecureRandom initialValue() { return new SecureRandom(); } }; /* do not touch, @see serializeObject(Object) */ public static void serializeObject(Object obj, OutputStream out) throws IOException { byte[] data = serializeObject(obj); out.write(data, 0, data.length); } /* do not touch, @see serializeObject(Object) */ public static Object deserializeObject(byte[] source) { if (source == null) { return null; } /* skip the object size integer */ try (Input input = new Input(Arrays.copyOfRange(source, Integer.SIZE / 8, source.length))) { Kryo kryo = kryoTL.get(); return kryo.readClassAndObject(input); } } /* do not touch if you do not know what you're doing, critical for serialize/deserialize * implementation to be stable to retain backward compatibility */ public static byte[] serializeObject(Object obj) { Kryo kryo = kryoTL.get(); ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); try (Output out = new Output(byteOut)) { kryo.writeClassAndObject(out, obj); out.flush(); byte[] data = byteOut.toByteArray(); ByteBuffer result = ByteBuffer.allocate(data.length + Integer.SIZE / 8); result.putInt(data.length); result.put(data); return result.array(); } } public static Collection<List<Record>> generateRecordBatches(List<Record> records) { return generateRecordBatches(records, false); } public static Collection<List<Record>> generateRecordBatches(List<Record> records, boolean normalizeTableName) { /* if the records have identities (unique table category and name) as the following * "ABABABCCAACBDABCABCDBAC", the job of this method is to make it like the following, * {"AAAAAAAA", "BBBBBBB", "CCCCCC", "DD" } */ Map<String, List<Record>> recordBatches = new HashMap<>(); List<Record> recordBatch; for (Record record : records) { if (normalizeTableName) { record.setTableName(normalizeTableName(record.getTableName())); } recordBatch = recordBatches.get(calculateRecordIdentity(record)); if (recordBatch == null) { recordBatch = new ArrayList<>(); recordBatches.put(calculateRecordIdentity(record), recordBatch); } recordBatch.add(record); } return recordBatches.values(); } public static String calculateRecordIdentity(Record record) { return normalizeTableName(record.getTableName()); } public static String normalizeTableName(String tableName) { return tableName.toUpperCase(); } /** * This method is used to generate an UUID from the target table name to make sure that it is a compact * name that can be fitted in all the supported RDBMSs. For example, Oracle has a table name * length of 30. So we must translate source table names to hashed strings, which here will have * a very low probability of clashing. */ public static String generateTableUUID(String tableName) { try { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(byteOut); /* we've to limit it to 64 bits */ dout.writeInt(tableName.hashCode()); dout.close(); byteOut.close(); String result = Base64.getEncoder().encodeToString(byteOut.toByteArray()); result = result.replace('=', '_'); result = result.replace('+', '_'); result = result.replace('/', '_'); /* a table name must start with a letter */ return ANALYTICS_USER_TABLE_PREFIX + result; } catch (IOException e) { /* this will never happen */ throw new RuntimeException(e); } } public static byte[] encodeRecordValues(Map<String, Object> values) throws AnalyticsException { ByteArrayDataOutput byteOut = ByteStreams.newDataOutput(); String name; Object value; for (Map.Entry<String, Object> entry : values.entrySet()) { name = entry.getKey(); value = entry.getValue(); byteOut.write(encodeElement(name, value)); } return byteOut.toByteArray(); } public static byte[] encodeElement(String name, Object value) throws AnalyticsException { ByteArrayDataOutput buffer = ByteStreams.newDataOutput(); byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8); buffer.writeInt(nameBytes.length); buffer.write(nameBytes); if (value instanceof String) { buffer.write(DATA_TYPE_STRING); String strVal = (String) value; byte[] strBytes = strVal.getBytes(StandardCharsets.UTF_8); buffer.writeInt(strBytes.length); buffer.write(strBytes); } else if (value instanceof Long) { buffer.write(DATA_TYPE_LONG); buffer.writeLong((Long) value); } else if (value instanceof Double) { buffer.write(DATA_TYPE_DOUBLE); buffer.writeDouble((Double) value); } else if (value instanceof Boolean) { buffer.write(DATA_TYPE_BOOLEAN); boolean boolVal = (Boolean) value; if (boolVal) { buffer.write(BOOLEAN_TRUE); } else { buffer.write(BOOLEAN_FALSE); } } else if (value instanceof Integer) { buffer.write(DATA_TYPE_INTEGER); buffer.writeInt((Integer) value); } else if (value instanceof Float) { buffer.write(DATA_TYPE_FLOAT); buffer.writeFloat((Float) value); } else if (value instanceof byte[]) { buffer.write(DATA_TYPE_BINARY); byte[] binData = (byte[]) value; buffer.writeInt(binData.length); buffer.write(binData); } else if (value == null) { buffer.write(DATA_TYPE_NULL); } else { buffer.write(DATA_TYPE_OBJECT); byte[] binData = serializeObject(value); buffer.writeInt(binData.length); buffer.write(binData); } return buffer.toByteArray(); } public static Map<String, Object> decodeRecordValues(byte[] data, Set<String> columns) throws AnalyticsException { /* using LinkedHashMap to retain the column order */ Map<String, Object> result = new LinkedHashMap<>(); int type, size; String colName; Object value; byte[] buff; byte boolVal; byte[] binData; try { ByteBuffer buffer = ByteBuffer.wrap(data); while (buffer.remaining() > 0) { size = buffer.getInt(); if (size == 0) { break; } buff = new byte[size]; buffer.get(buff, 0, size); colName = new String(buff, StandardCharsets.UTF_8); type = buffer.get(); switch (type) { case DATA_TYPE_STRING: size = buffer.getInt(); buff = new byte[size]; buffer.get(buff, 0, size); value = new String(buff, StandardCharsets.UTF_8); break; case DATA_TYPE_LONG: value = buffer.getLong(); break; case DATA_TYPE_DOUBLE: value = buffer.getDouble(); break; case DATA_TYPE_BOOLEAN: boolVal = buffer.get(); if (boolVal == BOOLEAN_TRUE) { value = true; } else if (boolVal == BOOLEAN_FALSE) { value = false; } else { throw new AnalyticsException("Invalid encoded boolean value: " + boolVal); } break; case DATA_TYPE_INTEGER: value = buffer.getInt(); break; case DATA_TYPE_FLOAT: value = buffer.getFloat(); break; case DATA_TYPE_BINARY: size = buffer.getInt(); binData = new byte[size]; buffer.get(binData); value = binData; break; case DATA_TYPE_OBJECT: size = buffer.getInt(); binData = new byte[size]; buffer.get(binData); value = deserializeObject(binData); break; case DATA_TYPE_NULL: value = null; break; default: throw new AnalyticsException("Unknown encoded data source type : " + type); } if (columns == null || columns.contains(colName)) { result.put(colName, value); } } } catch (Exception e) { throw new AnalyticsException("Error in decoding record values: " + e.getMessage(), e); } return result; } public static List<Integer[]> splitNumberRange(int count, int nsplit) { List<Integer[]> result = new ArrayList<>(nsplit); int range = Math.max(1, count / nsplit); int current = 0; for (int i = 0; i < nsplit; i++) { if (current >= count) { break; } if (i + 1 >= nsplit) { result.add(new Integer[]{current, count - current}); } else { result.add(new Integer[]{current, current + range > count ? count - current : range}); current += range; } } return result; } public static void closeQuietly(Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (IOException ignore) { /* ignore */ } } public static List<Record> listRecords(AnalyticsRecordStore rs, RecordGroup[] rgs) throws AnalyticsException { List<Record> result = new ArrayList<>(); for (RecordGroup rg : rgs) { result.addAll(IteratorUtils.toList(rs.readRecords(rg))); } return result; } public static List<Record> listRecords(AnalyticsDataService ads, AnalyticsDataResponse response) throws AnalyticsException { List<Record> result = new ArrayList<>(); for (AnalyticsDataResponse.Entry entry : response.getEntries()) { result.addAll(IteratorUtils.toList(ads.readRecords(entry.getRecordStoreName(), entry.getRecordGroup()))); } return result; } public static String getAnalyticsConfDirectory() throws AnalyticsException { File confDir = null; try { confDir = new File(getConfDirectoryPath()); } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.debug("Error in getting the config path: " + e.getMessage(), e); } } if (confDir == null || !confDir.exists()) { return getCustomAnalyticsConfDirectory(); } else { return confDir.getAbsolutePath(); } } public static String getAbsoluteDataSourceConfigDir() throws AnalyticsException { /*Path carbonConfigPath = Paths.get("", getConfDirectoryPath()); Path dataSourcePath = DataSourceUtils.getDataSourceConfigPath(); String dataSourceDir = carbonConfigPath.relativize(dataSourcePath).toString(); return Paths.get(getConfDirectoryPath(), dataSourceDir).toAbsolutePath().toString();*/ //TODO: Recheck path logic after Kernel bug is fixed (https://github.com/wso2/carbon-kernel/issues/1309) return getConfDirectoryPath() + File.separator + "datasources"; } private static String getCustomAnalyticsConfDirectory() throws AnalyticsException { String path = System.getProperty(WSO2_ANALYTICS_CONF_DIRECTORY_SYS_PROP); if (path == null) { path = Paths.get("").toAbsolutePath().toString() + File.separator + CUSTOM_WSO2_CONF_DIR_NAME; } File confDir = new File(path); if (!confDir.exists()) { throw new AnalyticsException("The custom WSO2 configuration directory does not exist at '" + path + "'. " + "This can be given by correctly pointing to a valid configuration directory by setting the " + "Java system property '" + WSO2_ANALYTICS_CONF_DIRECTORY_SYS_PROP + "'."); } return confDir.getAbsolutePath(); } public static String getConfDirectoryPath() throws AnalyticsException { //TODO: Recheck path logic after Kernel bug is fixed (https://github.com/wso2/carbon-kernel/issues/1309) /*Path carbonDir = Utils.getCarbonConfigHome(); if (carbonDir != null) { return carbonDir.toString(); } else {*/ String carbonConfigDirPath = System.getProperty(WSO2_CARBON_CONF_DIR_SYS_PROP); if (carbonConfigDirPath == null) { carbonConfigDirPath = System.getenv("CARBON_CONFIG_DIR_PATH"); if (carbonConfigDirPath == null) { throw new AnalyticsException("The WSO2 configuration directory does not exist. " + "This can be given by setting the Java system property '" + WSO2_CARBON_CONF_DIR_SYS_PROP + "', to a valid carbon configuration directory.."); } } return carbonConfigDirPath; /*}*/ } public static Object loadDatasource(String dsName) { try { return AnalyticsCommonServiceHolder.getDataSourceService().getDataSource(dsName); } catch (Exception e) { e.printStackTrace(); return new Object(); } } public static String convertStreamNameToTableName(String stream) { return stream.replaceAll("\\.", "_"); } public static File getFileFromSystemResources(String fileName) throws URISyntaxException { File file = null; ClassLoader classLoader = ClassLoader.getSystemClassLoader(); if (classLoader != null) { URL url = classLoader.getResource(fileName); if (url == null) { url = classLoader.getResource(File.separator + fileName); } file = new File(url.toURI()); } return file; } /** * This method preprocesses the records before adding to the record store, * e.g. update the record ids if its not already set by using the table * schema's primary keys. * * @param recordBatches batch of records */ public static void preProcessRecords(Collection<List<Record>> recordBatches, AnalyticsDataService analyticsDataService) throws AnalyticsException { for (List<Record> recordBatch : recordBatches) { preProcessRecordBatch(recordBatch, analyticsDataService); } } private static void preProcessRecordBatch(List<Record> recordBatch, AnalyticsDataService service) throws AnalyticsException { Record firstRecord = recordBatch.get(0); AnalyticsSchema schema = service.getTableSchema(firstRecord.getTableName()); List<String> primaryKeys = schema.getPrimaryKeys(); if (primaryKeys != null && primaryKeys.size() > 0) { populateRecordsWithPrimaryKeyAwareIds(recordBatch, primaryKeys); } else { populateWithGenerateIds(recordBatch); } } private static void populateWithGenerateIds(List<Record> records) { records.stream().filter(record -> record.getId() == null).forEach( record -> record.setId(AnalyticsCommonUtils.generateRecordID())); } private static void populateRecordWithPrimaryKeyAwareId(Record record, List<String> primaryKeys) { record.setId(generateRecordIdFromPrimaryKeyValues(record.getValues(), primaryKeys)); } public static String generateRecordIdFromPrimaryKeyValues(Map<String, Object> values, List<String> primaryKeys) { StringBuilder builder = new StringBuilder(); Object obj; for (String key : primaryKeys) { obj = values.get(key); if (obj != null) { builder.append(obj.toString()); } } // to make sure, we don't have an empty string builder.append(""); try { byte[] data = builder.toString().getBytes(AnalyticsCommonConstants.DEFAULT_CHARSET); return UUID.nameUUIDFromBytes(data).toString(); } catch (UnsupportedEncodingException e) { // This wouldn't happen throw new RuntimeException(e); } } private static void populateRecordsWithPrimaryKeyAwareIds(List<Record> records, List<String> primaryKeys) { /* users have the ability to explicitly provide a record id, * in-spite of having primary keys defined to auto generate the id */ records.stream().filter(record -> record.getId() == null).forEach(record -> populateRecordWithPrimaryKeyAwareId(record, primaryKeys)); } }
components/analytics-data-commons/org.wso2.carbon.analytics.data.commons/src/main/java/org/wso2/carbon/analytics/data/commons/utils/AnalyticsCommonUtils.java
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.analytics.data.commons.utils; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; import org.apache.commons.collections.IteratorUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.analytics.data.commons.AnalyticsDataService; import org.wso2.carbon.analytics.data.commons.AnalyticsRecordStore; import org.wso2.carbon.analytics.data.commons.exception.AnalyticsException; import org.wso2.carbon.analytics.data.commons.service.AnalyticsSchema; import org.wso2.carbon.analytics.data.commons.sources.AnalyticsCommonConstants; import org.wso2.carbon.analytics.data.commons.service.AnalyticsDataResponse; import org.wso2.carbon.analytics.data.commons.sources.Record; import org.wso2.carbon.analytics.data.commons.sources.RecordGroup; import java.io.*; import java.net.URISyntaxException; import java.net.URL; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import java.security.SecureRandom; import java.util.*; public class AnalyticsCommonUtils { private static final byte BOOLEAN_TRUE = 1; private static final byte BOOLEAN_FALSE = 0; private static final byte DATA_TYPE_NULL = 0x00; private static final byte DATA_TYPE_STRING = 0x01; private static final byte DATA_TYPE_INTEGER = 0x02; private static final byte DATA_TYPE_LONG = 0x03; private static final byte DATA_TYPE_FLOAT = 0x04; private static final byte DATA_TYPE_DOUBLE = 0x05; private static final byte DATA_TYPE_BOOLEAN = 0x06; private static final byte DATA_TYPE_BINARY = 0x07; private static final byte DATA_TYPE_OBJECT = 0x10; private static final String ANALYTICS_USER_TABLE_PREFIX = "ANX"; private static final String CUSTOM_WSO2_CONF_DIR_NAME = "conf"; public static final String WSO2_ANALYTICS_CONF_DIRECTORY_SYS_PROP = "wso2_custom_conf_dir"; private static final Log LOG = LogFactory.getLog(AnalyticsCommonUtils.class); private static ThreadLocal<Kryo> kryoTL = new ThreadLocal<Kryo>() { protected Kryo initialValue() { return new Kryo(); } }; public static String generateRecordID() { byte[] data = new byte[16]; secureRandom.get().nextBytes(data); ByteBuffer buff = ByteBuffer.wrap(data); return new UUID(buff.getLong(), buff.getLong()).toString(); } private static ThreadLocal<SecureRandom> secureRandom = new ThreadLocal<SecureRandom>() { protected SecureRandom initialValue() { return new SecureRandom(); } }; /* do not touch, @see serializeObject(Object) */ public static void serializeObject(Object obj, OutputStream out) throws IOException { byte[] data = serializeObject(obj); out.write(data, 0, data.length); } /* do not touch, @see serializeObject(Object) */ public static Object deserializeObject(byte[] source) { if (source == null) { return null; } /* skip the object size integer */ try (Input input = new Input(Arrays.copyOfRange(source, Integer.SIZE / 8, source.length))) { Kryo kryo = kryoTL.get(); return kryo.readClassAndObject(input); } } /* do not touch if you do not know what you're doing, critical for serialize/deserialize * implementation to be stable to retain backward compatibility */ public static byte[] serializeObject(Object obj) { Kryo kryo = kryoTL.get(); ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); try (Output out = new Output(byteOut)) { kryo.writeClassAndObject(out, obj); out.flush(); byte[] data = byteOut.toByteArray(); ByteBuffer result = ByteBuffer.allocate(data.length + Integer.SIZE / 8); result.putInt(data.length); result.put(data); return result.array(); } } public static Collection<List<Record>> generateRecordBatches(List<Record> records) { return generateRecordBatches(records, false); } public static Collection<List<Record>> generateRecordBatches(List<Record> records, boolean normalizeTableName) { /* if the records have identities (unique table category and name) as the following * "ABABABCCAACBDABCABCDBAC", the job of this method is to make it like the following, * {"AAAAAAAA", "BBBBBBB", "CCCCCC", "DD" } */ Map<String, List<Record>> recordBatches = new HashMap<>(); List<Record> recordBatch; for (Record record : records) { if (normalizeTableName) { record.setTableName(normalizeTableName(record.getTableName())); } recordBatch = recordBatches.get(calculateRecordIdentity(record)); if (recordBatch == null) { recordBatch = new ArrayList<>(); recordBatches.put(calculateRecordIdentity(record), recordBatch); } recordBatch.add(record); } return recordBatches.values(); } public static String calculateRecordIdentity(Record record) { return normalizeTableName(record.getTableName()); } public static String normalizeTableName(String tableName) { return tableName.toUpperCase(); } /** * This method is used to generate an UUID from the target table name to make sure that it is a compact * name that can be fitted in all the supported RDBMSs. For example, Oracle has a table name * length of 30. So we must translate source table names to hashed strings, which here will have * a very low probability of clashing. */ public static String generateTableUUID(String tableName) { try { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(byteOut); /* we've to limit it to 64 bits */ dout.writeInt(tableName.hashCode()); dout.close(); byteOut.close(); String result = Base64.getEncoder().encodeToString(byteOut.toByteArray()); result = result.replace('=', '_'); result = result.replace('+', '_'); result = result.replace('/', '_'); /* a table name must start with a letter */ return ANALYTICS_USER_TABLE_PREFIX + result; } catch (IOException e) { /* this will never happen */ throw new RuntimeException(e); } } public static byte[] encodeRecordValues(Map<String, Object> values) throws AnalyticsException { ByteArrayDataOutput byteOut = ByteStreams.newDataOutput(); String name; Object value; for (Map.Entry<String, Object> entry : values.entrySet()) { name = entry.getKey(); value = entry.getValue(); byteOut.write(encodeElement(name, value)); } return byteOut.toByteArray(); } public static byte[] encodeElement(String name, Object value) throws AnalyticsException { ByteArrayDataOutput buffer = ByteStreams.newDataOutput(); byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8); buffer.writeInt(nameBytes.length); buffer.write(nameBytes); if (value instanceof String) { buffer.write(DATA_TYPE_STRING); String strVal = (String) value; byte[] strBytes = strVal.getBytes(StandardCharsets.UTF_8); buffer.writeInt(strBytes.length); buffer.write(strBytes); } else if (value instanceof Long) { buffer.write(DATA_TYPE_LONG); buffer.writeLong((Long) value); } else if (value instanceof Double) { buffer.write(DATA_TYPE_DOUBLE); buffer.writeDouble((Double) value); } else if (value instanceof Boolean) { buffer.write(DATA_TYPE_BOOLEAN); boolean boolVal = (Boolean) value; if (boolVal) { buffer.write(BOOLEAN_TRUE); } else { buffer.write(BOOLEAN_FALSE); } } else if (value instanceof Integer) { buffer.write(DATA_TYPE_INTEGER); buffer.writeInt((Integer) value); } else if (value instanceof Float) { buffer.write(DATA_TYPE_FLOAT); buffer.writeFloat((Float) value); } else if (value instanceof byte[]) { buffer.write(DATA_TYPE_BINARY); byte[] binData = (byte[]) value; buffer.writeInt(binData.length); buffer.write(binData); } else if (value == null) { buffer.write(DATA_TYPE_NULL); } else { buffer.write(DATA_TYPE_OBJECT); byte[] binData = serializeObject(value); buffer.writeInt(binData.length); buffer.write(binData); } return buffer.toByteArray(); } public static Map<String, Object> decodeRecordValues(byte[] data, Set<String> columns) throws AnalyticsException { /* using LinkedHashMap to retain the column order */ Map<String, Object> result = new LinkedHashMap<>(); int type, size; String colName; Object value; byte[] buff; byte boolVal; byte[] binData; try { ByteBuffer buffer = ByteBuffer.wrap(data); while (buffer.remaining() > 0) { size = buffer.getInt(); if (size == 0) { break; } buff = new byte[size]; buffer.get(buff, 0, size); colName = new String(buff, StandardCharsets.UTF_8); type = buffer.get(); switch (type) { case DATA_TYPE_STRING: size = buffer.getInt(); buff = new byte[size]; buffer.get(buff, 0, size); value = new String(buff, StandardCharsets.UTF_8); break; case DATA_TYPE_LONG: value = buffer.getLong(); break; case DATA_TYPE_DOUBLE: value = buffer.getDouble(); break; case DATA_TYPE_BOOLEAN: boolVal = buffer.get(); if (boolVal == BOOLEAN_TRUE) { value = true; } else if (boolVal == BOOLEAN_FALSE) { value = false; } else { throw new AnalyticsException("Invalid encoded boolean value: " + boolVal); } break; case DATA_TYPE_INTEGER: value = buffer.getInt(); break; case DATA_TYPE_FLOAT: value = buffer.getFloat(); break; case DATA_TYPE_BINARY: size = buffer.getInt(); binData = new byte[size]; buffer.get(binData); value = binData; break; case DATA_TYPE_OBJECT: size = buffer.getInt(); binData = new byte[size]; buffer.get(binData); value = deserializeObject(binData); break; case DATA_TYPE_NULL: value = null; break; default: throw new AnalyticsException("Unknown encoded data source type : " + type); } if (columns == null || columns.contains(colName)) { result.put(colName, value); } } } catch (Exception e) { throw new AnalyticsException("Error in decoding record values: " + e.getMessage(), e); } return result; } public static List<Integer[]> splitNumberRange(int count, int nsplit) { List<Integer[]> result = new ArrayList<>(nsplit); int range = Math.max(1, count / nsplit); int current = 0; for (int i = 0; i < nsplit; i++) { if (current >= count) { break; } if (i + 1 >= nsplit) { result.add(new Integer[]{current, count - current}); } else { result.add(new Integer[]{current, current + range > count ? count - current : range}); current += range; } } return result; } public static void closeQuietly(Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (IOException ignore) { /* ignore */ } } public static List<Record> listRecords(AnalyticsRecordStore rs, RecordGroup[] rgs) throws AnalyticsException { List<Record> result = new ArrayList<>(); for (RecordGroup rg : rgs) { result.addAll(IteratorUtils.toList(rs.readRecords(rg))); } return result; } public static List<Record> listRecords(AnalyticsDataService ads, AnalyticsDataResponse response) throws AnalyticsException { List<Record> result = new ArrayList<>(); for (AnalyticsDataResponse.Entry entry : response.getEntries()) { result.addAll(IteratorUtils.toList(ads.readRecords(entry.getRecordStoreName(), entry.getRecordGroup()))); } return result; } public static String getAnalyticsConfDirectory() throws AnalyticsException { File confDir = null; try { confDir = new File(getConfDirectoryPath()); } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.debug("Error in getting the config path: " + e.getMessage(), e); } } if (confDir == null || !confDir.exists()) { return getCustomAnalyticsConfDirectory(); } else { return confDir.getAbsolutePath(); } } private static String getCustomAnalyticsConfDirectory() throws AnalyticsException { String path = System.getProperty(WSO2_ANALYTICS_CONF_DIRECTORY_SYS_PROP); if (path == null) { path = Paths.get("").toAbsolutePath().toString() + File.separator + CUSTOM_WSO2_CONF_DIR_NAME; } File confDir = new File(path); if (!confDir.exists()) { throw new AnalyticsException("The custom WSO2 configuration directory does not exist at '" + path + "'. " + "This can be given by correctly pointing to a valid configuration directory by setting the " + "Java system property '" + WSO2_ANALYTICS_CONF_DIRECTORY_SYS_PROP + "'."); } return confDir.getAbsolutePath(); } public static String getConfDirectoryPath() { String carbonConfigDirPath = System.getProperty("carbon.config.dir.path"); if (carbonConfigDirPath == null) { carbonConfigDirPath = System.getenv("CARBON_CONFIG_DIR_PATH"); if (carbonConfigDirPath == null) { return getBaseDirectoryPath() + File.separator + "conf"; } } return carbonConfigDirPath; } public static String getBaseDirectoryPath() { String baseDir = System.getProperty("analytics.home"); if (baseDir == null) { baseDir = System.getenv("ANALYTICS_HOME"); System.setProperty("analytics.home", baseDir); } return baseDir; } public static String convertStreamNameToTableName(String stream) { return stream.replaceAll("\\.", "_"); } public static File getFileFromSystemResources(String fileName) throws URISyntaxException { File file = null; ClassLoader classLoader = ClassLoader.getSystemClassLoader(); if (classLoader != null) { URL url = classLoader.getResource(fileName); if (url == null) { url = classLoader.getResource(File.separator + fileName); } file = new File(url.toURI()); } return file; } /** * This method preprocesses the records before adding to the record store, * e.g. update the record ids if its not already set by using the table * schema's primary keys. * * @param recordBatches batch of records */ public static void preProcessRecords(Collection<List<Record>> recordBatches, AnalyticsDataService analyticsDataService) throws AnalyticsException { for (List<Record> recordBatch : recordBatches) { preProcessRecordBatch(recordBatch, analyticsDataService); } } private static void preProcessRecordBatch(List<Record> recordBatch, AnalyticsDataService service) throws AnalyticsException { Record firstRecord = recordBatch.get(0); AnalyticsSchema schema = service.getTableSchema(firstRecord.getTableName()); List<String> primaryKeys = schema.getPrimaryKeys(); if (primaryKeys != null && primaryKeys.size() > 0) { populateRecordsWithPrimaryKeyAwareIds(recordBatch, primaryKeys); } else { populateWithGenerateIds(recordBatch); } } private static void populateWithGenerateIds(List<Record> records) { records.stream().filter(record -> record.getId() == null).forEach( record -> record.setId(AnalyticsCommonUtils.generateRecordID())); } private static void populateRecordWithPrimaryKeyAwareId(Record record, List<String> primaryKeys) { record.setId(generateRecordIdFromPrimaryKeyValues(record.getValues(), primaryKeys)); } private static String generateRecordIdFromPrimaryKeyValues(Map<String, Object> values, List<String> primaryKeys) { StringBuilder builder = new StringBuilder(); Object obj; for (String key : primaryKeys) { obj = values.get(key); if (obj != null) { builder.append(obj.toString()); } } // to make sure, we don't have an empty string builder.append(""); try { byte[] data = builder.toString().getBytes(AnalyticsCommonConstants.DEFAULT_CHARSET); return UUID.nameUUIDFromBytes(data).toString(); } catch (UnsupportedEncodingException e) { // This wouldn't happen throw new RuntimeException(e); } } private static void populateRecordsWithPrimaryKeyAwareIds(List<Record> records, List<String> primaryKeys) { /* users have the ability to explicitly provide a record id, * in-spite of having primary keys defined to auto generate the id */ records.stream().filter(record -> record.getId() == null).forEach(record -> populateRecordWithPrimaryKeyAwareId(record, primaryKeys)); } }
Homogenize path logic for DAL
components/analytics-data-commons/org.wso2.carbon.analytics.data.commons/src/main/java/org/wso2/carbon/analytics/data/commons/utils/AnalyticsCommonUtils.java
Homogenize path logic for DAL
Java
apache-2.0
ca725a2385e4c1a1434c99c93c7b366d5a72c550
0
adligo/i_util.adligo.org
package org.adligo.i.util.client; /** * this class provides method not available in jme * for java.lang.Exception like fill in stacktrace and getStackTrace * * @author scott * */ public class ThrowableHelperFactory { protected static I_ThrowableHelper helper; public static void fillInStackTrace(Throwable p) { helper.fillInStackTrace(p); } public static String getStackTraceAsString(Throwable p) { return helper.getStackTraceAsString(p); } protected synchronized static void init(I_ThrowableHelper p) throws Exception { if (p == null) { throw new Exception("" + ClassUtils.getClassName(ThrowableHelperFactory.class) + " can't accept a null in parameter."); } helper = p; } public static boolean isInit() { if (helper == null) { return false; } return true; } }
src/org/adligo/i/util/client/ThrowableHelperFactory.java
package org.adligo.i.util.client; /** * this class provides method not available in jme * for java.lang.Exception like fill in stacktrace and getStackTrace * * @author scott * */ public class ThrowableHelperFactory { protected static I_ThrowableHelper helper; public void fillInStackTrace(Throwable p) { helper.fillInStackTrace(p); } public String getStackTraceAsString(Throwable p) { return helper.getStackTraceAsString(p); } protected synchronized static void init(I_ThrowableHelper p) throws Exception { if (p == null) { throw new Exception("" + ClassUtils.getClassName(ThrowableHelperFactory.class) + " can't accept a null in parameter."); } helper = p; } public static boolean isInit() { if (helper == null) { return false; } return true; } }
updates for jme
src/org/adligo/i/util/client/ThrowableHelperFactory.java
updates for jme
Java
apache-2.0
640edff925b2d3784673d24362946e7bb2b92054
0
luosx/oauth,luosx/oauth,luosx/oauth
/* * Copyright 2008 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.oauth.client; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.net.URL; import java.util.Collection; import java.util.List; import java.util.Map; import junit.framework.TestCase; import net.oauth.OAuth; import net.oauth.OAuthAccessor; import net.oauth.OAuthConsumer; import net.oauth.OAuthMessage; import net.oauth.OAuthProblemException; import net.oauth.client.OAuthClient.ParameterStyle; import net.oauth.client.httpclient4.HttpClient4; import net.oauth.http.HttpMessage; import net.oauth.http.HttpMessageDecoder; import net.oauth.http.HttpResponseMessage; import net.oauth.signature.Echo; import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.ServletHolder; import org.mortbay.servlet.GzipFilter; import org.mortbay.thread.BoundedThreadPool; public class OAuthClientTest extends TestCase { public void testRedirect() throws Exception { final OAuthMessage request = new OAuthMessage("GET", "http://google.com/search", OAuth.newList("q", "Java")); final Integer expectedStatus = Integer.valueOf(301); final String expectedLocation = "http://www.google.com/search?q=Java"; for (OAuthClient client : clients) { try { OAuthMessage response = client.invoke(request, OAuthClient.ParameterStyle.BODY); fail("response: " + response); } catch (OAuthProblemException e) { Map<String, Object> parameters = e.getParameters(); assertEquals("status", expectedStatus, parameters.get(HttpResponseMessage.STATUS_CODE)); assertEquals("Location", expectedLocation, parameters.get(HttpResponseMessage.LOCATION)); } } } public void testInvokeMessage() throws Exception { final String echo = "http://localhost:" + port + "/Echo"; final String data = new String(new char[] { 0, 1, ' ', 'a', 127, 128, 0xFF, 0x3000, 0x4E00 }); final byte[] utf8 = data.getBytes("UTF-8"); List<OAuth.Parameter> parameters = OAuth.newList("x", "y", "oauth_token", "t"); String parametersForm = "oauth_token=t&x=y"; final Object[][] messages = new Object[][] { { new OAuthMessage("GET", echo, parameters), "GET\n" + parametersForm + "\n" + "null\n", null }, { new OAuthMessage("POST", echo, parameters), "POST\n" + parametersForm + "\n" + parametersForm.length() + "\n", OAuth.FORM_ENCODED }, { new MessageWithBody("PUT", echo, parameters, "text/OAuthClientTest; charset=\"UTF-8\"", utf8), "PUT\n" + parametersForm + "\n" + utf8.length + "\n" + data, "text/OAuthClientTest; charset=UTF-8" }, { new MessageWithBody("PUT", echo, parameters, "application/octet-stream", utf8), "PUT\n" + parametersForm + "\n" + utf8.length + "\n" + new String(utf8, "ISO-8859-1"), "application/octet-stream" }, { new OAuthMessage("DELETE", echo, parameters), "DELETE\n" + parametersForm + "\n" + "null\n", null } }; final ParameterStyle[] styles = new ParameterStyle[] { ParameterStyle.BODY, ParameterStyle.AUTHORIZATION_HEADER }; final long startTime = System.nanoTime(); for (OAuthClient client : clients) { for (Object[] testCase : messages) { for (ParameterStyle style : styles) { OAuthMessage request = (OAuthMessage) testCase[0]; final String id = client + " " + request.method + " " + style; OAuthMessage response = null; // System.out.println(id + " ..."); try { response = client.invoke(request, style); } catch (Exception e) { AssertionError failure = new AssertionError(id); failure.initCause(e); throw failure; } // System.out.println(response.getDump() // .get(OAuthMessage.HTTP_REQUEST)); String expectedBody = (String) testCase[1]; if ("POST".equalsIgnoreCase(request.method) && style == ParameterStyle.AUTHORIZATION_HEADER) { // Only the non-oauth parameters went in the body. expectedBody = expectedBody.replace("\n" + parametersForm.length() + "\n", "\n3\n"); } String body = response.readBodyAsString(); assertEquals(id, expectedBody, body); assertEquals(id, testCase[2], response.getHeader(HttpMessage.CONTENT_TYPE)); } } } final long endTime = System.nanoTime(); final float elapsedSec = ((float) (endTime - startTime)) / 1000000000L; if (elapsedSec > 10) { fail("elapsed time = " + elapsedSec + " sec"); // This often means the client isn't re-using TCP connections, // and consequently all the Jetty server threads are occupied // waiting for data on the wasted connections. } } public void testGzip() throws Exception { final OAuthConsumer consumer = new OAuthConsumer(null, null, null, null); consumer.setProperty(OAuthConsumer.ACCEPT_ENCODING, HttpMessageDecoder.ACCEPTED); consumer.setProperty(OAuth.OAUTH_SIGNATURE_METHOD, "PLAINTEXT"); final OAuthAccessor accessor = new OAuthAccessor(consumer); final String url = "http://localhost:" + port + "/Echo"; final List<OAuth.Parameter> parameters = OAuth.newList("echoData", "21", OAuth.OAUTH_NONCE, "n", OAuth.OAUTH_TIMESTAMP, "1"); final String expected = "POST\n" + "echoData=21&oauth_consumer_key=&oauth_nonce=n&oauth_signature_method=PLAINTEXT&oauth_timestamp=1&oauth_version=1.0\n" + "abcdefghi1abcdefghi2\n\n" // 21 bytes of data + "134\n" // content-length ; for (OAuthClient client : clients) { try { OAuthMessage response = client.invoke(accessor, "POST", url, parameters); System.out.println(response.getDump().get(HttpMessage.REQUEST)); System.out.println(response.getDump().get(HttpMessage.RESPONSE)); String id = client.getClass().getName(); assertNull(id, response.getHeader(HttpMessage.CONTENT_ENCODING)); assertNull(id, response.getHeader(HttpMessage.CONTENT_LENGTH)); assertEquals(id, expected, response.readBodyAsString()); // assertEqual(id, OAuth.decodeForm(expected), response.getParameters()); } catch (OAuthProblemException e) { Map<String, Object> p = e.getParameters(); System.out.println(p.get(HttpMessage.REQUEST)); System.err.println(p.get(HttpMessage.RESPONSE)); throw e; } catch(Exception e) { AssertionError a = new AssertionError(client.getClass().getName()); a.initCause(e); throw a; } System.out.println(); } } public void testUpload() throws IOException, OAuthProblemException { final String echo = "http://localhost:" + port + "/Echo"; final Class myClass = getClass(); final String sourceName = "/" + myClass.getPackage().getName().replace('.', '/') + "/flower.jpg"; final URL source = myClass.getResource(sourceName); assertNotNull(sourceName, source); for (OAuthClient client : clients) { for (ParameterStyle style : new ParameterStyle[] { ParameterStyle.AUTHORIZATION_HEADER, ParameterStyle.QUERY_STRING }) { final String id = client + " POST " + style; OAuthMessage response = null; InputStream input = source.openStream(); try { OAuthMessage request = new OAuthMessage(OAuthMessage.PUT, echo, null, input); request.addParameter(new OAuth.Parameter("oauth_token", "t")); request.getHeaders().add(new OAuth.Parameter("Content-Type", "image/jpeg")); response = client.invoke(request, style); } catch (OAuthProblemException e) { System.err.println(e.getParameters().get(HttpMessage.REQUEST)); System.err.println(e.getParameters().get(HttpMessage.RESPONSE)); throw e; } catch (Exception e) { AssertionError failure = new AssertionError(); failure.initCause(e); throw failure; } finally { input.close(); } assertEquals(id, "image/jpeg", response.getHeader("Content-Type")); byte[] data = readAll(source.openStream()); Integer contentLength = (client.getHttpClient() instanceof HttpClient4) ? null : new Integer( data.length); byte[] expected = concatenate((OAuthMessage.PUT + "\noauth_token=t\n" + contentLength + "\n") .getBytes(), data); byte[] actual = readAll(response.getBodyAsStream()); StreamTest.assertEqual(id, expected, actual); } } } static byte[] readAll(InputStream from) throws IOException { ByteArrayOutputStream into = new ByteArrayOutputStream(); try { byte[] buf = new byte[1024]; for (int n; 0 < (n = from.read(buf));) { into.write(buf, 0, n); } } finally { from.close(); } into.close(); return into.toByteArray(); } static byte[] concatenate(byte[] x, byte[] y) { byte[] z = new byte[x.length + y.length]; System.arraycopy(x, 0, z, 0, x.length); System.arraycopy(y, 0, z, x.length, y.length); return z; } private OAuthClient[] clients; private int port = 1025; private Server server; @Override public void setUp() throws Exception { clients = new OAuthClient[] { new OAuthClient(new URLConnectionClient()), new OAuthClient(new net.oauth.client.httpclient3.HttpClient3()), new OAuthClient(new net.oauth.client.httpclient4.HttpClient4()) }; { // Get an ephemeral local port number: Socket s = new Socket(); s.bind(null); port = s.getLocalPort(); s.close(); } server = new Server(port); Context context = new Context(server, "/", Context.SESSIONS); context.addFilter(GzipFilter.class, "/*", 1); context.addServlet(new ServletHolder(new Echo()), "/Echo/*"); BoundedThreadPool pool = new BoundedThreadPool(); pool.setMaxThreads(4); server.setThreadPool(pool); server.start(); } @Override public void tearDown() throws Exception { server.stop(); } private static class MessageWithBody extends OAuthMessage { public MessageWithBody(String method, String URL, Collection<OAuth.Parameter> parameters, String contentType, byte[] body) { super(method, URL, parameters); this.body = body; Collection<Map.Entry<String, String>> headers = getHeaders(); headers.add(new OAuth.Parameter(HttpMessage.ACCEPT_ENCODING, HttpMessageDecoder.ACCEPTED)); if (body != null) { headers.add(new OAuth.Parameter(HttpMessage.CONTENT_LENGTH, String.valueOf(body.length))); } if (contentType != null) { headers.add(new OAuth.Parameter(HttpMessage.CONTENT_TYPE, contentType)); } } private final byte[] body; @Override public InputStream getBodyAsStream() { return (body == null) ? null : new ByteArrayInputStream(body); } } }
core/src/test/java/net/oauth/client/OAuthClientTest.java
/* * Copyright 2008 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.oauth.client; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.net.URL; import java.util.Collection; import java.util.List; import java.util.Map; import junit.framework.TestCase; import net.oauth.OAuth; import net.oauth.OAuthAccessor; import net.oauth.OAuthConsumer; import net.oauth.OAuthMessage; import net.oauth.OAuthProblemException; import net.oauth.client.OAuthClient.ParameterStyle; import net.oauth.client.httpclient4.HttpClient4; import net.oauth.http.HttpMessage; import net.oauth.http.HttpMessageDecoder; import net.oauth.http.HttpResponseMessage; import net.oauth.signature.Echo; import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.ServletHolder; import org.mortbay.servlet.GzipFilter; import org.mortbay.thread.BoundedThreadPool; public class OAuthClientTest extends TestCase { public void testRedirect() throws Exception { final OAuthMessage request = new OAuthMessage("GET", "http://google.com/search", OAuth.newList("q", "Java")); final Integer expectedStatus = Integer.valueOf(301); final String expectedLocation = "http://www.google.com/search?q=Java"; for (OAuthClient client : clients) { try { OAuthMessage response = client.invoke(request, OAuthClient.ParameterStyle.BODY); fail("response: " + response); } catch (OAuthProblemException e) { Map<String, Object> parameters = e.getParameters(); assertEquals("status", expectedStatus, parameters.get(HttpResponseMessage.STATUS_CODE)); assertEquals("Location", expectedLocation, parameters.get(HttpResponseMessage.LOCATION)); } } } public void testInvokeMessage() throws Exception { final String echo = "http://localhost:" + port + "/Echo"; final String data = new String(new char[] { 0, 1, ' ', 'a', 127, 128, 0xFF, 0x3000, 0x4E00 }); final byte[] utf8 = data.getBytes("UTF-8"); List<OAuth.Parameter> parameters = OAuth.newList("x", "y", "oauth_token", "t"); String parametersForm = "oauth_token=t&x=y"; final Object[][] messages = new Object[][] { { new OAuthMessage("GET", echo, parameters), "GET\n" + parametersForm + "\n" + "null\n", null }, { new OAuthMessage("POST", echo, parameters), "POST\n" + parametersForm + "\n" + parametersForm.length() + "\n", OAuth.FORM_ENCODED }, { new MessageWithBody("PUT", echo, parameters, "text/OAuthClientTest; charset=\"UTF-8\"", utf8), "PUT\n" + parametersForm + "\n" + utf8.length + "\n" + data, "text/OAuthClientTest; charset=UTF-8" }, { new MessageWithBody("PUT", echo, parameters, "application/octet-stream", utf8), "PUT\n" + parametersForm + "\n" + utf8.length + "\n" + new String(utf8, "ISO-8859-1"), "application/octet-stream" }, { new OAuthMessage("DELETE", echo, parameters), "DELETE\n" + parametersForm + "\n" + "null\n", null } }; final ParameterStyle[] styles = new ParameterStyle[] { ParameterStyle.BODY, ParameterStyle.AUTHORIZATION_HEADER }; final long startTime = System.nanoTime(); for (OAuthClient client : clients) { for (Object[] testCase : messages) { for (ParameterStyle style : styles) { OAuthMessage request = (OAuthMessage) testCase[0]; final String id = client + " " + request.method + " " + style; OAuthMessage response = null; // System.out.println(id + " ..."); try { response = client.invoke(request, style); } catch (Exception e) { AssertionError failure = new AssertionError(id); failure.initCause(e); throw failure; } // System.out.println(response.getDump() // .get(OAuthMessage.HTTP_REQUEST)); String expectedBody = (String) testCase[1]; if ("POST".equalsIgnoreCase(request.method) && style == ParameterStyle.AUTHORIZATION_HEADER) { // Only the non-oauth parameters went in the body. expectedBody = expectedBody.replace("\n" + parametersForm.length() + "\n", "\n3\n"); } String body = response.readBodyAsString(); assertEquals(id, expectedBody, body); assertEquals(id, testCase[2], response.getHeader(HttpMessage.CONTENT_TYPE)); } } } final long endTime = System.nanoTime(); final float elapsedSec = ((float) (endTime - startTime)) / 1000000000L; if (elapsedSec > 10) { fail("elapsed time = " + elapsedSec + " sec"); // This often means the client isn't re-using TCP connections, // and consequently all the Jetty server threads are occupied // waiting for data on the wasted connections. } } public void testGzip() throws Exception { final OAuthConsumer consumer = new OAuthConsumer(null, null, null, null); consumer.setProperty(OAuthConsumer.ACCEPT_ENCODING, HttpMessageDecoder.ACCEPTED); consumer.setProperty(OAuth.OAUTH_SIGNATURE_METHOD, "PLAINTEXT"); final OAuthAccessor accessor = new OAuthAccessor(consumer); final String url = "http://localhost:" + port + "/Echo"; final List<OAuth.Parameter> parameters = OAuth.newList("echoData", "21", OAuth.OAUTH_NONCE, "n", OAuth.OAUTH_TIMESTAMP, "1"); final String expected = "POST\n" + "echoData=21&oauth_consumer_key=&oauth_nonce=n&oauth_signature_method=PLAINTEXT&oauth_timestamp=1&oauth_version=1.0\n" + "abcdefghi1abcdefghi2\n\n" // 21 bytes of data + "134\n" // content-length ; for (OAuthClient client : clients) { try { OAuthMessage response = client.invoke(accessor, "POST", url, parameters); System.out.println(response.getDump().get(HttpMessage.REQUEST)); System.out.println(response.getDump().get(HttpMessage.RESPONSE)); String id = client.getClass().getName(); assertNull(id, response.getHeader(HttpMessage.CONTENT_ENCODING)); assertNull(id, response.getHeader(HttpMessage.CONTENT_LENGTH)); assertEquals(id, expected, response.readBodyAsString()); // assertEqual(id, OAuth.decodeForm(expected), response.getParameters()); } catch (OAuthProblemException e) { Map<String, Object> p = e.getParameters(); System.out.println(p.get(HttpMessage.REQUEST)); System.err.println(p.get(HttpMessage.RESPONSE)); throw e; } catch(Exception e) { AssertionError a = new AssertionError(client.getClass().getName()); a.initCause(e); throw a; } System.out.println(); } } public void testUpload() throws IOException, OAuthProblemException { final String echo = "http://localhost:" + port + "/Echo"; final Class myClass = getClass(); final String sourceName = "/" + myClass.getPackage().getName().replace('.', '/') + "/flower.jpg"; final URL source = myClass.getResource(sourceName); assertNotNull(sourceName, source); for (OAuthClient client : clients) { for (ParameterStyle style : new ParameterStyle[] { ParameterStyle.AUTHORIZATION_HEADER, ParameterStyle.QUERY_STRING }) { final String id = client + " POST " + style; OAuthMessage response = null; InputStream input = source.openStream(); try { OAuthMessage request = new InputStreamMessage(OAuthMessage.PUT, echo, input); request.addParameter(new OAuth.Parameter("oauth_token", "t")); request.getHeaders().add(new OAuth.Parameter("Content-Type", "image/jpeg")); response = client.invoke(request, style); } catch (OAuthProblemException e) { System.err.println(e.getParameters().get(HttpMessage.REQUEST)); System.err.println(e.getParameters().get(HttpMessage.RESPONSE)); throw e; } catch (Exception e) { AssertionError failure = new AssertionError(); failure.initCause(e); throw failure; } finally { input.close(); } assertEquals(id, "image/jpeg", response.getHeader("Content-Type")); byte[] data = readAll(source.openStream()); Integer contentLength = (client.getHttpClient() instanceof HttpClient4) ? null : new Integer( data.length); byte[] expected = concatenate((OAuthMessage.PUT + "\noauth_token=t\n" + contentLength + "\n") .getBytes(), data); byte[] actual = readAll(response.getBodyAsStream()); StreamTest.assertEqual(id, expected, actual); } } } static byte[] readAll(InputStream from) throws IOException { ByteArrayOutputStream into = new ByteArrayOutputStream(); try { byte[] buf = new byte[1024]; for (int n; 0 < (n = from.read(buf));) { into.write(buf, 0, n); } } finally { from.close(); } into.close(); return into.toByteArray(); } static byte[] concatenate(byte[] x, byte[] y) { byte[] z = new byte[x.length + y.length]; System.arraycopy(x, 0, z, 0, x.length); System.arraycopy(y, 0, z, x.length, y.length); return z; } private OAuthClient[] clients; private int port = 1025; private Server server; @Override public void setUp() throws Exception { clients = new OAuthClient[] { new OAuthClient(new URLConnectionClient()), new OAuthClient(new net.oauth.client.httpclient3.HttpClient3()), new OAuthClient(new net.oauth.client.httpclient4.HttpClient4()) }; { // Get an ephemeral local port number: Socket s = new Socket(); s.bind(null); port = s.getLocalPort(); s.close(); } server = new Server(port); Context context = new Context(server, "/", Context.SESSIONS); context.addFilter(GzipFilter.class, "/*", 1); context.addServlet(new ServletHolder(new Echo()), "/Echo/*"); BoundedThreadPool pool = new BoundedThreadPool(); pool.setMaxThreads(4); server.setThreadPool(pool); server.start(); } @Override public void tearDown() throws Exception { server.stop(); } private static class MessageWithBody extends OAuthMessage { public MessageWithBody(String method, String URL, Collection<OAuth.Parameter> parameters, String contentType, byte[] body) { super(method, URL, parameters); this.body = body; Collection<Map.Entry<String, String>> headers = getHeaders(); headers.add(new OAuth.Parameter(HttpMessage.ACCEPT_ENCODING, HttpMessageDecoder.ACCEPTED)); if (body != null) { headers.add(new OAuth.Parameter(HttpMessage.CONTENT_LENGTH, String.valueOf(body.length))); } if (contentType != null) { headers.add(new OAuth.Parameter(HttpMessage.CONTENT_TYPE, contentType)); } } private final byte[] body; @Override public InputStream getBodyAsStream() { return (body == null) ? null : new ByteArrayInputStream(body); } } static class InputStreamMessage extends OAuthMessage { InputStreamMessage(String method, String url, InputStream body) { super(method, url, null); this.body = body; } private final InputStream body; @Override public InputStream getBodyAsStream() throws IOException { return body; } } }
take advantage of OAuthMessage.bodyAsString
core/src/test/java/net/oauth/client/OAuthClientTest.java
take advantage of OAuthMessage.bodyAsString
Java
apache-2.0
970f934341c2151a8b01707157d8f0f9d1e82817
0
thelastpickle/cassandra-reaper,thelastpickle/cassandra-reaper,thelastpickle/cassandra-reaper,thelastpickle/cassandra-reaper,thelastpickle/cassandra-reaper
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.spotify.reaper.cassandra; import static com.google.common.base.Preconditions.checkNotNull; import java.io.IOException; import java.math.BigInteger; import java.net.MalformedURLException; import java.util.AbstractMap; 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.Set; import javax.management.InstanceNotFoundException; import javax.management.JMX; import javax.management.ListenerNotFoundException; import javax.management.MBeanServerConnection; import javax.management.MalformedObjectNameException; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import javax.validation.constraints.NotNull; import org.apache.cassandra.db.ColumnFamilyStoreMBean; import org.apache.cassandra.db.compaction.CompactionManager; import org.apache.cassandra.db.compaction.CompactionManagerMBean; import org.apache.cassandra.repair.RepairParallelism; import org.apache.cassandra.service.ActiveRepairService; import org.apache.cassandra.service.StorageServiceMBean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.collect.Lists; import com.spotify.reaper.ReaperException; import com.spotify.reaper.core.Cluster; import com.spotify.reaper.service.RingRange; public class JmxProxy implements NotificationListener, AutoCloseable { private static final Logger LOG = LoggerFactory.getLogger(JmxProxy.class); private static final int JMX_PORT = 7199; private static final String JMX_URL = "service:jmx:rmi:///jndi/rmi://%s:%d/jmxrmi"; private static final String SS_OBJECT_NAME = "org.apache.cassandra.db:type=StorageService"; private static final String AES_OBJECT_NAME = "org.apache.cassandra.internal:type=AntiEntropySessions"; private static final String COMP_OBJECT_NAME = "org.apache.cassandra.metrics:type=Compaction"; private final JMXConnector jmxConnector; private final ObjectName ssMbeanName; private final MBeanServerConnection mbeanServer; private final CompactionManagerMBean cmProxy; private final StorageServiceMBean ssProxy; private final Optional<RepairStatusHandler> repairStatusHandler; private final String host; private final JMXServiceURL jmxUrl; private final String clusterName; private JmxProxy(Optional<RepairStatusHandler> handler, String host, JMXServiceURL jmxUrl, JMXConnector jmxConnector, StorageServiceMBean ssProxy, ObjectName ssMbeanName, MBeanServerConnection mbeanServer, CompactionManagerMBean cmProxy) { this.host = host; this.jmxUrl = jmxUrl; this.jmxConnector = jmxConnector; this.ssMbeanName = ssMbeanName; this.mbeanServer = mbeanServer; this.ssProxy = ssProxy; this.repairStatusHandler = handler; this.cmProxy = cmProxy; this.clusterName = Cluster.toSymbolicName(ssProxy.getClusterName()); } /** * @see JmxProxy#connect(Optional, String, int, String, String) */ static JmxProxy connect(Optional<RepairStatusHandler> handler, String host, String username, String password) throws ReaperException { assert null != host : "null host given to JmxProxy.connect()"; String[] parts = host.split(":"); if (parts.length == 2) { return connect(handler, parts[0], Integer.valueOf(parts[1]), username, password); } else { return connect(handler, host, JMX_PORT, username, password); } } /** * Connect to JMX interface on the given host and port. * * @param handler Implementation of {@link RepairStatusHandler} to process incoming * notifications * of repair events. * @param host hostname or ip address of Cassandra node * @param port port number to use for JMX connection * @param username username to use for JMX authentication * @param password password to use for JMX authentication */ static JmxProxy connect(Optional<RepairStatusHandler> handler, String host, int port, String username, String password) throws ReaperException { ObjectName ssMbeanName; ObjectName cmMbeanName; JMXServiceURL jmxUrl; try { jmxUrl = new JMXServiceURL(String.format(JMX_URL, host, port)); ssMbeanName = new ObjectName(SS_OBJECT_NAME); cmMbeanName = new ObjectName(CompactionManager.MBEAN_OBJECT_NAME); } catch (MalformedURLException | MalformedObjectNameException e) { LOG.error(String.format("Failed to prepare the JMX connection to %s:%s", host, port)); throw new ReaperException("Failure during preparations for JMX connection", e); } try { Map<String, Object> env = new HashMap<String, Object>(); if (username != null && password != null) { String[] creds = {username, password}; env.put(JMXConnector.CREDENTIALS, creds); } JMXConnector jmxConn = JMXConnectorFactory.connect(jmxUrl, env); MBeanServerConnection mbeanServerConn = jmxConn.getMBeanServerConnection(); StorageServiceMBean ssProxy = JMX.newMBeanProxy(mbeanServerConn, ssMbeanName, StorageServiceMBean.class); CompactionManagerMBean cmProxy = JMX.newMBeanProxy(mbeanServerConn, cmMbeanName, CompactionManagerMBean.class); JmxProxy proxy = new JmxProxy(handler, host, jmxUrl, jmxConn, ssProxy, ssMbeanName, mbeanServerConn, cmProxy); // registering a listener throws bunch of exceptions, so we do it here rather than in the // constructor mbeanServerConn.addNotificationListener(ssMbeanName, proxy, null, null); LOG.debug(String.format("JMX connection to %s properly connected: %s", host, jmxUrl.toString())); return proxy; } catch (IOException | InstanceNotFoundException e) { LOG.error(String.format("Failed to establish JMX connection to %s:%s", host, port)); throw new ReaperException("Failure when establishing JMX connection", e); } } public String getHost() { return host; } /** * @return list of tokens in the cluster */ public List<BigInteger> getTokens() { checkNotNull(ssProxy, "Looks like the proxy is not connected"); return Lists.transform( Lists.newArrayList(ssProxy.getTokenToEndpointMap().keySet()), new Function<String, BigInteger>() { @Override public BigInteger apply(String s) { return new BigInteger(s); } }); } public Map<List<String>, List<String>> getRangeToEndpointMap(String keyspace) throws ReaperException { checkNotNull(ssProxy, "Looks like the proxy is not connected"); try { return ssProxy.getRangeToEndpointMap(keyspace); } catch (AssertionError e) { LOG.error(e.getMessage()); throw new ReaperException(e.getMessage()); } } /** * @return all hosts owning a range of tokens */ @NotNull public List<String> tokenRangeToEndpoint(String keyspace, RingRange tokenRange) { checkNotNull(ssProxy, "Looks like the proxy is not connected"); Set<Map.Entry<List<String>, List<String>>> entries = ssProxy.getRangeToEndpointMap(keyspace).entrySet(); for (Map.Entry<List<String>, List<String>> entry : entries) { BigInteger rangeStart = new BigInteger(entry.getKey().get(0)); BigInteger rangeEnd = new BigInteger(entry.getKey().get(1)); if (new RingRange(rangeStart, rangeEnd).encloses(tokenRange)) { return entry.getValue(); } } return Lists.newArrayList(); } /** * @return full class name of Cassandra's partitioner. */ public String getPartitioner() { checkNotNull(ssProxy, "Looks like the proxy is not connected"); return ssProxy.getPartitionerName(); } /** * @return Cassandra cluster name. */ public String getClusterName() { checkNotNull(ssProxy, "Looks like the proxy is not connected"); return ssProxy.getClusterName(); } /** * @return list of available keyspaces */ public List<String> getKeyspaces() { checkNotNull(ssProxy, "Looks like the proxy is not connected"); return ssProxy.getKeyspaces(); } public Set<String> getTableNamesForKeyspace(String keyspace) throws ReaperException { Set<String> tableNames = new HashSet<>(); Iterator<Map.Entry<String, ColumnFamilyStoreMBean>> proxies; try { proxies = ColumnFamilyStoreMBeanIterator.getColumnFamilyStoreMBeanProxies(mbeanServer); } catch (IOException | MalformedObjectNameException e) { e.printStackTrace(); throw new ReaperException("failed to get ColumnFamilyStoreMBean instances from JMX"); } while (proxies.hasNext()) { Map.Entry<String, ColumnFamilyStoreMBean> proxyEntry = proxies.next(); String keyspaceName = proxyEntry.getKey(); if (keyspace.equalsIgnoreCase(keyspaceName)) { ColumnFamilyStoreMBean columnFamilyMBean = proxyEntry.getValue(); tableNames.add(columnFamilyMBean.getColumnFamilyName()); } } return tableNames; } /** * @return number of pending compactions on the node this proxy is connected to */ public int getPendingCompactions() { checkNotNull(cmProxy, "Looks like the proxy is not connected"); try { ObjectName name = new ObjectName(COMP_OBJECT_NAME); int pendingCount = (int) mbeanServer.getAttribute(name, "PendingTasks"); return pendingCount; } catch (IOException ignored) { LOG.warn("Failed to connect to " + host + " using JMX"); } catch (MalformedObjectNameException ignored) { LOG.error("Internal error, malformed name"); } catch (InstanceNotFoundException e) { // This happens if no repair has yet been run on the node // The AntiEntropySessions object is created on the first repair return 0; } catch (Exception e) { LOG.error("Error getting attribute from JMX", e); } // If uncertain, assume it's running return 0; } /** * @return true if any repairs are running on the node. */ public boolean isRepairRunning() { // Check if AntiEntropySession is actually running on the node try { ObjectName name = new ObjectName(AES_OBJECT_NAME); int activeCount = (Integer) mbeanServer.getAttribute(name, "ActiveCount"); long pendingCount = (Long) mbeanServer.getAttribute(name, "PendingTasks"); return activeCount + pendingCount != 0; } catch (IOException ignored) { LOG.warn("Failed to connect to " + host + " using JMX"); } catch (MalformedObjectNameException ignored) { LOG.error("Internal error, malformed name"); } catch (InstanceNotFoundException e) { // This happens if no repair has yet been run on the node // The AntiEntropySessions object is created on the first repair return false; } catch (Exception e) { LOG.error("Error getting attribute from JMX", e); } // If uncertain, assume it's running return true; } /** * Terminates all ongoing repairs on the node this proxy is connected to */ public void cancelAllRepairs() { checkNotNull(ssProxy, "Looks like the proxy is not connected"); try { ssProxy.forceTerminateAllRepairSessions(); } catch (RuntimeException e) { // This can happen if the node is down (UndeclaredThrowableException), // in which case repairs will be cancelled anyway... LOG.warn("Failed to terminate all repair sessions; node down?", e); } } /** * Checks if table exists in the cluster by instantiating a MBean for that table. */ public boolean tableExists(String ks, String cf) { try { String type = cf.contains(".") ? "IndexColumnFamilies" : "ColumnFamilies"; String nameStr = String.format("org.apache.cassandra.db:type=*%s,keyspace=%s,columnfamily=%s", type, ks, cf); Set<ObjectName> beans = mbeanServer.queryNames(new ObjectName(nameStr), null); if (beans.isEmpty() || beans.size() != 1) { return false; } ObjectName bean = beans.iterator().next(); JMX.newMBeanProxy(mbeanServer, bean, ColumnFamilyStoreMBean.class); } catch (MalformedObjectNameException | IOException e) { String errMsg = String.format("ColumnFamilyStore for %s/%s not found: %s", ks, cf, e.getMessage()); LOG.warn(errMsg); return false; } return true; } /** * Triggers a repair of range (beginToken, endToken] for given keyspace and column family. * The repair is triggered by {@link org.apache.cassandra.service.StorageServiceMBean#forceRepairRangeAsync} * For time being, we don't allow local nor snapshot repairs. * * @return Repair command number, or 0 if nothing to repair */ public int triggerRepair(BigInteger beginToken, BigInteger endToken, String keyspace, RepairParallelism repairParallelism, Collection<String> columnFamilies, boolean fullRepair) { checkNotNull(ssProxy, "Looks like the proxy is not connected"); String cassandraVersion = ssProxy.getReleaseVersion(); boolean canUseDatacenterAware = false; try { canUseDatacenterAware = versionCompare(cassandraVersion, "2.0.12") >= 0; } catch (ReaperException e) { LOG.warn("failed on version comparison, not using dc aware repairs by default"); } String msg = String.format("Triggering repair of range (%s,%s] for keyspace \"%s\" on " + "host %s, with repair parallelism %s, in cluster with Cassandra " + "version '%s' (can use DATACENTER_AWARE '%s'), " + "for column families: %s", beginToken.toString(), endToken.toString(), keyspace, this.host, repairParallelism, cassandraVersion, canUseDatacenterAware, columnFamilies); LOG.info(msg); if(fullRepair) { if (repairParallelism.equals(RepairParallelism.DATACENTER_AWARE)) { if (canUseDatacenterAware) { return ssProxy.forceRepairRangeAsync(beginToken.toString(), endToken.toString(), keyspace, repairParallelism.ordinal(), null, null, fullRepair, columnFamilies .toArray(new String[columnFamilies.size()])); } else { LOG.info("Cannot use DATACENTER_AWARE repair policy for Cassandra cluster with version {}," + " falling back to SEQUENTIAL repair.", cassandraVersion); repairParallelism = RepairParallelism.SEQUENTIAL; } } boolean snapshotRepair = repairParallelism.equals(RepairParallelism.SEQUENTIAL); return ssProxy.forceRepairRangeAsync(beginToken.toString(), endToken.toString(), keyspace, snapshotRepair, false, fullRepair, columnFamilies.toArray(new String[columnFamilies.size()])); } else { return ssProxy.forceRepairAsync(keyspace, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE, fullRepair, columnFamilies.toArray(new String[columnFamilies.size()])); } } /** * Invoked when the MBean this class listens to publishes an event. * We're only interested in repair-related events. * Their format is explained at {@link org.apache.cassandra.service.StorageServiceMBean#forceRepairAsync} * The format is: notification type: "repair" notification userData: int array of length 2 where * [0] = command number [1] = ordinal of AntiEntropyService.Status */ @Override public void handleNotification(Notification notification, Object handback) { Thread.currentThread().setName(clusterName); // we're interested in "repair" String type = notification.getType(); LOG.debug("Received notification: {}", notification.toString()); if (repairStatusHandler.isPresent() && type.equals("repair")) { int[] data = (int[]) notification.getUserData(); // get the repair sequence number int repairNo = data[0]; // get the repair status ActiveRepairService.Status status = ActiveRepairService.Status.values()[data[1]]; // this is some text message like "Starting repair...", "Finished repair...", etc. String message = notification.getMessage(); // let the handler process the event repairStatusHandler.get().handle(repairNo, status, message); } } public String getConnectionId() throws IOException { return jmxConnector.getConnectionId(); } public boolean isConnectionAlive() { try { String connectionId = getConnectionId(); return null != connectionId && connectionId.length() > 0; } catch (IOException e) { e.printStackTrace(); } return false; } /** * Cleanly shut down by un-registering the listener and closing the JMX connection. */ @Override public void close() throws ReaperException { LOG.debug(String.format("close JMX connection to '%s': %s", host, jmxUrl)); try { mbeanServer.removeNotificationListener(ssMbeanName, this); } catch (InstanceNotFoundException | ListenerNotFoundException | IOException e) { LOG.warn("failed on removing notification listener"); e.printStackTrace(); } try { jmxConnector.close(); } catch (IOException e) { LOG.warn("failed closing a JMX connection"); e.printStackTrace(); } } /** * NOTICE: This code is loosely based on StackOverflow answer: * http://stackoverflow.com/questions/6701948/efficient-way-to-compare-version-strings-in-java * * Compares two version strings. * * Use this instead of String.compareTo() for a non-lexicographical * comparison that works for version strings. e.g. "1.10".compareTo("1.6"). * * @param str1 a string of ordinal numbers separated by decimal points. * @param str2 a string of ordinal numbers separated by decimal points. * @return The result is a negative integer if str1 is _numerically_ less than str2. * The result is a positive integer if str1 is _numerically_ greater than str2. * The result is zero if the strings are _numerically_ equal. * It does not work if "1.10" is supposed to be equal to "1.10.0". */ public static Integer versionCompare(String str1, String str2) throws ReaperException { try { str1 = str1.split(" ")[0].replaceAll("[-_~]", "."); str2 = str2.split(" ")[0].replaceAll("[-_~]", "."); String[] parts1 = str1.split("\\."); String[] parts2 = str2.split("\\."); int i = 0; // set index to first non-equal ordinal or length of shortest version string while (i < parts1.length && i < parts2.length) { try { Integer.parseInt(parts1[i]); Integer.parseInt(parts2[i]); } catch (NumberFormatException ex) { if (i == 0) { throw ex; // just comparing two non-version strings should fail } // first non integer part, so let's just stop comparison here and ignore the rest i--; break; } if (parts1[i].equals(parts2[i])) { i++; continue; } break; } // compare first non-equal ordinal number if (i < parts1.length && i < parts2.length) { int diff = Integer.valueOf(parts1[i]).compareTo(Integer.valueOf(parts2[i])); return Integer.signum(diff); } // the strings are equal or one string is a substring of the other // e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4" else { return Integer.signum(parts1.length - parts2.length); } } catch (Exception ex) { LOG.error("failed comparing strings for versions: '{}' '{}'", str1, str2); throw new ReaperException(ex); } } public void clearSnapshot(String repairId, String keyspaceName) throws ReaperException { if (repairId == null || repairId.equals("")) { // Passing in null or empty string will clear all snapshots on the host throw new IllegalArgumentException("repairId cannot be null or empty string"); } try { ssProxy.clearSnapshot(repairId, keyspaceName); } catch (IOException e) { throw new ReaperException(e); } } } /** * This code is copied and adjusted from from NodeProbe.java from Cassandra source. */ class ColumnFamilyStoreMBeanIterator implements Iterator<Map.Entry<String, ColumnFamilyStoreMBean>> { private Iterator<ObjectName> resIter; private MBeanServerConnection mbeanServerConn; public ColumnFamilyStoreMBeanIterator(MBeanServerConnection mbeanServerConn) throws MalformedObjectNameException, NullPointerException, IOException { ObjectName query = new ObjectName("org.apache.cassandra.db:type=ColumnFamilies,*"); resIter = mbeanServerConn.queryNames(query, null).iterator(); this.mbeanServerConn = mbeanServerConn; } static Iterator<Map.Entry<String, ColumnFamilyStoreMBean>> getColumnFamilyStoreMBeanProxies( MBeanServerConnection mbeanServerConn) throws IOException, MalformedObjectNameException { return new ColumnFamilyStoreMBeanIterator(mbeanServerConn); } @Override public boolean hasNext() { return resIter.hasNext(); } @Override public Map.Entry<String, ColumnFamilyStoreMBean> next() { ObjectName objectName = resIter.next(); String keyspaceName = objectName.getKeyProperty("keyspace"); ColumnFamilyStoreMBean cfsProxy = JMX.newMBeanProxy(mbeanServerConn, objectName, ColumnFamilyStoreMBean.class); return new AbstractMap.SimpleImmutableEntry<>(keyspaceName, cfsProxy); } @Override public void remove() { throw new UnsupportedOperationException(); } }
src/main/java/com/spotify/reaper/cassandra/JmxProxy.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.spotify.reaper.cassandra; import static com.google.common.base.Preconditions.checkNotNull; import java.io.IOException; import java.math.BigInteger; import java.net.MalformedURLException; import java.util.AbstractMap; 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.Set; import javax.management.InstanceNotFoundException; import javax.management.JMX; import javax.management.ListenerNotFoundException; import javax.management.MBeanServerConnection; import javax.management.MalformedObjectNameException; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import javax.validation.constraints.NotNull; import org.apache.cassandra.db.ColumnFamilyStoreMBean; import org.apache.cassandra.db.compaction.CompactionManager; import org.apache.cassandra.db.compaction.CompactionManagerMBean; import org.apache.cassandra.repair.RepairParallelism; import org.apache.cassandra.service.ActiveRepairService; import org.apache.cassandra.service.StorageServiceMBean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.collect.Lists; import com.spotify.reaper.ReaperException; import com.spotify.reaper.core.Cluster; import com.spotify.reaper.service.RingRange; public class JmxProxy implements NotificationListener, AutoCloseable { private static final Logger LOG = LoggerFactory.getLogger(JmxProxy.class); private static final int JMX_PORT = 7199; private static final String JMX_URL = "service:jmx:rmi:///jndi/rmi://%s:%d/jmxrmi"; private static final String SS_OBJECT_NAME = "org.apache.cassandra.db:type=StorageService"; private static final String AES_OBJECT_NAME = "org.apache.cassandra.internal:type=AntiEntropySessions"; private final JMXConnector jmxConnector; private final ObjectName ssMbeanName; private final MBeanServerConnection mbeanServer; private final CompactionManagerMBean cmProxy; private final StorageServiceMBean ssProxy; private final Optional<RepairStatusHandler> repairStatusHandler; private final String host; private final JMXServiceURL jmxUrl; private final String clusterName; private JmxProxy(Optional<RepairStatusHandler> handler, String host, JMXServiceURL jmxUrl, JMXConnector jmxConnector, StorageServiceMBean ssProxy, ObjectName ssMbeanName, MBeanServerConnection mbeanServer, CompactionManagerMBean cmProxy) { this.host = host; this.jmxUrl = jmxUrl; this.jmxConnector = jmxConnector; this.ssMbeanName = ssMbeanName; this.mbeanServer = mbeanServer; this.ssProxy = ssProxy; this.repairStatusHandler = handler; this.cmProxy = cmProxy; this.clusterName = Cluster.toSymbolicName(ssProxy.getClusterName()); } /** * @see JmxProxy#connect(Optional, String, int, String, String) */ static JmxProxy connect(Optional<RepairStatusHandler> handler, String host, String username, String password) throws ReaperException { assert null != host : "null host given to JmxProxy.connect()"; String[] parts = host.split(":"); if (parts.length == 2) { return connect(handler, parts[0], Integer.valueOf(parts[1]), username, password); } else { return connect(handler, host, JMX_PORT, username, password); } } /** * Connect to JMX interface on the given host and port. * * @param handler Implementation of {@link RepairStatusHandler} to process incoming * notifications * of repair events. * @param host hostname or ip address of Cassandra node * @param port port number to use for JMX connection * @param username username to use for JMX authentication * @param password password to use for JMX authentication */ static JmxProxy connect(Optional<RepairStatusHandler> handler, String host, int port, String username, String password) throws ReaperException { ObjectName ssMbeanName; ObjectName cmMbeanName; JMXServiceURL jmxUrl; try { jmxUrl = new JMXServiceURL(String.format(JMX_URL, host, port)); ssMbeanName = new ObjectName(SS_OBJECT_NAME); cmMbeanName = new ObjectName(CompactionManager.MBEAN_OBJECT_NAME); } catch (MalformedURLException | MalformedObjectNameException e) { LOG.error(String.format("Failed to prepare the JMX connection to %s:%s", host, port)); throw new ReaperException("Failure during preparations for JMX connection", e); } try { Map<String, Object> env = new HashMap<String, Object>(); if (username != null && password != null) { String[] creds = {username, password}; env.put(JMXConnector.CREDENTIALS, creds); } JMXConnector jmxConn = JMXConnectorFactory.connect(jmxUrl, env); MBeanServerConnection mbeanServerConn = jmxConn.getMBeanServerConnection(); StorageServiceMBean ssProxy = JMX.newMBeanProxy(mbeanServerConn, ssMbeanName, StorageServiceMBean.class); CompactionManagerMBean cmProxy = JMX.newMBeanProxy(mbeanServerConn, cmMbeanName, CompactionManagerMBean.class); JmxProxy proxy = new JmxProxy(handler, host, jmxUrl, jmxConn, ssProxy, ssMbeanName, mbeanServerConn, cmProxy); // registering a listener throws bunch of exceptions, so we do it here rather than in the // constructor mbeanServerConn.addNotificationListener(ssMbeanName, proxy, null, null); LOG.debug(String.format("JMX connection to %s properly connected: %s", host, jmxUrl.toString())); return proxy; } catch (IOException | InstanceNotFoundException e) { LOG.error(String.format("Failed to establish JMX connection to %s:%s", host, port)); throw new ReaperException("Failure when establishing JMX connection", e); } } public String getHost() { return host; } /** * @return list of tokens in the cluster */ public List<BigInteger> getTokens() { checkNotNull(ssProxy, "Looks like the proxy is not connected"); return Lists.transform( Lists.newArrayList(ssProxy.getTokenToEndpointMap().keySet()), new Function<String, BigInteger>() { @Override public BigInteger apply(String s) { return new BigInteger(s); } }); } public Map<List<String>, List<String>> getRangeToEndpointMap(String keyspace) throws ReaperException { checkNotNull(ssProxy, "Looks like the proxy is not connected"); try { return ssProxy.getRangeToEndpointMap(keyspace); } catch (AssertionError e) { LOG.error(e.getMessage()); throw new ReaperException(e.getMessage()); } } /** * @return all hosts owning a range of tokens */ @NotNull public List<String> tokenRangeToEndpoint(String keyspace, RingRange tokenRange) { checkNotNull(ssProxy, "Looks like the proxy is not connected"); Set<Map.Entry<List<String>, List<String>>> entries = ssProxy.getRangeToEndpointMap(keyspace).entrySet(); for (Map.Entry<List<String>, List<String>> entry : entries) { BigInteger rangeStart = new BigInteger(entry.getKey().get(0)); BigInteger rangeEnd = new BigInteger(entry.getKey().get(1)); if (new RingRange(rangeStart, rangeEnd).encloses(tokenRange)) { return entry.getValue(); } } return Lists.newArrayList(); } /** * @return full class name of Cassandra's partitioner. */ public String getPartitioner() { checkNotNull(ssProxy, "Looks like the proxy is not connected"); return ssProxy.getPartitionerName(); } /** * @return Cassandra cluster name. */ public String getClusterName() { checkNotNull(ssProxy, "Looks like the proxy is not connected"); return ssProxy.getClusterName(); } /** * @return list of available keyspaces */ public List<String> getKeyspaces() { checkNotNull(ssProxy, "Looks like the proxy is not connected"); return ssProxy.getKeyspaces(); } public Set<String> getTableNamesForKeyspace(String keyspace) throws ReaperException { Set<String> tableNames = new HashSet<>(); Iterator<Map.Entry<String, ColumnFamilyStoreMBean>> proxies; try { proxies = ColumnFamilyStoreMBeanIterator.getColumnFamilyStoreMBeanProxies(mbeanServer); } catch (IOException | MalformedObjectNameException e) { e.printStackTrace(); throw new ReaperException("failed to get ColumnFamilyStoreMBean instances from JMX"); } while (proxies.hasNext()) { Map.Entry<String, ColumnFamilyStoreMBean> proxyEntry = proxies.next(); String keyspaceName = proxyEntry.getKey(); if (keyspace.equalsIgnoreCase(keyspaceName)) { ColumnFamilyStoreMBean columnFamilyMBean = proxyEntry.getValue(); tableNames.add(columnFamilyMBean.getColumnFamilyName()); } } return tableNames; } /** * @return number of pending compactions on the node this proxy is connected to */ public int getPendingCompactions() { checkNotNull(cmProxy, "Looks like the proxy is not connected"); return cmProxy.getPendingTasks(); } /** * @return true if any repairs are running on the node. */ public boolean isRepairRunning() { // Check if AntiEntropySession is actually running on the node try { ObjectName name = new ObjectName(AES_OBJECT_NAME); int activeCount = (Integer) mbeanServer.getAttribute(name, "ActiveCount"); long pendingCount = (Long) mbeanServer.getAttribute(name, "PendingTasks"); return activeCount + pendingCount != 0; } catch (IOException ignored) { LOG.warn("Failed to connect to " + host + " using JMX"); } catch (MalformedObjectNameException ignored) { LOG.error("Internal error, malformed name"); } catch (InstanceNotFoundException e) { // This happens if no repair has yet been run on the node // The AntiEntropySessions object is created on the first repair return false; } catch (Exception e) { LOG.error("Error getting attribute from JMX", e); } // If uncertain, assume it's running return true; } /** * Terminates all ongoing repairs on the node this proxy is connected to */ public void cancelAllRepairs() { checkNotNull(ssProxy, "Looks like the proxy is not connected"); try { ssProxy.forceTerminateAllRepairSessions(); } catch (RuntimeException e) { // This can happen if the node is down (UndeclaredThrowableException), // in which case repairs will be cancelled anyway... LOG.warn("Failed to terminate all repair sessions; node down?", e); } } /** * Checks if table exists in the cluster by instantiating a MBean for that table. */ public boolean tableExists(String ks, String cf) { try { String type = cf.contains(".") ? "IndexColumnFamilies" : "ColumnFamilies"; String nameStr = String.format("org.apache.cassandra.db:type=*%s,keyspace=%s,columnfamily=%s", type, ks, cf); Set<ObjectName> beans = mbeanServer.queryNames(new ObjectName(nameStr), null); if (beans.isEmpty() || beans.size() != 1) { return false; } ObjectName bean = beans.iterator().next(); JMX.newMBeanProxy(mbeanServer, bean, ColumnFamilyStoreMBean.class); } catch (MalformedObjectNameException | IOException e) { String errMsg = String.format("ColumnFamilyStore for %s/%s not found: %s", ks, cf, e.getMessage()); LOG.warn(errMsg); return false; } return true; } /** * Triggers a repair of range (beginToken, endToken] for given keyspace and column family. * The repair is triggered by {@link org.apache.cassandra.service.StorageServiceMBean#forceRepairRangeAsync} * For time being, we don't allow local nor snapshot repairs. * * @return Repair command number, or 0 if nothing to repair */ public int triggerRepair(BigInteger beginToken, BigInteger endToken, String keyspace, RepairParallelism repairParallelism, Collection<String> columnFamilies, boolean fullRepair) { checkNotNull(ssProxy, "Looks like the proxy is not connected"); String cassandraVersion = ssProxy.getReleaseVersion(); boolean canUseDatacenterAware = false; try { canUseDatacenterAware = versionCompare(cassandraVersion, "2.0.12") >= 0; } catch (ReaperException e) { LOG.warn("failed on version comparison, not using dc aware repairs by default"); } String msg = String.format("Triggering repair of range (%s,%s] for keyspace \"%s\" on " + "host %s, with repair parallelism %s, in cluster with Cassandra " + "version '%s' (can use DATACENTER_AWARE '%s'), " + "for column families: %s", beginToken.toString(), endToken.toString(), keyspace, this.host, repairParallelism, cassandraVersion, canUseDatacenterAware, columnFamilies); LOG.info(msg); if(fullRepair) { if (repairParallelism.equals(RepairParallelism.DATACENTER_AWARE)) { if (canUseDatacenterAware) { return ssProxy.forceRepairRangeAsync(beginToken.toString(), endToken.toString(), keyspace, repairParallelism.ordinal(), null, null, fullRepair, columnFamilies .toArray(new String[columnFamilies.size()])); } else { LOG.info("Cannot use DATACENTER_AWARE repair policy for Cassandra cluster with version {}," + " falling back to SEQUENTIAL repair.", cassandraVersion); repairParallelism = RepairParallelism.SEQUENTIAL; } } boolean snapshotRepair = repairParallelism.equals(RepairParallelism.SEQUENTIAL); return ssProxy.forceRepairRangeAsync(beginToken.toString(), endToken.toString(), keyspace, snapshotRepair, false, fullRepair, columnFamilies.toArray(new String[columnFamilies.size()])); } else { return ssProxy.forceRepairAsync(keyspace, Boolean.FALSE, Boolean.FALSE, Boolean.TRUE, fullRepair, columnFamilies.toArray(new String[columnFamilies.size()])); } } /** * Invoked when the MBean this class listens to publishes an event. * We're only interested in repair-related events. * Their format is explained at {@link org.apache.cassandra.service.StorageServiceMBean#forceRepairAsync} * The format is: notification type: "repair" notification userData: int array of length 2 where * [0] = command number [1] = ordinal of AntiEntropyService.Status */ @Override public void handleNotification(Notification notification, Object handback) { Thread.currentThread().setName(clusterName); // we're interested in "repair" String type = notification.getType(); LOG.debug("Received notification: {}", notification.toString()); if (repairStatusHandler.isPresent() && type.equals("repair")) { int[] data = (int[]) notification.getUserData(); // get the repair sequence number int repairNo = data[0]; // get the repair status ActiveRepairService.Status status = ActiveRepairService.Status.values()[data[1]]; // this is some text message like "Starting repair...", "Finished repair...", etc. String message = notification.getMessage(); // let the handler process the event repairStatusHandler.get().handle(repairNo, status, message); } } public String getConnectionId() throws IOException { return jmxConnector.getConnectionId(); } public boolean isConnectionAlive() { try { String connectionId = getConnectionId(); return null != connectionId && connectionId.length() > 0; } catch (IOException e) { e.printStackTrace(); } return false; } /** * Cleanly shut down by un-registering the listener and closing the JMX connection. */ @Override public void close() throws ReaperException { LOG.debug(String.format("close JMX connection to '%s': %s", host, jmxUrl)); try { mbeanServer.removeNotificationListener(ssMbeanName, this); } catch (InstanceNotFoundException | ListenerNotFoundException | IOException e) { LOG.warn("failed on removing notification listener"); e.printStackTrace(); } try { jmxConnector.close(); } catch (IOException e) { LOG.warn("failed closing a JMX connection"); e.printStackTrace(); } } /** * NOTICE: This code is loosely based on StackOverflow answer: * http://stackoverflow.com/questions/6701948/efficient-way-to-compare-version-strings-in-java * * Compares two version strings. * * Use this instead of String.compareTo() for a non-lexicographical * comparison that works for version strings. e.g. "1.10".compareTo("1.6"). * * @param str1 a string of ordinal numbers separated by decimal points. * @param str2 a string of ordinal numbers separated by decimal points. * @return The result is a negative integer if str1 is _numerically_ less than str2. * The result is a positive integer if str1 is _numerically_ greater than str2. * The result is zero if the strings are _numerically_ equal. * It does not work if "1.10" is supposed to be equal to "1.10.0". */ public static Integer versionCompare(String str1, String str2) throws ReaperException { try { str1 = str1.split(" ")[0].replaceAll("[-_~]", "."); str2 = str2.split(" ")[0].replaceAll("[-_~]", "."); String[] parts1 = str1.split("\\."); String[] parts2 = str2.split("\\."); int i = 0; // set index to first non-equal ordinal or length of shortest version string while (i < parts1.length && i < parts2.length) { try { Integer.parseInt(parts1[i]); Integer.parseInt(parts2[i]); } catch (NumberFormatException ex) { if (i == 0) { throw ex; // just comparing two non-version strings should fail } // first non integer part, so let's just stop comparison here and ignore the rest i--; break; } if (parts1[i].equals(parts2[i])) { i++; continue; } break; } // compare first non-equal ordinal number if (i < parts1.length && i < parts2.length) { int diff = Integer.valueOf(parts1[i]).compareTo(Integer.valueOf(parts2[i])); return Integer.signum(diff); } // the strings are equal or one string is a substring of the other // e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4" else { return Integer.signum(parts1.length - parts2.length); } } catch (Exception ex) { LOG.error("failed comparing strings for versions: '{}' '{}'", str1, str2); throw new ReaperException(ex); } } public void clearSnapshot(String repairId, String keyspaceName) throws ReaperException { if (repairId == null || repairId.equals("")) { // Passing in null or empty string will clear all snapshots on the host throw new IllegalArgumentException("repairId cannot be null or empty string"); } try { ssProxy.clearSnapshot(repairId, keyspaceName); } catch (IOException e) { throw new ReaperException(e); } } } /** * This code is copied and adjusted from from NodeProbe.java from Cassandra source. */ class ColumnFamilyStoreMBeanIterator implements Iterator<Map.Entry<String, ColumnFamilyStoreMBean>> { private Iterator<ObjectName> resIter; private MBeanServerConnection mbeanServerConn; public ColumnFamilyStoreMBeanIterator(MBeanServerConnection mbeanServerConn) throws MalformedObjectNameException, NullPointerException, IOException { ObjectName query = new ObjectName("org.apache.cassandra.db:type=ColumnFamilies,*"); resIter = mbeanServerConn.queryNames(query, null).iterator(); this.mbeanServerConn = mbeanServerConn; } static Iterator<Map.Entry<String, ColumnFamilyStoreMBean>> getColumnFamilyStoreMBeanProxies( MBeanServerConnection mbeanServerConn) throws IOException, MalformedObjectNameException { return new ColumnFamilyStoreMBeanIterator(mbeanServerConn); } @Override public boolean hasNext() { return resIter.hasNext(); } @Override public Map.Entry<String, ColumnFamilyStoreMBean> next() { ObjectName objectName = resIter.next(); String keyspaceName = objectName.getKeyProperty("keyspace"); ColumnFamilyStoreMBean cfsProxy = JMX.newMBeanProxy(mbeanServerConn, objectName, ColumnFamilyStoreMBean.class); return new AbstractMap.SimpleImmutableEntry<>(keyspaceName, cfsProxy); } @Override public void remove() { throw new UnsupportedOperationException(); } }
fix for getPendingTasks() that disappeared in C* 3.0 (using JMX directly to get pending compactions) disabled primary range repair for incremental repair as it leaves unrepaired data on disk
src/main/java/com/spotify/reaper/cassandra/JmxProxy.java
fix for getPendingTasks() that disappeared in C* 3.0 (using JMX directly to get pending compactions) disabled primary range repair for incremental repair as it leaves unrepaired data on disk
Java
apache-2.0
890befe7759c515101582631e12442cc7084d9a5
0
KernelHaven/KernelHaven,KernelHaven/KernelHaven
package net.ssehub.kernel_haven.code_model.ast; import java.util.ArrayList; import java.util.List; import net.ssehub.kernel_haven.util.logic.Formula; import net.ssehub.kernel_haven.util.null_checks.NonNull; import net.ssehub.kernel_haven.util.null_checks.Nullable; /** * A preprocessor block with a variability condition (e.g. an #ifdef block). The nested children in this element * are the elements inside the preprocessor block. * * @author El-Sharkawy */ public class CppBlock extends AbstractSyntaxElementWithChildreen implements ICode { /** * The kind of preprocessor block. */ public static enum Type { IF, IFDEF, IFNDEF, ELSEIF, ELSE; } private @Nullable Formula condition; private @NonNull Type type; private List<CppBlock> siblings; /** * Creates a {@link CppBlock}. * * @param presenceCondition The presence condition of this element. * @param condition The variability condition of this block. * @param type The {@link Type} of preprocessor block that this is. */ public CppBlock(@NonNull Formula presenceCondition, @Nullable Formula condition, @NonNull Type type) { super(presenceCondition); this.condition = condition; this.type = type; siblings = new ArrayList<>(); } /** * Adds another if, elif, else block, which belongs to the same block. * @param sibling Another if, elif, else block, which belongs to the this block structure. */ public void addSibling(CppBlock sibling) { siblings.add(sibling); } @Override public @Nullable Formula getCondition() { return condition; } /** * Returns the {@link Type} of preprocessor block that this is. * * @return The {@link Type} of preprocessor block that this is. */ public @NonNull Type getType() { return type; } @Override public @NonNull String elementToString(@NonNull String indentation) { String result = "#" + type.name(); Formula condition = this.condition; if (condition != null) { result += " " + condition.toString(); } return result + "\n"; } @Override public void accept(@NonNull ISyntaxElementVisitor visitor) { visitor.visitCppBlock(this); } }
src/net/ssehub/kernel_haven/code_model/ast/CppBlock.java
package net.ssehub.kernel_haven.code_model.ast; import net.ssehub.kernel_haven.util.logic.Formula; import net.ssehub.kernel_haven.util.null_checks.NonNull; import net.ssehub.kernel_haven.util.null_checks.Nullable; /** * A preprocessor block with a variability condition (e.g. an #ifdef block). The nested children in this element * are the elements inside the preprocessor block. * * @author El-Sharkawy */ public class CppBlock extends AbstractSyntaxElementWithChildreen implements ICode { /** * The kind of preprocessor block. */ public static enum Type { IF, IFDEF, IFNDEF, ELSEIF, ELSE; } private @Nullable Formula condition; private @NonNull Type type; // TODO: add reference to siblings? /** * Creates a {@link CppBlock}. * * @param presenceCondition The presence condition of this element. * @param condition The variability condition of this block. * @param type The {@link Type} of preprocessor block that this is. */ public CppBlock(@NonNull Formula presenceCondition, @Nullable Formula condition, @NonNull Type type) { super(presenceCondition); this.condition = condition; this.type = type; } @Override public @Nullable Formula getCondition() { return condition; } /** * Returns the {@link Type} of preprocessor block that this is. * * @return The {@link Type} of preprocessor block that this is. */ public @NonNull Type getType() { return type; } @Override public @NonNull String elementToString(@NonNull String indentation) { String result = "#" + type.name(); Formula condition = this.condition; if (condition != null) { result += " " + condition.toString(); } return result + "\n"; } @Override public void accept(@NonNull ISyntaxElementVisitor visitor) { visitor.visitCppBlock(this); } }
CppBlock: May store siblings
src/net/ssehub/kernel_haven/code_model/ast/CppBlock.java
CppBlock: May store siblings
Java
apache-2.0
1d44b587e573851259e6205610bea70eee59aed6
0
google/truth,cgruber/truth,google/truth,google/truth,cgruber/truth
/* * Copyright (c) 2011 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.truth; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.truth.StringUtil.format; import static com.google.common.truth.SubjectUtils.accumulate; import com.google.common.base.Objects; import com.google.common.base.Predicates; import com.google.common.collect.Iterables; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.util.Arrays; import java.util.List; import javax.annotation.Nullable; /** * An object that lets you perform checks on the value under test. For example, {@code Subject} * contains {@link #isEqualTo(Object)} and {@link #isInstanceOf(Class)}, and {@link StringSubject} * contains {@link StringSubject#startsWith startsWith(String)}. * * <p>To create a {@code Subject} instance, most users will call an {@link Truth#assertThat * assertThat} method. For information about other ways to create an instance, see <a * href="https://google.github.io/truth/faq#full-chain">this FAQ entry</a>. * * <h3>For people extending Truth</h3> * * <p>For information about writing a custom {@link Subject}, see <a * href="https://google.github.io/truth/extension">our doc on extensions</a>. * * @param <S> the self-type, allowing {@code this}-returning methods to avoid needing subclassing * @param <T> the type of the object being tested by this {@code Subject} * @author David Saff * @author Christian Gruber */ public class Subject<S extends Subject<S, T>, T> { /** * In a fluent assertion chain, the argument to the common overload of {@link * StandardSubjectBuilder#about(Subject.Factory) about}, the method that specifies what kind of * {@link Subject} to create. * * <p>For more information about the fluent chain, see <a * href="https://google.github.io/truth/faq#full-chain">this FAQ entry</a>. * * <h3>For people extending Truth</h3> * * <p>When you write a custom subject, see <a href="https://google.github.io/truth/extension">our doc on * extensions</a>. It explains where {@code Subject.Factory} fits into the process. */ public interface Factory<SubjectT extends Subject<SubjectT, ActualT>, ActualT> { /** Creates a new {@link Subject}. */ SubjectT createSubject(FailureMetadata metadata, ActualT actual); } private static final FailureStrategy IGNORE_STRATEGY = new AbstractFailureStrategy() { @Override public void fail(String message, Throwable cause) {} }; private final FailureMetadata metadata; private final T actual; private String customName = null; /** * Constructor for use by subclasses. If you want to create an instance of this class itself, call * {@link Subject#check}{@code .that(actual)}. */ protected Subject(FailureMetadata metadata, @Nullable T actual) { this.metadata = actual instanceof Throwable ? metadata.offerRootCause((Throwable) actual) : metadata; this.actual = actual; } /** An internal method used to obtain the value set by {@link #named(String, Object...)}. */ protected String internalCustomName() { return customName; } /** * Adds a prefix to the subject, when it is displayed in error messages. This is especially useful * in the context of types that have no helpful {@code toString()} representation, e.g. boolean. * Writing {@code assertThat(foo).named("foo").isTrue();} then results in a more reasonable error * message. * * <p>{@code named()} takes a format template and argument objects which will be substituted into * the template, similar to {@link String#format(String, Object...)}, the chief difference being * that extra parameters (for which there are no template variables) will be appended to the * resulting string in brackets. Additionally, this only supports the {@code %s} template variable * type. */ @SuppressWarnings("unchecked") @CanIgnoreReturnValue public S named(String format, Object... args) { checkNotNull(format, "Name passed to named() cannot be null."); this.customName = StringUtil.format(format, args); return (S) this; } /** Fails if the subject is not null. */ public void isNull() { if (actual() != null) { fail("is null"); } } /** Fails if the subject is null. */ public void isNotNull() { if (actual() == null) { failWithoutActual("is a non-null reference"); } } /** * Fails if the subject is not equal to the given object. For the purposes of this comparison, two * objects are equal if any of the following is true: * * <ul> * <li>they are equal according to {@link Objects#equal} * <li>they are arrays and are considered equal by the appropriate {@link Arrays#equals} * overload * <li>they are boxed integer types ({@code Byte}, {@code Short}, {@code Character}, {@code * Integer}, or {@code Long}) and they are numerically equal when converted to {@code Long}. * </ul> */ public void isEqualTo(@Nullable Object other) { doEqualCheck(actual(), other, true); } /** * Fails if the subject is equal to the given object. The meaning of equality is the same as for * the {@link #isEqualTo} method. */ public void isNotEqualTo(@Nullable Object other) { doEqualCheck(actual(), other, false); } private void doEqualCheck( @Nullable Object rawActual, @Nullable Object rawOther, boolean expectEqual) { Object actual; Object other; boolean actualEqual; if (isIntegralBoxedPrimitive(rawActual) && isIntegralBoxedPrimitive(rawOther)) { actual = integralValue(rawActual); other = integralValue(rawOther); actualEqual = Objects.equal(actual, other); } else { actual = rawActual; other = rawOther; if (rawActual instanceof Double && rawOther instanceof Double) { actualEqual = Double.compare((Double) rawActual, (Double) rawOther) == 0; } else if (rawActual instanceof Float && rawOther instanceof Float) { actualEqual = Float.compare((Float) rawActual, (Float) rawOther) == 0; } else { actualEqual = Objects.equal(actual, other); } } if (actualEqual != expectEqual) { failComparingToStrings( expectEqual ? "is equal to" : "is not equal to", actual, other, rawOther, expectEqual); } } private static boolean isIntegralBoxedPrimitive(@Nullable Object o) { return o instanceof Byte || o instanceof Short || o instanceof Character || o instanceof Integer || o instanceof Long; } private static Long integralValue(Object o) { if (o instanceof Character) { return (long) ((Character) o).charValue(); } else if (o instanceof Number) { return ((Number) o).longValue(); } else { throw new AssertionError(o + " must be either a Character or a Number."); } } /** Fails if the subject is not the same instance as the given object. */ public void isSameAs(@Nullable Object other) { if (actual() != other) { failComparingToStrings("is the same instance as", actual(), other, other, true); } } /** Fails if the subject is the same instance as the given object. */ public void isNotSameAs(@Nullable Object other) { if (actual() == other) { fail("is not the same instance as", other); } } /** Fails if the subject is not an instance of the given class. */ public void isInstanceOf(Class<?> clazz) { if (clazz == null) { throw new NullPointerException("clazz"); } if (!Platform.isInstanceOfType(actual(), clazz)) { if (actual() != null) { if (classMetadataUnsupported()) { throw new UnsupportedOperationException( actualAsString() + ", an instance of " + actual().getClass().getName() + ", may or may not be an instance of " + clazz.getName() + ". Under -XdisableClassMetadata, we do not have enough information to tell."); } failWithBadResults( "is an instance of", clazz.getName(), "is an instance of", actual().getClass().getName()); } else { fail("is an instance of", clazz.getName()); } } } /** Fails if the subject is an instance of the given class. */ public void isNotInstanceOf(Class<?> clazz) { if (clazz == null) { throw new NullPointerException("clazz"); } if (classMetadataUnsupported()) { throw new UnsupportedOperationException( "isNotInstanceOf is not supported under -XdisableClassMetadata"); } if (actual() == null) { return; // null is not an instance of clazz. } if (Platform.isInstanceOfType(actual(), clazz)) { failWithRawMessage( "%s expected not to be an instance of %s, but was.", actualAsString(), clazz.getName()); } } /** Fails unless the subject is equal to any element in the given iterable. */ public void isIn(Iterable<?> iterable) { if (!Iterables.contains(iterable, actual())) { fail("is equal to any element in", iterable); } } /** Fails unless the subject is equal to any of the given elements. */ public void isAnyOf(@Nullable Object first, @Nullable Object second, @Nullable Object... rest) { List<Object> list = accumulate(first, second, rest); if (!list.contains(actual())) { fail("is equal to any of", list); } } /** Fails if the subject is equal to any element in the given iterable. */ public void isNotIn(Iterable<?> iterable) { int index = Iterables.indexOf(iterable, Predicates.<Object>equalTo(actual())); if (index != -1) { failWithRawMessage( "Not true that %s is not in %s. It was found at index %s", actualAsString(), iterable, index); } } /** Fails if the subject is equal to any of the given elements. */ public void isNoneOf(@Nullable Object first, @Nullable Object second, @Nullable Object... rest) { isNotIn(accumulate(first, second, rest)); } /** @deprecated Prefer {@code #actual()} for direct access to the subject. */ @Deprecated protected T getSubject() { // TODO(cgruber): move functionality to actual() and delete when no callers. return actual; } /** Returns the unedited, unformatted raw actual value. */ protected final T actual() { return getSubject(); } /** @deprecated Prefer {@code #actualAsString()} for display-formatted access to the subject. */ @Deprecated protected String getDisplaySubject() { // TODO(cgruber) migrate people from this method once no one is subclassing it. String formatted = actualCustomStringRepresentation(); if (customName != null) { // Covers some rare cases where a type might return "" from their custom formatter. // This is actually pretty terrible, as it comes from subjects overriding (formerly) // getDisplaySubject() in cases of .named() to make it not prefixing but replacing. // That goes against the stated contract of .named(). Once displayedAs() is in place, // we can rip this out and callers can use that instead. // TODO(cgruber) return customName + (formatted.isEmpty() ? "" : " (<" + formatted + ">)"); } else { return "<" + formatted + ">"; } } /** * Returns a string representation of the actual value. This will either be the toString() of the * value or a prefixed "name" along with the string representation. */ protected final String actualAsString() { return getDisplaySubject(); } /** * Supplies the direct string representation of the actual value to other methods which may prefix * or otherwise position it in an error message. This should only be overridden to provide an * improved string representation of the value under test, as it would appear in any given error * message, and should not be used for additional prefixing. * * <p>Subjects should override this with care. * * <p>By default, this returns {@code String.ValueOf(getActualValue())}. */ protected String actualCustomStringRepresentation() { return String.valueOf(actual()); } /** * Begins a new call chain based on the {@link FailureMetadata} of the current subject. By calling * this method, subject implementations can delegate to other subjects. For example, {@link * ThrowableSubject#hasMessageThat} is implemented with {@code * check().that(actual().getMessage()}, which returns a {@link StringSubject}. */ protected final StandardSubjectBuilder check() { return new StandardSubjectBuilder(metadata); } /** * Begins a new call chain that ignores any failures. This is useful for subjects that normally * delegate with to other subjects by using {@link #check} but have already reported a failure. In * such cases it may still be necessary to return a {@code Subject} instance even though any * subsequent assertions are meaningless. For example, if a user chains together more {@link * ThrowableSubject#hasCauseThat} calls than the actual exception has causes, {@code hasCauseThat} * returns {@code ignoreCheck().that(... a dummy exception ...)}. */ protected final StandardSubjectBuilder ignoreCheck() { return StandardSubjectBuilder.forCustomFailureStrategy(IGNORE_STRATEGY); } /** * Reports a failure constructing a message from a simple verb. * * @param check the check being asserted */ protected final void fail(String check) { metadata.fail("Not true that " + actualAsString() + " " + check); } /** * Assembles a failure message and passes such to the FailureStrategy. Also performs * disambiguation if the subject and {@code other} have the same toString()'s. * * @param verb the check being asserted * @param other the value against which the subject is compared */ protected final void fail(String verb, Object other) { failComparingToStrings(verb, actual(), other, other, false); } private void failComparingToStrings( String verb, Object actual, Object other, Object displayOther, boolean compareToStrings) { StringBuilder message = new StringBuilder("Not true that ").append(actualAsString()).append(" "); // If the actual and parts aren't null, and they have equal toString()'s but different // classes, we need to disambiguate them. boolean neitherNull = (other != null) && (actual != null); boolean sameToStrings = actualCustomStringRepresentation().equals(String.valueOf(other)); boolean needsClassDisambiguation = neitherNull && sameToStrings && !actual.getClass().equals(other.getClass()); if (needsClassDisambiguation) { message.append("(").append(actual.getClass().getName()).append(") "); } message.append(verb).append(" <").append(displayOther).append(">"); if (needsClassDisambiguation) { message.append(" (").append(other.getClass().getName()).append(")"); } if (!needsClassDisambiguation && sameToStrings && compareToStrings) { message.append(" (although their toString() representations are the same)"); } metadata.fail(message.toString()); } /** * Assembles a failure message and passes such to the FailureStrategy * * @param verb the check being asserted * @param messageParts the expectations against which the subject is compared */ protected final void fail(String verb, Object... messageParts) { // For backwards binary compatibility if (messageParts.length == 0) { fail(verb); } else if (messageParts.length == 1) { fail(verb, messageParts[0]); } else { StringBuilder message = new StringBuilder("Not true that "); message.append(actualAsString()).append(" ").append(verb); for (Object part : messageParts) { message.append(" <").append(part).append(">"); } metadata.fail(message.toString()); } } /** * Assembles a failure message and passes it to the FailureStrategy * * @param verb the check being asserted * @param expected the expectations against which the subject is compared * @param failVerb the failure of the check being asserted * @param actual the actual value the subject was compared against */ protected final void failWithBadResults( String verb, Object expected, String failVerb, Object actual) { String message = format( "Not true that %s %s <%s>. It %s <%s>", actualAsString(), verb, expected, failVerb, (actual == null) ? "null reference" : actual); metadata.fail(message); } /** * Assembles a failure message with an alternative representation of the wrapped subject and * passes it to the FailureStrategy * * @param verb the check being asserted * @param expected the expected value of the check * @param actual the custom representation of the subject to be reported in the failure. */ protected final void failWithCustomSubject(String verb, Object expected, Object actual) { String message = format( "Not true that <%s> %s <%s>", (actual == null) ? "null reference" : actual, verb, expected); metadata.fail(message); } /** @deprecated Use {@link #failWithoutActual(String)} */ @Deprecated protected final void failWithoutSubject(String check) { String strSubject = this.customName == null ? "the subject" : "\"" + customName + "\""; metadata.fail(format("Not true that %s %s", strSubject, check)); } /** * Assembles a failure message without a given subject and passes it to the FailureStrategy * * @param check the check being asserted */ protected final void failWithoutActual(String check) { failWithoutSubject(check); } /** * Passes through a failure message verbatim. Used for {@link Subject} subclasses which need to * provide alternate language for more fit-to-purpose error messages. * * @param message the message template to be passed to the failure. Note, this method only * guarantees to process {@code %s} tokens. It is not guaranteed to be compatible with {@code * String.format()}. Any other formatting desired (such as floats or scientific notation) * should be performed before the method call and the formatted value passed in as a string. * @param parameters the object parameters which will be applied to the message template. */ // TODO(cgruber) final protected void failWithRawMessage(String message, Object... parameters) { metadata.fail(format(message, parameters)); } /** Passes through a failure message verbatim, along with a cause. */ protected final void failWithRawMessageAndCause(String message, Throwable cause) { metadata.fail(message, cause); } /** * Passes through a failure message verbatim, along with the expected and actual values that the * {@link FailureStrategy} may use to construct a {@code ComparisonFailure}. */ protected final void failComparing(String message, CharSequence expected, CharSequence actual) { metadata.failComparing(message, expected, actual); } /** * Passes through a failure message verbatim, along with a cause and the expected and actual * values that the {@link FailureStrategy} may use to construct a {@code ComparisonFailure}. */ protected final void failComparing( String message, CharSequence expected, CharSequence actual, Throwable cause) { metadata.failComparing(message, expected, actual, cause); } /** * @throws UnsupportedOperationException always * @deprecated {@link Object#equals(Object)} is not supported on Truth subjects. If you meant to * test object equality between an expected and the actual value, use {@link * #isEqualTo(Object)} instead. */ @Deprecated @Override public final boolean equals(@Nullable Object o) { throw new UnsupportedOperationException( "If you meant to test object equality, use .isEqualTo(other) instead."); } /** * @throws UnsupportedOperationException always * @deprecated {@link Object#hashCode()} is not supported on Truth subjects. */ @Deprecated @Override public final int hashCode() { throw new UnsupportedOperationException("Subject.hashCode() is not supported."); } private static boolean classMetadataUnsupported() { // https://github.com/google/truth/issues/198 // TODO(cpovirk): Consider whether to remove instanceof tests under GWT entirely. // TODO(cpovirk): Run more Truth tests under GWT, and add tests for this. return String.class.getSuperclass() == null; } }
core/src/main/java/com/google/common/truth/Subject.java
/* * Copyright (c) 2011 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.truth; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.truth.StringUtil.format; import static com.google.common.truth.SubjectUtils.accumulate; import com.google.common.base.Objects; import com.google.common.base.Predicates; import com.google.common.collect.Iterables; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.util.Arrays; import java.util.List; import javax.annotation.Nullable; /** * An object that lets you perform checks on the value under test. For example, {@code Subject} * contains {@link #isEqualTo(Object)} and {@link #isInstanceOf(Class)}, and {@link StringSubject} * contains {@link StringSubject#startsWith startsWith(String)}. * * <p>To create a {@code Subject} instance, most users will call an {@link Truth#assertThat * assertThat} method. For information about other ways to create an instance, see <a * href="https://google.github.io/truth/faq#full-chain">this FAQ entry</a>. * * <h3>For people extending Truth</h3> * * <p>For information about writing a custom {@link Subject}, see <a * href="https://google.github.io/truth/extension">our doc on extensions</a>. * * @param <S> the self-type, allowing {@code this}-returning methods to avoid needing subclassing * @param <T> the type of the object being tested by this {@code Subject} * @author David Saff * @author Christian Gruber */ public class Subject<S extends Subject<S, T>, T> { /** * In a fluent assertion chain, the argument to the common overload of {@link * StandardSubjectBuilder#about(Subject.Factory) about}, the method that specifies what kind of * {@link Subject} to create. * * <p>For more information about the fluent chain, see <a * href="https://google.github.io/truth/faq#full-chain">this FAQ entry</a>. * * <h3>For people extending Truth</h3> * * <p>When you write a custom subject, see <a href="https://google.github.io/truth/extension">our doc on * extensions</a>. It explains where {@code Subject.Factory} fits into the process. */ public interface Factory<SubjectT extends Subject<SubjectT, ActualT>, ActualT> { /** Creates a new {@link Subject}. */ SubjectT createSubject(FailureMetadata metadata, ActualT actual); } private static final FailureStrategy IGNORE_STRATEGY = new AbstractFailureStrategy() { @Override public void fail(String message, Throwable cause) {} }; private final FailureMetadata metadata; private final T actual; private String customName = null; /** * Constructor for use by subclasses. If you want to create an instance of this class itself, call * {@link Subject#check}{@code .that(actual)}. */ protected Subject(FailureMetadata metadata, @Nullable T actual) { this.metadata = actual instanceof Throwable ? metadata.offerRootCause((Throwable) actual) : metadata; this.actual = actual; } /** An internal method used to obtain the value set by {@link #named(String, Object...)}. */ protected String internalCustomName() { return customName; } /** * Adds a prefix to the subject, when it is displayed in error messages. This is especially useful * in the context of types that have no helpful {@code toString()} representation, e.g. boolean. * Writing {@code assertThat(foo).named("foo").isTrue();} then results in a more reasonable error * message. * * <p>{@code named()} takes a format template and argument objects which will be substituted into * the template, similar to {@link String#format(String, Object...)}, the chief difference being * that extra parameters (for which there are no template variables) will be appended to the * resulting string in brackets. Additionally, this only supports the {@code %s} template variable * type. */ @SuppressWarnings("unchecked") @CanIgnoreReturnValue public S named(String format, Object... args) { checkNotNull(format, "Name passed to named() cannot be null."); this.customName = StringUtil.format(format, args); return (S) this; } /** Fails if the subject is not null. */ public void isNull() { if (actual() != null) { fail("is null"); } } /** Fails if the subject is null. */ public void isNotNull() { if (actual() == null) { failWithoutActual("is a non-null reference"); } } /** * Fails if the subject is not equal to the given object. For the purposes of this comparison, two * objects are equal if any of the following is true: * * <ul> * <li>they are equal according to {@link Objects#equal} * <li>they are arrays and are considered equal by the appropriate {@link Arrays#equals} * overload * <li>they are boxed integer types ({@code Byte}, {@code Short}, {@code Character}, {@code * Integer}, or {@code Long}) and they are numerically equal when converted to {@code Long}. * </ul> */ public void isEqualTo(@Nullable Object other) { doEqualCheck(actual(), other, true); } /** * Fails if the subject is equal to the given object. The meaning of equality is the same as for * the {@link #isEqualTo} method. */ public void isNotEqualTo(@Nullable Object other) { doEqualCheck(actual(), other, false); } private void doEqualCheck( @Nullable Object rawActual, @Nullable Object rawOther, boolean expectEqual) { Object actual; Object other; boolean actualEqual; if (isIntegralBoxedPrimitive(rawActual) && isIntegralBoxedPrimitive(rawOther)) { actual = integralValue(rawActual); other = integralValue(rawOther); actualEqual = Objects.equal(actual, other); } else { actual = rawActual; other = rawOther; if (rawActual instanceof Double && rawOther instanceof Double) { actualEqual = Double.compare((Double) rawActual, (Double) rawOther) == 0; } else if (rawActual instanceof Float && rawOther instanceof Float) { actualEqual = Float.compare((Float) rawActual, (Float) rawOther) == 0; } else { actualEqual = Objects.equal(actual, other); } } if (actualEqual != expectEqual) { failComparingToStrings( expectEqual ? "is equal to" : "is not equal to", actual, other, rawOther, expectEqual); } } private static boolean isIntegralBoxedPrimitive(@Nullable Object o) { return o instanceof Byte || o instanceof Short || o instanceof Character || o instanceof Integer || o instanceof Long; } private static Long integralValue(Object o) { if (o instanceof Character) { return (long) ((Character) o).charValue(); } else if (o instanceof Number) { return ((Number) o).longValue(); } else { throw new AssertionError(o + " must be either a Character or a Number."); } } /** Fails if the subject is not the same instance as the given object. */ public void isSameAs(@Nullable Object other) { if (actual() != other) { failComparingToStrings("is the same instance as", actual(), other, other, true); } } /** Fails if the subject is the same instance as the given object. */ public void isNotSameAs(@Nullable Object other) { if (actual() == other) { fail("is not the same instance as", other); } } /** Fails if the subject is not an instance of the given class. */ public void isInstanceOf(Class<?> clazz) { if (clazz == null) { throw new NullPointerException("clazz"); } if (!Platform.isInstanceOfType(actual(), clazz)) { if (actual() != null) { if (classMetadataUnsupported()) { throw new UnsupportedOperationException( actualAsString() + ", an instance of " + actual().getClass().getName() + ", may or may not be an instance of " + clazz.getName() + ". Under -XdisableClassMetadata, we do not have enough information to tell."); } failWithBadResults( "is an instance of", clazz.getName(), "is an instance of", actual().getClass().getName()); } else { fail("is an instance of", clazz.getName()); } } } /** Fails if the subject is an instance of the given class. */ public void isNotInstanceOf(Class<?> clazz) { if (clazz == null) { throw new NullPointerException("clazz"); } if (classMetadataUnsupported()) { throw new UnsupportedOperationException( "isNotInstanceOf is not supported under -XdisableClassMetadata"); } if (actual() == null) { return; // null is not an instance of clazz. } if (Platform.isInstanceOfType(actual(), clazz)) { failWithRawMessage( "%s expected not to be an instance of %s, but was.", actualAsString(), clazz.getName()); } } /** Fails unless the subject is equal to any element in the given iterable. */ public void isIn(Iterable<?> iterable) { if (!Iterables.contains(iterable, actual())) { fail("is equal to any element in", iterable); } } /** Fails unless the subject is equal to any of the given elements. */ public void isAnyOf(@Nullable Object first, @Nullable Object second, @Nullable Object... rest) { List<Object> list = accumulate(first, second, rest); if (!list.contains(actual())) { fail("is equal to any of", list); } } /** Fails if the subject is equal to any element in the given iterable. */ public void isNotIn(Iterable<?> iterable) { int index = Iterables.indexOf(iterable, Predicates.<Object>equalTo(actual())); if (index != -1) { failWithRawMessage( "Not true that %s is not in %s. It was found at index %s", actualAsString(), iterable, index); } } /** Fails if the subject is equal to any of the given elements. */ public void isNoneOf(@Nullable Object first, @Nullable Object second, @Nullable Object... rest) { isNotIn(accumulate(first, second, rest)); } /** @deprecated Prefer {@code #actual()} for direct access to the subject. */ @Deprecated protected T getSubject() { // TODO(cgruber): move functionality to actual() and delete when no callers. return actual; } /** Returns the unedited, unformatted raw actual value. */ protected final T actual() { return getSubject(); } /** @deprecated Prefer {@code #actualAsString()} for display-formatted access to the subject. */ @Deprecated protected String getDisplaySubject() { // TODO(cgruber) migrate people from this method once no one is subclassing it. String formatted = actualCustomStringRepresentation(); if (customName != null) { // Covers some rare cases where a type might return "" from their custom formatter. // This is actually pretty terrible, as it comes from subjects overriding (formerly) // getDisplaySubject() in cases of .named() to make it not prefixing but replacing. // That goes against the stated contract of .named(). Once displayedAs() is in place, // we can rip this out and callers can use that instead. // TODO(cgruber) return customName + (formatted.isEmpty() ? "" : " (<" + formatted + ">)"); } else { return "<" + formatted + ">"; } } /** * Returns a string representation of the actual value. This will either be the toString() of the * value or a prefixed "name" along with the string representation. */ protected final String actualAsString() { return getDisplaySubject(); } /** * Supplies the direct string representation of the actual value to other methods which may prefix * or otherwise position it in an error message. This should only be overridden to provide an * improved string representation of the value under test, as it would appear in any given error * message, and should not be used for additional prefixing. * * <p>Subjects should override this with care. * * <p>By default, this returns {@code String.ValueOf(getActualValue())}. */ protected String actualCustomStringRepresentation() { return String.valueOf(actual()); } /** * Begins a new call chain based on the {@link FailureMetadata} of the current subject. By calling * this method, subject implementations can delegate to other subjects. For example, {@link * ThrowableSubject#hasMessageThat} is implemented with {@code * check().that(actual().getMessage()}, which returns a {@link StringSubject}. */ // TODO(diamondm) this should be final, can we do that safely? protected StandardSubjectBuilder check() { return new StandardSubjectBuilder(metadata); } /** * Begins a new call chain that ignores any failures. This is useful for subjects that normally * delegate with to other subjects by using {@link #check} but have already reported a failure. In * such cases it may still be necessary to return a {@code Subject} instance even though any * subsequent assertions are meaningless. For example, if a user chains together more {@link * ThrowableSubject#hasCauseThat} calls than the actual exception has causes, {@code hasCauseThat} * returns {@code ignoreCheck().that(... a dummy exception ...)}. */ protected final StandardSubjectBuilder ignoreCheck() { return StandardSubjectBuilder.forCustomFailureStrategy(IGNORE_STRATEGY); } /** * Reports a failure constructing a message from a simple verb. * * @param check the check being asserted */ protected final void fail(String check) { metadata.fail("Not true that " + actualAsString() + " " + check); } /** * Assembles a failure message and passes such to the FailureStrategy. Also performs * disambiguation if the subject and {@code other} have the same toString()'s. * * @param verb the check being asserted * @param other the value against which the subject is compared */ protected final void fail(String verb, Object other) { failComparingToStrings(verb, actual(), other, other, false); } private void failComparingToStrings( String verb, Object actual, Object other, Object displayOther, boolean compareToStrings) { StringBuilder message = new StringBuilder("Not true that ").append(actualAsString()).append(" "); // If the actual and parts aren't null, and they have equal toString()'s but different // classes, we need to disambiguate them. boolean neitherNull = (other != null) && (actual != null); boolean sameToStrings = actualCustomStringRepresentation().equals(String.valueOf(other)); boolean needsClassDisambiguation = neitherNull && sameToStrings && !actual.getClass().equals(other.getClass()); if (needsClassDisambiguation) { message.append("(").append(actual.getClass().getName()).append(") "); } message.append(verb).append(" <").append(displayOther).append(">"); if (needsClassDisambiguation) { message.append(" (").append(other.getClass().getName()).append(")"); } if (!needsClassDisambiguation && sameToStrings && compareToStrings) { message.append(" (although their toString() representations are the same)"); } metadata.fail(message.toString()); } /** * Assembles a failure message and passes such to the FailureStrategy * * @param verb the check being asserted * @param messageParts the expectations against which the subject is compared */ protected final void fail(String verb, Object... messageParts) { // For backwards binary compatibility if (messageParts.length == 0) { fail(verb); } else if (messageParts.length == 1) { fail(verb, messageParts[0]); } else { StringBuilder message = new StringBuilder("Not true that "); message.append(actualAsString()).append(" ").append(verb); for (Object part : messageParts) { message.append(" <").append(part).append(">"); } metadata.fail(message.toString()); } } /** * Assembles a failure message and passes it to the FailureStrategy * * @param verb the check being asserted * @param expected the expectations against which the subject is compared * @param failVerb the failure of the check being asserted * @param actual the actual value the subject was compared against */ protected final void failWithBadResults( String verb, Object expected, String failVerb, Object actual) { String message = format( "Not true that %s %s <%s>. It %s <%s>", actualAsString(), verb, expected, failVerb, (actual == null) ? "null reference" : actual); metadata.fail(message); } /** * Assembles a failure message with an alternative representation of the wrapped subject and * passes it to the FailureStrategy * * @param verb the check being asserted * @param expected the expected value of the check * @param actual the custom representation of the subject to be reported in the failure. */ protected final void failWithCustomSubject(String verb, Object expected, Object actual) { String message = format( "Not true that <%s> %s <%s>", (actual == null) ? "null reference" : actual, verb, expected); metadata.fail(message); } /** @deprecated Use {@link #failWithoutActual(String)} */ @Deprecated protected final void failWithoutSubject(String check) { String strSubject = this.customName == null ? "the subject" : "\"" + customName + "\""; metadata.fail(format("Not true that %s %s", strSubject, check)); } /** * Assembles a failure message without a given subject and passes it to the FailureStrategy * * @param check the check being asserted */ protected final void failWithoutActual(String check) { failWithoutSubject(check); } /** * Passes through a failure message verbatim. Used for {@link Subject} subclasses which need to * provide alternate language for more fit-to-purpose error messages. * * @param message the message template to be passed to the failure. Note, this method only * guarantees to process {@code %s} tokens. It is not guaranteed to be compatible with {@code * String.format()}. Any other formatting desired (such as floats or scientific notation) * should be performed before the method call and the formatted value passed in as a string. * @param parameters the object parameters which will be applied to the message template. */ // TODO(cgruber) final protected void failWithRawMessage(String message, Object... parameters) { metadata.fail(format(message, parameters)); } /** Passes through a failure message verbatim, along with a cause. */ protected final void failWithRawMessageAndCause(String message, Throwable cause) { metadata.fail(message, cause); } /** * Passes through a failure message verbatim, along with the expected and actual values that the * {@link FailureStrategy} may use to construct a {@code ComparisonFailure}. */ protected final void failComparing(String message, CharSequence expected, CharSequence actual) { metadata.failComparing(message, expected, actual); } /** * Passes through a failure message verbatim, along with a cause and the expected and actual * values that the {@link FailureStrategy} may use to construct a {@code ComparisonFailure}. */ protected final void failComparing( String message, CharSequence expected, CharSequence actual, Throwable cause) { metadata.failComparing(message, expected, actual, cause); } /** * @throws UnsupportedOperationException always * @deprecated {@link Object#equals(Object)} is not supported on Truth subjects. If you meant to * test object equality between an expected and the actual value, use {@link * #isEqualTo(Object)} instead. */ @Deprecated @Override public final boolean equals(@Nullable Object o) { throw new UnsupportedOperationException( "If you meant to test object equality, use .isEqualTo(other) instead."); } /** * @throws UnsupportedOperationException always * @deprecated {@link Object#hashCode()} is not supported on Truth subjects. */ @Deprecated @Override public final int hashCode() { throw new UnsupportedOperationException("Subject.hashCode() is not supported."); } private static boolean classMetadataUnsupported() { // https://github.com/google/truth/issues/198 // TODO(cpovirk): Consider whether to remove instanceof tests under GWT entirely. // TODO(cpovirk): Run more Truth tests under GWT, and add tests for this. return String.class.getSuperclass() == null; } }
Make check() final. No one overrides it, and no one should. RELNOTES=Made `StandardSubjectBuilder.check()` final. ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=179961554
core/src/main/java/com/google/common/truth/Subject.java
Make check() final.
Java
apache-2.0
aa702e30e5666d916da3c6fb3ee9b26198e5cc63
0
apache/derby,trejkaz/derby,apache/derby,trejkaz/derby,apache/derby,apache/derby,trejkaz/derby
/* * * Derby - Class org.apache.derbyTesting.functionTests.util.JDBC * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ package org.apache.derbyTesting.junit; import java.sql.*; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import junit.framework.Assert; /** * JDBC utility methods for the JUnit tests. * */ public class JDBC { /** * Tell if we are allowed to use DriverManager to create database * connections. */ private static final boolean HAVE_DRIVER = haveClass("java.sql.Driver"); /** * Does the Savepoint class exist, indicates * JDBC 3 (or JSR 169). */ private static final boolean HAVE_SAVEPOINT = haveClass("java.sql.Savepoint"); /** * Does the java.sql.SQLXML class exist, indicates JDBC 4. */ private static final boolean HAVE_SQLXML = haveClass("java.sql.SQLXML"); /** * Can we load a specific class, use this to determine JDBC level. * @param className Class to attempt load on. * @return true if class can be loaded, false otherwise. */ protected static boolean haveClass(String className) { try { Class.forName(className); return true; } catch (Exception e) { return false; } } /** * <p> * Return true if the virtual machine environment * supports JDBC4 or later. * </p> */ public static boolean vmSupportsJDBC4() { return HAVE_DRIVER && HAVE_SQLXML; } /** * <p> * Return true if the virtual machine environment * supports JDBC3 or later. * </p> */ public static boolean vmSupportsJDBC3() { return HAVE_DRIVER && HAVE_SAVEPOINT; } /** * <p> * Return true if the virtual machine environment * supports JDBC2 or later. * </p> */ public static boolean vmSupportsJDBC2() { return HAVE_DRIVER; } /** * <p> * Return true if the virtual machine environment * supports JSR169 (JDBC 3 subset). * </p> */ public static boolean vmSupportsJSR169() { return !HAVE_DRIVER && HAVE_SAVEPOINT; } /** * Rollback and close a connection for cleanup. * Test code that is expecting Connection.close to succeed * normally should just call conn.close(). * * <P> * If conn is not-null and isClosed() returns false * then both rollback and close will be called. * If both methods throw exceptions * then they will be chained together and thrown. * @throws SQLException Error closing connection. */ public static void cleanup(Connection conn) throws SQLException { if (conn == null) return; if (conn.isClosed()) return; SQLException sqle = null; try { conn.rollback(); } catch (SQLException e) { sqle = e; } try { conn.close(); } catch (SQLException e) { if (sqle == null) sqle = e; else sqle.setNextException(e); throw sqle; } } /** * Drop a database schema by dropping all objects in it * and then executing DROP SCHEMA. If the schema is * APP it is cleaned but DROP SCHEMA is not executed. * * TODO: Handle dependencies by looping in some intelligent * way until everything can be dropped. * * * @param dmd DatabaseMetaData object for database * @param schema Name of the schema * @throws SQLException database error */ public static void dropSchema(DatabaseMetaData dmd, String schema) throws SQLException { Connection conn = dmd.getConnection(); Assert.assertFalse(conn.getAutoCommit()); Statement s = dmd.getConnection().createStatement(); // Functions - not supported by JDBC meta data until JDBC 4 PreparedStatement psf = conn.prepareStatement( "SELECT ALIAS FROM SYS.SYSALIASES A, SYS.SYSSCHEMAS S" + " WHERE A.SCHEMAID = S.SCHEMAID " + " AND A.ALIASTYPE = 'F' " + " AND S.SCHEMANAME = ?"); psf.setString(1, schema); ResultSet rs = psf.executeQuery(); dropUsingDMD(s, rs, schema, "ALIAS", "FUNCTION"); psf.close(); // Procedures rs = dmd.getProcedures((String) null, schema, (String) null); dropUsingDMD(s, rs, schema, "PROCEDURE_NAME", "PROCEDURE"); // Views rs = dmd.getTables((String) null, schema, (String) null, new String[] {"VIEW"}); dropUsingDMD(s, rs, schema, "TABLE_NAME", "VIEW"); // Tables rs = dmd.getTables((String) null, schema, (String) null, new String[] {"TABLE"}); dropUsingDMD(s, rs, schema, "TABLE_NAME", "TABLE"); // At this point there may be tables left due to // foreign key constraints leading to a dependency loop. // Drop any constraints that remain and then drop the tables. // If there are no tables then this should be a quick no-op. rs = dmd.getExportedKeys((String) null, schema, (String) null); while (rs.next()) { short keyPosition = rs.getShort("KEY_SEQ"); if (keyPosition != 1) continue; String fkName = rs.getString("FK_NAME"); // No name, probably can't happen but couldn't drop it anyway. if (fkName == null) continue; String fkSchema = rs.getString("FKTABLE_SCHEM"); String fkTable = rs.getString("FKTABLE_NAME"); String ddl = "ALTER TABLE " + JDBC.escape(fkSchema, fkTable) + " DROP FOREIGN KEY " + JDBC.escape(fkName); s.executeUpdate(ddl); } rs.close(); conn.commit(); // Tables (again) rs = dmd.getTables((String) null, schema, (String) null, new String[] {"TABLE"}); dropUsingDMD(s, rs, schema, "TABLE_NAME", "TABLE"); // Synonyms - need work around for DERBY-1790 where // passing a table type of SYNONYM fails. rs = dmd.getTables((String) null, schema, (String) null, new String[] {"AA_DERBY-1790-SYNONYM"}); dropUsingDMD(s, rs, schema, "TABLE_NAME", "SYNONYM"); // Finally drop the schema if it is not APP if (!schema.equals("APP")) { s.executeUpdate("DROP SCHEMA " + JDBC.escape(schema) + " RESTRICT"); } conn.commit(); s.close(); } /** * DROP a set of objects based upon a ResultSet from a * DatabaseMetaData call. * * TODO: Handle errors to ensure all objects are dropped, * probably requires interaction with its caller. * * @param s Statement object used to execute the DROP commands. * @param rs DatabaseMetaData ResultSet * @param schema Schema the objects are contained in * @param mdColumn The column name used to extract the object's * name from rs * @param dropType The keyword to use after DROP in the SQL statement * @throws SQLException database errors. */ private static void dropUsingDMD( Statement s, ResultSet rs, String schema, String mdColumn, String dropType) throws SQLException { String dropLeadIn = "DROP " + dropType + " "; // First collect the set of DROP SQL statements. ArrayList ddl = new ArrayList(); while (rs.next()) { String objectName = rs.getString(mdColumn); ddl.add(dropLeadIn + JDBC.escape(schema, objectName)); } rs.close(); // Execute them as a complete batch, hoping they will all succeed. s.clearBatch(); int batchCount = 0; for (Iterator i = ddl.iterator(); i.hasNext(); ) { Object sql = i.next(); if (sql != null) { s.addBatch(sql.toString()); batchCount++; } } int[] results; boolean hadError; try { results = s.executeBatch(); Assert.assertNotNull(results); Assert.assertEquals("Incorrect result length from executeBatch", batchCount, results.length); hadError = false; } catch (BatchUpdateException batchException) { results = batchException.getUpdateCounts(); Assert.assertNotNull(results); Assert.assertTrue("Too many results in BatchUpdateException", results.length <= batchCount); hadError = true; } // Remove any statements from the list that succeeded. boolean didDrop = false; for (int i = 0; i < results.length; i++) { int result = results[i]; if (result == -3 /* Statement.EXECUTE_FAILED*/) hadError = true; else if (result == -2/*Statement.SUCCESS_NO_INFO*/) didDrop = true; else if (result >= 0) didDrop = true; else Assert.fail("Negative executeBatch status"); if (didDrop) ddl.set(i, null); } s.clearBatch(); if (didDrop) { // Commit any work we did do. s.getConnection().commit(); } // If we had failures drop them as individual statements // until there are none left or none succeed. We need to // do this because the batch processing stops at the first // error. This copes with the simple case where there // are objects of the same type that depend on each other // and a different drop order will allow all or most // to be dropped. if (hadError) { do { hadError = false; didDrop = false; for (ListIterator i = ddl.listIterator(); i.hasNext();) { Object sql = i.next(); if (sql != null) { try { s.executeUpdate(sql.toString()); i.set(null); didDrop = true; } catch (SQLException e) { hadError = true; } } } if (didDrop) s.getConnection().commit(); } while (hadError && didDrop); } } /** * Assert all columns in the ResultSetMetaData match the * table's defintion through DatabaseMetadDta. Only works * if the complete select list correspond to columns from * base tables. * <BR> * Does not require that the complete set of any table's columns are * returned. * @throws SQLException * */ public static void assertMetaDataMatch(DatabaseMetaData dmd, ResultSetMetaData rsmd) throws SQLException { for (int col = 1; col <= rsmd.getColumnCount(); col++) { // Only expect a single column back ResultSet column = dmd.getColumns( rsmd.getCatalogName(col), rsmd.getSchemaName(col), rsmd.getTableName(col), rsmd.getColumnName(col)); Assert.assertTrue("Column missing " + rsmd.getColumnName(col), column.next()); Assert.assertEquals(column.getInt("DATA_TYPE"), rsmd.getColumnType(col)); Assert.assertEquals(column.getInt("NULLABLE"), rsmd.isNullable(col)); Assert.assertEquals(column.getString("TYPE_NAME"), rsmd.getColumnTypeName(col)); column.close(); } } /** * Drain a single ResultSet by reading all of its * rows and columns. Each column is accessed using * getString() and asserted that the returned value * matches the state of ResultSet.wasNull(). * * Provides simple testing of the ResultSet when the * contents are not important. * * @param rs Result set to drain. * @throws SQLException */ public static void assertDrainResults(ResultSet rs) throws SQLException { assertDrainResults(rs, -1); } /** * Does the work of assertDrainResults() as described * above. If the received row count is non-negative, * this method also asserts that the number of rows * in the result set matches the received row count. * * @param rs Result set to drain. * @param expectedRows If non-negative, indicates how * many rows we expected to see in the result set. * @throws SQLException */ public static void assertDrainResults(ResultSet rs, int expectedRows) throws SQLException { ResultSetMetaData rsmd = rs.getMetaData(); int rows = 0; while (rs.next()) { for (int col = 1; col <= rsmd.getColumnCount(); col++) { String s = rs.getString(col); Assert.assertEquals(s == null, rs.wasNull()); } rows++; } rs.close(); if (expectedRows >= 0) Assert.assertEquals("Unexpected row count:", expectedRows, rows); } /** * Takes a result set and an array of expected colum names (as * Strings) and asserts that the column names in the result * set metadata match the number, order, and names of those * in the array. * * @param rs ResultSet for which we're checking column names. * @param expectedColNames Array of expected column names. */ public static void assertColumnNames(ResultSet rs, String [] expectedColNames) throws SQLException { ResultSetMetaData rsmd = rs.getMetaData(); int actualCols = rsmd.getColumnCount(); Assert.assertEquals("Unexpected column count:", expectedColNames.length, rsmd.getColumnCount()); for (int i = 0; i < actualCols; i++) { Assert.assertEquals("Column names do not match:", expectedColNames[i], rsmd.getColumnName(i+1)); } } /** * Asserts a ResultSet returns a single row with a single * column equal to the passed in String value. The value can * be null to indicate SQL NULL. The comparision is make * using assertFullResultSet in trimmed string mode. */ public static void assertSingleValueResultSet(ResultSet rs, String value) throws SQLException { String[] row = new String[] {value}; String[][] set = new String[][] {row}; assertFullResultSet(rs, set); } /** * assertFullResultSet() using trimmed string comparisions. * Equal to * <code> * assertFullResultSet(rs, expectedRows, true) * </code> */ public static void assertFullResultSet(ResultSet rs, String [][] expectedRows) throws SQLException { assertFullResultSet(rs, expectedRows, true); } /** * Takes a result set and a two-dimensional array and asserts * that the rows and columns in the result set match the number, * order, and values of those in the array. Each row in * the array is compared with the corresponding row in the * result set. * * Will throw an assertion failure if any of the following * is true: * * 1. Expected vs actual number of columns doesn't match * 2. Expected vs actual number of rows doesn't match * 3. Any column in any row of the result set does not "equal" * the corresponding column in the expected 2-d array. If * "allAsTrimmedStrings" is true then the result set value * will be retrieved as a String and compared, via the ".equals()" * method, to the corresponding object in the array (with the * assumption being that the objects in the array are all * Strings). Otherwise the result set value will be retrieved * and compared as an Object, which is useful when asserting * the JDBC types of the columns in addition to their values. * * NOTE: It follows from #3 that the order of the rows in the * in received result set must match the order of the rows in * the received 2-d array. Otherwise the result will be an * assertion failure. * * @param rs The actual result set. * @param expectedRows 2-Dimensional array of objects representing * the expected result set. * @param allAsTrimmedStrings Whether or not to fetch (and compare) * all values from the actual result set as trimmed Strings; if * false the values will be fetched and compared as Objects. For * more on how this parameter is used, see assertRowInResultSet(). */ public static void assertFullResultSet(ResultSet rs, Object [][] expectedRows, boolean allAsTrimmedStrings) throws SQLException { int rows; ResultSetMetaData rsmd = rs.getMetaData(); // Assert that we have the right number of columns. Assert.assertEquals("Unexpected column count:", expectedRows[0].length, rsmd.getColumnCount()); for (rows = 0; rs.next(); rows++) { /* If we have more actual rows than expected rows, don't * try to assert the row. Instead just keep iterating * to see exactly how many rows the actual result set has. */ if (rows < expectedRows.length) { assertRowInResultSet(rs, rows + 1, expectedRows[rows], allAsTrimmedStrings); } } // And finally, assert the row count. Assert.assertEquals("Unexpected row count:", expectedRows.length, rows); } /** * Assert that every column in the current row of the received * result set matches the corresponding column in the received * array. This means that the order of the columns in the result * set must match the order of the values in expectedRow. * * <p> * If the expected value for a given row/column is a SQL NULL, * then the corresponding value in the array should be a Java * null. * * <p> * If a given row/column could have different values (for instance, * because it contains a timestamp), the expected value of that * row/column could be an object whose <code>equals()</code> method * returns <code>true</code> for all acceptable values. (This does * not work if one of the acceptable values is <code>null</code>.) * * @param rs Result set whose current row we'll check. * @param rowNum Row number (w.r.t expected rows) that we're * checking. * @param expectedRow Array of objects representing the expected * values for the current row. * @param asTrimmedStrings Whether or not to fetch and compare * all values from "rs" as trimmed Strings. If true then the * value from rs.getString() AND the expected value will both * be trimmed before comparison. If such trimming is not * desired (ex. if we were testing the padding of CHAR columns) * then this param should be FALSE and the expected values in * the received array should include the expected whitespace. * If for example the caller wants to check the padding of a * CHAR(8) column, asTrimmedStrings should be FALSE and the * expected row should contain the expected padding, such as * "FRED ". */ private static void assertRowInResultSet(ResultSet rs, int rowNum, Object [] expectedRow, boolean asTrimmedStrings) throws SQLException { ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 0; i < expectedRow.length; i++) { Object obj; if (asTrimmedStrings) { // Trim the expected value, if non-null. if (expectedRow[i] != null) expectedRow[i] = ((String)expectedRow[i]).trim(); /* Different clients can return different values for * boolean columns--namely, 0/1 vs false/true. So in * order to keep things uniform, take boolean columns * and get the JDBC string version. Note: since * Derby doesn't have a BOOLEAN type, we assume that * if the column's type is SMALLINT and the expected * value's string form is "true" or "false", then the * column is intended to be a mock boolean column. */ if ((expectedRow[i] != null) && (rsmd.getColumnType(i+1) == Types.SMALLINT)) { String s = expectedRow[i].toString(); if (s.equals("true") || s.equals("false")) obj = (rs.getShort(i+1) == 0) ? "false" : "true"; else obj = rs.getString(i+1); } else { obj = rs.getString(i+1); } // Trim the rs string. if (obj != null) obj = ((String)obj).trim(); } else obj = rs.getObject(i+1); boolean ok = (rs.wasNull() && (expectedRow[i] == null)) || (!rs.wasNull() && (expectedRow[i] != null) && expectedRow[i].equals(obj)); if (!ok) { Assert.fail("Column value mismatch @ column '" + rsmd.getColumnName(i+1) + "', row " + rowNum + ":\n Expected: >" + expectedRow[i] + "<\n Found: >" + obj + "<"); } } } /** * Escape a non-qualified name so that it is suitable * for use in a SQL query executed by JDBC. */ public static String escape(String name) { return "\"" + name + "\""; } /** * Escape a schama-qualified name so that it is suitable * for use in a SQL query executed by JDBC. */ public static String escape(String schema, String name) { return "\"" + schema + "\".\"" + name + "\""; } }
java/testing/org/apache/derbyTesting/junit/JDBC.java
/* * * Derby - Class org.apache.derbyTesting.functionTests.util.JDBC * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ package org.apache.derbyTesting.junit; import java.sql.*; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import junit.framework.Assert; /** * JDBC utility methods for the JUnit tests. * */ public class JDBC { /** * Tell if we are allowed to use DriverManager to create database * connections. */ private static final boolean HAVE_DRIVER = haveClass("java.sql.Driver"); /** * Does the Savepoint class exist, indicates * JDBC 3 (or JSR 169). */ private static final boolean HAVE_SAVEPOINT = haveClass("java.sql.Savepoint"); /** * Does the java.sql.SQLXML class exist, indicates JDBC 4. */ private static final boolean HAVE_SQLXML = haveClass("java.sql.SQLXML"); /** * Can we load a specific class, use this to determine JDBC level. * @param className Class to attempt load on. * @return true if class can be loaded, false otherwise. */ protected static boolean haveClass(String className) { try { Class.forName(className); return true; } catch (Exception e) { return false; } } /** * <p> * Return true if the virtual machine environment * supports JDBC4 or later. * </p> */ public static boolean vmSupportsJDBC4() { return HAVE_DRIVER && HAVE_SQLXML; } /** * <p> * Return true if the virtual machine environment * supports JDBC3 or later. * </p> */ public static boolean vmSupportsJDBC3() { return HAVE_DRIVER && HAVE_SAVEPOINT; } /** * <p> * Return true if the virtual machine environment * supports JDBC2 or later. * </p> */ public static boolean vmSupportsJDBC2() { return HAVE_DRIVER; } /** * <p> * Return true if the virtual machine environment * supports JSR169 (JDBC 3 subset). * </p> */ public static boolean vmSupportsJSR169() { return !HAVE_DRIVER && HAVE_SAVEPOINT; } /** * Rollback and close a connection for cleanup. * Test code that is expecting Connection.close to succeed * normally should just call conn.close(). * * <P> * If conn is not-null and isClosed() returns false * then both rollback and close will be called. * If both methods throw exceptions * then they will be chained together and thrown. * @throws SQLException Error closing connection. */ public static void cleanup(Connection conn) throws SQLException { if (conn == null) return; if (conn.isClosed()) return; SQLException sqle = null; try { conn.rollback(); } catch (SQLException e) { sqle = e; } try { conn.close(); } catch (SQLException e) { if (sqle == null) sqle = e; else sqle.setNextException(e); throw sqle; } } /** * Drop a database schema by dropping all objects in it * and then executing DROP SCHEMA. If the schema is * APP it is cleaned but DROP SCHEMA is not executed. * * TODO: Handle dependencies by looping in some intelligent * way until everything can be dropped. * * * @param dmd DatabaseMetaData object for database * @param schema Name of the schema * @throws SQLException database error */ public static void dropSchema(DatabaseMetaData dmd, String schema) throws SQLException { Connection conn = dmd.getConnection(); Assert.assertFalse(conn.getAutoCommit()); Statement s = dmd.getConnection().createStatement(); // Functions - not supported by JDBC meta data until JDBC 4 PreparedStatement psf = conn.prepareStatement( "SELECT ALIAS FROM SYS.SYSALIASES A, SYS.SYSSCHEMAS S" + " WHERE A.SCHEMAID = S.SCHEMAID " + " AND A.ALIASTYPE = 'F' " + " AND S.SCHEMANAME = ?"); psf.setString(1, schema); ResultSet rs = psf.executeQuery(); dropUsingDMD(s, rs, schema, "ALIAS", "FUNCTION"); psf.close(); // Procedures rs = dmd.getProcedures((String) null, schema, (String) null); dropUsingDMD(s, rs, schema, "PROCEDURE_NAME", "PROCEDURE"); // Views rs = dmd.getTables((String) null, schema, (String) null, new String[] {"VIEW"}); dropUsingDMD(s, rs, schema, "TABLE_NAME", "VIEW"); // Tables rs = dmd.getTables((String) null, schema, (String) null, new String[] {"TABLE"}); dropUsingDMD(s, rs, schema, "TABLE_NAME", "TABLE"); // At this point there may be tables left due to // foreign key constraints leading to a dependency loop. // Drop any constraints that remain and then drop the tables. // If there are no tables then this should be a quick no-op. rs = dmd.getExportedKeys((String) null, schema, (String) null); while (rs.next()) { short keyPosition = rs.getShort("KEY_SEQ"); if (keyPosition != 1) continue; String fkName = rs.getString("FK_NAME"); // No name, probably can't happen but couldn't drop it anyway. if (fkName == null) continue; String fkSchema = rs.getString("FKTABLE_SCHEM"); String fkTable = rs.getString("FKTABLE_NAME"); String ddl = "ALTER TABLE " + JDBC.escape(fkSchema, fkTable) + " DROP FOREIGN KEY " + JDBC.escape(fkName); s.executeUpdate(ddl); } conn.commit(); // Tables (again) rs = dmd.getTables((String) null, schema, (String) null, new String[] {"TABLE"}); dropUsingDMD(s, rs, schema, "TABLE_NAME", "TABLE"); // Synonyms - need work around for DERBY-1790 where // passing a table type of SYNONYM fails. rs = dmd.getTables((String) null, schema, (String) null, new String[] {"AA_DERBY-1790-SYNONYM"}); dropUsingDMD(s, rs, schema, "TABLE_NAME", "SYNONYM"); // Finally drop the schema if it is not APP if (!schema.equals("APP")) { s.executeUpdate("DROP SCHEMA " + JDBC.escape(schema) + " RESTRICT"); } conn.commit(); s.close(); } /** * DROP a set of objects based upon a ResultSet from a * DatabaseMetaData call. * * TODO: Handle errors to ensure all objects are dropped, * probably requires interaction with its caller. * * @param s Statement object used to execute the DROP commands. * @param rs DatabaseMetaData ResultSet * @param schema Schema the objects are contained in * @param mdColumn The column name used to extract the object's * name from rs * @param dropType The keyword to use after DROP in the SQL statement * @throws SQLException database errors. */ private static void dropUsingDMD( Statement s, ResultSet rs, String schema, String mdColumn, String dropType) throws SQLException { String dropLeadIn = "DROP " + dropType + " "; // First collect the set of DROP SQL statements. ArrayList ddl = new ArrayList(); while (rs.next()) { String objectName = rs.getString(mdColumn); ddl.add(dropLeadIn + JDBC.escape(schema, objectName)); } rs.close(); // Execute them as a complete batch, hoping they will all succeed. s.clearBatch(); int batchCount = 0; for (Iterator i = ddl.iterator(); i.hasNext(); ) { Object sql = i.next(); if (sql != null) { s.addBatch(sql.toString()); batchCount++; } } int[] results; boolean hadError; try { results = s.executeBatch(); Assert.assertNotNull(results); Assert.assertEquals("Incorrect result length from executeBatch", batchCount, results.length); hadError = false; } catch (BatchUpdateException batchException) { results = batchException.getUpdateCounts(); Assert.assertNotNull(results); Assert.assertTrue("Too many results in BatchUpdateException", results.length <= batchCount); hadError = true; } // Remove any statements from the list that succeeded. boolean didDrop = false; for (int i = 0; i < results.length; i++) { int result = results[i]; if (result == -3 /* Statement.EXECUTE_FAILED*/) hadError = true; else if (result == -2/*Statement.SUCCESS_NO_INFO*/) didDrop = true; else if (result >= 0) didDrop = true; else Assert.fail("Negative executeBatch status"); if (didDrop) ddl.set(i, null); } s.clearBatch(); if (didDrop) { // Commit any work we did do. s.getConnection().commit(); } // If we had failures drop them as individual statements // until there are none left or none succeed. We need to // do this because the batch processing stops at the first // error. This copes with the simple case where there // are objects of the same type that depend on each other // and a different drop order will allow all or most // to be dropped. if (hadError) { do { hadError = false; didDrop = false; for (ListIterator i = ddl.listIterator(); i.hasNext();) { Object sql = i.next(); if (sql != null) { try { s.executeUpdate(sql.toString()); i.set(null); didDrop = true; } catch (SQLException e) { hadError = true; } } } if (didDrop) s.getConnection().commit(); } while (hadError && didDrop); } } /** * Assert all columns in the ResultSetMetaData match the * table's defintion through DatabaseMetadDta. Only works * if the complete select list correspond to columns from * base tables. * <BR> * Does not require that the complete set of any table's columns are * returned. * @throws SQLException * */ public static void assertMetaDataMatch(DatabaseMetaData dmd, ResultSetMetaData rsmd) throws SQLException { for (int col = 1; col <= rsmd.getColumnCount(); col++) { // Only expect a single column back ResultSet column = dmd.getColumns( rsmd.getCatalogName(col), rsmd.getSchemaName(col), rsmd.getTableName(col), rsmd.getColumnName(col)); Assert.assertTrue("Column missing " + rsmd.getColumnName(col), column.next()); Assert.assertEquals(column.getInt("DATA_TYPE"), rsmd.getColumnType(col)); Assert.assertEquals(column.getInt("NULLABLE"), rsmd.isNullable(col)); Assert.assertEquals(column.getString("TYPE_NAME"), rsmd.getColumnTypeName(col)); column.close(); } } /** * Drain a single ResultSet by reading all of its * rows and columns. Each column is accessed using * getString() and asserted that the returned value * matches the state of ResultSet.wasNull(). * * Provides simple testing of the ResultSet when the * contents are not important. * * @param rs Result set to drain. * @throws SQLException */ public static void assertDrainResults(ResultSet rs) throws SQLException { assertDrainResults(rs, -1); } /** * Does the work of assertDrainResults() as described * above. If the received row count is non-negative, * this method also asserts that the number of rows * in the result set matches the received row count. * * @param rs Result set to drain. * @param expectedRows If non-negative, indicates how * many rows we expected to see in the result set. * @throws SQLException */ public static void assertDrainResults(ResultSet rs, int expectedRows) throws SQLException { ResultSetMetaData rsmd = rs.getMetaData(); int rows = 0; while (rs.next()) { for (int col = 1; col <= rsmd.getColumnCount(); col++) { String s = rs.getString(col); Assert.assertEquals(s == null, rs.wasNull()); } rows++; } rs.close(); if (expectedRows >= 0) Assert.assertEquals("Unexpected row count:", expectedRows, rows); } /** * Takes a result set and an array of expected colum names (as * Strings) and asserts that the column names in the result * set metadata match the number, order, and names of those * in the array. * * @param rs ResultSet for which we're checking column names. * @param expectedColNames Array of expected column names. */ public static void assertColumnNames(ResultSet rs, String [] expectedColNames) throws SQLException { ResultSetMetaData rsmd = rs.getMetaData(); int actualCols = rsmd.getColumnCount(); Assert.assertEquals("Unexpected column count:", expectedColNames.length, rsmd.getColumnCount()); for (int i = 0; i < actualCols; i++) { Assert.assertEquals("Column names do not match:", expectedColNames[i], rsmd.getColumnName(i+1)); } } /** * Asserts a ResultSet returns a single row with a single * column equal to the passed in String value. The value can * be null to indicate SQL NULL. The comparision is make * using assertFullResultSet in trimmed string mode. */ public static void assertSingleValueResultSet(ResultSet rs, String value) throws SQLException { String[] row = new String[] {value}; String[][] set = new String[][] {row}; assertFullResultSet(rs, set); } /** * assertFullResultSet() using trimmed string comparisions. * Equal to * <code> * assertFullResultSet(rs, expectedRows, true) * </code> */ public static void assertFullResultSet(ResultSet rs, String [][] expectedRows) throws SQLException { assertFullResultSet(rs, expectedRows, true); } /** * Takes a result set and a two-dimensional array and asserts * that the rows and columns in the result set match the number, * order, and values of those in the array. Each row in * the array is compared with the corresponding row in the * result set. * * Will throw an assertion failure if any of the following * is true: * * 1. Expected vs actual number of columns doesn't match * 2. Expected vs actual number of rows doesn't match * 3. Any column in any row of the result set does not "equal" * the corresponding column in the expected 2-d array. If * "allAsTrimmedStrings" is true then the result set value * will be retrieved as a String and compared, via the ".equals()" * method, to the corresponding object in the array (with the * assumption being that the objects in the array are all * Strings). Otherwise the result set value will be retrieved * and compared as an Object, which is useful when asserting * the JDBC types of the columns in addition to their values. * * NOTE: It follows from #3 that the order of the rows in the * in received result set must match the order of the rows in * the received 2-d array. Otherwise the result will be an * assertion failure. * * @param rs The actual result set. * @param expectedRows 2-Dimensional array of objects representing * the expected result set. * @param allAsTrimmedStrings Whether or not to fetch (and compare) * all values from the actual result set as trimmed Strings; if * false the values will be fetched and compared as Objects. For * more on how this parameter is used, see assertRowInResultSet(). */ public static void assertFullResultSet(ResultSet rs, Object [][] expectedRows, boolean allAsTrimmedStrings) throws SQLException { int rows; ResultSetMetaData rsmd = rs.getMetaData(); // Assert that we have the right number of columns. Assert.assertEquals("Unexpected column count:", expectedRows[0].length, rsmd.getColumnCount()); for (rows = 0; rs.next(); rows++) { /* If we have more actual rows than expected rows, don't * try to assert the row. Instead just keep iterating * to see exactly how many rows the actual result set has. */ if (rows < expectedRows.length) { assertRowInResultSet(rs, rows + 1, expectedRows[rows], allAsTrimmedStrings); } } // And finally, assert the row count. Assert.assertEquals("Unexpected row count:", expectedRows.length, rows); } /** * Assert that every column in the current row of the received * result set matches the corresponding column in the received * array. This means that the order of the columns in the result * set must match the order of the values in expectedRow. * * <p> * If the expected value for a given row/column is a SQL NULL, * then the corresponding value in the array should be a Java * null. * * <p> * If a given row/column could have different values (for instance, * because it contains a timestamp), the expected value of that * row/column could be an object whose <code>equals()</code> method * returns <code>true</code> for all acceptable values. (This does * not work if one of the acceptable values is <code>null</code>.) * * @param rs Result set whose current row we'll check. * @param rowNum Row number (w.r.t expected rows) that we're * checking. * @param expectedRow Array of objects representing the expected * values for the current row. * @param asTrimmedStrings Whether or not to fetch and compare * all values from "rs" as trimmed Strings. If true then the * value from rs.getString() AND the expected value will both * be trimmed before comparison. If such trimming is not * desired (ex. if we were testing the padding of CHAR columns) * then this param should be FALSE and the expected values in * the received array should include the expected whitespace. * If for example the caller wants to check the padding of a * CHAR(8) column, asTrimmedStrings should be FALSE and the * expected row should contain the expected padding, such as * "FRED ". */ private static void assertRowInResultSet(ResultSet rs, int rowNum, Object [] expectedRow, boolean asTrimmedStrings) throws SQLException { ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 0; i < expectedRow.length; i++) { Object obj; if (asTrimmedStrings) { // Trim the expected value, if non-null. if (expectedRow[i] != null) expectedRow[i] = ((String)expectedRow[i]).trim(); /* Different clients can return different values for * boolean columns--namely, 0/1 vs false/true. So in * order to keep things uniform, take boolean columns * and get the JDBC string version. Note: since * Derby doesn't have a BOOLEAN type, we assume that * if the column's type is SMALLINT and the expected * value's string form is "true" or "false", then the * column is intended to be a mock boolean column. */ if ((expectedRow[i] != null) && (rsmd.getColumnType(i+1) == Types.SMALLINT)) { String s = expectedRow[i].toString(); if (s.equals("true") || s.equals("false")) obj = (rs.getShort(i+1) == 0) ? "false" : "true"; else obj = rs.getString(i+1); } else { obj = rs.getString(i+1); } // Trim the rs string. if (obj != null) obj = ((String)obj).trim(); } else obj = rs.getObject(i+1); boolean ok = (rs.wasNull() && (expectedRow[i] == null)) || (!rs.wasNull() && (expectedRow[i] != null) && expectedRow[i].equals(obj)); if (!ok) { Assert.fail("Column value mismatch @ column '" + rsmd.getColumnName(i+1) + "', row " + rowNum + ":\n Expected: >" + expectedRow[i] + "<\n Found: >" + obj + "<"); } } } /** * Escape a non-qualified name so that it is suitable * for use in a SQL query executed by JDBC. */ public static String escape(String name) { return "\"" + name + "\""; } /** * Escape a schama-qualified name so that it is suitable * for use in a SQL query executed by JDBC. */ public static String escape(String schema, String name) { return "\"" + schema + "\".\"" + name + "\""; } }
Close one of the ResultSets used to clean up databases from CleanDatabaseTestSetup. git-svn-id: 2c06e9c5008124d912b69f0b82df29d4867c0ce2@476315 13f79535-47bb-0310-9956-ffa450edef68
java/testing/org/apache/derbyTesting/junit/JDBC.java
Close one of the ResultSets used to clean up databases from CleanDatabaseTestSetup.
Java
bsd-2-clause
1d9fcc8d2d81074bd600915afee941bad9a63ad3
0
edgehosting/jira-dvcs-connector,markphip/testing,markphip/testing,markphip/testing,edgehosting/jira-dvcs-connector,edgehosting/jira-dvcs-connector
package com.atlassian.jira.plugins.dvcs.ondemand; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.atlassian.jira.plugins.dvcs.model.Credential; import com.atlassian.jira.plugins.dvcs.model.Organization; import com.atlassian.jira.plugins.dvcs.ondemand.AccountsConfig.BitbucketAccountInfo; import com.atlassian.jira.plugins.dvcs.ondemand.AccountsConfig.Links; import com.atlassian.jira.plugins.dvcs.service.OrganizationService; import com.atlassian.jira.plugins.dvcs.spi.bitbucket.BitbucketCommunicator; import com.atlassian.util.concurrent.ThreadFactories; /** * TODO implement sec. checks so int. account can not be i.e. deleted * * BitbucketAccountsConfigService * * * <br /><br /> * Created on 1.8.2012, 13:41:20 * <br /><br /> * @author jhocman@atlassian.com * */ public class BitbucketAccountsConfigService implements AccountsConfigService { private static final Logger log = LoggerFactory.getLogger(BitbucketAccountsConfigService.class); private static final String BITBUCKET_URL = "https://bitbucket.org"; private final AccountsConfigProvider configProvider; private final OrganizationService organizationService; private ExecutorService executorService; public BitbucketAccountsConfigService(AccountsConfigProvider configProvider, OrganizationService organizationService) { super(); this.configProvider = configProvider; this.organizationService = organizationService; this.executorService = Executors.newFixedThreadPool(1, ThreadFactories.namedThreadFactory("BitbucketAccountsConfigService")); } @Override public void reload() { executorService.submit(new Runnable() { @Override public void run() { try { runInternal(); } catch (Exception e) { log.error("", e); } } }); } private void runInternal() { // // supported only at ondemand instances // if (!supportsIntegratedAccounts()) { return; } // AccountsConfig configuration = configProvider.provideConfiguration(); Organization integratedAccount = organizationService.findIntegratedAccount(); // // new or update // if (integratedAccount == null) { if (configuration != null) { doNewAccount(configuration); } else { // probably not ondemand instance log.debug("No integrated account found and no configration is provided."); } } else { if (configuration != null) { // integrated account found doUpdateConfiguration(configuration, integratedAccount); } else { log.debug("Integrated account has been found and no configration is provided. Deleting integrated account."); removeAccount(integratedAccount); } } } private void doNewAccount(AccountsConfig configuration) { AccountInfo info = toInfoNewAccount(configuration); Organization userAddedAccount = getUserAddedAccount(info); Organization newOrganization = null; if (userAddedAccount == null) { // create brand new log.info("Creating new integrated account."); newOrganization = createNewOrganization(info); } else { log.info("Found the same user-added account."); removeAccount(userAddedAccount); // make integrated account from user-added account newOrganization = copyValues(info, userAddedAccount); } organizationService.save(newOrganization); } private Organization getUserAddedAccount(AccountInfo info) { Organization userAddedAccount = organizationService.getByHostAndName(BITBUCKET_URL, info.accountName); if (userAddedAccount != null && (StringUtils.isBlank(userAddedAccount.getCredential().getOauthKey()) || StringUtils.isBlank(userAddedAccount.getCredential().getOauthSecret())) ) { return userAddedAccount; } else { return null; } } /** * BL comes from https://sdog.jira.com/wiki/pages/viewpage.action?pageId=47284285 */ private void doUpdateConfiguration(AccountsConfig configuration, Organization integratedNotNullAccount) { AccountInfo info = toInfoExistingAccount(configuration); if (info != null) { // modify :? Organization userAddedAccount = getUserAddedAccount(info); if (userAddedAccount == null) { if (configHasChanged(integratedNotNullAccount, info)) { log.info("Detected credentials change."); organizationService.updateCredentialsKeySecret(integratedNotNullAccount.getId(), info.oauthKey, info.oauthSecret); } else if (accountNameHasChanged(integratedNotNullAccount, info)) { log.debug("Detected integrated account name change."); removeAccount(integratedNotNullAccount); organizationService.save(createNewOrganization(info)); } else { // nothing has changed log.info("No changes detect on integrated account"); } } else { // should not happened // existing integrated account with the same name as user added log.warn("Detected existing integrated account with the same name as user added."); removeAccount(userAddedAccount); } } else { // // delete account // removeAccount(integratedNotNullAccount); } } private boolean configHasChanged(Organization integratedNotNullAccount, AccountInfo info) { return StringUtils.equals(info.accountName, integratedNotNullAccount.getName()) && ( !StringUtils.equals(info.oauthKey, integratedNotNullAccount.getCredential().getOauthKey()) || !StringUtils.equals(info.oauthSecret, integratedNotNullAccount.getCredential().getOauthSecret())); } private boolean accountNameHasChanged(Organization integratedNotNullAccount, AccountInfo info) { return !StringUtils.equals(info.accountName, integratedNotNullAccount.getName()); } private void removeAccount(Organization integratedNotNullAccount) { organizationService.remove(integratedNotNullAccount.getId()); } private AccountInfo toInfoNewAccount(AccountsConfig configuration) { try { AccountInfo info = new AccountInfo(); // // crawl to information // Links links = configuration.getSysadminApplicationLinks().get(0); BitbucketAccountInfo bitbucketAccountInfo = links.getBitbucket().get(0); // info.accountName = bitbucketAccountInfo.getAccount(); info.oauthKey = bitbucketAccountInfo.getKey(); info.oauthSecret = bitbucketAccountInfo.getSecret(); // // // assertNotBlank(info.accountName, "accountName have to be provided for new account"); assertNotBlank(info.oauthKey, "oauthKey have to be provided for new account"); assertNotBlank(info.oauthSecret, "oauthSecret have to be provided for new account"); // return info; } catch (Exception e) { throw new IllegalStateException("Wrong configuration.", e); } } private AccountInfo toInfoExistingAccount(AccountsConfig configuration) { // // try to find configuration, otherwise assuming it is deletion of the integrated account // Links links = null; try { links = configuration.getSysadminApplicationLinks().get(0); } catch (Exception e) { log.debug("Bitbucket links not present. " + e + ": " + e.getMessage()); // return null; // } BitbucketAccountInfo bitbucketAccountInfo = null; if (links != null) { try { bitbucketAccountInfo = links.getBitbucket().get(0); } catch (Exception e) { log.debug("Bitbucket accounts info not present. " + e + ": " + e.getMessage()); // return null; // } } AccountInfo info = new AccountInfo(); if (bitbucketAccountInfo != null) { info.accountName = bitbucketAccountInfo.getAccount(); info.oauthKey = bitbucketAccountInfo.getKey(); info.oauthSecret = bitbucketAccountInfo.getSecret(); } // if (isBlank(info.accountName)) { log.debug("accountName is empty assuming deletion"); // return null; } if (isBlank(info.oauthKey)) { log.debug("oauthKey is empty assuming deletion"); // return null; } if (isBlank(info.oauthSecret)) { log.debug("oauthSecret is empty assuming deletion"); // return null; } // // return info; } private static void assertNotBlank(String string, String msg) { if(isBlank(string)) { throw new IllegalArgumentException(msg); } } private static boolean isBlank(String string) { return StringUtils.isBlank(string); } private boolean supportsIntegratedAccounts() { return configProvider.supportsIntegratedAccounts(); } private Organization createNewOrganization(AccountInfo info) { Organization newOrganization = new Organization(); copyValues(info, newOrganization); return newOrganization; } private Organization copyValues(AccountInfo info, Organization organization) { organization.setId(0); organization.setName(info.accountName); organization.setCredential(new Credential(null, null, null, info.oauthKey, info.oauthSecret)); organization.setHostUrl(BITBUCKET_URL); organization.setDvcsType(BitbucketCommunicator.BITBUCKET); organization.setAutolinkNewRepos(true); organization.setSmartcommitsOnNewRepos(true); return organization; } private static class AccountInfo { String accountName; String oauthKey; String oauthSecret; } }
jira-dvcs-connector-plugin/src/main/java/com/atlassian/jira/plugins/dvcs/ondemand/BitbucketAccountsConfigService.java
package com.atlassian.jira.plugins.dvcs.ondemand; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.atlassian.jira.plugins.dvcs.model.Credential; import com.atlassian.jira.plugins.dvcs.model.Organization; import com.atlassian.jira.plugins.dvcs.ondemand.AccountsConfig.BitbucketAccountInfo; import com.atlassian.jira.plugins.dvcs.ondemand.AccountsConfig.Links; import com.atlassian.jira.plugins.dvcs.service.OrganizationService; import com.atlassian.jira.plugins.dvcs.spi.bitbucket.BitbucketCommunicator; import com.atlassian.util.concurrent.ThreadFactories; /** * TODO implement sec. checks so int. account can not be i.e. deleted * * BitbucketAccountsConfigService * * * <br /><br /> * Created on 1.8.2012, 13:41:20 * <br /><br /> * @author jhocman@atlassian.com * */ public class BitbucketAccountsConfigService implements AccountsConfigService { private static final Logger log = LoggerFactory.getLogger(BitbucketAccountsConfigService.class); private static final String BITBUCKET_URL = "https://bitbucket.org"; private final AccountsConfigProvider configProvider; private final OrganizationService organizationService; private ExecutorService executorService; public BitbucketAccountsConfigService(AccountsConfigProvider configProvider, OrganizationService organizationService) { super(); this.configProvider = configProvider; this.organizationService = organizationService; this.executorService = Executors.newFixedThreadPool(1, ThreadFactories.namedThreadFactory("BitbucketAccountsConfigService")); } @Override public void reload() { executorService.submit(new Runnable() { @Override public void run() { try { runInternal(); } catch (Exception e) { log.error("", e); } } }); } private void runInternal() { // // supported only at ondemand instances // if (!supportsIntegratedAccounts()) { return; } // AccountsConfig configuration = configProvider.provideConfiguration(); Organization integratedAccount = organizationService.findIntegratedAccount(); // // new or update // if (integratedAccount == null) { if (configuration != null) { doNewAccount(configuration); } else { // probably not ondemand instance log.debug("No integrated account found and no configration is provided."); } } else { if (configuration != null) { // integrated account found doUpdateConfiguration(configuration, integratedAccount); } else { log.debug("Integrated account has been found and no configration is provided. Deleting integrated account."); removeAccount(integratedAccount); } } } private void doNewAccount(AccountsConfig configuration) { AccountInfo info = toInfoNewAccount(configuration); Organization userAddedAccount = getUserAddedAccount(info); Organization newOrganization = null; if (userAddedAccount == null) { // create brand new newOrganization = createNewOrganization(info); } else { removeAccount(userAddedAccount); // make integrated account from user-added account newOrganization = copyValues(info, userAddedAccount); } organizationService.save(newOrganization); } private Organization getUserAddedAccount(AccountInfo info) { Organization userAddedAccount = organizationService.getByHostAndName(BITBUCKET_URL, info.accountName); if (userAddedAccount != null && (StringUtils.isBlank(userAddedAccount.getCredential().getOauthKey()) || StringUtils.isBlank(userAddedAccount.getCredential().getOauthSecret())) ) { return userAddedAccount; } else { return null; } } /** * BL comes from https://sdog.jira.com/wiki/pages/viewpage.action?pageId=47284285 */ private void doUpdateConfiguration(AccountsConfig configuration, Organization integratedNotNullAccount) { AccountInfo info = toInfoExistingAccount(configuration); if (info != null) { // modify :? Organization userAddedAccount = getUserAddedAccount(info); if (userAddedAccount == null) { if (configHasChanged(integratedNotNullAccount, info)) { copyValues(info, integratedNotNullAccount); organizationService.updateCredentialsKeySecret(integratedNotNullAccount.getId(), info.oauthKey, info.oauthSecret); } else if (accountNameHasChanged(integratedNotNullAccount, info)) { removeAccount(userAddedAccount); organizationService.save(createNewOrganization(info)); } else { // nothing has changed log.debug("No changes detect on integrated account"); } } else { // should not happened // existing integrated account with the same name as user added log.warn("Detected existing integrated account with the same name as user added."); removeAccount(userAddedAccount); } } else { // // delete account // removeAccount(integratedNotNullAccount); } } private boolean configHasChanged(Organization integratedNotNullAccount, AccountInfo info) { return StringUtils.equals(info.accountName, integratedNotNullAccount.getName()) && ( !StringUtils.equals(info.oauthKey, integratedNotNullAccount.getCredential().getOauthKey()) || !StringUtils.equals(info.oauthSecret, integratedNotNullAccount.getCredential().getOauthSecret())); } private boolean accountNameHasChanged(Organization integratedNotNullAccount, AccountInfo info) { return !StringUtils.equals(info.accountName, integratedNotNullAccount.getName()); } private void removeAccount(Organization integratedNotNullAccount) { organizationService.remove(integratedNotNullAccount.getId()); } private AccountInfo toInfoNewAccount(AccountsConfig configuration) { try { AccountInfo info = new AccountInfo(); // // crawl to information // Links links = configuration.getSysadminApplicationLinks().get(0); BitbucketAccountInfo bitbucketAccountInfo = links.getBitbucket().get(0); // info.accountName = bitbucketAccountInfo.getAccount(); info.oauthKey = bitbucketAccountInfo.getKey(); info.oauthSecret = bitbucketAccountInfo.getSecret(); // // // assertNotBlank(info.accountName, "accountName have to be provided for new account"); assertNotBlank(info.oauthKey, "oauthKey have to be provided for new account"); assertNotBlank(info.oauthSecret, "oauthSecret have to be provided for new account"); // return info; } catch (Exception e) { throw new IllegalStateException("Wrong configuration.", e); } } private AccountInfo toInfoExistingAccount(AccountsConfig configuration) { // // try to find configuration, otherwise assuming it is deletion of the integrated account // Links links = null; try { links = configuration.getSysadminApplicationLinks().get(0); } catch (Exception e) { log.debug("Bitbucket links not present. " + e + ": " + e.getMessage()); // return null; // } BitbucketAccountInfo bitbucketAccountInfo = null; if (links != null) { try { bitbucketAccountInfo = links.getBitbucket().get(0); } catch (Exception e) { log.debug("Bitbucket accounts info not present. " + e + ": " + e.getMessage()); // return null; // } } AccountInfo info = new AccountInfo(); if (bitbucketAccountInfo != null) { info.accountName = bitbucketAccountInfo.getAccount(); info.oauthKey = bitbucketAccountInfo.getKey(); info.oauthSecret = bitbucketAccountInfo.getSecret(); } // if (isBlank(info.accountName)) { log.debug("accountName is empty assuming deletion"); // return null; } if (isBlank(info.oauthKey)) { log.debug("oauthKey is empty assuming deletion"); // return null; } if (isBlank(info.oauthSecret)) { log.debug("oauthSecret is empty assuming deletion"); // return null; } // // return info; } private static void assertNotBlank(String string, String msg) { if(isBlank(string)) { throw new IllegalArgumentException(msg); } } private static boolean isBlank(String string) { return StringUtils.isBlank(string); } private boolean supportsIntegratedAccounts() { return configProvider.supportsIntegratedAccounts(); } private Organization createNewOrganization(AccountInfo info) { Organization newOrganization = new Organization(); copyValues(info, newOrganization); return newOrganization; } private Organization copyValues(AccountInfo info, Organization organization) { organization.setId(0); organization.setName(info.accountName); organization.setCredential(new Credential(null, null, null, info.oauthKey, info.oauthSecret)); organization.setHostUrl(BITBUCKET_URL); organization.setDvcsType(BitbucketCommunicator.BITBUCKET); organization.setAutolinkNewRepos(true); organization.setSmartcommitsOnNewRepos(true); return organization; } private static class AccountInfo { String accountName; String oauthKey; String oauthSecret; } }
BBC-234 - bugfixes and refinements..
jira-dvcs-connector-plugin/src/main/java/com/atlassian/jira/plugins/dvcs/ondemand/BitbucketAccountsConfigService.java
BBC-234 - bugfixes and refinements..
Java
bsd-2-clause
c561d7c24c87d5859d2a68d9de1157726952ca6b
0
meganz/sdk,meganz/sdk,meganz/sdk,meganz/sdk,meganz/sdk,meganz/sdk,meganz/sdk
/* * (c) 2013-2015 by Mega Limited, Auckland, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK is distributed in the hope that it will be useful,\ * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * @copyright Simplified (2-clause) BSD License. * You should have received a copy of the license along with this * program. */ package nz.mega.sdk; import org.jetbrains.annotations.NotNull; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; /** * Java Application Programming Interface (API) to access MEGA SDK services on a MEGA account or shared public folder. * <p> * An appKey must be specified to use the MEGA SDK. Generate an appKey for free here: <br> * - https://mega.co.nz/#sdk * <p> * Save on data usage and start up time by enabling local node caching. This can be enabled by passing a local path * in the constructor. Local node caching prevents the need to download the entire file system each time the MegaApiJava * object is logged in. * <p> * To take advantage of local node caching, the application needs to save the session key after login * (MegaApiJava.dumpSession()) and use it to login during the next session. A persistent local node cache will only be * loaded if logging in with a session key. * Local node caching is also recommended in order to enhance security as it prevents the account password from being * stored by the application. * <p> * To access MEGA services using the MEGA SDK, an object of this class (MegaApiJava) needs to be created and one of the * MegaApiJava.login() options used to log into a MEGA account or a public folder. If the login request succeeds, * call MegaApiJava.fetchNodes() to get the account's file system from MEGA. Once the file system is retrieved, all other * requests including file management and transfers can be used. * <p> * After using MegaApiJava.logout() you can reuse the same MegaApi object to log in to another MEGA account or a public * folder. */ public class MegaApiJava { MegaApi megaApi; MegaGfxProcessor gfxProcessor; void runCallback(Runnable runnable) { runnable.run(); } static Set<DelegateMegaRequestListener> activeRequestListeners = Collections.synchronizedSet(new LinkedHashSet<DelegateMegaRequestListener>()); static Set<DelegateMegaTransferListener> activeTransferListeners = Collections.synchronizedSet(new LinkedHashSet<DelegateMegaTransferListener>()); static Set<DelegateMegaGlobalListener> activeGlobalListeners = Collections.synchronizedSet(new LinkedHashSet<DelegateMegaGlobalListener>()); static Set<DelegateMegaListener> activeMegaListeners = Collections.synchronizedSet(new LinkedHashSet<DelegateMegaListener>()); static Set<DelegateMegaLogger> activeMegaLoggers = Collections.synchronizedSet(new LinkedHashSet<DelegateMegaLogger>()); static Set<DelegateMegaTreeProcessor> activeMegaTreeProcessors = Collections.synchronizedSet(new LinkedHashSet<DelegateMegaTreeProcessor>()); static Set<DelegateMegaTransferListener> activeHttpServerListeners = Collections.synchronizedSet(new LinkedHashSet<DelegateMegaTransferListener>()); /** * INVALID_HANDLE Invalid value for a handle * * This value is used to represent an invalid handle. Several MEGA objects can have * a handle but it will never be INVALID_HANDLE. */ public final static long INVALID_HANDLE = ~(long)0; // Very severe error event that will presumably lead the application to abort. public final static int LOG_LEVEL_FATAL = MegaApi.LOG_LEVEL_FATAL; // Error information but application will continue run. public final static int LOG_LEVEL_ERROR = MegaApi.LOG_LEVEL_ERROR; // Information representing errors in application but application will keep running public final static int LOG_LEVEL_WARNING = MegaApi.LOG_LEVEL_WARNING; // Mainly useful to represent current progress of application. public final static int LOG_LEVEL_INFO = MegaApi.LOG_LEVEL_INFO; // Informational logs, that are useful for developers. Only applicable if DEBUG is defined. public final static int LOG_LEVEL_DEBUG = MegaApi.LOG_LEVEL_DEBUG; public final static int LOG_LEVEL_MAX = MegaApi.LOG_LEVEL_MAX; public final static int ATTR_TYPE_THUMBNAIL = MegaApi.ATTR_TYPE_THUMBNAIL; public final static int ATTR_TYPE_PREVIEW = MegaApi.ATTR_TYPE_PREVIEW; public final static int USER_ATTR_AVATAR = MegaApi.USER_ATTR_AVATAR; public final static int USER_ATTR_FIRSTNAME = MegaApi.USER_ATTR_FIRSTNAME; public final static int USER_ATTR_LASTNAME = MegaApi.USER_ATTR_LASTNAME; public final static int USER_ATTR_AUTHRING = MegaApi.USER_ATTR_AUTHRING; public final static int USER_ATTR_LAST_INTERACTION = MegaApi.USER_ATTR_LAST_INTERACTION; public final static int USER_ATTR_ED25519_PUBLIC_KEY = MegaApi.USER_ATTR_ED25519_PUBLIC_KEY; public final static int USER_ATTR_CU25519_PUBLIC_KEY = MegaApi.USER_ATTR_CU25519_PUBLIC_KEY; public final static int USER_ATTR_KEYRING = MegaApi.USER_ATTR_KEYRING; public final static int USER_ATTR_SIG_RSA_PUBLIC_KEY = MegaApi.USER_ATTR_SIG_RSA_PUBLIC_KEY; public final static int USER_ATTR_SIG_CU255_PUBLIC_KEY = MegaApi.USER_ATTR_SIG_CU255_PUBLIC_KEY; public final static int USER_ATTR_LANGUAGE = MegaApi.USER_ATTR_LANGUAGE; public final static int USER_ATTR_PWD_REMINDER = MegaApi.USER_ATTR_PWD_REMINDER; public final static int USER_ATTR_DISABLE_VERSIONS = MegaApi.USER_ATTR_DISABLE_VERSIONS; public final static int USER_ATTR_CONTACT_LINK_VERIFICATION = MegaApi.USER_ATTR_CONTACT_LINK_VERIFICATION; public final static int USER_ATTR_RICH_PREVIEWS = MegaApi.USER_ATTR_RICH_PREVIEWS; public final static int USER_ATTR_RUBBISH_TIME = MegaApi.USER_ATTR_RUBBISH_TIME; public final static int USER_ATTR_LAST_PSA = MegaApi.USER_ATTR_LAST_PSA; public final static int USER_ATTR_STORAGE_STATE = MegaApi.USER_ATTR_STORAGE_STATE; public final static int USER_ATTR_GEOLOCATION = MegaApi.USER_ATTR_GEOLOCATION; public final static int USER_ATTR_CAMERA_UPLOADS_FOLDER = MegaApi.USER_ATTR_CAMERA_UPLOADS_FOLDER; public final static int USER_ATTR_MY_CHAT_FILES_FOLDER = MegaApi.USER_ATTR_MY_CHAT_FILES_FOLDER; public final static int USER_ATTR_PUSH_SETTINGS = MegaApi.USER_ATTR_PUSH_SETTINGS; public final static int USER_ATTR_ALIAS = MegaApi.USER_ATTR_ALIAS; public final static int USER_ATTR_DEVICE_NAMES = MegaApi.USER_ATTR_DEVICE_NAMES; public final static int USER_ATTR_MY_BACKUPS_FOLDER = MegaApi.USER_ATTR_MY_BACKUPS_FOLDER; // deprecated: public final static int USER_ATTR_BACKUP_NAMES = MegaApi.USER_ATTR_BACKUP_NAMES; public final static int USER_ATTR_COOKIE_SETTINGS = MegaApi.USER_ATTR_COOKIE_SETTINGS; public final static int NODE_ATTR_DURATION = MegaApi.NODE_ATTR_DURATION; public final static int NODE_ATTR_COORDINATES = MegaApi.NODE_ATTR_COORDINATES; public final static int NODE_ATTR_LABEL = MegaApi.NODE_ATTR_LABEL; public final static int NODE_ATTR_FAV = MegaApi.NODE_ATTR_FAV; public final static int PAYMENT_METHOD_BALANCE = MegaApi.PAYMENT_METHOD_BALANCE; public final static int PAYMENT_METHOD_PAYPAL = MegaApi.PAYMENT_METHOD_PAYPAL; public final static int PAYMENT_METHOD_ITUNES = MegaApi.PAYMENT_METHOD_ITUNES; public final static int PAYMENT_METHOD_GOOGLE_WALLET = MegaApi.PAYMENT_METHOD_GOOGLE_WALLET; public final static int PAYMENT_METHOD_BITCOIN = MegaApi.PAYMENT_METHOD_BITCOIN; public final static int PAYMENT_METHOD_UNIONPAY = MegaApi.PAYMENT_METHOD_UNIONPAY; public final static int PAYMENT_METHOD_FORTUMO = MegaApi.PAYMENT_METHOD_FORTUMO; public final static int PAYMENT_METHOD_STRIPE = MegaApi.PAYMENT_METHOD_STRIPE; public final static int PAYMENT_METHOD_CREDIT_CARD = MegaApi.PAYMENT_METHOD_CREDIT_CARD; public final static int PAYMENT_METHOD_CENTILI = MegaApi.PAYMENT_METHOD_CENTILI; public final static int PAYMENT_METHOD_PAYSAFE_CARD = MegaApi.PAYMENT_METHOD_PAYSAFE_CARD; public final static int PAYMENT_METHOD_ASTROPAY = MegaApi.PAYMENT_METHOD_ASTROPAY; public final static int PAYMENT_METHOD_RESERVED = MegaApi.PAYMENT_METHOD_RESERVED; public final static int PAYMENT_METHOD_WINDOWS_STORE = MegaApi.PAYMENT_METHOD_WINDOWS_STORE; public final static int PAYMENT_METHOD_TPAY = MegaApi.PAYMENT_METHOD_TPAY; public final static int PAYMENT_METHOD_DIRECT_RESELLER = MegaApi.PAYMENT_METHOD_DIRECT_RESELLER; public final static int PAYMENT_METHOD_ECP = MegaApi.PAYMENT_METHOD_ECP; public final static int PAYMENT_METHOD_SABADELL = MegaApi.PAYMENT_METHOD_SABADELL; public final static int PAYMENT_METHOD_HUAWEI_WALLET = MegaApi.PAYMENT_METHOD_HUAWEI_WALLET; public final static int PAYMENT_METHOD_STRIPE2 = MegaApi.PAYMENT_METHOD_STRIPE2; public final static int PAYMENT_METHOD_WIRE_TRANSFER = MegaApi.PAYMENT_METHOD_WIRE_TRANSFER; public final static int TRANSFER_METHOD_NORMAL = MegaApi.TRANSFER_METHOD_NORMAL; public final static int TRANSFER_METHOD_ALTERNATIVE_PORT = MegaApi.TRANSFER_METHOD_ALTERNATIVE_PORT; public final static int TRANSFER_METHOD_AUTO = MegaApi.TRANSFER_METHOD_AUTO; public final static int TRANSFER_METHOD_AUTO_NORMAL = MegaApi.TRANSFER_METHOD_AUTO_NORMAL; public final static int TRANSFER_METHOD_AUTO_ALTERNATIVE = MegaApi.TRANSFER_METHOD_AUTO_ALTERNATIVE; public final static int PUSH_NOTIFICATION_ANDROID = MegaApi.PUSH_NOTIFICATION_ANDROID; public final static int PUSH_NOTIFICATION_IOS_VOIP = MegaApi.PUSH_NOTIFICATION_IOS_VOIP; public final static int PUSH_NOTIFICATION_IOS_STD = MegaApi.PUSH_NOTIFICATION_IOS_STD; public final static int PASSWORD_STRENGTH_VERYWEAK = MegaApi.PASSWORD_STRENGTH_VERYWEAK; public final static int PASSWORD_STRENGTH_WEAK = MegaApi.PASSWORD_STRENGTH_WEAK; public final static int PASSWORD_STRENGTH_MEDIUM = MegaApi.PASSWORD_STRENGTH_MEDIUM; public final static int PASSWORD_STRENGTH_GOOD = MegaApi.PASSWORD_STRENGTH_GOOD; public final static int PASSWORD_STRENGTH_STRONG = MegaApi.PASSWORD_STRENGTH_STRONG; public final static int RETRY_NONE = MegaApi.RETRY_NONE; public final static int RETRY_CONNECTIVITY = MegaApi.RETRY_CONNECTIVITY; public final static int RETRY_SERVERS_BUSY = MegaApi.RETRY_SERVERS_BUSY; public final static int RETRY_API_LOCK = MegaApi.RETRY_API_LOCK; public final static int RETRY_RATE_LIMIT = MegaApi.RETRY_RATE_LIMIT; public final static int RETRY_LOCAL_LOCK = MegaApi.RETRY_LOCAL_LOCK; public final static int RETRY_UNKNOWN = MegaApi.RETRY_UNKNOWN; public final static int KEEP_ALIVE_CAMERA_UPLOADS = MegaApi.KEEP_ALIVE_CAMERA_UPLOADS; public final static int STORAGE_STATE_UNKNOWN = MegaApi.STORAGE_STATE_UNKNOWN; public final static int STORAGE_STATE_GREEN = MegaApi.STORAGE_STATE_GREEN; public final static int STORAGE_STATE_ORANGE = MegaApi.STORAGE_STATE_ORANGE; public final static int STORAGE_STATE_RED = MegaApi.STORAGE_STATE_RED; public final static int STORAGE_STATE_CHANGE = MegaApi.STORAGE_STATE_CHANGE; public final static int STORAGE_STATE_PAYWALL = MegaApi.STORAGE_STATE_PAYWALL; public final static int BUSINESS_STATUS_EXPIRED = MegaApi.BUSINESS_STATUS_EXPIRED; public final static int BUSINESS_STATUS_INACTIVE = MegaApi.BUSINESS_STATUS_INACTIVE; public final static int BUSINESS_STATUS_ACTIVE = MegaApi.BUSINESS_STATUS_ACTIVE; public final static int BUSINESS_STATUS_GRACE_PERIOD = MegaApi.BUSINESS_STATUS_GRACE_PERIOD; public final static int AFFILIATE_TYPE_INVALID = MegaApi.AFFILIATE_TYPE_INVALID; public final static int AFFILIATE_TYPE_ID = MegaApi.AFFILIATE_TYPE_ID; public final static int AFFILIATE_TYPE_FILE_FOLDER = MegaApi.AFFILIATE_TYPE_FILE_FOLDER; public final static int AFFILIATE_TYPE_CHAT = MegaApi.AFFILIATE_TYPE_CHAT; public final static int AFFILIATE_TYPE_CONTACT = MegaApi.AFFILIATE_TYPE_CONTACT; public final static int CREATE_ACCOUNT = MegaApi.CREATE_ACCOUNT; public final static int RESUME_ACCOUNT = MegaApi.RESUME_ACCOUNT; public final static int CANCEL_ACCOUNT = MegaApi.CANCEL_ACCOUNT; public final static int CREATE_EPLUSPLUS_ACCOUNT = MegaApi.CREATE_EPLUSPLUS_ACCOUNT; public final static int RESUME_EPLUSPLUS_ACCOUNT = MegaApi.RESUME_EPLUSPLUS_ACCOUNT; public final static int ORDER_NONE = MegaApi.ORDER_NONE; public final static int ORDER_DEFAULT_ASC = MegaApi.ORDER_DEFAULT_ASC; public final static int ORDER_DEFAULT_DESC = MegaApi.ORDER_DEFAULT_DESC; public final static int ORDER_SIZE_ASC = MegaApi.ORDER_SIZE_ASC; public final static int ORDER_SIZE_DESC = MegaApi.ORDER_SIZE_DESC; public final static int ORDER_CREATION_ASC = MegaApi.ORDER_CREATION_ASC; public final static int ORDER_CREATION_DESC = MegaApi.ORDER_CREATION_DESC; public final static int ORDER_MODIFICATION_ASC = MegaApi.ORDER_MODIFICATION_ASC; public final static int ORDER_MODIFICATION_DESC = MegaApi.ORDER_MODIFICATION_DESC; public final static int ORDER_ALPHABETICAL_ASC = MegaApi.ORDER_ALPHABETICAL_ASC; public final static int ORDER_ALPHABETICAL_DESC = MegaApi.ORDER_ALPHABETICAL_DESC; public final static int ORDER_PHOTO_ASC = MegaApi.ORDER_PHOTO_ASC; public final static int ORDER_PHOTO_DESC = MegaApi.ORDER_PHOTO_DESC; public final static int ORDER_VIDEO_ASC = MegaApi.ORDER_VIDEO_ASC; public final static int ORDER_VIDEO_DESC = MegaApi.ORDER_VIDEO_DESC; public final static int ORDER_LINK_CREATION_ASC = MegaApi.ORDER_LINK_CREATION_ASC; public final static int ORDER_LINK_CREATION_DESC = MegaApi.ORDER_LINK_CREATION_DESC; public final static int ORDER_LABEL_ASC = MegaApi.ORDER_LABEL_ASC; public final static int ORDER_LABEL_DESC = MegaApi.ORDER_LABEL_DESC; public final static int ORDER_FAV_ASC = MegaApi.ORDER_FAV_ASC; public final static int ORDER_FAV_DESC = MegaApi.ORDER_FAV_DESC; public final static int TCP_SERVER_DENY_ALL = MegaApi.TCP_SERVER_DENY_ALL; public final static int TCP_SERVER_ALLOW_ALL = MegaApi.TCP_SERVER_ALLOW_ALL; public final static int TCP_SERVER_ALLOW_CREATED_LOCAL_LINKS = MegaApi.TCP_SERVER_ALLOW_CREATED_LOCAL_LINKS; public final static int TCP_SERVER_ALLOW_LAST_LOCAL_LINK = MegaApi.TCP_SERVER_ALLOW_LAST_LOCAL_LINK; public final static int HTTP_SERVER_DENY_ALL = MegaApi.HTTP_SERVER_DENY_ALL; public final static int HTTP_SERVER_ALLOW_ALL = MegaApi.HTTP_SERVER_ALLOW_ALL; public final static int HTTP_SERVER_ALLOW_CREATED_LOCAL_LINKS = MegaApi.HTTP_SERVER_ALLOW_CREATED_LOCAL_LINKS; public final static int HTTP_SERVER_ALLOW_LAST_LOCAL_LINK = MegaApi.HTTP_SERVER_ALLOW_LAST_LOCAL_LINK; public final static int FILE_TYPE_DEFAULT = MegaApi.FILE_TYPE_DEFAULT; public final static int FILE_TYPE_PHOTO = MegaApi.FILE_TYPE_PHOTO; public final static int FILE_TYPE_AUDIO = MegaApi.FILE_TYPE_AUDIO; public final static int FILE_TYPE_VIDEO = MegaApi.FILE_TYPE_VIDEO; public final static int FILE_TYPE_DOCUMENT = MegaApi.FILE_TYPE_DOCUMENT; public final static int SEARCH_TARGET_INSHARE = MegaApi.SEARCH_TARGET_INSHARE; public final static int SEARCH_TARGET_OUTSHARE = MegaApi.SEARCH_TARGET_OUTSHARE; public final static int SEARCH_TARGET_PUBLICLINK = MegaApi.SEARCH_TARGET_PUBLICLINK; public final static int SEARCH_TARGET_ROOTNODE = MegaApi.SEARCH_TARGET_ROOTNODE; public final static int SEARCH_TARGET_ALL = MegaApi.SEARCH_TARGET_ALL; public final static int BACKUP_TYPE_INVALID = MegaApi.BACKUP_TYPE_INVALID; public final static int BACKUP_TYPE_TWO_WAY_SYNC = MegaApi.BACKUP_TYPE_TWO_WAY_SYNC; public final static int BACKUP_TYPE_UP_SYNC = MegaApi.BACKUP_TYPE_UP_SYNC; public final static int BACKUP_TYPE_DOWN_SYNC = MegaApi.BACKUP_TYPE_DOWN_SYNC; public final static int BACKUP_TYPE_CAMERA_UPLOADS = MegaApi.BACKUP_TYPE_CAMERA_UPLOADS; public final static int BACKUP_TYPE_MEDIA_UPLOADS = MegaApi.BACKUP_TYPE_MEDIA_UPLOADS; public final static int GOOGLE_ADS_DEFAULT = MegaApi.GOOGLE_ADS_DEFAULT; public final static int GOOGLE_ADS_FORCE_ADS = MegaApi.GOOGLE_ADS_FORCE_ADS; public final static int GOOGLE_ADS_IGNORE_MEGA = MegaApi.GOOGLE_ADS_IGNORE_MEGA; public final static int GOOGLE_ADS_IGNORE_COUNTRY = MegaApi.GOOGLE_ADS_IGNORE_COUNTRY; public final static int GOOGLE_ADS_IGNORE_IP = MegaApi.GOOGLE_ADS_IGNORE_IP; public final static int GOOGLE_ADS_IGNORE_PRO = MegaApi.GOOGLE_ADS_IGNORE_PRO; public final static int GOOGLE_ADS_FLAG_IGNORE_ROLLOUT = MegaApi.GOOGLE_ADS_FLAG_IGNORE_ROLLOUT; MegaApi getMegaApi() { return megaApi; } /** * Constructor suitable for most applications. * * @param appKey * AppKey of your application. * Generate an AppKey for free here: https://mega.co.nz/#sdk * * @param basePath * Base path to store the local cache. * If you pass null to this parameter, the SDK won't use any local cache. */ public MegaApiJava(String appKey, String basePath) { megaApi = new MegaApi(appKey, basePath); } /** * MegaApi Constructor that allows use of a custom GFX processor. * <p> * The SDK attaches thumbnails and previews to all uploaded images. To generate them, it needs a graphics processor. * You can build the SDK with one of the provided built-in graphics processors. If none are available * in your app, you can implement the MegaGfxProcessor interface to provide a custom processor. Please * read the documentation of MegaGfxProcessor carefully to ensure that your implementation is valid. * * @param appKey * AppKey of your application. * Generate an AppKey for free here: https://mega.co.nz/#sdk * * @param userAgent * User agent to use in network requests. * If you pass null to this parameter, a default user agent will be used. * * @param basePath * Base path to store the local cache. * If you pass null to this parameter, the SDK won't use any local cache. * * @param gfxProcessor * Image processor. The SDK will use it to generate previews and thumbnails. * If you pass null to this parameter, the SDK will try to use the built-in image processors. * */ public MegaApiJava(String appKey, String userAgent, String basePath, MegaGfxProcessor gfxProcessor) { this.gfxProcessor = gfxProcessor; megaApi = new MegaApi(appKey, gfxProcessor, basePath, userAgent); } /** * Constructor suitable for most applications. * * @param appKey * AppKey of your application. * Generate an AppKey for free here: https://mega.co.nz/#sdk */ public MegaApiJava(String appKey) { megaApi = new MegaApi(appKey); } /****************************************************************************************************/ // LISTENER MANAGEMENT /****************************************************************************************************/ /** * Register a listener to receive all events (requests, transfers, global, synchronization). * <p> * You can use MegaApiJava.removeListener() to stop receiving events. * * @param listener * Listener that will receive all events (requests, transfers, global, synchronization). */ public void addListener(MegaListenerInterface listener) { megaApi.addListener(createDelegateMegaListener(listener)); } /** * Register a listener to receive all events about requests. * <p> * You can use MegaApiJava.removeRequestListener() to stop receiving events. * * @param listener * Listener that will receive all events about requests. */ public void addRequestListener(MegaRequestListenerInterface listener) { megaApi.addRequestListener(createDelegateRequestListener(listener, false)); } /** * Register a listener to receive all events about transfers. * <p> * You can use MegaApiJava.removeTransferListener() to stop receiving events. * * @param listener * Listener that will receive all events about transfers. */ public void addTransferListener(MegaTransferListenerInterface listener) { megaApi.addTransferListener(createDelegateTransferListener(listener, false)); } /** * Register a listener to receive global events. * <p> * You can use MegaApiJava.removeGlobalListener() to stop receiving events. * * @param listener * Listener that will receive global events. */ public void addGlobalListener(MegaGlobalListenerInterface listener) { megaApi.addGlobalListener(createDelegateGlobalListener(listener)); } /** * Unregister a listener. * <p> * Stop receiving events from the specified listener. * * @param listener * Object that is unregistered. */ public void removeListener(MegaListenerInterface listener) { ArrayList<DelegateMegaListener> listenersToRemove = new ArrayList<DelegateMegaListener>(); synchronized (activeMegaListeners) { Iterator<DelegateMegaListener> it = activeMegaListeners.iterator(); while (it.hasNext()) { DelegateMegaListener delegate = it.next(); if (delegate.getUserListener() == listener) { listenersToRemove.add(delegate); it.remove(); } } } for (int i=0;i<listenersToRemove.size();i++){ megaApi.removeListener(listenersToRemove.get(i)); } } /** * Unregister a MegaRequestListener. * <p> * Stop receiving events from the specified listener. * * @param listener * Object that is unregistered. */ public void removeRequestListener(MegaRequestListenerInterface listener) { ArrayList<DelegateMegaRequestListener> listenersToRemove = new ArrayList<DelegateMegaRequestListener>(); synchronized (activeRequestListeners) { Iterator<DelegateMegaRequestListener> it = activeRequestListeners.iterator(); while (it.hasNext()) { DelegateMegaRequestListener delegate = it.next(); if (delegate.getUserListener() == listener) { listenersToRemove.add(delegate); it.remove(); } } } for (int i=0;i<listenersToRemove.size();i++){ megaApi.removeRequestListener(listenersToRemove.get(i)); } } /** * Unregister a MegaTransferListener. * <p> * Stop receiving events from the specified listener. * * @param listener * Object that is unregistered. */ public void removeTransferListener(MegaTransferListenerInterface listener) { ArrayList<DelegateMegaTransferListener> listenersToRemove = new ArrayList<DelegateMegaTransferListener>(); synchronized (activeTransferListeners) { Iterator<DelegateMegaTransferListener> it = activeTransferListeners.iterator(); while (it.hasNext()) { DelegateMegaTransferListener delegate = it.next(); if (delegate.getUserListener() == listener) { listenersToRemove.add(delegate); it.remove(); } } } for (int i=0;i<listenersToRemove.size();i++){ megaApi.removeTransferListener(listenersToRemove.get(i)); } } /** * Unregister a MegaGlobalListener. * <p> * Stop receiving events from the specified listener. * * @param listener * Object that is unregistered. */ public void removeGlobalListener(MegaGlobalListenerInterface listener) { ArrayList<DelegateMegaGlobalListener> listenersToRemove = new ArrayList<DelegateMegaGlobalListener>(); synchronized (activeGlobalListeners) { Iterator<DelegateMegaGlobalListener> it = activeGlobalListeners.iterator(); while (it.hasNext()) { DelegateMegaGlobalListener delegate = it.next(); if (delegate.getUserListener() == listener) { listenersToRemove.add(delegate); it.remove(); } } } for (int i=0;i<listenersToRemove.size();i++){ megaApi.removeGlobalListener(listenersToRemove.get(i)); } } /****************************************************************************************************/ // UTILS /****************************************************************************************************/ /** * Get an URL to transfer the current session to the webclient * * This function creates a new session for the link so logging out in the web client won't log out * the current session. * * The associated request type with this request is MegaRequest::TYPE_GET_SESSION_TRANSFER_URL * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getLink - URL to open the desired page with the same account * * You take the ownership of the returned value. * * @param path Path inside https://mega.nz/# that we want to open with the current session * * For example, if you want to open https://mega.nz/#pro, the parameter of this function should be "pro". * * @param listener MegaRequestListener to track this request */ public void getSessionTransferURL(String path, MegaRequestListenerInterface listener){ megaApi.getSessionTransferURL(path, createDelegateRequestListener(listener)); } /** * Get an URL to transfer the current session to the webclient * * This function creates a new session for the link so logging out in the web client won't log out * the current session. * * The associated request type with this request is MegaRequest::TYPE_GET_SESSION_TRANSFER_URL * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getLink - URL to open the desired page with the same account * * You take the ownership of the returned value. * * @param path Path inside https://mega.nz/# that we want to open with the current session * * For example, if you want to open https://mega.nz/#pro, the parameter of this function should be "pro". */ public void getSessionTransferURL(String path){ megaApi.getSessionTransferURL(path); } /** * Converts a Base32-encoded user handle (JID) to a MegaHandle. * <p> * @param base32Handle * Base32-encoded handle (JID). * @return User handle. */ public static long base32ToHandle(String base32Handle) { return MegaApi.base32ToHandle(base32Handle); } /** * Converts a Base64-encoded node handle to a MegaHandle. * <p> * The returned value can be used to recover a MegaNode using MegaApiJava.getNodeByHandle(). * You can revert this operation using MegaApiJava.handleToBase64(). * * @param base64Handle * Base64-encoded node handle. * @return Node handle. */ public static long base64ToHandle(String base64Handle) { return MegaApi.base64ToHandle(base64Handle); } /** * Converts a Base64-encoded user handle to a MegaHandle * * You can revert this operation using MegaApi::userHandleToBase64 * * @param base64Handle Base64-encoded node handle * @return Node handle */ public static long base64ToUserHandle(String base64Handle){ return MegaApi.base64ToUserHandle(base64Handle); } /** * Converts a MegaHandle to a Base64-encoded string. * <p> * You can revert this operation using MegaApiJava.base64ToHandle(). * * @param handle * to be converted. * @return Base64-encoded node handle. */ public static String handleToBase64(long handle) { return MegaApi.handleToBase64(handle); } /** * Converts a MegaHandle to a Base64-encoded string. * <p> * You take the ownership of the returned value. * You can revert this operation using MegaApiJava.base64ToHandle(). * * @param handle * handle to be converted. * @return Base64-encoded user handle. */ public static String userHandleToBase64(long handle) { return MegaApi.userHandleToBase64(handle); } /** * Add entropy to internal random number generators. * <p> * It's recommended to call this function with random data to * enhance security. * * @param data * Byte array with random data. * @param size * Size of the byte array (in bytes). */ public void addEntropy(String data, long size) { megaApi.addEntropy(data, size); } /** * Reconnect and retry all transfers. */ public void reconnect() { megaApi.retryPendingConnections(true, true); } /** * Retry all pending requests. * <p> * When requests fails they wait some time before being retried. That delay grows exponentially if the request * fails again. For this reason, and since this request is very lightweight, it's recommended to call it with * the default parameters on every user interaction with the application. This will prevent very big delays * completing requests. */ public void retryPendingConnections() { megaApi.retryPendingConnections(); } /** * Check if server-side Rubbish Bin autopurging is enabled for the current account * * Before using this function, it's needed to: * - If you are logged-in: call to MegaApi::login and MegaApi::fetchNodes. * * @return True if this feature is enabled. Otherwise false. */ public boolean serverSideRubbishBinAutopurgeEnabled(){ return megaApi.serverSideRubbishBinAutopurgeEnabled(); } /** * Check if the new format for public links is enabled * * Before using this function, it's needed to: * - If you are logged-in: call to MegaApi::login and MegaApi::fetchNodes. * - If you are not logged-in: call to MegaApi::getMiscFlags. * * @return True if this feature is enabled. Otherwise, false. */ public boolean newLinkFormatEnabled() { return megaApi.newLinkFormatEnabled(); } /** * Check if multi-factor authentication can be enabled for the current account. * * Before using this function, it's needed to: * - If you are logged-in: call to MegaApi::login and MegaApi::fetchNodes. * - If you are not logged-in: call to MegaApi::getMiscFlags. * * @return True if multi-factor authentication can be enabled for the current account, otherwise false. */ public boolean multiFactorAuthAvailable () { return megaApi.multiFactorAuthAvailable(); } /** * Reset the verified phone number for the account logged in. * * The associated request type with this request is MegaRequest::TYPE_RESET_SMS_VERIFIED_NUMBER * If there's no verified phone number associated for the account logged in, the error code * provided in onRequestFinish is MegaError::API_ENOENT. * * @param listener MegaRequestListener to track this request */ public void resetSmsVerifiedPhoneNumber(MegaRequestListenerInterface listener) { megaApi.resetSmsVerifiedPhoneNumber(createDelegateRequestListener(listener)); } /** * Reset the verified phone number for the account logged in. * * The associated request type with this request is MegaRequest::TYPE_RESET_SMS_VERIFIED_NUMBER * If there's no verified phone number associated for the account logged in, the error code * provided in onRequestFinish is MegaError::API_ENOENT. */ public void resetSmsVerifiedPhoneNumber() { megaApi.resetSmsVerifiedPhoneNumber(); } /** * Check if multi-factor authentication is enabled for an account * * The associated request type with this request is MegaRequest::TYPE_MULTI_FACTOR_AUTH_CHECK * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getEmail - Returns the email sent in the first parameter * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getFlag - Returns true if multi-factor authentication is enabled or false if it's disabled. * * @param email Email to check * @param listener MegaRequestListener to track this request */ public void multiFactorAuthCheck(String email, MegaRequestListenerInterface listener){ megaApi.multiFactorAuthCheck(email, createDelegateRequestListener(listener)); } /** * Check if multi-factor authentication is enabled for an account * * The associated request type with this request is MegaRequest::TYPE_MULTI_FACTOR_AUTH_CHECK * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getEmail - Returns the email sent in the first parameter * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getFlag - Returns true if multi-factor authentication is enabled or false if it's disabled. * * @param email Email to check */ public void multiFactorAuthCheck(String email){ megaApi.multiFactorAuthCheck(email); } /** * Get the secret code of the account to enable multi-factor authentication * The MegaApi object must be logged into an account to successfully use this function. * * The associated request type with this request is MegaRequest::TYPE_MULTI_FACTOR_AUTH_GET * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Returns the Base32 secret code needed to configure multi-factor authentication. * * @param listener MegaRequestListener to track this request */ public void multiFactorAuthGetCode(MegaRequestListenerInterface listener){ megaApi.multiFactorAuthGetCode(createDelegateRequestListener(listener)); } /** * Get the secret code of the account to enable multi-factor authentication * The MegaApi object must be logged into an account to successfully use this function. * * The associated request type with this request is MegaRequest::TYPE_MULTI_FACTOR_AUTH_GET * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Returns the Base32 secret code needed to configure multi-factor authentication. */ public void multiFactorAuthGetCode(){ megaApi.multiFactorAuthGetCode(); } /** * Enable multi-factor authentication for the account * The MegaApi object must be logged into an account to successfully use this function. * * The associated request type with this request is MegaRequest::TYPE_MULTI_FACTOR_AUTH_SET * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getFlag - Returns true * - MegaRequest::getPassword - Returns the pin sent in the first parameter * * @param pin Valid pin code for multi-factor authentication * @param listener MegaRequestListener to track this request */ public void multiFactorAuthEnable(String pin, MegaRequestListenerInterface listener){ megaApi.multiFactorAuthEnable(pin, createDelegateRequestListener(listener)); } /** * Enable multi-factor authentication for the account * The MegaApi object must be logged into an account to successfully use this function. * * The associated request type with this request is MegaRequest::TYPE_MULTI_FACTOR_AUTH_SET * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getFlag - Returns true * - MegaRequest::getPassword - Returns the pin sent in the first parameter * * @param pin Valid pin code for multi-factor authentication */ public void multiFactorAuthEnable(String pin){ megaApi.multiFactorAuthEnable(pin); } /** * Disable multi-factor authentication for the account * The MegaApi object must be logged into an account to successfully use this function. * * The associated request type with this request is MegaRequest::TYPE_MULTI_FACTOR_AUTH_SET * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getFlag - Returns false * - MegaRequest::getPassword - Returns the pin sent in the first parameter * * @param pin Valid pin code for multi-factor authentication * @param listener MegaRequestListener to track this request */ public void multiFactorAuthDisable(String pin, MegaRequestListenerInterface listener){ megaApi.multiFactorAuthDisable(pin, createDelegateRequestListener(listener)); } /** * Disable multi-factor authentication for the account * The MegaApi object must be logged into an account to successfully use this function. * * The associated request type with this request is MegaRequest::TYPE_MULTI_FACTOR_AUTH_SET * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getFlag - Returns false * - MegaRequest::getPassword - Returns the pin sent in the first parameter * * @param pin Valid pin code for multi-factor authentication */ public void multiFactorAuthDisable(String pin){ megaApi.multiFactorAuthDisable(pin); } /** * Log in to a MEGA account with multi-factor authentication enabled * * The associated request type with this request is MegaRequest::TYPE_LOGIN. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getEmail - Returns the first parameter * - MegaRequest::getPassword - Returns the second parameter * - MegaRequest::getText - Returns the third parameter * * If the email/password aren't valid the error code provided in onRequestFinish is * MegaError::API_ENOENT. * * @param email Email of the user * @param password Password * @param pin Pin code for multi-factor authentication * @param listener MegaRequestListener to track this request */ public void multiFactorAuthLogin(String email, String password, String pin, MegaRequestListenerInterface listener){ megaApi.multiFactorAuthLogin(email, password, pin, createDelegateRequestListener(listener)); } /** * Log in to a MEGA account with multi-factor authentication enabled * * The associated request type with this request is MegaRequest::TYPE_LOGIN. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getEmail - Returns the first parameter * - MegaRequest::getPassword - Returns the second parameter * - MegaRequest::getText - Returns the third parameter * * If the email/password aren't valid the error code provided in onRequestFinish is * MegaError::API_ENOENT. * * @param email Email of the user * @param password Password * @param pin Pin code for multi-factor authentication */ public void multiFactorAuthLogin(String email, String password, String pin){ megaApi.multiFactorAuthLogin(email, password, pin); } /** * Change the password of a MEGA account with multi-factor authentication enabled * * The associated request type with this request is MegaRequest::TYPE_CHANGE_PW * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getPassword - Returns the old password (if it was passed as parameter) * - MegaRequest::getNewPassword - Returns the new password * - MegaRequest::getText - Returns the pin code for multi-factor authentication * * @param oldPassword Old password (optional, it can be NULL to not check the old password) * @param newPassword New password * @param pin Pin code for multi-factor authentication * @param listener MegaRequestListener to track this request */ public void multiFactorAuthChangePassword(String oldPassword, String newPassword, String pin, MegaRequestListenerInterface listener){ megaApi.multiFactorAuthChangePassword(oldPassword, newPassword, pin, createDelegateRequestListener(listener)); } /** * Change the password of a MEGA account with multi-factor authentication enabled * * The associated request type with this request is MegaRequest::TYPE_CHANGE_PW * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getPassword - Returns the old password (if it was passed as parameter) * - MegaRequest::getNewPassword - Returns the new password * - MegaRequest::getText - Returns the pin code for multi-factor authentication * * @param oldPassword Old password (optional, it can be NULL to not check the old password) * @param newPassword New password * @param pin Pin code for multi-factor authentication */ public void multiFactorAuthChangePassword(String oldPassword, String newPassword, String pin){ megaApi.multiFactorAuthChangePassword(oldPassword, newPassword, pin); } /** * Initialize the change of the email address associated to an account with multi-factor authentication enabled. * * The associated request type with this request is MegaRequest::TYPE_GET_CHANGE_EMAIL_LINK. * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getEmail - Returns the email for the account * - MegaRequest::getText - Returns the pin code for multi-factor authentication * * If this request succeeds, a change-email link will be sent to the specified email address. * If no user is logged in, you will get the error code MegaError::API_EACCESS in onRequestFinish(). * * If the MEGA account is a sub-user business account, onRequestFinish will * be called with the error code MegaError::API_EMASTERONLY. * * @param email The new email to be associated to the account. * @param pin Pin code for multi-factor authentication * @param listener MegaRequestListener to track this request */ public void multiFactorAuthChangeEmail(String email, String pin, MegaRequestListenerInterface listener){ megaApi.multiFactorAuthChangeEmail(email, pin, createDelegateRequestListener(listener)); } /** * Initialize the change of the email address associated to an account with multi-factor authentication enabled. * * The associated request type with this request is MegaRequest::TYPE_GET_CHANGE_EMAIL_LINK. * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getEmail - Returns the email for the account * - MegaRequest::getText - Returns the pin code for multi-factor authentication * * If this request succeeds, a change-email link will be sent to the specified email address. * If no user is logged in, you will get the error code MegaError::API_EACCESS in onRequestFinish(). * * If the MEGA account is a sub-user business account, onRequestFinish will * be called with the error code MegaError::API_EMASTERONLY. * * @param email The new email to be associated to the account. * @param pin Pin code for multi-factor authentication */ public void multiFactorAuthChangeEmail(String email, String pin){ megaApi.multiFactorAuthChangeEmail(email, pin); } /** * Initialize the cancellation of an account. * * The associated request type with this request is MegaRequest::TYPE_GET_CANCEL_LINK. * * If this request succeeds, a cancellation link will be sent to the email address of the user. * If no user is logged in, you will get the error code MegaError::API_EACCESS in onRequestFinish(). * * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getText - Returns the pin code for multi-factor authentication * * If the MEGA account is a sub-user business account, onRequestFinish will * be called with the error code MegaError::API_EMASTERONLY. * * @see MegaApi::confirmCancelAccount * * @param pin Pin code for multi-factor authentication * @param listener MegaRequestListener to track this request */ public void multiFactorAuthCancelAccount(String pin, MegaRequestListenerInterface listener){ megaApi.multiFactorAuthCancelAccount(pin, createDelegateRequestListener(listener)); } /** * Initialize the cancellation of an account. * * The associated request type with this request is MegaRequest::TYPE_GET_CANCEL_LINK. * * If this request succeeds, a cancellation link will be sent to the email address of the user. * If no user is logged in, you will get the error code MegaError::API_EACCESS in onRequestFinish(). * * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getText - Returns the pin code for multi-factor authentication * * If the MEGA account is a sub-user business account, onRequestFinish will * be called with the error code MegaError::API_EMASTERONLY. * * @see MegaApi::confirmCancelAccount * * @param pin Pin code for multi-factor authentication */ public void multiFactorAuthCancelAccount(String pin){ megaApi.multiFactorAuthCancelAccount(pin); } /** * Fetch details related to time zones and the current default * * The associated request type with this request is MegaRequest::TYPE_FETCH_TIMEZONE. * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaTimeZoneDetails - Returns details about timezones and the current default * * @param listener MegaRequestListener to track this request */ void fetchTimeZone(MegaRequestListenerInterface listener){ megaApi.fetchTimeZone(createDelegateRequestListener(listener)); } /** * Fetch details related to time zones and the current default * * The associated request type with this request is MegaRequest::TYPE_FETCH_TIMEZONE. * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaTimeZoneDetails - Returns details about timezones and the current default * */ void fetchTimeZone(){ megaApi.fetchTimeZone(); } /** * Log in to a MEGA account. * <p> * The associated request type with this request is MegaRequest.TYPE_LOGIN. * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getEmail() - Returns the first parameter. <br> * - MegaRequest.getPassword() - Returns the second parameter. * <p> * If the email/password are not valid the error code provided in onRequestFinish() is * MegaError.API_ENOENT. * * @param email * Email of the user. * @param password * Password. * @param listener * MegaRequestListener to track this request. */ public void login(String email, String password, MegaRequestListenerInterface listener) { megaApi.login(email, password, createDelegateRequestListener(listener)); } /** * Log in to a MEGA account. * <p> * @param email * Email of the user. * @param password * Password. */ public void login(String email, String password) { megaApi.login(email, password); } /** * Log in to a public folder using a folder link. * <p> * After a successful login, you should call MegaApiJava.fetchNodes() to get filesystem and * start working with the folder. * <p> * The associated request type with this request is MegaRequest.TYPE_LOGIN. * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getEmail() - Returns the string "FOLDER". <br> * - MegaRequest.getLink() - Returns the public link to the folder. * * @param megaFolderLink * link to a folder in MEGA. * @param listener * MegaRequestListener to track this request. */ public void loginToFolder(String megaFolderLink, MegaRequestListenerInterface listener) { megaApi.loginToFolder(megaFolderLink, createDelegateRequestListener(listener)); } /** * Log in to a public folder using a folder link. * <p> * After a successful login, you should call MegaApiJava.fetchNodes() to get filesystem and * start working with the folder. * * @param megaFolderLink * link to a folder in MEGA. */ public void loginToFolder(String megaFolderLink) { megaApi.loginToFolder(megaFolderLink); } /** * Log in to a MEGA account using precomputed keys. * <p> * The associated request type with this request is MegaRequest.TYPE_LOGIN. * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getEmail() - Returns the first parameter. <br> * - MegaRequest.getPassword() - Returns the second parameter. <br> * - MegaRequest.getPrivateKey() - Returns the third parameter. * <p> * If the email/stringHash/base64pwKey are not valid the error code provided in onRequestFinish() is * MegaError.API_ENOENT. * * @param email * Email of the user. * @param stringHash * Hash of the email returned by MegaApiJava.getStringHash(). * @param base64pwkey * Private key calculated using MegaApiJava.getBase64PwKey(). * @param listener * MegaRequestListener to track this request. */ public void fastLogin(String email, String stringHash, String base64pwkey, MegaRequestListenerInterface listener) { megaApi.fastLogin(email, stringHash, base64pwkey, createDelegateRequestListener(listener)); } /** * Log in to a MEGA account using precomputed keys. * * @param email * Email of the user. * @param stringHash * Hash of the email returned by MegaApiJava.getStringHash(). * @param base64pwkey * Private key calculated using MegaApiJava.getBase64PwKey(). */ public void fastLogin(String email, String stringHash, String base64pwkey) { megaApi.fastLogin(email, stringHash, base64pwkey); } /** * Log in to a MEGA account using a session key. * <p> * The associated request type with this request is MegaRequest.TYPE_LOGIN. * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getSessionKey() - Returns the session key. * * @param session * Session key previously dumped with MegaApiJava.dumpSession(). * @param listener * MegaRequestListener to track this request. */ public void fastLogin(String session, MegaRequestListenerInterface listener) { megaApi.fastLogin(session, createDelegateRequestListener(listener)); } /** * Log in to a MEGA account using a session key. * * @param session * Session key previously dumped with MegaApiJava.dumpSession(). */ public void fastLogin(String session) { megaApi.fastLogin(session); } /** * Close a MEGA session. * * All clients using this session will be automatically logged out. * <p> * You can get session information using MegaApiJava.getExtendedAccountDetails(). * Then use MegaAccountDetails.getNumSessions and MegaAccountDetails.getSession * to get session info. * MegaAccountSession.getHandle provides the handle that this function needs. * <p> * If you use mega.INVALID_HANDLE, all sessions except the current one will be closed. * * @param sessionHandle * of the session. Use mega.INVALID_HANDLE to cancel all sessions except the current one. * @param listener * MegaRequestListenerInterface to track this request. */ public void killSession(long sessionHandle, MegaRequestListenerInterface listener) { megaApi.killSession(sessionHandle, createDelegateRequestListener(listener)); } /** * Close a MEGA session. * <p> * All clients using this session will be automatically logged out. * <p> * You can get session information using MegaApiJava.getExtendedAccountDetails(). * Then use MegaAccountDetails.getNumSessions and MegaAccountDetails.getSession * to get session info. * MegaAccountSession.getHandle provides the handle that this function needs. * <p> * If you use mega.INVALID_HANDLE, all sessions except the current one will be closed. * * @param sessionHandle * of the session. Use mega.INVALID_HANDLE to cancel all sessions except the current one. */ public void killSession(long sessionHandle) { megaApi.killSession(sessionHandle); } /** * Get data about the logged account. * <p> * The associated request type with this request is MegaRequest.TYPE_GET_USER_DATA. * <p> * Valid data in the MegaRequest object received in onRequestFinish() when the error code * is MegaError.API_OK: <br> * - MegaRequest.getName() - Returns the name of the logged user. <br> * - MegaRequest.getPassword() - Returns the the public RSA key of the account, Base64-encoded. <br> * - MegaRequest.getPrivateKey() - Returns the private RSA key of the account, Base64-encoded. * * @param listener * MegaRequestListenerInterface to track this request. */ public void getUserData(MegaRequestListenerInterface listener) { megaApi.getUserData(createDelegateRequestListener(listener)); } /** * Get data about the logged account. * */ public void getUserData() { megaApi.getUserData(); } /** * Get data about a contact. * <p> * The associated request type with this request is MegaRequest.TYPE_GET_USER_DATA. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest.getEmail - Returns the email of the contact * <p> * Valid data in the MegaRequest object received in onRequestFinish() when the error code * is MegaError.API_OK: <br> * - MegaRequest.getText() - Returns the XMPP ID of the contact. <br> * - MegaRequest.getPassword() - Returns the public RSA key of the contact, Base64-encoded. * * @param user * Contact to get the data. * @param listener * MegaRequestListenerInterface to track this request. */ public void getUserData(MegaUser user, MegaRequestListenerInterface listener) { megaApi.getUserData(user, createDelegateRequestListener(listener)); } /** * Get data about a contact. * * @param user * Contact to get the data. */ public void getUserData(MegaUser user) { megaApi.getUserData(user); } /** * Get data about a contact. * <p> * The associated request type with this request is MegaRequest.TYPE_GET_USER_DATA. * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getEmail() - Returns the email or the Base64 handle of the contact. * <p> * Valid data in the MegaRequest object received in onRequestFinish() when the error code * is MegaError.API_OK: <br> * - MegaRequest.getText() - Returns the XMPP ID of the contact. <br> * - MegaRequest.getPassword() - Returns the public RSA key of the contact, Base64-encoded. * * @param user * Email or Base64 handle of the contact. * @param listener * MegaRequestListenerInterface to track this request. */ public void getUserData(String user, MegaRequestListenerInterface listener) { megaApi.getUserData(user, createDelegateRequestListener(listener)); } /** * Get data about a contact. * * @param user * Email or Base64 handle of the contact. */ public void getUserData(String user) { megaApi.getUserData(user); } /** * Fetch miscellaneous flags when not logged in * * The associated request type with this request is MegaRequest::TYPE_GET_MISC_FLAGS. * * When onRequestFinish is called with MegaError::API_OK, the global flags are available. * If you are logged in into an account, the error code provided in onRequestFinish is * MegaError::API_EACCESS. * * @see MegaApi::multiFactorAuthAvailable * @see MegaApi::newLinkFormatEnabled * @see MegaApi::smsAllowedState * * @param listener MegaRequestListener to track this request */ public void getMiscFlags(MegaRequestListenerInterface listener) { megaApi.getMiscFlags(createDelegateRequestListener(listener)); } /** * Fetch miscellaneous flags when not logged in * * The associated request type with this request is MegaRequest::TYPE_GET_MISC_FLAGS. * * When onRequestFinish is called with MegaError::API_OK, the global flags are available. * If you are logged in into an account, the error code provided in onRequestFinish is * MegaError::API_EACCESS. * * @see MegaApi::multiFactorAuthAvailable * @see MegaApi::newLinkFormatEnabled * @see MegaApi::smsAllowedState */ public void getMiscFlags() { megaApi.getMiscFlags(); } /** * Trigger special account state changes for own accounts, for testing * * Because the dev API command allows a wide variety of state changes including suspension and unsuspension, * it has restrictions on which accounts you can target, and where it can be called from. * * Your client must be on a company VPN IP address. * * The target account must be an @mega email address. The target account must either be the calling account, * OR a related account via a prefix and + character. For example if the calling account is name1+test@mega.co.nz * then it can perform a dev command on itself or on name1@mega.co.nz, name1+bob@mega.co.nz etc, but NOT on * name2@mega.co.nz or name2+test@meg.co.nz. * * The associated request type with this request is MegaRequest::TYPE_SEND_DEV_COMMAND. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getName - Returns the first parameter * - MegaRequest::getEmail - Returns the second parameter * * Possible errors are: * - EACCESS if the calling account is not allowed to perform this method (not a mega email account, not the right IP, etc). * - EARGS if the subcommand is not present or is invalid * - EBLOCKED if the target account is not allowed (this could also happen if the target account does not exist) * * Possible commands: * - "aodq" - Advance ODQ Warning State * If called, this will advance your ODQ warning state until the final warning state, * at which point it will turn on the ODQ paywall for your account. It requires an account lock on the target account. * This subcommand will return the 'step' of the warning flow you have advanced to - 1, 2, 3 or 4 * (the paywall is turned on at step 4) * * Valid data in the MegaRequest object received in onRequestFinish when the error code is MegaError::API_OK: * + MegaRequest::getNumber - Returns the number of warnings (1, 2, 3 or 4). * * Possible errors in addition to the standard dev ones are: * + EFAILED - your account is not in the RED stoplight state * * @param command The subcommand for the specific operation * @param email Optional email of the target email's account. If null, it will use the logged-in account * @param listener MegaRequestListener to track this request */ public void sendDevCommand(String command, String email, MegaRequestListenerInterface listener) { megaApi.sendDevCommand(command, email, createDelegateRequestListener(listener)); } /** * Returns the current session key. * <p> * You have to be logged in to get a valid session key. Otherwise, * this function returns null. * * @return Current session key. */ public String dumpSession() { return megaApi.dumpSession(); } /** * Get an authentication token that can be used to identify the user account * * If this MegaApi object is not logged into an account, this function will return NULL * * The value returned by this function can be used in other instances of MegaApi * thanks to the function MegaApi::setAccountAuth. * * You take the ownership of the returned value * * @return Authentication token */ public String getAccountAuth() { return megaApi.getAccountAuth(); } /** * Use an authentication token to identify an account while accessing public folders * * This function is useful to preserve the PRO status when a public folder is being * used. The identifier will be sent in all API requests made after the call to this function. * * To stop using the current authentication token, it's needed to explicitly call * this function with NULL as parameter. Otherwise, the value set would continue * being used despite this MegaApi object is logged in or logged out. * * It's recommended to call this function before the usage of MegaApi::loginToFolder * * @param auth Authentication token used to identify the account of the user. * You can get it using MegaApi::getAccountAuth with an instance of MegaApi logged into * an account. */ public void setAccountAuth(String auth) { megaApi.setAccountAuth(auth); } /** * Create Ephemeral++ account * * This kind of account allows to join chat links and to keep the session in the device * where it was created. * * The associated request type with this request is MegaRequest::TYPE_CREATE_ACCOUNT. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getName - Returns the firstname of the user * - MegaRequest::getText - Returns the lastname of the user * - MegaRequest::getParamType - Returns the value MegaApi:CREATE_EPLUSPLUS_ACCOUNT * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * MegaRequest::getSessionKey - Returns the session id to resume the process * * If this request succeeds, a new ephemeral++ account will be created for the new user. * The app may resume the create-account process by using MegaApi::resumeCreateAccountEphemeralPlusPlus. * * @note This account should be confirmed in same device it was created * * @param firstname Firstname of the user * @param lastname Lastname of the user * @param listener MegaRequestListener to track this request */ public void createEphemeralAccountPlusPlus(String firstname, String lastname, MegaRequestListenerInterface listener) { megaApi.createEphemeralAccountPlusPlus(firstname, lastname, createDelegateRequestListener(listener)); } /** * Initialize the creation of a new MEGA account, with firstname and lastname * * The associated request type with this request is MegaRequest::TYPE_CREATE_ACCOUNT. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getEmail - Returns the email for the account * - MegaRequest::getPassword - Returns the password for the account * - MegaRequest::getName - Returns the firstname of the user * - MegaRequest::getText - Returns the lastname of the user * - MegaRequest::getParamType - Returns the value MegaApi::CREATE_ACCOUNT * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getSessionKey - Returns the session id to resume the process * * If this request succeeds, a new ephemeral account will be created for the new user * and a confirmation email will be sent to the specified email address. The app may * resume the create-account process by using MegaApi::resumeCreateAccount. * * If an account with the same email already exists, you will get the error code * MegaError::API_EEXIST in onRequestFinish * * @param email Email for the account * @param password Password for the account * @param firstname Firstname of the user * @param lastname Lastname of the user * @param listener MegaRequestListener to track this request */ public void createAccount(String email, String password, String firstname, String lastname, MegaRequestListenerInterface listener){ megaApi.createAccount(email, password, firstname, lastname, createDelegateRequestListener(listener)); } /** * Initialize the creation of a new MEGA account, with firstname and lastname * * The associated request type with this request is MegaRequest::TYPE_CREATE_ACCOUNT. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getEmail - Returns the email for the account * - MegaRequest::getPassword - Returns the password for the account * - MegaRequest::getName - Returns the firstname of the user * - MegaRequest::getText - Returns the lastname of the user * - MegaRequest::getParamType - Returns the value MegaApi::CREATE_ACCOUNT * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getSessionKey - Returns the session id to resume the process * * If this request succeeds, a new ephemeral account will be created for the new user * and a confirmation email will be sent to the specified email address. The app may * resume the create-account process by using MegaApi::resumeCreateAccount. * * If an account with the same email already exists, you will get the error code * MegaError::API_EEXIST in onRequestFinish * * @param email Email for the account * @param password Password for the account * @param firstname Firstname of the user * @param lastname Lastname of the user */ public void createAccount(String email, String password, String firstname, String lastname){ megaApi.createAccount(email, password, firstname, lastname); } /** * Initialize the creation of a new MEGA account, with firstname and lastname * * The associated request type with this request is MegaRequest::TYPE_CREATE_ACCOUNT. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getEmail - Returns the email for the account * - MegaRequest::getPassword - Returns the password for the account * - MegaRequest::getName - Returns the firstname of the user * - MegaRequest::getText - Returns the lastname of the user * - MegaRequest::getNodeHandle - Returns the last public node handle accessed * - MegaRequest::getAccess - Returns the type of lastPublicHandle * - MegaRequest::getTransferredBytes - Returns the timestamp of the last access * - MegaRequest::getParamType - Returns the value MegaApi::CREATE_ACCOUNT * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getSessionKey - Returns the session id to resume the process * * If this request succeeds, a new ephemeral session will be created for the new user * and a confirmation email will be sent to the specified email address. The app may * resume the create-account process by using MegaApi::resumeCreateAccount. * * If an account with the same email already exists, you will get the error code * MegaError::API_EEXIST in onRequestFinish * * @param email Email for the account * @param password Password for the account * @param firstname Firstname of the user * @param lastname Lastname of the user * @param lastPublicHandle Last public node handle accessed by the user in the last 24h * @param lastPublicHandleType Indicates the type of lastPublicHandle, valid values are: * - MegaApi::AFFILIATE_TYPE_ID = 1 * - MegaApi::AFFILIATE_TYPE_FILE_FOLDER = 2 * - MegaApi::AFFILIATE_TYPE_CHAT = 3 * - MegaApi::AFFILIATE_TYPE_CONTACT = 4 * * @param lastAccessTimestamp Timestamp of the last access * @param listener MegaRequestListener to track this request */ public void createAccount(String email, String password, String firstname, String lastname, long lastPublicHandle, int lastPublicHandleType, long lastAccessTimestamp, MegaRequestListenerInterface listener) { megaApi.createAccount(email, password, firstname, lastname, lastPublicHandle, lastPublicHandleType, lastAccessTimestamp, createDelegateRequestListener(listener)); } /** * Initialize the creation of a new MEGA account, with firstname and lastname * * The associated request type with this request is MegaRequest::TYPE_CREATE_ACCOUNT. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getEmail - Returns the email for the account * - MegaRequest::getPassword - Returns the password for the account * - MegaRequest::getName - Returns the firstname of the user * - MegaRequest::getText - Returns the lastname of the user * - MegaRequest::getNodeHandle - Returns the last public node handle accessed * - MegaRequest::getAccess - Returns the type of lastPublicHandle * - MegaRequest::getTransferredBytes - Returns the timestamp of the last access * - MegaRequest::getParamType - Returns the value MegaApi::CREATE_ACCOUNT * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getSessionKey - Returns the session id to resume the process * * If this request succeeds, a new ephemeral session will be created for the new user * and a confirmation email will be sent to the specified email address. The app may * resume the create-account process by using MegaApi::resumeCreateAccount. * * If an account with the same email already exists, you will get the error code * MegaError::API_EEXIST in onRequestFinish * * @param email Email for the account * @param password Password for the account * @param firstname Firstname of the user * @param lastname Lastname of the user * @param lastPublicHandle Last public node handle accessed by the user in the last 24h * @param lastPublicHandleType Indicates the type of lastPublicHandle, valid values are: * - MegaApi::AFFILIATE_TYPE_ID = 1 * - MegaApi::AFFILIATE_TYPE_FILE_FOLDER = 2 * - MegaApi::AFFILIATE_TYPE_CHAT = 3 * - MegaApi::AFFILIATE_TYPE_CONTACT = 4 * * @param lastAccessTimestamp Timestamp of the last access */ public void createAccount(String email, String password, String firstname, String lastname, long lastPublicHandle, int lastPublicHandleType, long lastAccessTimestamp) { megaApi.createAccount(email, password, firstname, lastname, lastPublicHandle, lastPublicHandleType, lastAccessTimestamp); } /** * Resume a registration process * * When a user begins the account registration process by calling MegaApi::createAccount, * an ephemeral account is created. * * Until the user successfully confirms the signup link sent to the provided email address, * you can resume the ephemeral session in order to change the email address, resend the * signup link (@see MegaApi::sendSignupLink) and also to receive notifications in case the * user confirms the account using another client (MegaGlobalListener::onAccountUpdate or * MegaListener::onAccountUpdate). It is also possible to cancel the registration process by * MegaApi::cancelCreateAccount, which invalidates the signup link associated to the ephemeral * session (the session will be still valid). * * The associated request type with this request is MegaRequest::TYPE_CREATE_ACCOUNT. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getSessionKey - Returns the session id to resume the process * - MegaRequest::getParamType - Returns the value MegaApi::RESUME_ACCOUNT * * In case the account is already confirmed, the associated request will fail with * error MegaError::API_EARGS. * * @param sid Session id valid for the ephemeral account (@see MegaApi::createAccount) * @param listener MegaRequestListener to track this request */ public void resumeCreateAccount(String sid, MegaRequestListenerInterface listener) { megaApi.resumeCreateAccount(sid, createDelegateRequestListener(listener)); } /** * Resume a registration process * * When a user begins the account registration process by calling MegaApi::createAccount, * an ephemeral account is created. * * Until the user successfully confirms the signup link sent to the provided email address, * you can resume the ephemeral session in order to change the email address, resend the * signup link (@see MegaApi::sendSignupLink) and also to receive notifications in case the * user confirms the account using another client (MegaGlobalListener::onAccountUpdate or * MegaListener::onAccountUpdate). It is also possible to cancel the registration process by * MegaApi::cancelCreateAccount, which invalidates the signup link associated to the ephemeral * session (the session will be still valid). * * The associated request type with this request is MegaRequest::TYPE_CREATE_ACCOUNT. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getSessionKey - Returns the session id to resume the process * - MegaRequest::getParamType - Returns the value MegaApi::RESUME_ACCOUNT * * In case the account is already confirmed, the associated request will fail with * error MegaError::API_EARGS. * * @param sid Session id valid for the ephemeral account (@see MegaApi::createAccount) */ public void resumeCreateAccount(String sid) { megaApi.resumeCreateAccount(sid); } /** * Sends the confirmation email for a new account * * This function is useful to send the confirmation link again or to send it to a different * email address, in case the user mistyped the email at the registration form. * * @param email Email for the account * @param name Firstname of the user * @param password Password for the account * @param listener MegaRequestListener to track this request */ public void sendSignupLink(String email, String name, String password, MegaRequestListenerInterface listener) { megaApi.sendSignupLink(email, name, password, createDelegateRequestListener(listener)); } /** * Sends the confirmation email for a new account * * This function is useful to send the confirmation link again or to send it to a different * email address, in case the user mistyped the email at the registration form. * * @param email Email for the account * @param name Firstname of the user * @param password Password for the account */ public void sendSignupLink(String email, String name, String password) { megaApi.sendSignupLink(email, name, password); } /** * Get information about a confirmation link. * <p> * The associated request type with this request is MegaRequest.TYPE_QUERY_SIGNUP_LINK. * Valid data in the MegaRequest object received on all callbacks: <br> * - MegaRequest.getLink() - Returns the confirmation link. * <p> * Valid data in the MegaRequest object received in onRequestFinish() when the error code * is MegaError.API_OK: <br> * - MegaRequest.getEmail() - Return the email associated with the confirmation link. <br> * - MegaRequest.getName() - Returns the name associated with the confirmation link. * * @param link * Confirmation link. * @param listener * MegaRequestListener to track this request. */ public void querySignupLink(String link, MegaRequestListenerInterface listener) { megaApi.querySignupLink(link, createDelegateRequestListener(listener)); } /** * Get information about a confirmation link. * * @param link * Confirmation link. */ public void querySignupLink(String link) { megaApi.querySignupLink(link); } /** * Confirm a MEGA account using a confirmation link and the user password. * <p> * The associated request type with this request is MegaRequest.TYPE_CONFIRM_ACCOUNT * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getLink() - Returns the confirmation link. <br> * - MegaRequest.getPassword() - Returns the password. * <p> * Valid data in the MegaRequest object received in onRequestFinish() when the error code * is MegaError.API_OK: <br> * - MegaRequest.getEmail() - Email of the account. <br> * - MegaRequest.getName() - Name of the user. * * @param link * Confirmation link. * @param password * Password for the account. * @param listener * MegaRequestListener to track this request. */ public void confirmAccount(String link, String password, MegaRequestListenerInterface listener) { megaApi.confirmAccount(link, password, createDelegateRequestListener(listener)); } /** * Confirm a MEGA account using a confirmation link and the user password. * * @param link * Confirmation link. * @param password * Password for the account. */ public void confirmAccount(String link, String password) { megaApi.confirmAccount(link, password); } /** * Confirm a MEGA account using a confirmation link and a precomputed key. * <p> * The associated request type with this request is MegaRequest.TYPE_CONFIRM_ACCOUNT * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getLink() - Returns the confirmation link. <br> * - MegaRequest.getPrivateKey() - Returns the base64pwkey parameter. * <p> * Valid data in the MegaRequest object received in onRequestFinish() when the error code * is MegaError.API_OK: <br> * - MegaRequest.getEmail() - Email of the account. <br> * - MegaRequest.getName() - Name of the user. * * @param link * Confirmation link. * @param base64pwkey * Private key precomputed with MegaApiJava.getBase64PwKey(). * @param listener * MegaRequestListener to track this request. */ public void fastConfirmAccount(String link, String base64pwkey, MegaRequestListenerInterface listener) { megaApi.fastConfirmAccount(link, base64pwkey, createDelegateRequestListener(listener)); } /** * Confirm a MEGA account using a confirmation link and a precomputed key. * * @param link * Confirmation link. * @param base64pwkey * Private key precomputed with MegaApiJava.getBase64PwKey(). */ public void fastConfirmAccount(String link, String base64pwkey) { megaApi.fastConfirmAccount(link, base64pwkey); } /** * Initialize the reset of the existing password, with and without the Master Key. * * The associated request type with this request is MegaRequest::TYPE_GET_RECOVERY_LINK. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getEmail - Returns the email for the account * - MegaRequest::getFlag - Returns whether the user has a backup of the master key or not. * * If this request succeed, a recovery link will be sent to the user. * If no account is registered under the provided email, you will get the error code * MegaError::API_EEXIST in onRequestFinish * * @param email Email used to register the account whose password wants to be reset. * @param hasMasterKey True if the user has a backup of the master key. Otherwise, false. * @param listener MegaRequestListener to track this request */ public void resetPassword(String email, boolean hasMasterKey, MegaRequestListenerInterface listener){ megaApi.resetPassword(email, hasMasterKey, createDelegateRequestListener(listener)); } /** * Get information about a recovery link created by MegaApi::resetPassword. * * The associated request type with this request is MegaRequest::TYPE_QUERY_RECOVERY_LINK * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getLink - Returns the recovery link * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getEmail - Return the email associated with the link * - MegaRequest::getFlag - Return whether the link requires masterkey to reset password. * * @param link Recovery link (#recover) * @param listener MegaRequestListener to track this request */ public void queryResetPasswordLink(String link, MegaRequestListenerInterface listener){ megaApi.queryResetPasswordLink(link, createDelegateRequestListener(listener)); } /** * Set a new password for the account pointed by the recovery link. * * Recovery links are created by calling MegaApi::resetPassword and may or may not * require to provide the Master Key. * * @see The flag of the MegaRequest::TYPE_QUERY_RECOVERY_LINK in MegaApi::queryResetPasswordLink. * * The associated request type with this request is MegaRequest::TYPE_CONFIRM_ACCOUNT * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getLink - Returns the recovery link * - MegaRequest::getPassword - Returns the new password * - MegaRequest::getPrivateKey - Returns the Master Key, when provided * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getEmail - Return the email associated with the link * - MegaRequest::getFlag - Return whether the link requires masterkey to reset password. * * @param link The recovery link sent to the user's email address. * @param newPwd The new password to be set. * @param masterKey Base64-encoded string containing the master key (optional). * @param listener MegaRequestListener to track this request */ public void confirmResetPassword(String link, String newPwd, String masterKey, MegaRequestListenerInterface listener){ megaApi.confirmResetPassword(link, newPwd, masterKey, createDelegateRequestListener(listener)); } /** * Initialize the cancellation of an account. * * The associated request type with this request is MegaRequest::TYPE_GET_CANCEL_LINK. * * If this request succeed, a cancellation link will be sent to the email address of the user. * If no user is logged in, you will get the error code MegaError::API_EACCESS in onRequestFinish(). * * If the MEGA account is a sub-user business account, onRequestFinish will * be called with the error code MegaError::API_EMASTERONLY. * * @see MegaApi::confirmCancelAccount * * @param listener MegaRequestListener to track this request */ public void cancelAccount(MegaRequestListenerInterface listener){ megaApi.cancelAccount(createDelegateRequestListener(listener)); } /** * Get information about a cancel link created by MegaApi::cancelAccount. * * The associated request type with this request is MegaRequest::TYPE_QUERY_RECOVERY_LINK * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getLink - Returns the cancel link * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getEmail - Return the email associated with the link * * @param link Cancel link (#cancel) * @param listener MegaRequestListener to track this request */ public void queryCancelLink(String link, MegaRequestListenerInterface listener){ megaApi.queryCancelLink(link, createDelegateRequestListener(listener)); } /** * Effectively parks the user's account without creating a new fresh account. * * The contents of the account will then be purged after 60 days. Once the account is * parked, the user needs to contact MEGA support to restore the account. * * The associated request type with this request is MegaRequest::TYPE_CONFIRM_CANCEL_LINK. * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getLink - Returns the recovery link * - MegaRequest::getPassword - Returns the new password * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getEmail - Return the email associated with the link * * @param link Cancellation link sent to the user's email address; * @param pwd Password for the account. * @param listener MegaRequestListener to track this request */ public void confirmCancelAccount(String link, String pwd, MegaRequestListenerInterface listener){ megaApi.confirmCancelAccount(link, pwd, createDelegateRequestListener(listener)); } /** * Allow to resend the verification email for Weak Account Protection * * The verification email will be resent to the same address as it was previously sent to. * * This function can be called if the the reason for being blocked is: * 700: the account is supended for Weak Account Protection. * * If the logged in account is not suspended or is suspended for some other reason, * onRequestFinish will be called with the error code MegaError::API_EACCESS. * * If the logged in account has not been sent the unlock email before, * onRequestFinish will be called with the error code MegaError::API_EARGS. * * @param listener MegaRequestListener to track this request */ public void resendVerificationEmail(MegaRequestListenerInterface listener) { megaApi.resendVerificationEmail(createDelegateRequestListener(listener)); } /** * Allow to resend the verification email for Weak Account Protection * * The verification email will be resent to the same address as it was previously sent to. * * This function can be called if the the reason for being blocked is: * 700: the account is supended for Weak Account Protection. * * If the logged in account is not suspended or is suspended for some other reason, * onRequestFinish will be called with the error code MegaError::API_EACCESS. * * If the logged in account has not been sent the unlock email before, * onRequestFinish will be called with the error code MegaError::API_EARGS. */ public void resendVerificationEmail() { megaApi.resendVerificationEmail(); } /** * Initialize the change of the email address associated to the account. * * The associated request type with this request is MegaRequest::TYPE_GET_CHANGE_EMAIL_LINK. * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getEmail - Returns the email for the account * * If this request succeed, a change-email link will be sent to the specified email address. * If no user is logged in, you will get the error code MegaError::API_EACCESS in onRequestFinish(). * * If the MEGA account is a sub-user business account, onRequestFinish will * be called with the error code MegaError::API_EMASTERONLY. * * @param email The new email to be associated to the account. * @param listener MegaRequestListener to track this request */ public void changeEmail(String email, MegaRequestListenerInterface listener){ megaApi.changeEmail(email, createDelegateRequestListener(listener)); } /** * Get information about a change-email link created by MegaApi::changeEmail. * * If no user is logged in, you will get the error code MegaError::API_EACCESS in onRequestFinish(). * * The associated request type with this request is MegaRequest::TYPE_QUERY_RECOVERY_LINK * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getLink - Returns the change-email link * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getEmail - Return the email associated with the link * * @param link Change-email link (#verify) * @param listener MegaRequestListener to track this request */ public void queryChangeEmailLink(String link, MegaRequestListenerInterface listener){ megaApi.queryChangeEmailLink(link, createDelegateRequestListener(listener)); } /** * Effectively changes the email address associated to the account. * * The associated request type with this request is MegaRequest::TYPE_CONFIRM_CHANGE_EMAIL_LINK. * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getLink - Returns the change-email link * - MegaRequest::getPassword - Returns the password * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getEmail - Return the email associated with the link * * @param link Change-email link sent to the user's email address. * @param pwd Password for the account. * @param listener MegaRequestListener to track this request */ public void confirmChangeEmail(String link, String pwd, MegaRequestListenerInterface listener){ megaApi.confirmChangeEmail(link, pwd, createDelegateRequestListener(listener)); } /** * Set proxy settings. * <p> * The SDK will start using the provided proxy settings as soon as this function returns. * * @param proxySettings * settings. * @see MegaProxy */ public void setProxySettings(MegaProxy proxySettings) { megaApi.setProxySettings(proxySettings); } /** * Try to detect the system's proxy settings. * * Automatic proxy detection is currently supported on Windows only. * On other platforms, this function will return a MegaProxy object * of type MegaProxy.PROXY_NONE. * * @return MegaProxy object with the detected proxy settings. */ public MegaProxy getAutoProxySettings() { return megaApi.getAutoProxySettings(); } /** * Check if the MegaApi object is logged in. * * @return 0 if not logged in. Otherwise, a number >= 0. */ public int isLoggedIn() { return megaApi.isLoggedIn(); } /** * Check if we are logged in into an Ephemeral account ++ * @return true if logged into an Ephemeral account ++, Otherwise return false */ public boolean isEphemeralPlusPlus() { return megaApi.isEphemeralPlusPlus(); } /** * Check the reason of being blocked. * * The associated request type with this request is MegaRequest::TYPE_WHY_AM_I_BLOCKED. * * This request can be sent internally at anytime (whenever an account gets blocked), so * a MegaGlobalListener should process the result, show the reason and logout. * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Returns the reason string (in English) * - MegaRequest::getNumber - Returns the reason code. Possible values: * 0: The account is not blocked * 200: suspension message for any type of suspension, but copyright suspension. * 300: suspension only for multiple copyright violations. * 400: the subuser account has been disabled. * 401: the subuser account has been removed. * 500: The account needs to be verified by an SMS code. * 700: the account is supended for Weak Account Protection. * * If the error code in the MegaRequest object received in onRequestFinish * is MegaError::API_OK, the user is not blocked. * * @param listener MegaRequestListener to track this request */ public void whyAmIBlocked(MegaRequestListenerInterface listener) { megaApi.whyAmIBlocked(createDelegateRequestListener(listener)); } /** * Check the reason of being blocked. * * The associated request type with this request is MegaRequest::TYPE_WHY_AM_I_BLOCKED. * * This request can be sent internally at anytime (whenever an account gets blocked), so * a MegaGlobalListener should process the result, show the reason and logout. * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Returns the reason string (in English) * - MegaRequest::getNumber - Returns the reason code. Possible values: * 0: The account is not blocked * 200: suspension message for any type of suspension, but copyright suspension. * 300: suspension only for multiple copyright violations. * 400: the subuser account has been disabled. * 401: the subuser account has been removed. * 500: The account needs to be verified by an SMS code. * 700: the account is supended for Weak Account Protection. * * If the error code in the MegaRequest object received in onRequestFinish * is MegaError::API_OK, the user is not blocked. */ public void whyAmIBlocked() { megaApi.whyAmIBlocked(); } /** * Create a contact link * * The associated request type with this request is MegaRequest::TYPE_CONTACT_LINK_CREATE. * * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getFlag - Returns the value of \c renew parameter * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodeHandle - Return the handle of the new contact link * * @param renew True to invalidate the previous contact link (if any). * @param listener MegaRequestListener to track this request */ public void contactLinkCreate(boolean renew, MegaRequestListenerInterface listener){ megaApi.contactLinkCreate(renew, createDelegateRequestListener(listener)); } /** * Create a contact link * * The associated request type with this request is MegaRequest::TYPE_CONTACT_LINK_CREATE. * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodeHandle - Return the handle of the new contact link * */ public void contactLinkCreate(){ megaApi.contactLinkCreate(); } /** * Get information about a contact link * * The associated request type with this request is MegaRequest::TYPE_CONTACT_LINK_QUERY. * * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the contact link * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getEmail - Returns the email of the contact * - MegaRequest::getName - Returns the first name of the contact * - MegaRequest::getText - Returns the last name of the contact * * @param handle Handle of the contact link to check * @param listener MegaRequestListener to track this request */ public void contactLinkQuery(long handle, MegaRequestListenerInterface listener){ megaApi.contactLinkQuery(handle, createDelegateRequestListener(listener)); } /** * Get information about a contact link * * The associated request type with this request is MegaRequest::TYPE_CONTACT_LINK_QUERY. * * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the contact link * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getEmail - Returns the email of the contact * - MegaRequest::getName - Returns the first name of the contact * - MegaRequest::getText - Returns the last name of the contact * * @param handle Handle of the contact link to check */ public void contactLinkQuery(long handle){ megaApi.contactLinkQuery(handle); } /** * Delete a contact link * * The associated request type with this request is MegaRequest::TYPE_CONTACT_LINK_DELETE. * * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the contact link * * @param handle Handle of the contact link to delete * If the parameter is INVALID_HANDLE, the active contact link is deleted * * @param listener MegaRequestListener to track this request */ public void contactLinkDelete(long handle, MegaRequestListenerInterface listener){ megaApi.contactLinkDelete(handle, createDelegateRequestListener(listener)); } /** * Delete a contact link * * The associated request type with this request is MegaRequest::TYPE_CONTACT_LINK_DELETE. * * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the contact link * * @param handle Handle of the contact link to delete */ public void contactLinkDelete(long handle){ megaApi.contactLinkDelete(handle); } /** * Get the next PSA (Public Service Announcement) that should be shown to the user * * After the PSA has been accepted or dismissed by the user, app should * use MegaApi::setPSA to notify API servers about this event and * do not get the same PSA again in the next call to this function. * * The associated request type with this request is MegaRequest::TYPE_GET_PSA. * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNumber - Returns the id of the PSA (useful to call MegaApi::setPSA later) * Depending on the format of the PSA, the request may additionally return, for the new format: * - MegaRequest::getEmail - Returns the URL (or an empty string) * ...or for the old format: * - MegaRequest::getName - Returns the title of the PSA * - MegaRequest::getText - Returns the text of the PSA * - MegaRequest::getFile - Returns the URL of the image of the PSA * - MegaRequest::getPassword - Returns the text for the positive button (or an empty string) * - MegaRequest::getLink - Returns the link for the positive button (or an empty string) * * If there isn't any new PSA to show, onRequestFinish will be called with the error * code MegaError::API_ENOENT * * @param listener MegaRequestListener to track this request * @see MegaApi::setPSA */ public void getPSAWithUrl(MegaRequestListenerInterface listener){ megaApi.getPSAWithUrl(createDelegateRequestListener(listener)); } /** * Notify API servers that a PSA (Public Service Announcement) has been already seen * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER. * * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the value MegaApi::USER_ATTR_LAST_PSA * - MegaRequest::getText - Returns the id passed in the first parameter (as a string) * * @param id Identifier of the PSA * @param listener MegaRequestListener to track this request * * @see MegaApi::getPSA */ public void setPSA(int id, MegaRequestListenerInterface listener){ megaApi.setPSA(id, createDelegateRequestListener(listener)); } /** * Notify API servers that a PSA (Public Service Announcement) has been already seen * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER. * * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the value MegaApi::USER_ATTR_LAST_PSA * - MegaRequest::getText - Returns the id passed in the first parameter (as a string) * * @param id Identifier of the PSA * * @see MegaApi::getPSA */ public void setPSA(int id){ megaApi.setPSA(id); } /** * Command to acknowledge user alerts. * * Other clients will be notified that alerts to this point have been seen. * * @param listener MegaRequestListener to track this request */ public void acknowledgeUserAlerts(MegaRequestListenerInterface listener){ megaApi.acknowledgeUserAlerts(createDelegateRequestListener(listener)); } /** * Command to acknowledge user alerts. * * Other clients will be notified that alerts to this point have been seen. * * @see MegaApi::getUserAlerts */ public void acknowledgeUserAlerts(){ megaApi.acknowledgeUserAlerts(); } /** * Returns the email of the currently open account. * * If the MegaApi object is not logged in or the email is not available, * this function returns null. * * @return Email of the account. */ public String getMyEmail() { return megaApi.getMyEmail(); } /** * Returns the user handle of the currently open account * * If the MegaApi object isn't logged in, * this function returns null * * @return User handle of the account */ public String getMyUserHandle() { return megaApi.getMyUserHandle(); } /** * Returns the user handle of the currently open account * * If the MegaApi object isn't logged in, * this function returns INVALID_HANDLE * * @return User handle of the account */ public long getMyUserHandleBinary(){ return megaApi.getMyUserHandleBinary(); } /** * Get the MegaUser of the currently open account * * If the MegaApi object isn't logged in, this function returns NULL. * * You take the ownership of the returned value * * @note The visibility of your own user is unhdefined and shouldn't be used. * @return MegaUser of the currently open account, otherwise NULL */ public MegaUser getMyUser(){ return megaApi.getMyUser(); } /** * Returns whether MEGA Achievements are enabled for the open account * @return True if enabled, false otherwise. */ public boolean isAchievementsEnabled() { return megaApi.isAchievementsEnabled(); } /** * Check if the account is a business account. * @return returns true if it's a business account, otherwise false */ public boolean isBusinessAccount() { return megaApi.isBusinessAccount(); } /** * Check if the account is a master account. * * When a business account is a sub-user, not the master, some user actions will be blocked. * In result, the API will return the error code MegaError::API_EMASTERONLY. Some examples of * requests that may fail with this error are: * - MegaApi::cancelAccount * - MegaApi::changeEmail * - MegaApi::remove * - MegaApi::removeVersion * * @return returns true if it's a master account, false if it's a sub-user account */ public boolean isMasterBusinessAccount() { return megaApi.isMasterBusinessAccount(); } /** * Check if the business account is active or not. * * When a business account is not active, some user actions will be blocked. In result, the API * will return the error code MegaError::API_EBUSINESSPASTDUE. Some examples of requests * that may fail with this error are: * - MegaApi::startDownload * - MegaApi::startUpload * - MegaApi::copyNode * - MegaApi::share * - MegaApi::cleanRubbishBin * * @return returns true if the account is active, otherwise false */ public boolean isBusinessAccountActive() { return megaApi.isBusinessAccountActive(); } /** * Get the status of a business account. * @return Returns the business account status, possible values: * MegaApi::BUSINESS_STATUS_EXPIRED = -1 * MegaApi::BUSINESS_STATUS_INACTIVE = 0 * MegaApi::BUSINESS_STATUS_ACTIVE = 1 * MegaApi::BUSINESS_STATUS_GRACE_PERIOD = 2 */ public int getBusinessStatus() { return megaApi.getBusinessStatus(); } /** * Returns the deadline to remedy the storage overquota situation * * This value is valid only when MegaApi::getUserData has been called after * receiving a callback MegaListener/MegaGlobalListener::onEvent of type * MegaEvent::EVENT_STORAGE, reporting STORAGE_STATE_PAYWALL. * The value will become invalid once the state of storage changes. * * @return Timestamp representing the deadline to remedy the overquota */ public long getOverquotaDeadlineTs() { return megaApi.getOverquotaDeadlineTs(); } /** * Returns when the user was warned about overquota state * * This value is valid only when MegaApi::getUserData has been called after * receiving a callback MegaListener/MegaGlobalListener::onEvent of type * MegaEvent::EVENT_STORAGE, reporting STORAGE_STATE_PAYWALL. * The value will become invalid once the state of storage changes. * * You take the ownership of the returned value. * * @return MegaIntegerList with the timestamp corresponding to each warning */ public MegaIntegerList getOverquotaWarningsTs() { return megaApi.getOverquotaWarningsTs(); } /** * Check if the password is correct for the current account * @param password Password to check * @return True if the password is correct for the current account, otherwise false. */ public boolean checkPassword(String password){ return megaApi.checkPassword(password); } /** * Returns the credentials of the currently open account * * If the MegaApi object isn't logged in or there's no signing key available, * this function returns NULL * * You take the ownership of the returned value. * Use delete [] to free it. * * @return Fingerprint of the signing key of the current account */ public String getMyCredentials() { return megaApi.getMyCredentials(); } /** * Returns the credentials of a given user * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns MegaApi::USER_ATTR_ED25519_PUBLIC_KEY * - MegaRequest::getFlag - Returns true * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getPassword - Returns the credentials in hexadecimal format * * @param user MegaUser of the contact (see MegaApi::getContact) to get the fingerprint * @param listener MegaRequestListener to track this request */ public void getUserCredentials(MegaUser user, MegaRequestListenerInterface listener) { megaApi.getUserCredentials(user, createDelegateRequestListener(listener)); } /** * Checks if credentials are verified for the given user * * @param user MegaUser of the contact whose credentiasl want to be checked * @return true if verified, false otherwise */ public boolean areCredentialsVerified(MegaUser user){ return megaApi.areCredentialsVerified(user); } /** * Verify credentials of a given user * * This function allow to tag credentials of a user as verified. It should be called when the * logged in user compares the fingerprint of the user (provided by an independent and secure * method) with the fingerprint shown by the app (@see MegaApi::getUserCredentials). * * The associated request type with this request is MegaRequest::TYPE_VERIFY_CREDENTIALS * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns userhandle * * @param user MegaUser of the contact whose credentials want to be verified * @param listener MegaRequestListener to track this request */ public void verifyCredentials(MegaUser user, MegaRequestListenerInterface listener){ megaApi.verifyCredentials(user, createDelegateRequestListener(listener)); } /** * Reset credentials of a given user * * Call this function to forget the existing authentication of keys and signatures for a given * user. A full reload of the account will start the authentication process again. * * The associated request type with this request is MegaRequest::TYPE_VERIFY_CREDENTIALS * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns userhandle * - MegaRequest::getFlag - Returns true * * @param user MegaUser of the contact whose credentials want to be reset * @param listener MegaRequestListener to track this request */ public void resetCredentials(MegaUser user, MegaRequestListenerInterface listener) { megaApi.resetCredentials(user, createDelegateRequestListener(listener)); } /** * Set the active log level. * <p> * This function sets the log level of the logging system. If you set a log listener using * MegaApiJava.setLoggerObject(), you will receive logs with the same or a lower level than * the one passed to this function. * * @param logLevel * Active log level. These are the valid values for this parameter: <br> * - MegaApiJava.LOG_LEVEL_FATAL = 0. <br> * - MegaApiJava.LOG_LEVEL_ERROR = 1. <br> * - MegaApiJava.LOG_LEVEL_WARNING = 2. <br> * - MegaApiJava.LOG_LEVEL_INFO = 3. <br> * - MegaApiJava.LOG_LEVEL_DEBUG = 4. <br> * - MegaApiJava.LOG_LEVEL_MAX = 5. */ public static void setLogLevel(int logLevel) { MegaApi.setLogLevel(logLevel); } /** * Add a MegaLogger implementation to receive SDK logs * * Logs received by this objects depends on the active log level. * By default, it is MegaApi::LOG_LEVEL_INFO. You can change it * using MegaApi::setLogLevel. * * You can remove the existing logger by using MegaApi::removeLoggerObject. * * @param megaLogger MegaLogger implementation */ public static void addLoggerObject(MegaLoggerInterface megaLogger){ MegaApi.addLoggerObject(createDelegateMegaLogger(megaLogger)); } /** * Remove a MegaLogger implementation to stop receiving SDK logs * * If the logger was registered in the past, it will stop receiving log * messages after the call to this function. * * @param megaLogger Previously registered MegaLogger implementation */ public static void removeLoggerObject(MegaLoggerInterface megaLogger){ ArrayList<DelegateMegaLogger> listenersToRemove = new ArrayList<DelegateMegaLogger>(); synchronized (activeMegaLoggers) { Iterator<DelegateMegaLogger> it = activeMegaLoggers.iterator(); while (it.hasNext()) { DelegateMegaLogger delegate = it.next(); if (delegate.getUserListener() == megaLogger) { listenersToRemove.add(delegate); it.remove(); } } } for (int i=0;i<listenersToRemove.size();i++){ MegaApi.removeLoggerObject(listenersToRemove.get(i)); } } /** * Send a log to the logging system. * <p> * This log will be received by the active logger object (MegaApiJava.setLoggerObject()) if * the log level is the same or lower than the active log level (MegaApiJava.setLogLevel()). * * @param logLevel * Log level for this message. * @param message * Message for the logging system. * @param filename * Origin of the log message. * @param line * Line of code where this message was generated. */ public static void log(int logLevel, String message, String filename, int line) { MegaApi.log(logLevel, message, filename, line); } /** * Send a log to the logging system. * <p> * This log will be received by the active logger object (MegaApiJava.setLoggerObject()) if * the log level is the same or lower than the active log level (MegaApiJava.setLogLevel()). * * @param logLevel * Log level for this message. * @param message * Message for the logging system. * @param filename * Origin of the log message. */ public static void log(int logLevel, String message, String filename) { MegaApi.log(logLevel, message, filename); } /** * Send a log to the logging system. * <p> * This log will be received by the active logger object (MegaApiJava.setLoggerObject()) if * the log level is the same or lower than the active log level (MegaApiJava.setLogLevel()). * * @param logLevel * Log level for this message. * @param message * Message for the logging system. */ public static void log(int logLevel, String message) { MegaApi.log(logLevel, message); } /** * Create a folder in the MEGA account * * The associated request type with this request is MegaRequest::TYPE_CREATE_FOLDER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParentHandle - Returns the handle of the parent folder * - MegaRequest::getName - Returns the name of the new folder * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodeHandle - Handle of the new folder * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param name Name of the new folder * @param parent Parent folder * @param listener MegaRequestListener to track this request */ public void createFolder(String name, MegaNode parent, MegaRequestListenerInterface listener) { megaApi.createFolder(name, parent, createDelegateRequestListener(listener)); } /** * Create a folder in the MEGA account * * The associated request type with this request is MegaRequest::TYPE_CREATE_FOLDER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParentHandle - Returns the handle of the parent folder * - MegaRequest::getName - Returns the name of the new folder * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodeHandle - Handle of the new folder * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param name Name of the new folder * @param parent Parent folder */ public void createFolder(String name, MegaNode parent) { megaApi.createFolder(name, parent); } /** * Move a node in the MEGA account * * The associated request type with this request is MegaRequest::TYPE_MOVE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to move * - MegaRequest::getParentHandle - Returns the handle of the new parent for the node * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node Node to move * @param newParent New parent for the node * @param listener MegaRequestListener to track this request */ public void moveNode(MegaNode node, MegaNode newParent, MegaRequestListenerInterface listener) { megaApi.moveNode(node, newParent, createDelegateRequestListener(listener)); } /** * Move a node in the MEGA account * * The associated request type with this request is MegaRequest::TYPE_MOVE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to move * - MegaRequest::getParentHandle - Returns the handle of the new parent for the node * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node Node to move * @param newParent New parent for the node */ public void moveNode(MegaNode node, MegaNode newParent) { megaApi.moveNode(node, newParent); } /** * Move a node in the MEGA account changing the file name * * The associated request type with this request is MegaRequest::TYPE_MOVE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to move * - MegaRequest::getParentHandle - Returns the handle of the new parent for the node * - MegaRequest::getName - Returns the name for the new node * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node Node to move * @param newParent New parent for the node * @param newName Name for the new node * @param listener MegaRequestListener to track this request */ void moveNode(MegaNode node, MegaNode newParent, String newName, MegaRequestListenerInterface listener) { megaApi.moveNode(node, newParent, newName, createDelegateRequestListener(listener)); } /** * Move a node in the MEGA account changing the file name * * The associated request type with this request is MegaRequest::TYPE_MOVE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to move * - MegaRequest::getParentHandle - Returns the handle of the new parent for the node * - MegaRequest::getName - Returns the name for the new node * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node Node to move * @param newParent New parent for the node * @param newName Name for the new node */ void moveNode(MegaNode node, MegaNode newParent, String newName) { megaApi.moveNode(node, newParent, newName); } /** * Copy a node in the MEGA account * * The associated request type with this request is MegaRequest::TYPE_COPY * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to copy * - MegaRequest::getParentHandle - Returns the handle of the new parent for the new node * - MegaRequest::getPublicMegaNode - Returns the node to copy (if it is a public node) * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodeHandle - Handle of the new node * * If the status of the business account is expired, onRequestFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. * * @param node Node to copy * @param newParent Parent for the new node * @param listener MegaRequestListener to track this request */ public void copyNode(MegaNode node, MegaNode newParent, MegaRequestListenerInterface listener) { megaApi.copyNode(node, newParent, createDelegateRequestListener(listener)); } /** * Copy a node in the MEGA account * * The associated request type with this request is MegaRequest::TYPE_COPY * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to copy * - MegaRequest::getParentHandle - Returns the handle of the new parent for the new node * - MegaRequest::getPublicMegaNode - Returns the node to copy (if it is a public node) * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodeHandle - Handle of the new node * * If the status of the business account is expired, onRequestFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. * * @param node Node to copy * @param newParent Parent for the new node */ public void copyNode(MegaNode node, MegaNode newParent) { megaApi.copyNode(node, newParent); } /** * Copy a node in the MEGA account changing the file name * * The associated request type with this request is MegaRequest::TYPE_COPY * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to copy * - MegaRequest::getParentHandle - Returns the handle of the new parent for the new node * - MegaRequest::getPublicMegaNode - Returns the node to copy * - MegaRequest::getName - Returns the name for the new node * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodeHandle - Handle of the new node * * If the status of the business account is expired, onRequestFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. * * @param node Node to copy * @param newParent Parent for the new node * @param newName Name for the new node * @param listener MegaRequestListener to track this request */ public void copyNode(MegaNode node, MegaNode newParent, String newName, MegaRequestListenerInterface listener) { megaApi.copyNode(node, newParent, newName, createDelegateRequestListener(listener)); } /** * Copy a node in the MEGA account changing the file name * * The associated request type with this request is MegaRequest::TYPE_COPY * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to copy * - MegaRequest::getParentHandle - Returns the handle of the new parent for the new node * - MegaRequest::getPublicMegaNode - Returns the node to copy * - MegaRequest::getName - Returns the name for the new node * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodeHandle - Handle of the new node * * If the status of the business account is expired, onRequestFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. * * @param node Node to copy * @param newParent Parent for the new node * @param newName Name for the new node */ public void copyNode(MegaNode node, MegaNode newParent, String newName) { megaApi.copyNode(node, newParent, newName); } /** * Rename a node in the MEGA account * * The associated request type with this request is MegaRequest::TYPE_RENAME * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to rename * - MegaRequest::getName - Returns the new name for the node * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node Node to modify * @param newName New name for the node * @param listener MegaRequestListener to track this request */ public void renameNode(MegaNode node, String newName, MegaRequestListenerInterface listener) { megaApi.renameNode(node, newName, createDelegateRequestListener(listener)); } /** * Rename a node in the MEGA account * * The associated request type with this request is MegaRequest::TYPE_RENAME * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to rename * - MegaRequest::getName - Returns the new name for the node * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node Node to modify * @param newName New name for the node */ public void renameNode(MegaNode node, String newName) { megaApi.renameNode(node, newName); } /** * Remove a node from the MEGA account * * This function doesn't move the node to the Rubbish Bin, it fully removes the node. To move * the node to the Rubbish Bin use MegaApi::moveNode * * If the node has previous versions, they will be deleted too * * The associated request type with this request is MegaRequest::TYPE_REMOVE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to remove * - MegaRequest::getFlag - Returns false because previous versions won't be preserved * * If the MEGA account is a sub-user business account, onRequestFinish will * be called with the error code MegaError::API_EMASTERONLY. * * @param node Node to remove * @param listener MegaRequestListener to track this request */ public void remove(MegaNode node, MegaRequestListenerInterface listener) { megaApi.remove(node, createDelegateRequestListener(listener)); } /** * Remove a node from the MEGA account * * This function doesn't move the node to the Rubbish Bin, it fully removes the node. To move * the node to the Rubbish Bin use MegaApi::moveNode * * If the node has previous versions, they will be deleted too * * The associated request type with this request is MegaRequest::TYPE_REMOVE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to remove * - MegaRequest::getFlag - Returns false because previous versions won't be preserved * * If the MEGA account is a sub-user business account, onRequestFinish will * be called with the error code MegaError::API_EMASTERONLY. * * @param node Node to remove */ public void remove(MegaNode node) { megaApi.remove(node); } /** * Remove all versions from the MEGA account * * The associated request type with this request is MegaRequest::TYPE_REMOVE_VERSIONS * * When the request finishes, file versions might not be deleted yet. * Deletions are notified using onNodesUpdate callbacks. * * @param listener MegaRequestListener to track this request */ public void removeVersions(MegaRequestListenerInterface listener){ megaApi.removeVersions(createDelegateRequestListener(listener)); } /** * Remove a version of a file from the MEGA account * * This function doesn't move the node to the Rubbish Bin, it fully removes the node. To move * the node to the Rubbish Bin use MegaApi::moveNode. * * If the node has previous versions, they won't be deleted. * * The associated request type with this request is MegaRequest::TYPE_REMOVE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to remove * - MegaRequest::getFlag - Returns true because previous versions will be preserved * * If the MEGA account is a sub-user business account, onRequestFinish will * be called with the error code MegaError::API_EMASTERONLY. * * @param node Node to remove * @param listener MegaRequestListener to track this request */ public void removeVersion(MegaNode node, MegaRequestListenerInterface listener){ megaApi.removeVersion(node, createDelegateRequestListener(listener)); } /** * Restore a previous version of a file * * Only versions of a file can be restored, not the current version (because it's already current). * The node will be copied and set as current. All the version history will be preserved without changes, * being the old current node the previous version of the new current node, and keeping the restored * node also in its previous place in the version history. * * The associated request type with this request is MegaRequest::TYPE_RESTORE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to restore * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param version Node with the version to restore * @param listener MegaRequestListener to track this request */ public void restoreVersion(MegaNode version, MegaRequestListenerInterface listener){ megaApi.restoreVersion(version, createDelegateRequestListener(listener)); } /** * Clean the Rubbish Bin in the MEGA account * * This function effectively removes every node contained in the Rubbish Bin. In order to * avoid accidental deletions, you might want to warn the user about the action. * * The associated request type with this request is MegaRequest::TYPE_CLEAN_RUBBISH_BIN. This * request returns MegaError::API_ENOENT if the Rubbish bin is already empty. * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param listener MegaRequestListener to track this request */ public void cleanRubbishBin(MegaRequestListenerInterface listener) { megaApi.cleanRubbishBin(createDelegateRequestListener(listener)); } /** * Clean the Rubbish Bin in the MEGA account * * This function effectively removes every node contained in the Rubbish Bin. In order to * avoid accidental deletions, you might want to warn the user about the action. * * The associated request type with this request is MegaRequest::TYPE_CLEAN_RUBBISH_BIN. This * request returns MegaError::API_ENOENT if the Rubbish bin is already empty. * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. */ public void cleanRubbishBin() { megaApi.cleanRubbishBin(); } /** * Send a node to the Inbox of another MEGA user using a MegaUser * * The associated request type with this request is MegaRequest::TYPE_COPY * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to send * - MegaRequest::getEmail - Returns the email of the user that receives the node * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node Node to send * @param user User that receives the node * @param listener MegaRequestListener to track this request */ public void sendFileToUser(MegaNode node, MegaUser user, MegaRequestListenerInterface listener) { megaApi.sendFileToUser(node, user, createDelegateRequestListener(listener)); } /** * Send a node to the Inbox of another MEGA user using a MegaUser * * The associated request type with this request is MegaRequest::TYPE_COPY * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to send * - MegaRequest::getEmail - Returns the email of the user that receives the node * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node Node to send * @param user User that receives the node */ public void sendFileToUser(MegaNode node, MegaUser user) { megaApi.sendFileToUser(node, user); } /** * Send a node to the Inbox of another MEGA user using his email * * The associated request type with this request is MegaRequest::TYPE_COPY * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to send * - MegaRequest::getEmail - Returns the email of the user that receives the node * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node Node to send * @param email Email of the user that receives the node * @param listener MegaRequestListener to track this request */ public void sendFileToUser(MegaNode node, String email, MegaRequestListenerInterface listener){ megaApi.sendFileToUser(node, email, createDelegateRequestListener(listener)); } /** * Share or stop sharing a folder in MEGA with another user using a MegaUser * * To share a folder with an user, set the desired access level in the level parameter. If you * want to stop sharing a folder use the access level MegaShare::ACCESS_UNKNOWN * * The associated request type with this request is MegaRequest::TYPE_SHARE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the folder to share * - MegaRequest::getEmail - Returns the email of the user that receives the shared folder * - MegaRequest::getAccess - Returns the access that is granted to the user * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node The folder to share. It must be a non-root folder * @param user User that receives the shared folder * @param level Permissions that are granted to the user * Valid values for this parameter: * - MegaShare::ACCESS_UNKNOWN = -1 * Stop sharing a folder with this user * * - MegaShare::ACCESS_READ = 0 * - MegaShare::ACCESS_READWRITE = 1 * - MegaShare::ACCESS_FULL = 2 * - MegaShare::ACCESS_OWNER = 3 * * @param listener MegaRequestListener to track this request */ public void share(MegaNode node, MegaUser user, int level, MegaRequestListenerInterface listener) { megaApi.share(node, user, level, createDelegateRequestListener(listener)); } /** * Share or stop sharing a folder in MEGA with another user using a MegaUser * * To share a folder with an user, set the desired access level in the level parameter. If you * want to stop sharing a folder use the access level MegaShare::ACCESS_UNKNOWN * * The associated request type with this request is MegaRequest::TYPE_SHARE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the folder to share * - MegaRequest::getEmail - Returns the email of the user that receives the shared folder * - MegaRequest::getAccess - Returns the access that is granted to the user * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node The folder to share. It must be a non-root folder * @param user User that receives the shared folder * @param level Permissions that are granted to the user * Valid values for this parameter: * - MegaShare::ACCESS_UNKNOWN = -1 * Stop sharing a folder with this user * * - MegaShare::ACCESS_READ = 0 * - MegaShare::ACCESS_READWRITE = 1 * - MegaShare::ACCESS_FULL = 2 * - MegaShare::ACCESS_OWNER = 3 */ public void share(MegaNode node, MegaUser user, int level) { megaApi.share(node, user, level); } /** * Share or stop sharing a folder in MEGA with another user using his email * * To share a folder with an user, set the desired access level in the level parameter. If you * want to stop sharing a folder use the access level MegaShare::ACCESS_UNKNOWN * * The associated request type with this request is MegaRequest::TYPE_SHARE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the folder to share * - MegaRequest::getEmail - Returns the email of the user that receives the shared folder * - MegaRequest::getAccess - Returns the access that is granted to the user * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node The folder to share. It must be a non-root folder * @param email Email of the user that receives the shared folder. If it doesn't have a MEGA account, the folder will be shared anyway * and the user will be invited to register an account. * * @param level Permissions that are granted to the user * Valid values for this parameter: * - MegaShare::ACCESS_UNKNOWN = -1 * Stop sharing a folder with this user * * - MegaShare::ACCESS_READ = 0 * - MegaShare::ACCESS_READWRITE = 1 * - MegaShare::ACCESS_FULL = 2 * - MegaShare::ACCESS_OWNER = 3 * * @param listener MegaRequestListener to track this request */ public void share(MegaNode node, String email, int level, MegaRequestListenerInterface listener) { megaApi.share(node, email, level, createDelegateRequestListener(listener)); } /** * Share or stop sharing a folder in MEGA with another user using his email * * To share a folder with an user, set the desired access level in the level parameter. If you * want to stop sharing a folder use the access level MegaShare::ACCESS_UNKNOWN * * The associated request type with this request is MegaRequest::TYPE_SHARE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the folder to share * - MegaRequest::getEmail - Returns the email of the user that receives the shared folder * - MegaRequest::getAccess - Returns the access that is granted to the user * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node The folder to share. It must be a non-root folder * @param email Email of the user that receives the shared folder. If it doesn't have a MEGA account, the folder will be shared anyway * and the user will be invited to register an account. * * @param level Permissions that are granted to the user * Valid values for this parameter: * - MegaShare::ACCESS_UNKNOWN = -1 * Stop sharing a folder with this user * * - MegaShare::ACCESS_READ = 0 * - MegaShare::ACCESS_READWRITE = 1 * - MegaShare::ACCESS_FULL = 2 * - MegaShare::ACCESS_OWNER = 3 */ public void share(MegaNode node, String email, int level) { megaApi.share(node, email, level); } /** * Import a public link to the account * * The associated request type with this request is MegaRequest::TYPE_IMPORT_LINK * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getLink - Returns the public link to the file * - MegaRequest::getParentHandle - Returns the folder that receives the imported file * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodeHandle - Handle of the new node in the account * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param megaFileLink Public link to a file in MEGA * @param parent Parent folder for the imported file * @param listener MegaRequestListener to track this request */ public void importFileLink(String megaFileLink, MegaNode parent, MegaRequestListenerInterface listener) { megaApi.importFileLink(megaFileLink, parent, createDelegateRequestListener(listener)); } /** * Import a public link to the account * * The associated request type with this request is MegaRequest::TYPE_IMPORT_LINK * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getLink - Returns the public link to the file * - MegaRequest::getParentHandle - Returns the folder that receives the imported file * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodeHandle - Handle of the new node in the account * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param megaFileLink Public link to a file in MEGA * @param parent Parent folder for the imported file */ public void importFileLink(String megaFileLink, MegaNode parent) { megaApi.importFileLink(megaFileLink, parent); } /** * Decrypt password-protected public link * * The associated request type with this request is MegaRequest::TYPE_PASSWORD_LINK * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getLink - Returns the encrypted public link to the file/folder * - MegaRequest::getPassword - Returns the password to decrypt the link * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Decrypted public link * * @param link Password/protected public link to a file/folder in MEGA * @param password Password to decrypt the link * @param listener MegaRequestListenerInterface to track this request */ public void decryptPasswordProtectedLink(String link, String password, MegaRequestListenerInterface listener) { megaApi.decryptPasswordProtectedLink(link, password, createDelegateRequestListener(listener)); } /** * Decrypt password-protected public link * * The associated request type with this request is MegaRequest::TYPE_PASSWORD_LINK * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getLink - Returns the encrypted public link to the file/folder * - MegaRequest::getPassword - Returns the password to decrypt the link * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Decrypted public link * * @param link Password/protected public link to a file/folder in MEGA * @param password Password to decrypt the link */ public void decryptPasswordProtectedLink(String link, String password){ megaApi.decryptPasswordProtectedLink(link, password); } /** * Encrypt public link with password * * The associated request type with this request is MegaRequest::TYPE_PASSWORD_LINK * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getLink - Returns the public link to be encrypted * - MegaRequest::getPassword - Returns the password to encrypt the link * - MegaRequest::getFlag - Returns true * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Encrypted public link * * @param link Public link to be encrypted, including encryption key for the link * @param password Password to encrypt the link * @param listener MegaRequestListenerInterface to track this request */ public void encryptLinkWithPassword(String link, String password, MegaRequestListenerInterface listener) { megaApi.encryptLinkWithPassword(link, password, createDelegateRequestListener(listener)); } /** * Encrypt public link with password * * The associated request type with this request is MegaRequest::TYPE_PASSWORD_LINK * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getLink - Returns the public link to be encrypted * - MegaRequest::getPassword - Returns the password to encrypt the link * - MegaRequest::getFlag - Returns true * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Encrypted public link * * @param link Public link to be encrypted, including encryption key for the link * @param password Password to encrypt the link */ public void encryptLinkWithPassword(String link, String password) { megaApi.encryptLinkWithPassword(link, password); } /** * Get a MegaNode from a public link to a file * * A public node can be imported using MegaApi::copyNode or downloaded using MegaApi::startDownload * * The associated request type with this request is MegaRequest::TYPE_GET_PUBLIC_NODE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getLink - Returns the public link to the file * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getPublicMegaNode - Public MegaNode corresponding to the public link * - MegaRequest::getFlag - Return true if the provided key along the link is invalid. * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param megaFileLink Public link to a file in MEGA * @param listener MegaRequestListener to track this request */ public void getPublicNode(String megaFileLink, MegaRequestListenerInterface listener) { megaApi.getPublicNode(megaFileLink, createDelegateRequestListener(listener)); } /** * Get a MegaNode from a public link to a file * * A public node can be imported using MegaApi::copyNode or downloaded using MegaApi::startDownload * * The associated request type with this request is MegaRequest::TYPE_GET_PUBLIC_NODE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getLink - Returns the public link to the file * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getPublicMegaNode - Public MegaNode corresponding to the public link * - MegaRequest::getFlag - Return true if the provided key along the link is invalid. * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param megaFileLink Public link to a file in MEGA */ public void getPublicNode(String megaFileLink) { megaApi.getPublicNode(megaFileLink); } /** * Get the thumbnail of a node. * <p> * If the node does not have a thumbnail, the request fails with the MegaError.API_ENOENT * error code. * <p> * The associated request type with this request is MegaRequest.TYPE_GET_ATTR_FILE * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getNodeHandle() - Returns the handle of the node. <br> * - MegaRequest.getFile() - Returns the destination path. <br> * - MegaRequest.getParamType() - Returns MegaApiJava.ATTR_TYPE_THUMBNAIL. * * @param node * Node to get the thumbnail. * @param dstFilePath * Destination path for the thumbnail. * If this path is a local folder, it must end with a '\' or '/' character and (Base64-encoded handle + "0.jpg") * will be used as the file name inside that folder. If the path does not finish with * one of these characters, the file will be downloaded to a file in that path. * * @param listener * MegaRequestListener to track this request. */ public void getThumbnail(MegaNode node, String dstFilePath, MegaRequestListenerInterface listener) { megaApi.getThumbnail(node, dstFilePath, createDelegateRequestListener(listener)); } /** * Get the thumbnail of a node. * <p> * If the node does not have a thumbnail the request fails with the MegaError.API_ENOENT * error code. * * @param node * Node to get the thumbnail. * @param dstFilePath * Destination path for the thumbnail. * If this path is a local folder, it must end with a '\' or '/' character and (Base64-encoded handle + "0.jpg") * will be used as the file name inside that folder. If the path does not finish with * one of these characters, the file will be downloaded to a file in that path. */ public void getThumbnail(MegaNode node, String dstFilePath) { megaApi.getThumbnail(node, dstFilePath); } /** * Get the preview of a node. * <p> * If the node does not have a preview the request fails with the MegaError.API_ENOENT * error code. * <p> * The associated request type with this request is MegaRequest.TYPE_GET_ATTR_FILE * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getNodeHandle() - Returns the handle of the node. <br> * - MegaRequest.getFile() - Returns the destination path. <br> * - MegaRequest.getParamType() - Returns MegaApiJava.ATTR_TYPE_PREVIEW. * * @param node * Node to get the preview. * @param dstFilePath * Destination path for the preview. * If this path is a local folder, it must end with a '\' or '/' character and (Base64-encoded handle + "1.jpg") * will be used as the file name inside that folder. If the path does not finish with * one of these characters, the file will be downloaded to a file in that path. * * @param listener * MegaRequestListener to track this request. */ public void getPreview(MegaNode node, String dstFilePath, MegaRequestListenerInterface listener) { megaApi.getPreview(node, dstFilePath, createDelegateRequestListener(listener)); } /** * Get the preview of a node. * <p> * If the node does not have a preview the request fails with the MegaError.API_ENOENT * error code. * * @param node * Node to get the preview. * @param dstFilePath * Destination path for the preview. * If this path is a local folder, it must end with a '\' or '/' character and (Base64-encoded handle + "1.jpg") * will be used as the file name inside that folder. If the path does not finish with * one of these characters, the file will be downloaded to a file in that path. */ public void getPreview(MegaNode node, String dstFilePath) { megaApi.getPreview(node, dstFilePath); } /** * Get the avatar of a MegaUser. * <p> * The associated request type with this request is MegaRequest.TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getFile() - Returns the destination path. <br> * - MegaRequest.getEmail() - Returns the email of the user. * * @param user * MegaUser to get the avatar. * @param dstFilePath * Destination path for the avatar. It has to be a path to a file, not to a folder. * If this path is a local folder, it must end with a '\' or '/' character and (email + "0.jpg") * will be used as the file name inside that folder. If the path does not finish with * one of these characters, the file will be downloaded to a file in that path. * * @param listener * MegaRequestListener to track this request. */ public void getUserAvatar(MegaUser user, String dstFilePath, MegaRequestListenerInterface listener) { megaApi.getUserAvatar(user, dstFilePath, createDelegateRequestListener(listener)); } /** * Get the avatar of a MegaUser. * * @param user * MegaUser to get the avatar. * @param dstFilePath * Destination path for the avatar. It has to be a path to a file, not to a folder. * If this path is a local folder, it must end with a '\' or '/' character and (email + "0.jpg") * will be used as the file name inside that folder. If the path does not finish with * one of these characters, the file will be downloaded to a file in that path. */ public void getUserAvatar(MegaUser user, String dstFilePath) { megaApi.getUserAvatar(user, dstFilePath); } /** * Get the avatar of any user in MEGA * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getFile - Returns the destination path * - MegaRequest::getEmail - Returns the email or the handle of the user (the provided one as parameter) * * @param user email_or_user Email or user handle (Base64 encoded) to get the avatar. If this parameter is * set to null, the avatar is obtained for the active account * @param dstFilePath Destination path for the avatar. It has to be a path to a file, not to a folder. * If this path is a local folder, it must end with a '\' or '/' character and (email + "0.jpg") * will be used as the file name inside that folder. If the path doesn't finish with * one of these characters, the file will be downloaded to a file in that path. * * @param listener MegaRequestListenerInterface to track this request */ public void getUserAvatar(String email_or_handle, String dstFilePath, MegaRequestListenerInterface listener) { megaApi.getUserAvatar(email_or_handle, dstFilePath, createDelegateRequestListener(listener)); } /** * Get the avatar of any user in MEGA * * @param user email_or_user Email or user handle (Base64 encoded) to get the avatar. If this parameter is * set to null, the avatar is obtained for the active account * @param dstFilePath Destination path for the avatar. It has to be a path to a file, not to a folder. * If this path is a local folder, it must end with a '\' or '/' character and (email + "0.jpg") * will be used as the file name inside that folder. If the path doesn't finish with * one of these characters, the file will be downloaded to a file in that path. */ public void getUserAvatar(String email_or_handle, String dstFilePath) { megaApi.getUserAvatar(email_or_handle, dstFilePath); } /** * Get the avatar of the active account * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getFile - Returns the destination path * - MegaRequest::getEmail - Returns the email of the user * * @param dstFilePath Destination path for the avatar. It has to be a path to a file, not to a folder. * If this path is a local folder, it must end with a '\' or '/' character and (email + "0.jpg") * will be used as the file name inside that folder. If the path doesn't finish with * one of these characters, the file will be downloaded to a file in that path. * * @param listener MegaRequestListenerInterface to track this request */ public void getUserAvatar(String dstFilePath, MegaRequestListenerInterface listener) { megaApi.getUserAvatar(dstFilePath, createDelegateRequestListener(listener)); } /** * Get the avatar of the active account * * @param dstFilePath Destination path for the avatar. It has to be a path to a file, not to a folder. * If this path is a local folder, it must end with a '\' or '/' character and (email + "0.jpg") * will be used as the file name inside that folder. If the path doesn't finish with * one of these characters, the file will be downloaded to a file in that path. */ public void getUserAvatar(String dstFilePath) { megaApi.getUserAvatar(dstFilePath); } /** * Get the default color for the avatar. * * This color should be used only when the user doesn't have an avatar. * * You take the ownership of the returned value. * * @param user MegaUser to get the color of the avatar. If this parameter is set to NULL, the color * is obtained for the active account. * @return The RGB color as a string with 3 components in hex: #RGB. Ie. "#FF6A19" * If the user is not found, this function returns NULL. */ public String getUserAvatarColor(MegaUser user){ return megaApi.getUserAvatarColor(user); } /** * Get the default color for the avatar. * * This color should be used only when the user doesn't have an avatar. * * You take the ownership of the returned value. * * @param userhandle User handle (Base64 encoded) to get the avatar. If this parameter is * set to NULL, the avatar is obtained for the active account * @return The RGB color as a string with 3 components in hex: #RGB. Ie. "#FF6A19" * If the user is not found (invalid userhandle), this function returns NULL. */ public String getUserAvatarColor(String userhandle){ return megaApi.getUserAvatarColor(userhandle); } /** * Get an attribute of a MegaUser. * * User attributes can be private or public. Private attributes are accessible only by * your own user, while public ones are retrievable by any of your contacts. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Returns the value for public attributes * - MegaRequest::getMegaStringMap - Returns the value for private attributes * * @param user MegaUser to get the attribute. If this parameter is set to NULL, the attribute * is obtained for the active account * @param type Attribute type * * Valid values are: * * MegaApi::USER_ATTR_FIRSTNAME = 1 * Get the firstname of the user (public) * MegaApi::USER_ATTR_LASTNAME = 2 * Get the lastname of the user (public) * MegaApi::USER_ATTR_AUTHRING = 3 * Get the authentication ring of the user (private) * MegaApi::USER_ATTR_LAST_INTERACTION = 4 * Get the last interaction of the contacts of the user (private) * MegaApi::USER_ATTR_ED25519_PUBLIC_KEY = 5 * Get the public key Ed25519 of the user (public) * MegaApi::USER_ATTR_CU25519_PUBLIC_KEY = 6 * Get the public key Cu25519 of the user (public) * MegaApi::USER_ATTR_KEYRING = 7 * Get the key ring of the user: private keys for Cu25519 and Ed25519 (private) * MegaApi::USER_ATTR_SIG_RSA_PUBLIC_KEY = 8 * Get the signature of RSA public key of the user (public) * MegaApi::USER_ATTR_SIG_CU255_PUBLIC_KEY = 9 * Get the signature of Cu25519 public key of the user (public) * MegaApi::USER_ATTR_LANGUAGE = 14 * Get the preferred language of the user (private, non-encrypted) * MegaApi::USER_ATTR_PWD_REMINDER = 15 * Get the password-reminder-dialog information (private, non-encrypted) * MegaApi::USER_ATTR_DISABLE_VERSIONS = 16 * Get whether user has versions disabled or enabled (private, non-encrypted) * MegaApi::USER_ATTR_RICH_PREVIEWS = 18 * Get whether user generates rich-link messages or not (private) * MegaApi::USER_ATTR_RUBBISH_TIME = 19 * Get number of days for rubbish-bin cleaning scheduler (private non-encrypted) * MegaApi::USER_ATTR_STORAGE_STATE = 21 * Get the state of the storage (private non-encrypted) * MegaApi::USER_ATTR_GEOLOCATION = 22 * Get whether the user has enabled send geolocation messages (private) * MegaApi::USER_ATTR_PUSH_SETTINGS = 23 * Get the settings for push notifications (private non-encrypted) * * @param listener MegaRequestListener to track this request */ public void getUserAttribute(MegaUser user, int type, MegaRequestListenerInterface listener) { megaApi.getUserAttribute(user, type, createDelegateRequestListener(listener)); } /** * Get an attribute of a MegaUser. * * User attributes can be private or public. Private attributes are accessible only by * your own user, while public ones are retrievable by any of your contacts. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Returns the value for public attributes * - MegaRequest::getMegaStringMap - Returns the value for private attributes * * @param user MegaUser to get the attribute. If this parameter is set to NULL, the attribute * is obtained for the active account * @param type Attribute type * * Valid values are: * * MegaApi::USER_ATTR_FIRSTNAME = 1 * Get the firstname of the user (public) * MegaApi::USER_ATTR_LASTNAME = 2 * Get the lastname of the user (public) * MegaApi::USER_ATTR_AUTHRING = 3 * Get the authentication ring of the user (private) * MegaApi::USER_ATTR_LAST_INTERACTION = 4 * Get the last interaction of the contacts of the user (private) * MegaApi::USER_ATTR_ED25519_PUBLIC_KEY = 5 * Get the public key Ed25519 of the user (public) * MegaApi::USER_ATTR_CU25519_PUBLIC_KEY = 6 * Get the public key Cu25519 of the user (public) * MegaApi::USER_ATTR_KEYRING = 7 * Get the key ring of the user: private keys for Cu25519 and Ed25519 (private) * MegaApi::USER_ATTR_SIG_RSA_PUBLIC_KEY = 8 * Get the signature of RSA public key of the user (public) * MegaApi::USER_ATTR_SIG_CU255_PUBLIC_KEY = 9 * Get the signature of Cu25519 public key of the user (public) * MegaApi::USER_ATTR_LANGUAGE = 14 * Get the preferred language of the user (private, non-encrypted) * MegaApi::USER_ATTR_PWD_REMINDER = 15 * Get the password-reminder-dialog information (private, non-encrypted) * MegaApi::USER_ATTR_DISABLE_VERSIONS = 16 * Get whether user has versions disabled or enabled (private, non-encrypted) * MegaApi::USER_ATTR_RICH_PREVIEWS = 18 * Get whether user generates rich-link messages or not (private) * MegaApi::USER_ATTR_RUBBISH_TIME = 19 * Get number of days for rubbish-bin cleaning scheduler (private non-encrypted) * MegaApi::USER_ATTR_STORAGE_STATE = 21 * Get the state of the storage (private non-encrypted) * MegaApi::USER_ATTR_GEOLOCATION = 22 * Get whether the user has enabled send geolocation messages (private) * MegaApi::USER_ATTR_PUSH_SETTINGS = 23 * Get the settings for push notifications (private non-encrypted) */ public void getUserAttribute(MegaUser user, int type) { megaApi.getUserAttribute(user, type); } /** * Get an attribute of any user in MEGA. * * User attributes can be private or public. Private attributes are accessible only by * your own user, while public ones are retrievable by any of your contacts. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type * - MegaRequest::getEmail - Returns the email or the handle of the user (the provided one as parameter) * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Returns the value for public attributes * - MegaRequest::getMegaStringMap - Returns the value for private attributes * * @param email_or_handle Email or user handle (Base64 encoded) to get the attribute. * If this parameter is set to NULL, the attribute is obtained for the active account. * @param type Attribute type * * Valid values are: * * MegaApi::USER_ATTR_FIRSTNAME = 1 * Get the firstname of the user (public) * MegaApi::USER_ATTR_LASTNAME = 2 * Get the lastname of the user (public) * MegaApi::USER_ATTR_AUTHRING = 3 * Get the authentication ring of the user (private) * MegaApi::USER_ATTR_LAST_INTERACTION = 4 * Get the last interaction of the contacts of the user (private) * MegaApi::USER_ATTR_ED25519_PUBLIC_KEY = 5 * Get the public key Ed25519 of the user (public) * MegaApi::USER_ATTR_CU25519_PUBLIC_KEY = 6 * Get the public key Cu25519 of the user (public) * MegaApi::USER_ATTR_KEYRING = 7 * Get the key ring of the user: private keys for Cu25519 and Ed25519 (private) * MegaApi::USER_ATTR_SIG_RSA_PUBLIC_KEY = 8 * Get the signature of RSA public key of the user (public) * MegaApi::USER_ATTR_SIG_CU255_PUBLIC_KEY = 9 * Get the signature of Cu25519 public key of the user (public) * MegaApi::USER_ATTR_LANGUAGE = 14 * Get the preferred language of the user (private, non-encrypted) * MegaApi::USER_ATTR_PWD_REMINDER = 15 * Get the password-reminder-dialog information (private, non-encrypted) * MegaApi::USER_ATTR_DISABLE_VERSIONS = 16 * Get whether user has versions disabled or enabled (private, non-encrypted) * MegaApi::USER_ATTR_RUBBISH_TIME = 19 * Get number of days for rubbish-bin cleaning scheduler (private non-encrypted) * MegaApi::USER_ATTR_STORAGE_STATE = 21 * Get the state of the storage (private non-encrypted) * MegaApi::USER_ATTR_GEOLOCATION = 22 * Get whether the user has enabled send geolocation messages (private) * MegaApi::USER_ATTR_PUSH_SETTINGS = 23 * Get the settings for push notifications (private non-encrypted) * * @param listener MegaRequestListener to track this request */ public void getUserAttribute(String email_or_handle, int type, MegaRequestListenerInterface listener) { megaApi.getUserAttribute(email_or_handle, type, createDelegateRequestListener(listener)); } /** * Get an attribute of any user in MEGA. * * User attributes can be private or public. Private attributes are accessible only by * your own user, while public ones are retrievable by any of your contacts. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type * - MegaRequest::getEmail - Returns the email or the handle of the user (the provided one as parameter) * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Returns the value for public attributes * - MegaRequest::getMegaStringMap - Returns the value for private attributes * * @param email_or_handle Email or user handle (Base64 encoded) to get the attribute. * If this parameter is set to NULL, the attribute is obtained for the active account. * @param type Attribute type * * Valid values are: * * MegaApi::USER_ATTR_FIRSTNAME = 1 * Get the firstname of the user (public) * MegaApi::USER_ATTR_LASTNAME = 2 * Get the lastname of the user (public) * MegaApi::USER_ATTR_AUTHRING = 3 * Get the authentication ring of the user (private) * MegaApi::USER_ATTR_LAST_INTERACTION = 4 * Get the last interaction of the contacts of the user (private) * MegaApi::USER_ATTR_ED25519_PUBLIC_KEY = 5 * Get the public key Ed25519 of the user (public) * MegaApi::USER_ATTR_CU25519_PUBLIC_KEY = 6 * Get the public key Cu25519 of the user (public) * MegaApi::USER_ATTR_KEYRING = 7 * Get the key ring of the user: private keys for Cu25519 and Ed25519 (private) * MegaApi::USER_ATTR_SIG_RSA_PUBLIC_KEY = 8 * Get the signature of RSA public key of the user (public) * MegaApi::USER_ATTR_SIG_CU255_PUBLIC_KEY = 9 * Get the signature of Cu25519 public key of the user (public) * MegaApi::USER_ATTR_LANGUAGE = 14 * Get the preferred language of the user (private, non-encrypted) * MegaApi::USER_ATTR_PWD_REMINDER = 15 * Get the password-reminder-dialog information (private, non-encrypted) * MegaApi::USER_ATTR_DISABLE_VERSIONS = 16 * Get whether user has versions disabled or enabled (private, non-encrypted) * MegaApi::USER_ATTR_RUBBISH_TIME = 19 * Get number of days for rubbish-bin cleaning scheduler (private non-encrypted) * MegaApi::USER_ATTR_STORAGE_STATE = 21 * Get the state of the storage (private non-encrypted) * MegaApi::USER_ATTR_GEOLOCATION = 22 * Get whether the user has enabled send geolocation messages (private) * MegaApi::USER_ATTR_PUSH_SETTINGS = 23 * Get the settings for push notifications (private non-encrypted) * */ public void getUserAttribute(String email_or_handle, int type) { megaApi.getUserAttribute(email_or_handle, type); } /** * Get an attribute of the current account. * * User attributes can be private or public. Private attributes are accessible only by * your own user, while public ones are retrievable by any of your contacts. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Returns the value for public attributes * - MegaRequest::getMegaStringMap - Returns the value for private attributes * * @param type Attribute type * * Valid values are: * * MegaApi::USER_ATTR_FIRSTNAME = 1 * Get the firstname of the user (public) * MegaApi::USER_ATTR_LASTNAME = 2 * Get the lastname of the user (public) * MegaApi::USER_ATTR_AUTHRING = 3 * Get the authentication ring of the user (private) * MegaApi::USER_ATTR_LAST_INTERACTION = 4 * Get the last interaction of the contacts of the user (private) * MegaApi::USER_ATTR_ED25519_PUBLIC_KEY = 5 * Get the public key Ed25519 of the user (public) * MegaApi::USER_ATTR_CU25519_PUBLIC_KEY = 6 * Get the public key Cu25519 of the user (public) * MegaApi::USER_ATTR_KEYRING = 7 * Get the key ring of the user: private keys for Cu25519 and Ed25519 (private) * MegaApi::USER_ATTR_SIG_RSA_PUBLIC_KEY = 8 * Get the signature of RSA public key of the user (public) * MegaApi::USER_ATTR_SIG_CU255_PUBLIC_KEY = 9 * Get the signature of Cu25519 public key of the user (public) * MegaApi::USER_ATTR_LANGUAGE = 14 * Get the preferred language of the user (private, non-encrypted) * MegaApi::USER_ATTR_PWD_REMINDER = 15 * Get the password-reminder-dialog information (private, non-encrypted) * MegaApi::USER_ATTR_DISABLE_VERSIONS = 16 * Get whether user has versions disabled or enabled (private, non-encrypted) * MegaApi::USER_ATTR_RICH_PREVIEWS = 18 * Get whether user generates rich-link messages or not (private) * MegaApi::USER_ATTR_RUBBISH_TIME = 19 * Get number of days for rubbish-bin cleaning scheduler (private non-encrypted) * MegaApi::USER_ATTR_STORAGE_STATE = 21 * Get the state of the storage (private non-encrypted) * MegaApi::USER_ATTR_GEOLOCATION = 22 * Get whether the user has enabled send geolocation messages (private) * MegaApi::USER_ATTR_PUSH_SETTINGS = 23 * Get the settings for push notifications (private non-encrypted) * * @param listener MegaRequestListener to track this request */ public void getUserAttribute(int type, MegaRequestListenerInterface listener) { megaApi.getUserAttribute(type, createDelegateRequestListener(listener)); } /** * Get an attribute of the current account. * * User attributes can be private or public. Private attributes are accessible only by * your own user, while public ones are retrievable by any of your contacts. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Returns the value for public attributes * - MegaRequest::getMegaStringMap - Returns the value for private attributes * * @param type Attribute type * * Valid values are: * * MegaApi::USER_ATTR_FIRSTNAME = 1 * Get the firstname of the user (public) * MegaApi::USER_ATTR_LASTNAME = 2 * Get the lastname of the user (public) * MegaApi::USER_ATTR_AUTHRING = 3 * Get the authentication ring of the user (private) * MegaApi::USER_ATTR_LAST_INTERACTION = 4 * Get the last interaction of the contacts of the user (private) * MegaApi::USER_ATTR_ED25519_PUBLIC_KEY = 5 * Get the public key Ed25519 of the user (public) * MegaApi::USER_ATTR_CU25519_PUBLIC_KEY = 6 * Get the public key Cu25519 of the user (public) * MegaApi::USER_ATTR_KEYRING = 7 * Get the key ring of the user: private keys for Cu25519 and Ed25519 (private) * MegaApi::USER_ATTR_SIG_RSA_PUBLIC_KEY = 8 * Get the signature of RSA public key of the user (public) * MegaApi::USER_ATTR_SIG_CU255_PUBLIC_KEY = 9 * Get the signature of Cu25519 public key of the user (public) * MegaApi::USER_ATTR_LANGUAGE = 14 * Get the preferred language of the user (private, non-encrypted) * MegaApi::USER_ATTR_PWD_REMINDER = 15 * Get the password-reminder-dialog information (private, non-encrypted) * MegaApi::USER_ATTR_DISABLE_VERSIONS = 16 * Get whether user has versions disabled or enabled (private, non-encrypted) * MegaApi::USER_ATTR_RICH_PREVIEWS = 18 * Get whether user generates rich-link messages or not (private) * MegaApi::USER_ATTR_RUBBISH_TIME = 19 * Get number of days for rubbish-bin cleaning scheduler (private non-encrypted) * MegaApi::USER_ATTR_STORAGE_STATE = 21 * Get the state of the storage (private non-encrypted) * MegaApi::USER_ATTR_GEOLOCATION = 22 * Get whether the user has enabled send geolocation messages (private) * MegaApi::USER_ATTR_PUSH_SETTINGS = 23 * Get the settings for push notifications (private non-encrypted) * */ public void getUserAttribute(int type) { megaApi.getUserAttribute(type); } /** * Cancel the retrieval of a thumbnail. * <p> * The associated request type with this request is MegaRequest.TYPE_CANCEL_ATTR_FILE. * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getNodeHandle() - Returns the handle of the node. <br> * - MegaRequest.getParamType() - Returns MegaApiJava.ATTR_TYPE_THUMBNAIL. * * @param node * Node to cancel the retrieval of the thumbnail. * @param listener * MegaRequestListener to track this request. * @see #getThumbnail(MegaNode node, String dstFilePath) */ public void cancelGetThumbnail(MegaNode node, MegaRequestListenerInterface listener) { megaApi.cancelGetThumbnail(node, createDelegateRequestListener(listener)); } /** * Cancel the retrieval of a thumbnail. * * @param node * Node to cancel the retrieval of the thumbnail. * @see #getThumbnail(MegaNode node, String dstFilePath) */ public void cancelGetThumbnail(MegaNode node) { megaApi.cancelGetThumbnail(node); } /** * Cancel the retrieval of a preview. * <p> * The associated request type with this request is MegaRequest.TYPE_CANCEL_ATTR_FILE * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getNodeHandle - Returns the handle of the node. <br> * - MegaRequest.getParamType - Returns MegaApiJava.ATTR_TYPE_PREVIEW. * * @param node * Node to cancel the retrieval of the preview. * @param listener * MegaRequestListener to track this request. * @see MegaApi#getPreview(MegaNode node, String dstFilePath) */ public void cancelGetPreview(MegaNode node, MegaRequestListenerInterface listener) { megaApi.cancelGetPreview(node, createDelegateRequestListener(listener)); } /** * Cancel the retrieval of a preview. * * @param node * Node to cancel the retrieval of the preview. * @see MegaApi#getPreview(MegaNode node, String dstFilePath) */ public void cancelGetPreview(MegaNode node) { megaApi.cancelGetPreview(node); } /** * Set the thumbnail of a MegaNode. * * The associated request type with this request is MegaRequest.TYPE_SET_ATTR_FILE * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getNodeHandle() - Returns the handle of the node. <br> * - MegaRequest.getFile() - Returns the source path. <br> * - MegaRequest.getParamType() - Returns MegaApiJava.ATTR_TYPE_THUMBNAIL. * * @param node * MegaNode to set the thumbnail. * @param srcFilePath * Source path of the file that will be set as thumbnail. * @param listener * MegaRequestListener to track this request. */ public void setThumbnail(MegaNode node, String srcFilePath, MegaRequestListenerInterface listener) { megaApi.setThumbnail(node, srcFilePath, createDelegateRequestListener(listener)); } /** * Set the thumbnail of a MegaNode. * * @param node * MegaNode to set the thumbnail. * @param srcFilePath * Source path of the file that will be set as thumbnail. */ public void setThumbnail(MegaNode node, String srcFilePath) { megaApi.setThumbnail(node, srcFilePath); } /** * Set the preview of a MegaNode. * <p> * The associated request type with this request is MegaRequest.TYPE_SET_ATTR_FILE. * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getNodeHandle() - Returns the handle of the node. <br> * - MegaRequest.getFile() - Returns the source path. <br> * - MegaRequest.getParamType() - Returns MegaApiJava.ATTR_TYPE_PREVIEW. * * @param node * MegaNode to set the preview. * @param srcFilePath * Source path of the file that will be set as preview. * @param listener * MegaRequestListener to track this request. */ public void setPreview(MegaNode node, String srcFilePath, MegaRequestListenerInterface listener) { megaApi.setPreview(node, srcFilePath, createDelegateRequestListener(listener)); } /** * Set the preview of a MegaNode. * * @param node * MegaNode to set the preview. * @param srcFilePath * Source path of the file that will be set as preview. */ public void setPreview(MegaNode node, String srcFilePath) { megaApi.setPreview(node, srcFilePath); } /** * Set the avatar of the MEGA account. * <p> * The associated request type with this request is MegaRequest.TYPE_SET_ATTR_USER. * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getFile() - Returns the source path. * * @param srcFilePath * Source path of the file that will be set as avatar. * @param listener * MegaRequestListener to track this request. */ public void setAvatar(String srcFilePath, MegaRequestListenerInterface listener) { megaApi.setAvatar(srcFilePath, createDelegateRequestListener(listener)); } /** * Set the avatar of the MEGA account. * * @param srcFilePath * Source path of the file that will be set as avatar. */ public void setAvatar(String srcFilePath) { megaApi.setAvatar(srcFilePath); } /** * Set a public attribute of the current user * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type * - MegaRequest::getText - Returns the new value for the attribute * * @param type Attribute type * * Valid values are: * * MegaApi::USER_ATTR_FIRSTNAME = 1 * Set the firstname of the user (public) * MegaApi::USER_ATTR_LASTNAME = 2 * Set the lastname of the user (public) * MegaApi::USER_ATTR_ED25519_PUBLIC_KEY = 5 * Set the public key Ed25519 of the user (public) * MegaApi::USER_ATTR_CU25519_PUBLIC_KEY = 6 * Set the public key Cu25519 of the user (public) * MegaApi::USER_ATTR_RUBBISH_TIME = 19 * Set number of days for rubbish-bin cleaning scheduler (private non-encrypted) * * If the MEGA account is a sub-user business account, and the value of the parameter * type is equal to MegaApi::USER_ATTR_FIRSTNAME or MegaApi::USER_ATTR_LASTNAME * onRequestFinish will be called with the error code MegaError::API_EMASTERONLY. * * @param value New attribute value * @param listener MegaRequestListener to track this request */ public void setUserAttribute(int type, String value, MegaRequestListenerInterface listener) { megaApi.setUserAttribute(type, value, createDelegateRequestListener(listener)); } /** * Set a public attribute of the current user * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type * - MegaRequest::getText - Returns the new value for the attribute * * @param type Attribute type * * Valid values are: * * MegaApi::USER_ATTR_FIRSTNAME = 1 * Set the firstname of the user (public) * MegaApi::USER_ATTR_LASTNAME = 2 * Set the lastname of the user (public) * MegaApi::USER_ATTR_ED25519_PUBLIC_KEY = 5 * Set the public key Ed25519 of the user (public) * MegaApi::USER_ATTR_CU25519_PUBLIC_KEY = 6 * Set the public key Cu25519 of the user (public) * MegaApi::USER_ATTR_RUBBISH_TIME = 19 * Set number of days for rubbish-bin cleaning scheduler (private non-encrypted) * * If the MEGA account is a sub-user business account, and the value of the parameter * type is equal to MegaApi::USER_ATTR_FIRSTNAME or MegaApi::USER_ATTR_LASTNAME * onRequestFinish will be called with the error code MegaError::API_EMASTERONLY. * * @param value New attribute value */ public void setUserAttribute(int type, String value) { megaApi.setUserAttribute(type, value); } /** * Set a custom attribute for the node * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_NODE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node that receive the attribute * - MegaRequest::getName - Returns the name of the custom attribute * - MegaRequest::getText - Returns the text for the attribute * - MegaRequest::getFlag - Returns false (not official attribute) * * The attribute name must be an UTF8 string with between 1 and 7 bytes * If the attribute already has a value, it will be replaced * If value is NULL, the attribute will be removed from the node * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node Node that will receive the attribute * @param attrName Name of the custom attribute. * The length of this parameter must be between 1 and 7 UTF8 bytes * @param value Value for the attribute * @param listener MegaRequestListener to track this request */ public void setCustomNodeAttribute(MegaNode node, String attrName, String value, MegaRequestListenerInterface listener) { megaApi.setCustomNodeAttribute(node, attrName, value, createDelegateRequestListener(listener)); } /** * Set a custom attribute for the node * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_NODE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node that receive the attribute * - MegaRequest::getName - Returns the name of the custom attribute * - MegaRequest::getText - Returns the text for the attribute * - MegaRequest::getFlag - Returns false (not official attribute) * * The attribute name must be an UTF8 string with between 1 and 7 bytes * If the attribute already has a value, it will be replaced * If value is NULL, the attribute will be removed from the node * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node Node that will receive the attribute * @param attrName Name of the custom attribute. * The length of this parameter must be between 1 and 7 UTF8 bytes * @param value Value for the attribute */ public void setCustomNodeAttribute(MegaNode node, String attrName, String value) { megaApi.setCustomNodeAttribute(node, attrName, value); } /** * Set the GPS coordinates of image files as a node attribute. * * To remove the existing coordinates, set both the latitude and longitude to * the value MegaNode::INVALID_COORDINATE. * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_NODE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node that receive the attribute * - MegaRequest::getFlag - Returns true (official attribute) * - MegaRequest::getParamType - Returns MegaApi::NODE_ATTR_COORDINATES * - MegaRequest::getNumDetails - Returns the longitude, scaled to integer in the range of [0, 2^24] * - MegaRequest::getTransferTag() - Returns the latitude, scaled to integer in the range of [0, 2^24) * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node Node that will receive the information. * @param latitude Latitude in signed decimal degrees notation * @param longitude Longitude in signed decimal degrees notation * @param listener MegaRequestListener to track this request */ public void setNodeCoordinates(MegaNode node, double latitude, double longitude, MegaRequestListenerInterface listener){ megaApi.setNodeCoordinates(node, latitude, longitude, createDelegateRequestListener(listener)); } /** * Set node label as a node attribute. * Valid values for label attribute are: * - MegaNode::NODE_LBL_UNKNOWN = 0 * - MegaNode::NODE_LBL_RED = 1 * - MegaNode::NODE_LBL_ORANGE = 2 * - MegaNode::NODE_LBL_YELLOW = 3 * - MegaNode::NODE_LBL_GREEN = 4 * - MegaNode::NODE_LBL_BLUE = 5 * - MegaNode::NODE_LBL_PURPLE = 6 * - MegaNode::NODE_LBL_GREY = 7 * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_NODE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node that receive the attribute * - MegaRequest::getNumDetails - Returns the label for the node * - MegaRequest::getFlag - Returns true (official attribute) * - MegaRequest::getParamType - Returns MegaApi::NODE_ATTR_LABEL * * @param node Node that will receive the information. * @param label Label of the node * @param listener MegaRequestListener to track this request */ public void setNodeLabel(MegaNode node, int label, MegaRequestListenerInterface listener){ megaApi.setNodeLabel(node, label, createDelegateRequestListener(listener)); } /** * Set node label as a node attribute. * Valid values for label attribute are: * - MegaNode::NODE_LBL_UNKNOWN = 0 * - MegaNode::NODE_LBL_RED = 1 * - MegaNode::NODE_LBL_ORANGE = 2 * - MegaNode::NODE_LBL_YELLOW = 3 * - MegaNode::NODE_LBL_GREEN = 4 * - MegaNode::NODE_LBL_BLUE = 5 * - MegaNode::NODE_LBL_PURPLE = 6 * - MegaNode::NODE_LBL_GREY = 7 * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_NODE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node that receive the attribute * - MegaRequest::getNumDetails - Returns the label for the node * - MegaRequest::getFlag - Returns true (official attribute) * - MegaRequest::getParamType - Returns MegaApi::NODE_ATTR_LABEL * * @param node Node that will receive the information. * @param label Label of the node */ public void setNodeLabel(MegaNode node, int label){ megaApi.setNodeLabel(node, label); } /** * Remove node label * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_NODE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node that receive the attribute * - MegaRequest::getFlag - Returns true (official attribute) * - MegaRequest::getParamType - Returns MegaApi::NODE_ATTR_LABEL * * @param node Node that will receive the information. * @param listener MegaRequestListener to track this request */ public void resetNodeLabel(MegaNode node, MegaRequestListenerInterface listener){ megaApi.resetNodeLabel(node, createDelegateRequestListener(listener)); } /** * Remove node label * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_NODE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node that receive the attribute * - MegaRequest::getFlag - Returns true (official attribute) * - MegaRequest::getParamType - Returns MegaApi::NODE_ATTR_LABEL * * @param node Node that will receive the information. */ public void resetNodeLabel(MegaNode node){ megaApi.resetNodeLabel(node); } /** * Set node favourite as a node attribute. * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_NODE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node that receive the attribute * - MegaRequest::getNumDetails - Returns 1 if node is set as favourite, otherwise return 0 * - MegaRequest::getFlag - Returns true (official attribute) * - MegaRequest::getParamType - Returns MegaApi::NODE_ATTR_FAV * * @param node Node that will receive the information. * @param favourite if true set node as favourite, otherwise remove the attribute * @param listener MegaRequestListener to track this request */ public void setNodeFavourite(MegaNode node, boolean favourite, MegaRequestListenerInterface listener){ megaApi.setNodeFavourite(node, favourite, createDelegateRequestListener(listener)); } /** * Set node favourite as a node attribute. * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_NODE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node that receive the attribute * - MegaRequest::getNumDetails - Returns 1 if node is set as favourite, otherwise return 0 * - MegaRequest::getFlag - Returns true (official attribute) * - MegaRequest::getParamType - Returns MegaApi::NODE_ATTR_FAV * * @param node Node that will receive the information. * @param favourite if true set node as favourite, otherwise remove the attribute */ public void setNodeFavourite(MegaNode node, boolean favourite){ megaApi.setNodeFavourite(node, favourite); } /** * Generate a public link of a file/folder in MEGA * * The associated request type with this request is MegaRequest::TYPE_EXPORT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node * - MegaRequest::getAccess - Returns true * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getLink - Public link * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node MegaNode to get the public link * @param listener MegaRequestListener to track this request */ public void exportNode(MegaNode node, MegaRequestListenerInterface listener) { megaApi.exportNode(node, createDelegateRequestListener(listener)); } /** * Generate a public link of a file/folder in MEGA * * The associated request type with this request is MegaRequest::TYPE_EXPORT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node * - MegaRequest::getAccess - Returns true * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getLink - Public link * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node MegaNode to get the public link */ public void exportNode(MegaNode node) { megaApi.exportNode(node); } /** * Generate a temporary public link of a file/folder in MEGA * * The associated request type with this request is MegaRequest::TYPE_EXPORT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node * - MegaRequest::getAccess - Returns true * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getLink - Public link * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node MegaNode to get the public link * @param expireTime Unix timestamp until the public link will be valid * @param listener MegaRequestListener to track this request * * A Unix timestamp represents the number of seconds since 00:00 hours, Jan 1, 1970 UTC */ public void exportNode(MegaNode node, int expireTime, MegaRequestListenerInterface listener) { megaApi.exportNode(node, expireTime, createDelegateRequestListener(listener)); } /** * Generate a temporary public link of a file/folder in MEGA * * The associated request type with this request is MegaRequest::TYPE_EXPORT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node * - MegaRequest::getAccess - Returns true * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getLink - Public link * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node MegaNode to get the public link * @param expireTime Unix timestamp until the public link will be valid * * A Unix timestamp represents the number of seconds since 00:00 hours, Jan 1, 1970 UTC */ public void exportNode(MegaNode node, int expireTime) { megaApi.exportNode(node, expireTime); } /** * Stop sharing a file/folder * * The associated request type with this request is MegaRequest::TYPE_EXPORT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node * - MegaRequest::getAccess - Returns false * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node MegaNode to stop sharing * @param listener MegaRequestListener to track this request */ public void disableExport(MegaNode node, MegaRequestListenerInterface listener) { megaApi.disableExport(node, createDelegateRequestListener(listener)); } /** * Stop sharing a file/folder * * The associated request type with this request is MegaRequest::TYPE_EXPORT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node * - MegaRequest::getAccess - Returns false * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node MegaNode to stop sharing */ public void disableExport(MegaNode node) { megaApi.disableExport(node); } /** * Fetch the filesystem in MEGA. * <p> * The MegaApi object must be logged in in an account or a public folder * to successfully complete this request. * <p> * The associated request type with this request is MegaRequest.TYPE_FETCH_NODES. * * @param listener * MegaRequestListener to track this request. */ public void fetchNodes(MegaRequestListenerInterface listener) { megaApi.fetchNodes(createDelegateRequestListener(listener)); } /** * Fetch the filesystem in MEGA. * <p> * The MegaApi object must be logged in in an account or a public folder * to successfully complete this request. */ public void fetchNodes() { megaApi.fetchNodes(); } /** * Get details about the MEGA account * * Only basic data will be available. If you can get more data (sessions, transactions, purchases), * use MegaApi::getExtendedAccountDetails. * * The associated request type with this request is MegaRequest::TYPE_ACCOUNT_DETAILS * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaAccountDetails - Details of the MEGA account * - MegaRequest::getNumDetails - Requested flags * * The available flags are: * - storage quota: (numDetails & 0x01) * - transfer quota: (numDetails & 0x02) * - pro level: (numDetails & 0x04) * * @param listener MegaRequestListener to track this request */ public void getAccountDetails(MegaRequestListenerInterface listener) { megaApi.getAccountDetails(createDelegateRequestListener(listener)); } /** * Get details about the MEGA account * * Only basic data will be available. If you can get more data (sessions, transactions, purchases), * use MegaApi::getExtendedAccountDetails. * * The associated request type with this request is MegaRequest::TYPE_ACCOUNT_DETAILS * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaAccountDetails - Details of the MEGA account * - MegaRequest::getNumDetails - Requested flags * * The available flags are: * - storage quota: (numDetails & 0x01) * - transfer quota: (numDetails & 0x02) * - pro level: (numDetails & 0x04) */ public void getAccountDetails() { megaApi.getAccountDetails(); } /** * Get details about the MEGA account * * Only basic data will be available. If you need more data (sessions, transactions, purchases), * use MegaApi::getExtendedAccountDetails. * * The associated request type with this request is MegaRequest::TYPE_ACCOUNT_DETAILS * * Use this version of the function to get just the details you need, to minimise server load * and keep the system highly available for all. At least one flag must be set. * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaAccountDetails - Details of the MEGA account * - MegaRequest::getNumDetails - Requested flags * * The available flags are: * - storage quota: (numDetails & 0x01) * - transfer quota: (numDetails & 0x02) * - pro level: (numDetails & 0x04) * * In case none of the flags are set, the associated request will fail with error MegaError::API_EARGS. * * @param storage If true, account storage details are requested * @param transfer If true, account transfer details are requested * @param pro If true, pro level of account is requested * @param listener MegaRequestListener to track this request */ public void getSpecificAccountDetails(boolean storage, boolean transfer, boolean pro, MegaRequestListenerInterface listener) { megaApi.getSpecificAccountDetails(storage, transfer, pro, -1, createDelegateRequestListener(listener)); } /** * Get details about the MEGA account * * Only basic data will be available. If you need more data (sessions, transactions, purchases), * use MegaApi::getExtendedAccountDetails. * * The associated request type with this request is MegaRequest::TYPE_ACCOUNT_DETAILS * * Use this version of the function to get just the details you need, to minimise server load * and keep the system highly available for all. At least one flag must be set. * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaAccountDetails - Details of the MEGA account * - MegaRequest::getNumDetails - Requested flags * * The available flags are: * - storage quota: (numDetails & 0x01) * - transfer quota: (numDetails & 0x02) * - pro level: (numDetails & 0x04) * * In case none of the flags are set, the associated request will fail with error MegaError::API_EARGS. * * @param storage If true, account storage details are requested * @param transfer If true, account transfer details are requested * @param pro If true, pro level of account is requested */ public void getSpecificAccountDetails(boolean storage, boolean transfer, boolean pro) { megaApi.getSpecificAccountDetails(storage, transfer, pro, -1); } /** * Get details about the MEGA account * * This function allows to optionally get data about sessions, transactions and purchases related to the account. * * The associated request type with this request is MegaRequest::TYPE_ACCOUNT_DETAILS * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaAccountDetails - Details of the MEGA account * - MegaRequest::getNumDetails - Requested flags * * The available flags are: * - transactions: (numDetails & 0x08) * - purchases: (numDetails & 0x10) * - sessions: (numDetails & 0x020) * * In case none of the flags are set, the associated request will fail with error MegaError::API_EARGS. * * @param sessions If true, sessions are requested * @param purchases If true, purchases are requested * @param transactions If true, transactions are requested * @param listener MegaRequestListener to track this request */ public void getExtendedAccountDetails(boolean sessions, boolean purchases, boolean transactions, MegaRequestListenerInterface listener) { megaApi.getExtendedAccountDetails(sessions, purchases, transactions, createDelegateRequestListener(listener)); } /** * Get details about the MEGA account * * This function allows to optionally get data about sessions, transactions and purchases related to the account. * * The associated request type with this request is MegaRequest::TYPE_ACCOUNT_DETAILS * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaAccountDetails - Details of the MEGA account * - MegaRequest::getNumDetails - Requested flags * * The available flags are: * - transactions: (numDetails & 0x08) * - purchases: (numDetails & 0x10) * - sessions: (numDetails & 0x020) * * In case none of the flags are set, the associated request will fail with error MegaError::API_EARGS. * * @param sessions If true, sessions are requested * @param purchases If true, purchases are requested * @param transactions If true, transactions are requested */ public void getExtendedAccountDetails(boolean sessions, boolean purchases, boolean transactions) { megaApi.getExtendedAccountDetails(sessions, purchases, transactions); } /** * Get the available pricing plans to upgrade a MEGA account. * <p> * The associated request type with this request is MegaRequest.TYPE_GET_PRICING. * <p> * Valid data in the MegaRequest object received in onRequestFinish() when the error code * is MegaError.API_OK: <br> * - MegaRequest.getPricing() - MegaPricing object with all pricing plans. * * @param listener * MegaRequestListener to track this request. */ public void getPricing(MegaRequestListenerInterface listener) { megaApi.getPricing(createDelegateRequestListener(listener)); } /** * Get the available pricing plans to upgrade a MEGA account. */ public void getPricing() { megaApi.getPricing(); } /** * Get the payment URL for an upgrade * * The associated request type with this request is MegaRequest::TYPE_GET_PAYMENT_ID * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the product * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getLink - Payment ID * * @param productHandle Handle of the product (see MegaApi::getPricing) * @param listener MegaRequestListener to track this request * * @see MegaApi::getPricing */ public void getPaymentId(long productHandle, MegaRequestListenerInterface listener) { megaApi.getPaymentId(productHandle, createDelegateRequestListener(listener)); } /** * Get the payment URL for an upgrade * * The associated request type with this request is MegaRequest::TYPE_GET_PAYMENT_ID * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the product * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getLink - Payment ID * * @param productHandle Handle of the product (see MegaApi::getPricing) * * @see MegaApi::getPricing */ public void getPaymentId(long productHandle) { megaApi.getPaymentId(productHandle); } /** * Get the payment URL for an upgrade * * The associated request type with this request is MegaRequest::TYPE_GET_PAYMENT_ID * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the product * - MegaRequest::getParentHandle - Returns the last public node handle accessed * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getLink - Payment ID * * @param productHandle Handle of the product (see MegaApi::getPricing) * @param lastPublicHandle Last public node handle accessed by the user in the last 24h * @param listener MegaRequestListener to track this request * * @see MegaApi::getPricing */ public void getPaymentId(long productHandle, long lastPublicHandle, MegaRequestListenerInterface listener) { megaApi.getPaymentId(productHandle, lastPublicHandle, createDelegateRequestListener(listener)); } /** * Get the payment URL for an upgrade * * The associated request type with this request is MegaRequest::TYPE_GET_PAYMENT_ID * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the product * - MegaRequest::getParentHandle - Returns the last public node handle accessed * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getLink - Payment ID * * @param productHandle Handle of the product (see MegaApi::getPricing) * @param lastPublicHandle Last public node handle accessed by the user in the last 24h * * @see MegaApi::getPricing */ public void getPaymentId(long productHandle, long lastPublicHandle) { megaApi.getPaymentId(productHandle, lastPublicHandle); } /** * Get the payment URL for an upgrade * * The associated request type with this request is MegaRequest::TYPE_GET_PAYMENT_ID * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the product * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getLink - Payment ID * - MegaRequest::getParentHandle - Returns the last public node handle accessed * - MegaRequest::getParamType - Returns the type of lastPublicHandle * - MegaRequest::getTransferredBytes - Returns the timestamp of the last access * * @param productHandle Handle of the product (see MegaApi::getPricing) * @param lastPublicHandle Last public node handle accessed by the user in the last 24h * @param lastPublicHandleType Indicates the type of lastPublicHandle, valid values are: * - MegaApi::AFFILIATE_TYPE_ID = 1 * - MegaApi::AFFILIATE_TYPE_FILE_FOLDER = 2 * - MegaApi::AFFILIATE_TYPE_CHAT = 3 * - MegaApi::AFFILIATE_TYPE_CONTACT = 4 * * @param lastAccessTimestamp Timestamp of the last access * @param listener MegaRequestListener to track this request * @see MegaApi::getPricing */ public void getPaymentId(long productHandle, long lastPublicHandle, int lastPublicHandleType, long lastAccessTimestamp, MegaRequestListenerInterface listener) { megaApi.getPaymentId(productHandle, lastPublicHandle, lastPublicHandleType, lastAccessTimestamp, createDelegateRequestListener(listener)); } /** * Get the payment URL for an upgrade * * The associated request type with this request is MegaRequest::TYPE_GET_PAYMENT_ID * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the product * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getLink - Payment ID * - MegaRequest::getParentHandle - Returns the last public node handle accessed * - MegaRequest::getParamType - Returns the type of lastPublicHandle * - MegaRequest::getTransferredBytes - Returns the timestamp of the last access * * @param productHandle Handle of the product (see MegaApi::getPricing) * @param lastPublicHandle Last public node handle accessed by the user in the last 24h * @param lastPublicHandleType Indicates the type of lastPublicHandle, valid values are: * - MegaApi::AFFILIATE_TYPE_ID = 1 * - MegaApi::AFFILIATE_TYPE_FILE_FOLDER = 2 * - MegaApi::AFFILIATE_TYPE_CHAT = 3 * - MegaApi::AFFILIATE_TYPE_CONTACT = 4 * * @param lastAccessTimestamp Timestamp of the last access * @see MegaApi::getPricing */ public void getPaymentId(long productHandle, long lastPublicHandle, int lastPublicHandleType, long lastAccessTimestamp) { megaApi.getPaymentId(productHandle, lastPublicHandle, lastPublicHandleType, lastAccessTimestamp); } /** * Upgrade an account. * * @param productHandle Product handle to purchase. * It is possible to get all pricing plans with their product handles using * MegaApi.getPricing(). * * The associated request type with this request is MegaRequest.TYPE_UPGRADE_ACCOUNT. * * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getNodeHandle() - Returns the handle of the product. <br> * - MegaRequest.getNumber() - Returns the payment method. * * @param paymentMethod Payment method. * Valid values are: <br> * - MegaApi.PAYMENT_METHOD_BALANCE = 0. * Use the account balance for the payment. <br> * * - MegaApi.PAYMENT_METHOD_CREDIT_CARD = 8. * Complete the payment with your credit card. Use MegaApi.creditCardStore to add * a credit card to your account. * * @param listener MegaRequestListener to track this request. */ public void upgradeAccount(long productHandle, int paymentMethod, MegaRequestListenerInterface listener) { megaApi.upgradeAccount(productHandle, paymentMethod, createDelegateRequestListener(listener)); } /** * Upgrade an account. * * @param productHandle Product handle to purchase. * It is possible to get all pricing plans with their product handles using * MegaApi.getPricing(). * * @param paymentMethod Payment method. * Valid values are: <br> * - MegaApi.PAYMENT_METHOD_BALANCE = 0. * Use the account balance for the payment. <br> * * - MegaApi.PAYMENT_METHOD_CREDIT_CARD = 8. * Complete the payment with your credit card. Use MegaApi.creditCardStore() to add * a credit card to your account. */ public void upgradeAccount(long productHandle, int paymentMethod) { megaApi.upgradeAccount(productHandle, paymentMethod); } /** * Submit a purchase receipt for verification * * The associated request type with this request is MegaRequest::TYPE_SUBMIT_PURCHASE_RECEIPT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNumber - Returns the payment gateway * - MegaRequest::getText - Returns the purchase receipt * * @param gateway Payment gateway * Currently supported payment gateways are: * - MegaApi::PAYMENT_METHOD_ITUNES = 2 * - MegaApi::PAYMENT_METHOD_GOOGLE_WALLET = 3 * - MegaApi::PAYMENT_METHOD_WINDOWS_STORE = 13 * * @param receipt Purchase receipt * @param listener MegaRequestListener to track this request */ public void submitPurchaseReceipt(int gateway, String receipt, MegaRequestListenerInterface listener) { megaApi.submitPurchaseReceipt(gateway, receipt, createDelegateRequestListener(listener)); } /** * Submit a purchase receipt for verification * * The associated request type with this request is MegaRequest::TYPE_SUBMIT_PURCHASE_RECEIPT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNumber - Returns the payment gateway * - MegaRequest::getText - Returns the purchase receipt * * @param gateway Payment gateway * Currently supported payment gateways are: * - MegaApi::PAYMENT_METHOD_ITUNES = 2 * - MegaApi::PAYMENT_METHOD_GOOGLE_WALLET = 3 * - MegaApi::PAYMENT_METHOD_WINDOWS_STORE = 13 * * @param receipt Purchase receipt */ public void submitPurchaseReceipt(int gateway, String receipt) { megaApi.submitPurchaseReceipt(gateway, receipt); } /** * Submit a purchase receipt for verification * * The associated request type with this request is MegaRequest::TYPE_SUBMIT_PURCHASE_RECEIPT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNumber - Returns the payment gateway * - MegaRequest::getText - Returns the purchase receipt * - MegaRequest::getParentHandle - Returns the last public node handle accessed * * @param gateway Payment gateway * Currently supported payment gateways are: * - MegaApi::PAYMENT_METHOD_ITUNES = 2 * - MegaApi::PAYMENT_METHOD_GOOGLE_WALLET = 3 * - MegaApi::PAYMENT_METHOD_WINDOWS_STORE = 13 * * @param receipt Purchase receipt * @param lastPublicHandle Last public node handle accessed by the user in the last 24h * @param listener MegaRequestListener to track this request */ public void submitPurchaseReceipt(int gateway, String receipt, long lastPublicHandle, MegaRequestListenerInterface listener) { megaApi.submitPurchaseReceipt(gateway, receipt, lastPublicHandle, createDelegateRequestListener(listener)); } /** * Submit a purchase receipt for verification * * The associated request type with this request is MegaRequest::TYPE_SUBMIT_PURCHASE_RECEIPT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNumber - Returns the payment gateway * - MegaRequest::getText - Returns the purchase receipt * - MegaRequest::getParentHandle - Returns the last public node handle accessed * * @param gateway Payment gateway * Currently supported payment gateways are: * - MegaApi::PAYMENT_METHOD_ITUNES = 2 * - MegaApi::PAYMENT_METHOD_GOOGLE_WALLET = 3 * - MegaApi::PAYMENT_METHOD_WINDOWS_STORE = 13 * * @param receipt Purchase receipt * @param lastPublicHandle Last public node handle accessed by the user in the last 24h */ public void submitPurchaseReceipt(int gateway, String receipt, long lastPublicHandle) { megaApi.submitPurchaseReceipt(gateway, receipt, lastPublicHandle); } /** * Submit a purchase receipt for verification * * The associated request type with this request is MegaRequest::TYPE_SUBMIT_PURCHASE_RECEIPT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNumber - Returns the payment gateway * - MegaRequest::getText - Returns the purchase receipt * - MegaRequest::getParentHandle - Returns the last public node handle accessed * - MegaRequest::getParamType - Returns the type of lastPublicHandle * - MegaRequest::getTransferredBytes - Returns the timestamp of the last access * * @param gateway Payment gateway * Currently supported payment gateways are: * - MegaApi::PAYMENT_METHOD_ITUNES = 2 * - MegaApi::PAYMENT_METHOD_GOOGLE_WALLET = 3 * - MegaApi::PAYMENT_METHOD_WINDOWS_STORE = 13 * * @param receipt Purchase receipt * @param lastPublicHandle Last public node handle accessed by the user in the last 24h * @param lastPublicHandleType Indicates the type of lastPublicHandle, valid values are: * - MegaApi::AFFILIATE_TYPE_ID = 1 * - MegaApi::AFFILIATE_TYPE_FILE_FOLDER = 2 * - MegaApi::AFFILIATE_TYPE_CHAT = 3 * - MegaApi::AFFILIATE_TYPE_CONTACT = 4 * * @param lastAccessTimestamp Timestamp of the last access * @param listener MegaRequestListener to track this request */ public void submitPurchaseReceipt(int gateway, String receipt, long lastPublicHandle, int lastPublicHandleType, long lastAccessTimestamp, MegaRequestListenerInterface listener) { megaApi.submitPurchaseReceipt(gateway, receipt, lastPublicHandle, lastPublicHandleType, lastAccessTimestamp, createDelegateRequestListener(listener)); } /** * Submit a purchase receipt for verification * * The associated request type with this request is MegaRequest::TYPE_SUBMIT_PURCHASE_RECEIPT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNumber - Returns the payment gateway * - MegaRequest::getText - Returns the purchase receipt * - MegaRequest::getParentHandle - Returns the last public node handle accessed * - MegaRequest::getParamType - Returns the type of lastPublicHandle * - MegaRequest::getTransferredBytes - Returns the timestamp of the last access * * @param gateway Payment gateway * Currently supported payment gateways are: * - MegaApi::PAYMENT_METHOD_ITUNES = 2 * - MegaApi::PAYMENT_METHOD_GOOGLE_WALLET = 3 * - MegaApi::PAYMENT_METHOD_WINDOWS_STORE = 13 * * @param receipt Purchase receipt * @param lastPublicHandle Last public node handle accessed by the user in the last 24h * @param lastPublicHandleType Indicates the type of lastPublicHandle, valid values are: * - MegaApi::AFFILIATE_TYPE_ID = 1 * - MegaApi::AFFILIATE_TYPE_FILE_FOLDER = 2 * - MegaApi::AFFILIATE_TYPE_CHAT = 3 * - MegaApi::AFFILIATE_TYPE_CONTACT = 4 * * @param lastAccessTimestamp Timestamp of the last access */ public void submitPurchaseReceipt(int gateway, String receipt, long lastPublicHandle, int lastPublicHandleType, long lastAccessTimestamp) { megaApi.submitPurchaseReceipt(gateway, receipt, lastPublicHandle, lastPublicHandleType, lastAccessTimestamp); } /** * Store a credit card. * <p> * The associated request type with this request is MegaRequest.TYPE_CREDIT_CARD_STORE. * * @param address1 Billing address. * @param address2 Second line of the billing address (optional). * @param city City of the billing address. * @param province Province of the billing address. * @param country Country of the billing address. * @param postalcode Postal code of the billing address. * @param firstname Firstname of the owner of the credit card. * @param lastname Lastname of the owner of the credit card. * @param creditcard Credit card number. Only digits, no spaces nor dashes. * @param expire_month Expire month of the credit card. Must have two digits ("03" for example). * @param expire_year Expire year of the credit card. Must have four digits ("2010" for example). * @param cv2 Security code of the credit card (3 digits). * @param listener MegaRequestListener to track this request. */ public void creditCardStore(String address1, String address2, String city, String province, String country, String postalcode, String firstname, String lastname, String creditcard, String expire_month, String expire_year, String cv2, MegaRequestListenerInterface listener) { megaApi.creditCardStore(address1, address2, city, province, country, postalcode, firstname, lastname, creditcard, expire_month, expire_year, cv2, createDelegateRequestListener(listener)); } /** * Store a credit card. * * @param address1 Billing address. * @param address2 Second line of the billing address (optional). * @param city City of the billing address. * @param province Province of the billing address. * @param country Country of the billing address. * @param postalcode Postal code of the billing address. * @param firstname Firstname of the owner of the credit card. * @param lastname Lastname of the owner of the credit card. * @param creditcard Credit card number. Only digits, no spaces nor dashes. * @param expire_month Expire month of the credit card. Must have two digits ("03" for example). * @param expire_year Expire year of the credit card. Must have four digits ("2010" for example). * @param cv2 Security code of the credit card (3 digits). */ public void creditCardStore(String address1, String address2, String city, String province, String country, String postalcode, String firstname, String lastname, String creditcard, String expire_month, String expire_year, String cv2) { megaApi.creditCardStore(address1, address2, city, province, country, postalcode, firstname, lastname, creditcard, expire_month, expire_year, cv2); } /** * Get the credit card subscriptions of the account. * <p> * The associated request type with this request is MegaRequest.TYPE_CREDIT_CARD_QUERY_SUBSCRIPTIONS. * <p> * Valid data in the MegaRequest object received in onRequestFinish() when the error code * is MegaError.API_OK: <br> * - MegaRequest.getNumber() - Number of credit card subscriptions. * * @param listener MegaRequestListener to track this request. */ public void creditCardQuerySubscriptions(MegaRequestListenerInterface listener) { megaApi.creditCardQuerySubscriptions(createDelegateRequestListener(listener)); } /** * Get the credit card subscriptions of the account. * */ public void creditCardQuerySubscriptions() { megaApi.creditCardQuerySubscriptions(); } /** * Cancel credit card subscriptions of the account. * <p> * The associated request type with this request is MegaRequest.TYPE_CREDIT_CARD_CANCEL_SUBSCRIPTIONS. * * @param reason Reason for the cancellation. It can be null. * @param listener MegaRequestListener to track this request. */ public void creditCardCancelSubscriptions(String reason, MegaRequestListenerInterface listener) { megaApi.creditCardCancelSubscriptions(reason, createDelegateRequestListener(listener)); } /** * Cancel credit card subscriptions of the account. * * @param reason Reason for the cancellation. It can be null. * */ public void creditCardCancelSubscriptions(String reason) { megaApi.creditCardCancelSubscriptions(reason); } /** * Get the available payment methods. * <p> * The associated request type with this request is MegaRequest.TYPE_GET_PAYMENT_METHODS. * <p> * Valid data in the MegaRequest object received in onRequestFinish() when the error code * is MegaError.API_OK: <br> * - MegaRequest.getNumber() - Bitfield with available payment methods. * * To identify if a payment method is available, the following check can be performed: <br> * (request.getNumber() & (1 << MegaApiJava.PAYMENT_METHOD_CREDIT_CARD) != 0). * * @param listener MegaRequestListener to track this request. */ public void getPaymentMethods(MegaRequestListenerInterface listener) { megaApi.getPaymentMethods(createDelegateRequestListener(listener)); } /** * Get the available payment methods. */ public void getPaymentMethods() { megaApi.getPaymentMethods(); } /** * Export the master key of the account. * <p> * The returned value is a Base64-encoded string. * <p> * With the master key, it's possible to start the recovery of an account when the * password is lost: <br> * - https://mega.co.nz/#recovery. * * @return Base64-encoded master key. */ public String exportMasterKey() { return megaApi.exportMasterKey(); } /** * Notify the user has exported the master key * * This function should be called when the user exports the master key by * clicking on "Copy" or "Save file" options. * * As result, the user attribute MegaApi::USER_ATTR_PWD_REMINDER will be updated * to remember the user has a backup of his/her master key. In consequence, * MEGA will not ask the user to remind the password for the account. * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_PWD_REMINDER * - MegaRequest::getText - Returns the new value for the attribute * * @param listener MegaRequestListener to track this request */ public void masterKeyExported(MegaRequestListenerInterface listener){ megaApi.masterKeyExported(createDelegateRequestListener(listener)); } /** * Check if the master key has been exported * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_PWD_REMINDER * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getAccess - Returns true if the master key has been exported * * If the corresponding user attribute is not set yet, the request will fail with the * error code MegaError::API_ENOENT. * * @param listener MegaRequestListener to track this request */ public void isMasterKeyExported (MegaRequestListenerInterface listener) { megaApi.isMasterKeyExported(createDelegateRequestListener(listener)); } /** * Notify the user has successfully checked his password * * This function should be called when the user demonstrates that he remembers * the password to access the account * * As result, the user attribute MegaApi::USER_ATTR_PWD_REMINDER will be updated * to remember this event. In consequence, MEGA will not continue asking the user * to remind the password for the account in a short time. * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_PWD_REMINDER * - MegaRequest::getText - Returns the new value for the attribute * * @param listener MegaRequestListener to track this request */ public void passwordReminderDialogSucceeded(MegaRequestListenerInterface listener){ megaApi.passwordReminderDialogSucceeded(createDelegateRequestListener(listener)); } /** * Notify the user has successfully skipped the password check * * This function should be called when the user skips the verification of * the password to access the account * * As result, the user attribute MegaApi::USER_ATTR_PWD_REMINDER will be updated * to remember this event. In consequence, MEGA will not continue asking the user * to remind the password for the account in a short time. * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_PWD_REMINDER * - MegaRequest::getText - Returns the new value for the attribute * * @param listener MegaRequestListener to track this request */ public void passwordReminderDialogSkipped(MegaRequestListenerInterface listener){ megaApi.passwordReminderDialogSkipped(createDelegateRequestListener(listener)); } /** * Notify the user wants to totally disable the password check * * This function should be called when the user rejects to verify that he remembers * the password to access the account and doesn't want to see the reminder again. * * As result, the user attribute MegaApi::USER_ATTR_PWD_REMINDER will be updated * to remember this event. In consequence, MEGA will not ask the user * to remind the password for the account again. * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_PWD_REMINDER * - MegaRequest::getText - Returns the new value for the attribute * * @param listener MegaRequestListener to track this request */ public void passwordReminderDialogBlocked(MegaRequestListenerInterface listener){ megaApi.passwordReminderDialogBlocked(createDelegateRequestListener(listener)); } /** * Check if the app should show the password reminder dialog to the user * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_PWD_REMINDER * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getFlag - Returns true if the password reminder dialog should be shown * * @param atLogout True if the check is being done just before a logout * @param listener MegaRequestListener to track this request */ public void shouldShowPasswordReminderDialog(boolean atLogout, MegaRequestListenerInterface listener){ megaApi.shouldShowPasswordReminderDialog(atLogout, createDelegateRequestListener(listener)); } /** * Enable or disable the generation of rich previews * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_RICH_PREVIEWS * * @param enable True to enable the generation of rich previews * @param listener MegaRequestListener to track this request */ public void enableRichPreviews(boolean enable, MegaRequestListenerInterface listener){ megaApi.enableRichPreviews(enable, createDelegateRequestListener(listener)); } /** * Enable or disable the generation of rich previews * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_RICH_PREVIEWS * * @param enable True to enable the generation of rich previews */ public void enableRichPreviews(boolean enable){ megaApi.enableRichPreviews(enable); } /** * Check if rich previews are automatically generated * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_RICH_PREVIEWS * - MegaRequest::getNumDetails - Returns zero * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getFlag - Returns true if generation of rich previews is enabled * - MegaRequest::getMegaStringMap - Returns the raw content of the atribute: [<key><value>]* * * If the corresponding user attribute is not set yet, the request will fail with the * error code MegaError::API_ENOENT, but the value of MegaRequest::getFlag will still be valid (false). * * @param listener MegaRequestListener to track this request */ public void isRichPreviewsEnabled(MegaRequestListenerInterface listener){ megaApi.isRichPreviewsEnabled(createDelegateRequestListener(listener)); } /** * Check if rich previews are automatically generated * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_RICH_PREVIEWS * - MegaRequest::getNumDetails - Returns zero * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getFlag - Returns true if generation of rich previews is enabled * - MegaRequest::getMegaStringMap - Returns the raw content of the atribute: [<key><value>]* * * If the corresponding user attribute is not set yet, the request will fail with the * error code MegaError::API_ENOENT, but the value of MegaRequest::getFlag will still be valid (false). * */ public void isRichPreviewsEnabled(){ megaApi.isRichPreviewsEnabled(); } /** * Check if the app should show the rich link warning dialog to the user * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_RICH_PREVIEWS * - MegaRequest::getNumDetails - Returns one * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getFlag - Returns true if it is necessary to show the rich link warning * - MegaRequest::getNumber - Returns the number of times that user has indicated that doesn't want * modify the message with a rich link. If number is bigger than three, the extra option "Never" * must be added to the warning dialog. * - MegaRequest::getMegaStringMap - Returns the raw content of the atribute: [<key><value>]* * * If the corresponding user attribute is not set yet, the request will fail with the * error code MegaError::API_ENOENT, but the value of MegaRequest::getFlag will still be valid (true). * * @param listener MegaRequestListener to track this request */ public void shouldShowRichLinkWarning(MegaRequestListenerInterface listener){ megaApi.shouldShowRichLinkWarning(createDelegateRequestListener(listener)); } /** * Check if the app should show the rich link warning dialog to the user * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_RICH_PREVIEWS * - MegaRequest::getNumDetails - Returns one * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getFlag - Returns true if it is necessary to show the rich link warning * - MegaRequest::getNumber - Returns the number of times that user has indicated that doesn't want * modify the message with a rich link. If number is bigger than three, the extra option "Never" * must be added to the warning dialog. * - MegaRequest::getMegaStringMap - Returns the raw content of the atribute: [<key><value>]* * * If the corresponding user attribute is not set yet, the request will fail with the * error code MegaError::API_ENOENT, but the value of MegaRequest::getFlag will still be valid (true). * */ public void shouldShowRichLinkWarning(){ megaApi.shouldShowRichLinkWarning(); } /** * Set the number of times "Not now" option has been selected in the rich link warning dialog * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_RICH_PREVIEWS * * @param value Number of times "Not now" option has been selected * @param listener MegaRequestListener to track this request */ public void setRichLinkWarningCounterValue(int value, MegaRequestListenerInterface listener){ megaApi.setRichLinkWarningCounterValue(value, createDelegateRequestListener(listener)); } /** * Set the number of times "Not now" option has been selected in the rich link warning dialog * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_RICH_PREVIEWS * * @param value Number of times "Not now" option has been selected */ public void setRichLinkWarningCounterValue(int value){ megaApi.setRichLinkWarningCounterValue(value); } /** * Enable the sending of geolocation messages * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_GEOLOCATION * * @param listener MegaRequestListener to track this request */ public void enableGeolocation(MegaRequestListenerInterface listener){ megaApi.enableGeolocation(createDelegateRequestListener(listener)); } /** * Check if the sending of geolocation messages is enabled * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_GEOLOCATION * * Sending a Geolocation message is enabled if the MegaRequest object, received in onRequestFinish, * has error code MegaError::API_OK. In other cases, send geolocation messages is not enabled and * the application has to answer before send a message of this type. * * @param listener MegaRequestListener to track this request */ public void isGeolocationEnabled(MegaRequestListenerInterface listener){ megaApi.isGeolocationEnabled(createDelegateRequestListener(listener)); } /** * Set My Chat Files target folder. * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_MY_CHAT_FILES_FOLDER * - MegaRequest::getMegaStringMap - Returns a MegaStringMap. * The key "h" in the map contains the nodehandle specified as parameter encoded in B64 * * @param nodehandle MegaHandle of the node to be used as target folder * @param listener MegaRequestListener to track this request */ public void setMyChatFilesFolder(long nodehandle, MegaRequestListenerInterface listener) { megaApi.setMyChatFilesFolder(nodehandle, createDelegateRequestListener(listener)); } /** * Gets My chat files target folder. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_MY_CHAT_FILES_FOLDER * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodehandle - Returns the handle of the node where My Chat Files are stored * * If the folder is not set, the request will fail with the error code MegaError::API_ENOENT. * * @param listener MegaRequestListener to track this request */ public void getMyChatFilesFolder(MegaRequestListenerInterface listener){ megaApi.getMyChatFilesFolder(createDelegateRequestListener(listener)); } /** * Set Camera Uploads primary target folder. * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_CAMERA_UPLOADS_FOLDER * - MegaRequest::getFlag - Returns false * - MegaRequest::getNodehandle - Returns the provided node handle * - MegaRequest::getMegaStringMap - Returns a MegaStringMap. * The key "h" in the map contains the nodehandle specified as parameter encoded in B64 * * @param nodehandle MegaHandle of the node to be used as primary target folder * @param listener MegaRequestListener to track this request */ public void setCameraUploadsFolder(long nodehandle, MegaRequestListenerInterface listener){ megaApi.setCameraUploadsFolder(nodehandle, createDelegateRequestListener(listener)); } /** * Set Camera Uploads secondary target folder. * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_CAMERA_UPLOADS_FOLDER * - MegaRequest::getFlag - Returns true * - MegaRequest::getNodehandle - Returns the provided node handle * - MegaRequest::getMegaStringMap - Returns a MegaStringMap. * The key "sh" in the map contains the nodehandle specified as parameter encoded in B64 * * @param nodehandle MegaHandle of the node to be used as secondary target folder * @param listener MegaRequestListener to track this request */ public void setCameraUploadsFolderSecondary(long nodehandle, MegaRequestListenerInterface listener){ megaApi.setCameraUploadsFolderSecondary(nodehandle, createDelegateRequestListener(listener)); } /** * Set Camera Uploads for both primary and secondary target folder. * * If only one of the target folders wants to be set, simply pass a INVALID_HANDLE to * as the other target folder and it will remain untouched. * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_CAMERA_UPLOADS_FOLDER * - MegaRequest::getNodehandle - Returns the provided node handle for primary folder * - MegaRequest::getParentHandle - Returns the provided node handle for secondary folder * * @param primaryFolder MegaHandle of the node to be used as primary target folder * @param secondaryFolder MegaHandle of the node to be used as secondary target folder * @param listener MegaRequestListener to track this request */ public void setCameraUploadsFolders(long primaryFolder, long secondaryFolder, MegaRequestListenerInterface listener) { megaApi.setCameraUploadsFolders(primaryFolder, secondaryFolder, createDelegateRequestListener(listener)); } /** * Gets Camera Uploads primary target folder. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_CAMERA_UPLOADS_FOLDER * - MegaRequest::getFlag - Returns false * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodehandle - Returns the handle of the primary node where Camera Uploads files are stored * * If the folder is not set, the request will fail with the error code MegaError::API_ENOENT. * * @param listener MegaRequestListener to track this request */ public void getCameraUploadsFolder(MegaRequestListenerInterface listener){ megaApi.getCameraUploadsFolder(createDelegateRequestListener(listener)); } /** * Gets Camera Uploads secondary target folder. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_CAMERA_UPLOADS_FOLDER * - MegaRequest::getFlag - Returns true * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodehandle - Returns the handle of the secondary node where Camera Uploads files are stored * * If the secondary folder is not set, the request will fail with the error code MegaError::API_ENOENT. * * @param listener MegaRequestListener to track this request */ public void getCameraUploadsFolderSecondary(MegaRequestListenerInterface listener){ megaApi.getCameraUploadsFolderSecondary(createDelegateRequestListener(listener)); } /** * Gets the alias for an user * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_ALIAS * - MegaRequest::getNodeHandle - user handle in binary * - MegaRequest::getText - user handle encoded in B64 * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getName - Returns the user alias * * If the user alias doesn't exists the request will fail with the error code MegaError::API_ENOENT. * * @param uh handle of the user in binary * @param listener MegaRequestListener to track this request */ public void getUserAlias(long uh, MegaRequestListenerInterface listener) { megaApi.getUserAlias(uh, createDelegateRequestListener(listener)); } /** * Set or reset an alias for a user * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_ALIAS * - MegaRequest::getNodeHandle - Returns the user handle in binary * - MegaRequest::getText - Returns the user alias * * @param uh handle of the user in binary * @param alias the user alias, or null to reset the existing * @param listener MegaRequestListener to track this request */ public void setUserAlias(long uh, String alias, MegaRequestListenerInterface listener) { megaApi.setUserAlias(uh, alias, createDelegateRequestListener(listener)); } /** * Get push notification settings * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_PUSH_SETTINGS * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaPushNotificationSettings - Returns settings for push notifications * * @see MegaPushNotificationSettings class for more details. * * @param listener MegaRequestListener to track this request */ public void getPushNotificationSettings(MegaRequestListenerInterface listener) { megaApi.getPushNotificationSettings(createDelegateRequestListener(listener)); } /** * Set push notification settings * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_PUSH_SETTINGS * - MegaRequest::getMegaPushNotificationSettings - Returns settings for push notifications * * @see MegaPushNotificationSettings class for more details. You can prepare a new object by * calling MegaPushNotificationSettings::createInstance. * * @param settings MegaPushNotificationSettings with the new settings * @param listener MegaRequestListener to track this request */ public void setPushNotificationSettings(MegaPushNotificationSettings settings, MegaRequestListenerInterface listener) { megaApi.setPushNotificationSettings(settings, createDelegateRequestListener(listener)); } /** * Get the number of days for rubbish-bin cleaning scheduler * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_RUBBISH_TIME * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNumber - Returns the days for rubbish-bin cleaning scheduler. * Zero means that the rubbish-bin cleaning scheduler is disabled (only if the account is PRO) * Any negative value means that the configured value is invalid. * * @param listener MegaRequestListener to track this request */ public void getRubbishBinAutopurgePeriod(MegaRequestListenerInterface listener){ megaApi.getRubbishBinAutopurgePeriod(createDelegateRequestListener(listener)); } /** * Set the number of days for rubbish-bin cleaning scheduler * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_RUBBISH_TIME * - MegaRequest::getNumber - Returns the days for rubbish-bin cleaning scheduler passed as parameter * * @param days Number of days for rubbish-bin cleaning scheduler. It must be >= 0. * The value zero disables the rubbish-bin cleaning scheduler (only for PRO accounts). * * @param listener MegaRequestListener to track this request */ public void setRubbishBinAutopurgePeriod(int days, MegaRequestListenerInterface listener){ megaApi.setRubbishBinAutopurgePeriod(days, createDelegateRequestListener(listener)); } /** * Returns the id of this device * * You take the ownership of the returned value. * * @return The id of this device */ public String getDeviceId() { return megaApi.getDeviceId(); } /** * Returns the name set for this device * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_DEVICE_NAMES * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getName - Returns device name. * * @param listener MegaRequestListener to track this request */ public void getDeviceName(MegaRequestListenerInterface listener) { megaApi.getDeviceName(createDelegateRequestListener(listener)); } /** * Returns the name set for this device * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_DEVICE_NAMES * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getName - Returns device name. */ public void getDeviceName() { megaApi.getDeviceName(); } /** * Sets device name * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_DEVICE_NAMES * - MegaRequest::getName - Returns device name. * * @param deviceName String with device name * @param listener MegaRequestListener to track this request */ public void setDeviceName(String deviceName, MegaRequestListenerInterface listener) { megaApi.setDeviceName(deviceName, createDelegateRequestListener(listener)); } /** * Sets device name * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_DEVICE_NAMES * - MegaRequest::getName - Returns device name. * * @param deviceName String with device name */ public void setDeviceName(String deviceName) { megaApi.setDeviceName(deviceName); } /** * Returns the name set for this drive * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_DRIVE_NAMES * - MegaRequest::getFile - Returns the path to the drive * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getName - Returns drive name. * * @param pathToDrive Path to the root of the external drive * @param listener MegaRequestListener to track this request */ public void getDriveName(String pathToDrive, MegaRequestListenerInterface listener) { megaApi.getDriveName(pathToDrive, createDelegateRequestListener(listener)); } /** * Returns the name set for this drive * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_DRIVE_NAMES * - MegaRequest::getFile - Returns the path to the drive * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getName - Returns drive name. * * @param pathToDrive Path to the root of the external drive */ public void getDriveName(String pathToDrive) { megaApi.getDriveName(pathToDrive); } /** * Sets drive name * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_DRIVE_NAMES * - MegaRequest::getName - Returns drive name. * - MegaRequest::getFile - Returns the path to the drive * * @param pathToDrive Path to the root of the external drive * @param driveName String with drive name * @param listener MegaRequestListener to track this request */ public void setDriveName(String pathToDrive, String driveName, MegaRequestListenerInterface listener) { megaApi.setDriveName(pathToDrive, driveName, createDelegateRequestListener(listener)); } /** * Sets drive name * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_DRIVE_NAMES * - MegaRequest::getName - Returns drive name. * - MegaRequest::getFile - Returns the path to the drive * * @param pathToDrive Path to the root of the external drive * @param driveName String with drive name */ public void setDriveName(String pathToDrive, String driveName) { megaApi.setDriveName(pathToDrive, driveName); } /** * Change the password of the MEGA account * * The associated request type with this request is MegaRequest::TYPE_CHANGE_PW * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getPassword - Returns the old password (if it was passed as parameter) * - MegaRequest::getNewPassword - Returns the new password * * @param oldPassword Old password (optional, it can be NULL to not check the old password) * @param newPassword New password * @param listener MegaRequestListener to track this request */ public void changePassword(String oldPassword, String newPassword, MegaRequestListenerInterface listener) { megaApi.changePassword(oldPassword, newPassword, createDelegateRequestListener(listener)); } /** * Change the password of the MEGA account * * The associated request type with this request is MegaRequest::TYPE_CHANGE_PW * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getPassword - Returns the old password (if it was passed as parameter) * - MegaRequest::getNewPassword - Returns the new password * * @param oldPassword Old password (optional, it can be NULL to not check the old password) * @param newPassword New password */ public void changePassword(String oldPassword, String newPassword) { megaApi.changePassword(oldPassword, newPassword); } /** * Invite another person to be your MEGA contact. * <p> * The user does not need to be registered with MEGA. If the email is not associated with * a MEGA account, an invitation email will be sent with the text in the "message" parameter. * <p> * The associated request type with this request is MegaRequest.TYPE_INVITE_CONTACT. * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getEmail() - Returns the email of the contact. <br> * - MegaRequest.getText() - Returns the text of the invitation. * * @param email Email of the new contact. * @param message Message for the user (can be null). * @param action Action for this contact request. Valid values are: <br> * - MegaContactRequest.INVITE_ACTION_ADD = 0. <br> * - MegaContactRequest.INVITE_ACTION_DELETE = 1. <br> * - MegaContactRequest.INVITE_ACTION_REMIND = 2. * * @param listener MegaRequestListenerInterface to track this request. */ public void inviteContact(String email, String message, int action, MegaRequestListenerInterface listener) { megaApi.inviteContact(email, message, action, createDelegateRequestListener(listener)); } /** * Invite another person to be your MEGA contact. * <p> * The user does not need to be registered on MEGA. If the email is not associated with * a MEGA account, an invitation email will be sent with the text in the "message" parameter. * * @param email Email of the new contact. * @param message Message for the user (can be null). * @param action Action for this contact request. Valid values are: <br> * - MegaContactRequest.INVITE_ACTION_ADD = 0. <br> * - MegaContactRequest.INVITE_ACTION_DELETE = 1. <br> * - MegaContactRequest.INVITE_ACTION_REMIND = 2. */ public void inviteContact(String email, String message, int action) { megaApi.inviteContact(email, message, action); } /** * Invite another person to be your MEGA contact using a contact link handle * * The associated request type with this request is MegaRequest::TYPE_INVITE_CONTACT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getEmail - Returns the email of the contact * - MegaRequest::getText - Returns the text of the invitation * - MegaRequest::getNumber - Returns the action * - MegaRequest::getNodeHandle - Returns the contact link handle * * Sending a reminder within a two week period since you started or your last reminder will * fail the API returning the error code MegaError::API_EACCESS. * * @param email Email of the new contact * @param message Message for the user (can be NULL) * @param action Action for this contact request. Valid values are: * - MegaContactRequest::INVITE_ACTION_ADD = 0 * - MegaContactRequest::INVITE_ACTION_DELETE = 1 * - MegaContactRequest::INVITE_ACTION_REMIND = 2 * @param contactLink Contact link handle of the other account. This parameter is considered only if the * \c action is MegaContactRequest::INVITE_ACTION_ADD. Otherwise, it's ignored and it has no effect. * * @param listener MegaRequestListener to track this request */ public void inviteContact(String email, String message, int action, long contactLink, MegaRequestListenerInterface listener){ megaApi.inviteContact(email, message, action, contactLink, createDelegateRequestListener(listener)); } /** * Reply to a contact request. * * @param request Contact request. You can get your pending contact requests using * MegaApi.getIncomingContactRequests(). * @param action Action for this contact request. Valid values are: <br> * - MegaContactRequest.REPLY_ACTION_ACCEPT = 0. <br> * - MegaContactRequest.REPLY_ACTION_DENY = 1. <br> * - MegaContactRequest.REPLY_ACTION_IGNORE = 2. <br> * * The associated request type with this request is MegaRequest.TYPE_REPLY_CONTACT_REQUEST. * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getNodeHandle() - Returns the handle of the contact request. <br> * - MegaRequest.getNumber() - Returns the action. <br> * * @param listener MegaRequestListenerInterface to track this request. */ public void replyContactRequest(MegaContactRequest request, int action, MegaRequestListenerInterface listener) { megaApi.replyContactRequest(request, action, createDelegateRequestListener(listener)); } /** * Reply to a contact request. * * @param request Contact request. You can get your pending contact requests using MegaApi.getIncomingContactRequests() * @param action Action for this contact request. Valid values are: <br> * - MegaContactRequest.REPLY_ACTION_ACCEPT = 0. <br> * - MegaContactRequest.REPLY_ACTION_DENY = 1. <br> * - MegaContactRequest.REPLY_ACTION_IGNORE = 2. */ public void replyContactRequest(MegaContactRequest request, int action) { megaApi.replyContactRequest(request, action); } /** * Remove a contact to the MEGA account. * <p> * The associated request type with this request is MegaRequest.TYPE_REMOVE_CONTACT. * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getEmail() - Returns the email of the contact. * * @param user * Email of the contact. * @param listener * MegaRequestListener to track this request. */ public void removeContact(MegaUser user, MegaRequestListenerInterface listener) { megaApi.removeContact(user, createDelegateRequestListener(listener)); } /** * Remove a contact to the MEGA account. * <p> * The associated request type with this request is MegaRequest.TYPE_REMOVE_CONTACT. * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getEmail() - Returns the email of the contact. * @param user * Email of the contact. */ public void removeContact(MegaUser user) { megaApi.removeContact(user); } /** * Logout of the MEGA account. * * The associated request type with this request is MegaRequest.TYPE_LOGOUT * * @param listener * MegaRequestListener to track this request. */ public void logout(MegaRequestListenerInterface listener) { megaApi.logout(createDelegateRequestListener(listener)); } /** * Logout of the MEGA account. */ public void logout() { megaApi.logout(); } /** * Logout of the MEGA account without invalidating the session. * <p> * The associated request type with this request is MegaRequest.TYPE_LOGOUT. * * @param listener * MegaRequestListener to track this request. */ public void localLogout(MegaRequestListenerInterface listener) { megaApi.localLogout(createDelegateRequestListener(listener)); } /** * Logout of the MEGA account without invalidating the session. * */ public void localLogout() { megaApi.localLogout(); } /** * Invalidate the existing cache and create a fresh one */ public void invalidateCache(){ megaApi.invalidateCache(); } /** * Estimate the strength of a password * * Possible return values are: * - PASSWORD_STRENGTH_VERYWEAK = 0 * - PASSWORD_STRENGTH_WEAK = 1 * - PASSWORD_STRENGTH_MEDIUM = 2 * - PASSWORD_STRENGTH_GOOD = 3 * - PASSWORD_STRENGTH_STRONG = 4 * * @param password Password to check * @return Estimated strength of the password */ public int getPasswordStrength(String password){ return megaApi.getPasswordStrength(password); } /** * Use HTTPS communications only * * The default behavior is to use HTTP for transfers and the persistent connection * to wait for external events. Those communications don't require HTTPS because * all transfer data is already end-to-end encrypted and no data is transmitted * over the connection to wait for events (it's just closed when there are new events). * * This feature should only be enabled if there are problems to contact MEGA servers * through HTTP because otherwise it doesn't have any benefit and will cause a * higher CPU usage. * * See MegaApi::usingHttpsOnly * * @param httpsOnly True to use HTTPS communications only */ public void useHttpsOnly(boolean httpsOnly) { megaApi.useHttpsOnly(httpsOnly); } /** * Check if the SDK is using HTTPS communications only * * The default behavior is to use HTTP for transfers and the persistent connection * to wait for external events. Those communications don't require HTTPS because * all transfer data is already end-to-end encrypted and no data is transmitted * over the connection to wait for events (it's just closed when there are new events). * * See MegaApi::useHttpsOnly * * @return True if the SDK is using HTTPS communications only. Otherwise false. */ public boolean usingHttpsOnly() { return megaApi.usingHttpsOnly(); } /****************************************************************************************************/ // TRANSFERS /****************************************************************************************************/ /** * Upload a file or a folder * * If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file or folder * @param parent Parent node for the file or folder in the MEGA account * @param listener MegaTransferListener to track this transfer */ public void startUpload(String localPath, MegaNode parent, MegaTransferListenerInterface listener) { megaApi.startUpload(localPath, parent, createDelegateTransferListener(listener)); } /** * Upload a file or a folder * * If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file or folder * @param parent Parent node for the file or folder in the MEGA account */ public void startUpload(String localPath, MegaNode parent) { megaApi.startUpload(localPath, parent); } /** * Upload a file or a folder with a custom modification time * *If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file * @param parent Parent node for the file in the MEGA account * @param mtime Custom modification time for the file in MEGA (in seconds since the epoch) * @param listener MegaTransferListener to track this transfer * * The custom modification time will be only applied for file transfers. If a folder * is transferred using this function, the custom modification time won't have any effect, */ public void startUpload(String localPath, MegaNode parent, long mtime, MegaTransferListenerInterface listener) { megaApi.startUpload(localPath, parent, mtime, createDelegateTransferListener(listener)); } /** * Upload a file or a folder with a custom modification time * *If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file * @param parent Parent node for the file in the MEGA account * @param mtime Custom modification time for the file in MEGA (in seconds since the epoch) * * The custom modification time will be only applied for file transfers. If a folder * is transferred using this function, the custom modification time won't have any effect, */ public void startUpload(String localPath, MegaNode parent, long mtime) { megaApi.startUpload(localPath, parent, mtime); } /** * Upload a file or folder with a custom name * *If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file or folder * @param parent Parent node for the file or folder in the MEGA account * @param fileName Custom file name for the file or folder in MEGA * @param listener MegaTransferListener to track this transfer */ public void startUpload(String localPath, MegaNode parent, String fileName, MegaTransferListenerInterface listener) { megaApi.startUpload(localPath, parent, fileName, createDelegateTransferListener(listener)); } /** * Upload a file or folder with a custom name * *If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file or folder * @param parent Parent node for the file or folder in the MEGA account * @param fileName Custom file name for the file or folder in MEGA */ public void startUpload(String localPath, MegaNode parent, String fileName) { megaApi.startUpload(localPath, parent, fileName); } /** * Upload a file or a folder with a custom name and a custom modification time * *If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file * @param parent Parent node for the file in the MEGA account * @param fileName Custom file name for the file in MEGA * @param mtime Custom modification time for the file in MEGA (in seconds since the epoch) * @param listener MegaTransferListener to track this transfer * * The custom modification time will be only applied for file transfers. If a folder * is transferred using this function, the custom modification time won't have any effect */ public void startUpload(String localPath, MegaNode parent, String fileName, long mtime, MegaTransferListenerInterface listener) { megaApi.startUpload(localPath, parent, fileName, mtime, createDelegateTransferListener(listener)); } /** * Upload a file or a folder with a custom name and a custom modification time * *If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file * @param parent Parent node for the file in the MEGA account * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. If a transfer is started with exactly the same data * (local path and target parent) as another one in the transfer queue, the new transfer * fails with the error API_EEXISTS and the appData of the new transfer is appended to * the appData of the old transfer, using a '!' separator if the old transfer had already * appData. * @param fileName Custom file name for the file in MEGA * @param mtime Custom modification time for the file in MEGA (in seconds since the epoch) * @param listener MegaTransferListener to track this transfer * * The custom modification time will be only applied for file transfers. If a folder * is transferred using this function, the custom modification time won't have any effect */ public void startUpload(String localPath, MegaNode parent, String appData, String fileName, long mtime, MegaTransferListenerInterface listener) { megaApi.startUpload(localPath, parent, appData, fileName, mtime, createDelegateTransferListener(listener)); } /** * Upload a file or a folder with a custom name and a custom modification time * *If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file * @param parent Parent node for the file in the MEGA account * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. If a transfer is started with exactly the same data * (local path and target parent) as another one in the transfer queue, the new transfer * fails with the error API_EEXISTS and the appData of the new transfer is appended to * the appData of the old transfer, using a '!' separator if the old transfer had already * appData. * @param fileName Custom file name for the file in MEGA * @param mtime Custom modification time for the file in MEGA (in seconds since the epoch) * * The custom modification time will be only applied for file transfers. If a folder * is transferred using this function, the custom modification time won't have any effect */ public void startUpload(String localPath, MegaNode parent, String appData, String fileName, long mtime) { megaApi.startUpload(localPath, parent, appData, fileName, mtime); } /** * Upload a file or a folder with a custom name and a custom modification time * *If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file * @param parent Parent node for the file in the MEGA account * @param fileName Custom file name for the file in MEGA * @param mtime Custom modification time for the file in MEGA (in seconds since the epoch) * * The custom modification time will be only applied for file transfers. If a folder * is transferred using this function, the custom modification time won't have any effect */ public void startUpload(String localPath, MegaNode parent, String fileName, long mtime) { megaApi.startUpload(localPath, parent, fileName, mtime); } /** * Upload a file or a folder, saving custom app data during the transfer * * If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file or folder * @param parent Parent node for the file or folder in the MEGA account * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. If a transfer is started with exactly the same data * (local path and target parent) as another one in the transfer queue, the new transfer * fails with the error API_EEXISTS and the appData of the new transfer is appended to * the appData of the old transfer, using a '!' separator if the old transfer had already * appData. * @param listener MegaTransferListener to track this transfer */ public void startUploadWithData(String localPath, MegaNode parent, String appData, MegaTransferListenerInterface listener){ megaApi.startUploadWithData(localPath, parent, appData, createDelegateTransferListener(listener)); } /** * Upload a file or a folder, saving custom app data during the transfer * * If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file or folder * @param parent Parent node for the file or folder in the MEGA account * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. If a transfer is started with exactly the same data * (local path and target parent) as another one in the transfer queue, the new transfer * fails with the error API_EEXISTS and the appData of the new transfer is appended to * the appData of the old transfer, using a '!' separator if the old transfer had already * appData. */ public void startUploadWithData(String localPath, MegaNode parent, String appData){ megaApi.startUploadWithData(localPath, parent, appData); } /** * Upload a file or a folder, putting the transfer on top of the upload queue * * If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file or folder * @param parent Parent node for the file or folder in the MEGA account * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. If a transfer is started with exactly the same data * (local path and target parent) as another one in the transfer queue, the new transfer * fails with the error API_EEXISTS and the appData of the new transfer is appended to * the appData of the old transfer, using a '!' separator if the old transfer had already * appData. * @param isSourceTemporary Pass the ownership of the file to the SDK, that will DELETE it when the upload finishes. * This parameter is intended to automatically delete temporary files that are only created to be uploaded. * Use this parameter with caution. Set it to true only if you are sure about what are you doing. * @param listener MegaTransferListener to track this transfer */ public void startUploadWithTopPriority(String localPath, MegaNode parent, String appData, boolean isSourceTemporary, MegaTransferListenerInterface listener){ megaApi.startUploadWithTopPriority(localPath, parent, appData, isSourceTemporary, createDelegateTransferListener(listener)); } /** * Upload a file or a folder, putting the transfer on top of the upload queue * *If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file or folder * @param parent Parent node for the file or folder in the MEGA account * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. If a transfer is started with exactly the same data * (local path and target parent) as another one in the transfer queue, the new transfer * fails with the error API_EEXISTS and the appData of the new transfer is appended to * the appData of the old transfer, using a '!' separator if the old transfer had already * appData. * @param isSourceTemporary Pass the ownership of the file to the SDK, that will DELETE it when the upload finishes. * This parameter is intended to automatically delete temporary files that are only created to be uploaded. * Use this parameter with caution. Set it to true only if you are sure about what are you doing. */ public void startUploadWithTopPriority(String localPath, MegaNode parent, String appData, boolean isSourceTemporary){ megaApi.startUploadWithTopPriority(localPath, parent, appData, isSourceTemporary); } /** * Upload a file or a folder, putting the transfer on top of the upload queue * * If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file or folder * @param parent Parent node for the file or folder in the MEGA account * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. If a transfer is started with exactly the same data * (local path and target parent) as another one in the transfer queue, the new transfer * fails with the error API_EEXISTS and the appData of the new transfer is appended to * the appData of the old transfer, using a '!' separator if the old transfer had already * appData. * @param isSourceTemporary Pass the ownership of the file to the SDK, that will DELETE it when the upload finishes. * This parameter is intended to automatically delete temporary files that are only created to be uploaded. * Use this parameter with caution. Set it to true only if you are sure about what are you doing. * @param fileName Custom file name for the file or folder in MEGA * @param listener MegaTransferListener to track this transfer */ public void startUploadWithTopPriority(String localPath, MegaNode parent, String appData, boolean isSourceTemporary, String fileName, MegaTransferListenerInterface listener){ megaApi.startUploadWithTopPriority(localPath, parent, appData, isSourceTemporary, fileName, createDelegateTransferListener(listener)); } /** * Upload a file or a folder, putting the transfer on top of the upload queue * *If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file or folder * @param parent Parent node for the file or folder in the MEGA account * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. If a transfer is started with exactly the same data * (local path and target parent) as another one in the transfer queue, the new transfer * fails with the error API_EEXISTS and the appData of the new transfer is appended to * the appData of the old transfer, using a '!' separator if the old transfer had already * appData. * @param isSourceTemporary Pass the ownership of the file to the SDK, that will DELETE it when the upload finishes. * This parameter is intended to automatically delete temporary files that are only created to be uploaded. * Use this parameter with caution. Set it to true only if you are sure about what are you doing. * @param fileName Custom file name for the file or folder in MEGA */ public void startUploadWithTopPriority(String localPath, MegaNode parent, String appData, boolean isSourceTemporary, String fileName){ megaApi.startUploadWithTopPriority(localPath, parent, appData, isSourceTemporary, fileName); } /** * Upload a file or a folder * * This method should be used ONLY to share by chat a local file. In case the file * is already uploaded, but the corresponding node is missing the thumbnail and/or preview, * this method will force a new upload from the scratch (ensuring the file attributes are set), * instead of doing a remote copy. * * If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file or folder * @param parent Parent node for the file or folder in the MEGA account * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. If a transfer is started with exactly the same data * (local path and target parent) as another one in the transfer queue, the new transfer * fails with the error API_EEXISTS and the appData of the new transfer is appended to * the appData of the old transfer, using a '!' separator if the old transfer had already * appData. * @param isSourceTemporary Pass the ownership of the file to the SDK, that will DELETE it when the upload finishes. * This parameter is intended to automatically delete temporary files that are only created to be uploaded. * Use this parameter with caution. Set it to true only if you are sure about what are you doing. */ public void startUploadForChat(String localPath, MegaNode parent, String appData, boolean isSourceTemporary) { megaApi.startUploadForChat(localPath, parent, appData, isSourceTemporary); } /** * Upload a file or a folder * * This method should be used ONLY to share by chat a local file. In case the file * is already uploaded, but the corresponding node is missing the thumbnail and/or preview, * this method will force a new upload from the scratch (ensuring the file attributes are set), * instead of doing a remote copy. * * If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file or folder * @param parent Parent node for the file or folder in the MEGA account * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. If a transfer is started with exactly the same data * (local path and target parent) as another one in the transfer queue, the new transfer * fails with the error API_EEXISTS and the appData of the new transfer is appended to * the appData of the old transfer, using a '!' separator if the old transfer had already * appData. * @param isSourceTemporary Pass the ownership of the file to the SDK, that will DELETE it when the upload finishes. * This parameter is intended to automatically delete temporary files that are only created to be uploaded. * Use this parameter with caution. Set it to true only if you are sure about what are you doing. * @param fileName Custom file name for the file or folder in MEGA */ public void startUploadForChat(String localPath, MegaNode parent, String appData, boolean isSourceTemporary, String fileName) { megaApi.startUploadForChat(localPath, parent, appData, isSourceTemporary, fileName); } /** * Download a file or a folder from MEGA * *If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param node MegaNode that identifies the file or folder * @param localPath Destination path for the file or folder * If this path is a local folder, it must end with a '\' or '/' character and the file name * in MEGA will be used to store a file inside that folder. If the path doesn't finish with * one of these characters, the file will be downloaded to a file in that path. * * @param listener MegaTransferListener to track this transfer */ public void startDownload(MegaNode node, String localPath, MegaTransferListenerInterface listener) { megaApi.startDownload(node, localPath, createDelegateTransferListener(listener)); } /** * Download a file or a folder from MEGA * *If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param node MegaNode that identifies the file or folder * @param localPath Destination path for the file or folder * If this path is a local folder, it must end with a '\' or '/' character and the file name * in MEGA will be used to store a file inside that folder. If the path doesn't finish with * one of these characters, the file will be downloaded to a file in that path. */ public void startDownload(MegaNode node, String localPath) { megaApi.startDownload(node, localPath); } /** * Download a file or a folder from MEGA, saving custom app data during the transfer * * If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param node MegaNode that identifies the file or folder * @param localPath Destination path for the file or folder * If this path is a local folder, it must end with a '\' or '/' character and the file name * in MEGA will be used to store a file inside that folder. If the path doesn't finish with * one of these characters, the file will be downloaded to a file in that path. * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. * @param listener MegaTransferListener to track this transfer */ public void startDownloadWithData(MegaNode node, String localPath, String appData, MegaTransferListenerInterface listener){ megaApi.startDownloadWithData(node, localPath, appData, createDelegateTransferListener(listener)); } /** * Download a file or a folder from MEGA, saving custom app data during the transfer * * If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param node MegaNode that identifies the file or folder * @param localPath Destination path for the file or folder * If this path is a local folder, it must end with a '\' or '/' character and the file name * in MEGA will be used to store a file inside that folder. If the path doesn't finish with * one of these characters, the file will be downloaded to a file in that path. * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. */ public void startDownloadWithData(MegaNode node, String localPath, String appData){ megaApi.startDownloadWithData(node, localPath, appData); } /** * Download a file or a folder from MEGA, putting the transfer on top of the download queue. * * If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param node MegaNode that identifies the file or folder * @param localPath Destination path for the file or folder * If this path is a local folder, it must end with a '\' or '/' character and the file name * in MEGA will be used to store a file inside that folder. If the path doesn't finish with * one of these characters, the file will be downloaded to a file in that path. * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. * @param listener MegaTransferListener to track this transfer */ public void startDownloadWithTopPriority(MegaNode node, String localPath, String appData, MegaTransferListenerInterface listener){ megaApi.startDownloadWithTopPriority(node, localPath, appData, createDelegateTransferListener(listener)); } /** * Download a file or a folder from MEGA, putting the transfer on top of the download queue. * * If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param node MegaNode that identifies the file or folder * @param localPath Destination path for the file or folder * If this path is a local folder, it must end with a '\' or '/' character and the file name * in MEGA will be used to store a file inside that folder. If the path doesn't finish with * one of these characters, the file will be downloaded to a file in that path. * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. */ public void startDownloadWithTopPriority(MegaNode node, String localPath, String appData){ megaApi.startDownloadWithTopPriority(node, localPath, appData); } /** * Start an streaming download for a file in MEGA * * Streaming downloads don't save the downloaded data into a local file. It is provided * in MegaTransferListener::onTransferUpdate in a byte buffer. The pointer is returned by * MegaTransfer::getLastBytes and the size of the buffer in MegaTransfer::getDeltaSize * * The same byte array is also provided in the callback MegaTransferListener::onTransferData for * compatibility with other programming languages. Only the MegaTransferListener passed to this function * will receive MegaTransferListener::onTransferData callbacks. MegaTransferListener objects registered * with MegaApi::addTransferListener won't receive them for performance reasons * * If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param node MegaNode that identifies the file * @param startPos First byte to download from the file * @param size Size of the data to download * @param listener MegaTransferListener to track this transfer */ public void startStreaming(MegaNode node, long startPos, long size, MegaTransferListenerInterface listener) { megaApi.startStreaming(node, startPos, size, createDelegateTransferListener(listener)); } /** * Cancel a transfer. * <p> * When a transfer is cancelled, it will finish and will provide the error code * MegaError.API_EINCOMPLETE in MegaTransferListener.onTransferFinish() and * MegaListener.onTransferFinish(). * <p> * The associated request type with this request is MegaRequest.TYPE_CANCEL_TRANSFER * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getTransferTag() - Returns the tag of the cancelled transfer (MegaTransfer.getTag). * * @param transfer * MegaTransfer object that identifies the transfer. * You can get this object in any MegaTransferListener callback or any MegaListener callback * related to transfers. * @param listener * MegaRequestListener to track this request. */ public void cancelTransfer(MegaTransfer transfer, MegaRequestListenerInterface listener) { megaApi.cancelTransfer(transfer, createDelegateRequestListener(listener)); } /** * Cancel a transfer. * * @param transfer * MegaTransfer object that identifies the transfer. * You can get this object in any MegaTransferListener callback or any MegaListener callback * related to transfers. */ public void cancelTransfer(MegaTransfer transfer) { megaApi.cancelTransfer(transfer); } /** * Move a transfer one position up in the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_UP * * @param transfer Transfer to move * @param listener MegaRequestListener to track this request */ public void moveTransferUp(MegaTransfer transfer, MegaRequestListenerInterface listener) { megaApi.moveTransferUp(transfer, createDelegateRequestListener(listener)); } /** * Move a transfer one position up in the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_UP * * @param transfer Transfer to move */ public void moveTransferUp(MegaTransfer transfer) { megaApi.moveTransferUp(transfer); } /** * Move a transfer one position up in the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_UP * * @param transferTag Tag of the transfer to move * @param listener MegaRequestListener to track this request */ public void moveTransferUpByTag(int transferTag, MegaRequestListenerInterface listener) { megaApi.moveTransferUpByTag(transferTag, createDelegateRequestListener(listener)); } /** * Move a transfer one position up in the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_UP * * @param transferTag Tag of the transfer to move */ public void moveTransferUpByTag(int transferTag) { megaApi.moveTransferUpByTag(transferTag); } /** * Move a transfer one position down in the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_DOWN * * @param transfer Transfer to move * @param listener MegaRequestListener to track this request */ public void moveTransferDown(MegaTransfer transfer, MegaRequestListenerInterface listener) { megaApi.moveTransferDown(transfer, createDelegateRequestListener(listener)); } /** * Move a transfer one position down in the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_DOWN * * @param transfer Transfer to move */ public void moveTransferDown(MegaTransfer transfer) { megaApi.moveTransferDown(transfer); } /** * Move a transfer one position down in the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_DOWN * * @param transferTag Tag of the transfer to move * @param listener MegaRequestListener to track this request */ public void moveTransferDownByTag(int transferTag, MegaRequestListenerInterface listener) { megaApi.moveTransferDownByTag(transferTag, createDelegateRequestListener(listener)); } /** * Move a transfer one position down in the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_DOWN * * @param transferTag Tag of the transfer to move */ public void moveTransferDownByTag(int transferTag) { megaApi.moveTransferDownByTag(transferTag); } /** * Move a transfer to the top of the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_TOP * * @param transfer Transfer to move * @param listener MegaRequestListener to track this request */ public void moveTransferToFirst(MegaTransfer transfer, MegaRequestListenerInterface listener) { megaApi.moveTransferToFirst(transfer, createDelegateRequestListener(listener)); } /** * Move a transfer to the top of the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_TOP * * @param transfer Transfer to move */ public void moveTransferToFirst(MegaTransfer transfer) { megaApi.moveTransferToFirst(transfer); } /** * Move a transfer to the top of the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_TOP * * @param transferTag Tag of the transfer to move * @param listener MegaRequestListener to track this request */ public void moveTransferToFirstByTag(int transferTag, MegaRequestListenerInterface listener) { megaApi.moveTransferToFirstByTag(transferTag, createDelegateRequestListener(listener)); } /** * Move a transfer to the top of the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_TOP * * @param transferTag Tag of the transfer to move */ public void moveTransferToFirstByTag(int transferTag) { megaApi.moveTransferToFirstByTag(transferTag); } /** * Move a transfer to the bottom of the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_BOTTOM * * @param transfer Transfer to move * @param listener MegaRequestListener to track this request */ public void moveTransferToLast(MegaTransfer transfer, MegaRequestListenerInterface listener) { megaApi.moveTransferToLast(transfer, createDelegateRequestListener(listener)); } /** * Move a transfer to the bottom of the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_BOTTOM * * @param transfer Transfer to move */ public void moveTransferToLast(MegaTransfer transfer) { megaApi.moveTransferToLast(transfer); } /** * Move a transfer to the bottom of the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_BOTTOM * * @param transferTag Tag of the transfer to move * @param listener MegaRequestListener to track this request */ public void moveTransferToLastByTag(int transferTag, MegaRequestListenerInterface listener) { megaApi.moveTransferToLastByTag(transferTag, createDelegateRequestListener(listener)); } /** * Move a transfer to the bottom of the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_BOTTOM * * @param transferTag Tag of the transfer to move */ public void moveTransferToLastByTag(int transferTag) { megaApi.moveTransferToLastByTag(transferTag); } /** * Move a transfer before another one in the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns false (it means that it's a manual move) * - MegaRequest::getNumber - Returns the tag of the transfer with the target position * * @param transfer Transfer to move * @param prevTransfer Transfer with the target position * @param listener MegaRequestListener to track this request */ public void moveTransferBefore(MegaTransfer transfer, MegaTransfer prevTransfer, MegaRequestListenerInterface listener) { megaApi.moveTransferBefore(transfer, prevTransfer, createDelegateRequestListener(listener)); } /** * Move a transfer before another one in the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns false (it means that it's a manual move) * - MegaRequest::getNumber - Returns the tag of the transfer with the target position * * @param transfer Transfer to move * @param prevTransfer Transfer with the target position */ public void moveTransferBefore(MegaTransfer transfer, MegaTransfer prevTransfer) { megaApi.moveTransferBefore(transfer, prevTransfer); } /** * Move a transfer before another one in the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns false (it means that it's a manual move) * - MegaRequest::getNumber - Returns the tag of the transfer with the target position * * @param transferTag Tag of the transfer to move * @param prevTransferTag Tag of the transfer with the target position * @param listener MegaRequestListener to track this request */ public void moveTransferBeforeByTag(int transferTag, int prevTransferTag, MegaRequestListenerInterface listener) { megaApi.moveTransferBeforeByTag(transferTag, prevTransferTag, createDelegateRequestListener(listener)); } /** * Move a transfer before another one in the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns false (it means that it's a manual move) * - MegaRequest::getNumber - Returns the tag of the transfer with the target position * * @param transferTag Tag of the transfer to move * @param prevTransferTag Tag of the transfer with the target position */ public void moveTransferBeforeByTag(int transferTag, int prevTransferTag) { megaApi.moveTransferBeforeByTag(transferTag, prevTransferTag); } /** * Cancel the transfer with a specific tag. * <p> * When a transfer is cancelled, it will finish and will provide the error code * MegaError.API_EINCOMPLETE in MegaTransferListener.onTransferFinish() and * MegaListener.onTransferFinish(). * <p> * The associated request type with this request is MegaRequest.TYPE_CANCEL_TRANSFER * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getTransferTag() - Returns the tag of the cancelled transfer (MegaTransfer.getTag). * * @param transferTag * tag that identifies the transfer. * You can get this tag using MegaTransfer.getTag(). * * @param listener * MegaRequestListener to track this request. */ public void cancelTransferByTag(int transferTag, MegaRequestListenerInterface listener) { megaApi.cancelTransferByTag(transferTag, createDelegateRequestListener(listener)); } /** * Cancel the transfer with a specific tag. * * @param transferTag * tag that identifies the transfer. * You can get this tag using MegaTransfer.getTag(). */ public void cancelTransferByTag(int transferTag) { megaApi.cancelTransferByTag(transferTag); } /** * Cancel all transfers of the same type. * <p> * The associated request type with this request is MegaRequest.TYPE_CANCEL_TRANSFERS * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getParamType() - Returns the first parameter. * * @param direction * Type of transfers to cancel. * Valid values are: <br> * - MegaTransfer.TYPE_DOWNLOAD = 0. <br> * - MegaTransfer.TYPE_UPLOAD = 1. * * @param listener * MegaRequestListener to track this request. */ public void cancelTransfers(int direction, MegaRequestListenerInterface listener) { megaApi.cancelTransfers(direction, createDelegateRequestListener(listener)); } /** * Cancel all transfers of the same type. * * @param direction * Type of transfers to cancel. * Valid values are: <br> * - MegaTransfer.TYPE_DOWNLOAD = 0. <br> * - MegaTransfer.TYPE_UPLOAD = 1. */ public void cancelTransfers(int direction) { megaApi.cancelTransfers(direction); } /** * Pause/resume all transfers. * <p> * The associated request type with this request is MegaRequest.TYPE_PAUSE_TRANSFERS * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getFlag() - Returns the first parameter. * * @param pause * true to pause all transfers / false to resume all transfers. * @param listener * MegaRequestListener to track this request. */ public void pauseTransfers(boolean pause, MegaRequestListenerInterface listener) { megaApi.pauseTransfers(pause, createDelegateRequestListener(listener)); } /** * Pause/resume all transfers. * * @param pause * true to pause all transfers / false to resume all transfers. */ public void pauseTransfers(boolean pause) { megaApi.pauseTransfers(pause); } /** * Pause/resume all transfers in one direction (uploads or downloads) * * The associated request type with this request is MegaRequest::TYPE_PAUSE_TRANSFERS * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getFlag - Returns the first parameter * - MegaRequest::getNumber - Returns the direction of the transfers to pause/resume * * @param pause true to pause transfers / false to resume transfers * @param direction Direction of transfers to pause/resume * Valid values for this parameter are: * - MegaTransfer::TYPE_DOWNLOAD = 0 * - MegaTransfer::TYPE_UPLOAD = 1 * * @param listener MegaRequestListenerInterface to track this request */ public void pauseTransfers(boolean pause, int direction, MegaRequestListenerInterface listener) { megaApi.pauseTransfers(pause, direction, createDelegateRequestListener(listener)); } /** * Pause/resume all transfers in one direction (uploads or downloads) * * @param pause true to pause transfers / false to resume transfers * @param direction Direction of transfers to pause/resume * Valid values for this parameter are: * - MegaTransfer::TYPE_DOWNLOAD = 0 * - MegaTransfer::TYPE_UPLOAD = 1 */ public void pauseTransfers(boolean pause, int direction) { megaApi.pauseTransfers(pause, direction); } /** * Pause/resume a transfer * * The request finishes with MegaError::API_OK if the state of the transfer is the * desired one at that moment. That means that the request succeed when the transfer * is successfully paused or resumed, but also if the transfer was already in the * desired state and it wasn't needed to change anything. * * Resumed transfers don't necessarily continue just after the resumption. They * are tagged as queued and are processed according to its position on the request queue. * * The associated request type with this request is MegaRequest::TYPE_PAUSE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to pause or resume * - MegaRequest::getFlag - Returns true if the transfer has to be pause or false if it has to be resumed * * @param transfer Transfer to pause or resume * @param pause True to pause the transfer or false to resume it * @param listener MegaRequestListener to track this request */ public void pauseTransfer(MegaTransfer transfer, boolean pause, MegaRequestListenerInterface listener){ megaApi.pauseTransfer(transfer, pause, createDelegateRequestListener(listener)); } /** * Pause/resume a transfer * * The request finishes with MegaError::API_OK if the state of the transfer is the * desired one at that moment. That means that the request succeed when the transfer * is successfully paused or resumed, but also if the transfer was already in the * desired state and it wasn't needed to change anything. * * Resumed transfers don't necessarily continue just after the resumption. They * are tagged as queued and are processed according to its position on the request queue. * * The associated request type with this request is MegaRequest::TYPE_PAUSE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to pause or resume * - MegaRequest::getFlag - Returns true if the transfer has to be pause or false if it has to be resumed * * @param transferTag Tag of the transfer to pause or resume * @param pause True to pause the transfer or false to resume it * @param listener MegaRequestListener to track this request */ public void pauseTransferByTag(int transferTag, boolean pause, MegaRequestListenerInterface listener){ megaApi.pauseTransferByTag(transferTag, pause, createDelegateRequestListener(listener)); } /** * Returns the state (paused/unpaused) of transfers * @param direction Direction of transfers to check * Valid values for this parameter are: * - MegaTransfer::TYPE_DOWNLOAD = 0 * - MegaTransfer::TYPE_UPLOAD = 1 * * @return true if transfers on that direction are paused, false otherwise */ public boolean areTransfersPaused(int direction) { return megaApi.areTransfersPaused(direction); } /** * Set the upload speed limit. * <p> * The limit will be applied on the server side when starting a transfer. Thus the limit won't be * applied for already started uploads and it's applied per storage server. * * @param bpslimit * -1 to automatically select the limit, 0 for no limit, otherwise the speed limit * in bytes per second. */ public void setUploadLimit(int bpslimit) { megaApi.setUploadLimit(bpslimit); } /** * Set the transfer method for downloads * * Valid methods are: * - TRANSFER_METHOD_NORMAL = 0 * HTTP transfers using port 80. Data is already encrypted. * * - TRANSFER_METHOD_ALTERNATIVE_PORT = 1 * HTTP transfers using port 8080. Data is already encrypted. * * - TRANSFER_METHOD_AUTO = 2 * The SDK selects the transfer method automatically * * - TRANSFER_METHOD_AUTO_NORMAL = 3 * The SDK selects the transfer method automatically starting with port 80. * * - TRANSFER_METHOD_AUTO_ALTERNATIVE = 4 * The SDK selects the transfer method automatically starting with alternative port 8080. * * @param method Selected transfer method for downloads */ public void setDownloadMethod(int method) { megaApi.setDownloadMethod(method); } /** * Set the transfer method for uploads * * Valid methods are: * - TRANSFER_METHOD_NORMAL = 0 * HTTP transfers using port 80. Data is already encrypted. * * - TRANSFER_METHOD_ALTERNATIVE_PORT = 1 * HTTP transfers using port 8080. Data is already encrypted. * * - TRANSFER_METHOD_AUTO = 2 * The SDK selects the transfer method automatically * * - TRANSFER_METHOD_AUTO_NORMAL = 3 * The SDK selects the transfer method automatically starting with port 80. * * - TRANSFER_METHOD_AUTO_ALTERNATIVE = 4 * The SDK selects the transfer method automatically starting with alternative port 8080. * * @param method Selected transfer method for uploads */ public void setUploadMethod(int method) { megaApi.setUploadMethod(method); } /** * Get the active transfer method for downloads * * Valid values for the return parameter are: * - TRANSFER_METHOD_NORMAL = 0 * HTTP transfers using port 80. Data is already encrypted. * * - TRANSFER_METHOD_ALTERNATIVE_PORT = 1 * HTTP transfers using port 8080. Data is already encrypted. * * - TRANSFER_METHOD_AUTO = 2 * The SDK selects the transfer method automatically * * - TRANSFER_METHOD_AUTO_NORMAL = 3 * The SDK selects the transfer method automatically starting with port 80. * * - TRANSFER_METHOD_AUTO_ALTERNATIVE = 4 * The SDK selects the transfer method automatically starting with alternative port 8080. * * @return Active transfer method for downloads */ public int getDownloadMethod() { return megaApi.getDownloadMethod(); } /** * Get the active transfer method for uploads * * Valid values for the return parameter are: * - TRANSFER_METHOD_NORMAL = 0 * HTTP transfers using port 80. Data is already encrypted. * * - TRANSFER_METHOD_ALTERNATIVE_PORT = 1 * HTTP transfers using port 8080. Data is already encrypted. * * - TRANSFER_METHOD_AUTO = 2 * The SDK selects the transfer method automatically * * - TRANSFER_METHOD_AUTO_NORMAL = 3 * The SDK selects the transfer method automatically starting with port 80. * * - TRANSFER_METHOD_AUTO_ALTERNATIVE = 4 * The SDK selects the transfer method automatically starting with alternative port 8080. * * @return Active transfer method for uploads */ public int getUploadMethod() { return megaApi.getUploadMethod(); } /** * Get all active transfers. * * @return List with all active transfers. */ public ArrayList<MegaTransfer> getTransfers() { return transferListToArray(megaApi.getTransfers()); } /** * Get all active transfers based on the type. * * @param type * MegaTransfer.TYPE_DOWNLOAD || MegaTransfer.TYPE_UPLOAD. * * @return List with all active download or upload transfers. */ public ArrayList<MegaTransfer> getTransfers(int type) { return transferListToArray(megaApi.getTransfers(type)); } /** * Get the transfer with a transfer tag. * <p> * MegaTransfer.getTag() can be used to get the transfer tag. * * @param transferTag * tag to check. * @return MegaTransfer object with that tag, or null if there is not any * active transfer with it. * */ public MegaTransfer getTransferByTag(int transferTag) { return megaApi.getTransferByTag(transferTag); } /** * Get the maximum download speed in bytes per second * * The value 0 means unlimited speed * * @return Download speed in bytes per second */ public int getMaxDownloadSpeed(){ return megaApi.getMaxDownloadSpeed(); } /** * Get the maximum upload speed in bytes per second * * The value 0 means unlimited speed * * @return Upload speed in bytes per second */ public int getMaxUploadSpeed(){ return megaApi.getMaxUploadSpeed(); } /** * Return the current download speed * @return Download speed in bytes per second */ public int getCurrentDownloadSpeed(){ return megaApi.getCurrentDownloadSpeed(); } /** * Return the current download speed * @return Download speed in bytes per second */ public int getCurrentUploadSpeed(){ return megaApi.getCurrentUploadSpeed(); } /** * Return the current transfer speed * @param type Type of transfer to get the speed. * Valid values are MegaTransfer::TYPE_DOWNLOAD or MegaTransfer::TYPE_UPLOAD * @return Transfer speed for the transfer type, or 0 if the parameter is invalid */ public int getCurrentSpeed(int type){ return megaApi.getCurrentSpeed(type); } /** * Get information about transfer queues * @param listener MegaTransferListener to start receiving information about transfers * @return Information about transfer queues */ public MegaTransferData getTransferData(MegaTransferListenerInterface listener){ return megaApi.getTransferData(createDelegateTransferListener(listener, false)); } /** * Get the first transfer in a transfer queue * * You take the ownership of the returned value. * * @param type queue to get the first transfer (MegaTransfer::TYPE_DOWNLOAD or MegaTransfer::TYPE_UPLOAD) * @return MegaTransfer object related to the first transfer in the queue or NULL if there isn't any transfer */ public MegaTransfer getFirstTransfer(int type){ return megaApi.getFirstTransfer(type); } /** * Force an onTransferUpdate callback for the specified transfer * * The callback will be received by transfer listeners registered to receive all * callbacks related to callbacks and additionally by the listener in the last * parameter of this function, if it's not NULL. * * @param transfer Transfer that will be provided in the onTransferUpdate callback * @param listener Listener that will receive the callback */ public void notifyTransfer(MegaTransfer transfer, MegaTransferListenerInterface listener){ megaApi.notifyTransfer(transfer, createDelegateTransferListener(listener)); } /** * Force an onTransferUpdate callback for the specified transfer * * The callback will be received by transfer listeners registered to receive all * callbacks related to callbacks and additionally by the listener in the last * parameter of this function, if it's not NULL. * * @param transferTag Tag of the transfer that will be provided in the onTransferUpdate callback * @param listener Listener that will receive the callback */ public void notifyTransferByTag(int transferTag, MegaTransferListenerInterface listener){ megaApi.notifyTransferByTag(transferTag, createDelegateTransferListener(listener)); } /** * Get a list of transfers that belong to a folder transfer * * This function provides the list of transfers started in the context * of a folder transfer. * * If the tag in the parameter doesn't belong to a folder transfer, * this function returns an empty list. * * The transfers provided by this function are the ones that are added to the * transfer queue when this function is called. Finished transfers, or transfers * not added to the transfer queue yet (for example, uploads that are waiting for * the creation of the parent folder in MEGA) are not returned by this function. * * @param transferTag Tag of the folder transfer to check * @return List of transfers in the context of the selected folder transfer * @see MegaTransfer::isFolderTransfer, MegaTransfer::getFolderTransferTag */ public ArrayList<MegaTransfer> getChildTransfers(int transferTag) { return transferListToArray(megaApi.getChildTransfers(transferTag)); } /** * Check if the SDK is waiting for the server. * * @return true if the SDK is waiting for the server to complete a request. */ public int isWaiting() { return megaApi.isWaiting(); } /** * Check if the SDK is waiting for the server * @return true if the SDK is waiting for the server to complete a request */ public int areServersBusy(){ return megaApi.areServersBusy(); } /** * Get the number of pending uploads * * @return Pending uploads * * Function related to statistics will be reviewed in future updates to * provide more data and avoid race conditions. They could change or be removed in the current form. */ public int getNumPendingUploads() { return megaApi.getNumPendingUploads(); } /** * Get the number of pending downloads * @return Pending downloads * * Function related to statistics will be reviewed in future updates to * provide more data and avoid race conditions. They could change or be removed in the current form. */ public int getNumPendingDownloads() { return megaApi.getNumPendingDownloads(); } /** * Get the number of queued uploads since the last call to MegaApi::resetTotalUploads * @return Number of queued uploads since the last call to MegaApi::resetTotalUploads * * Function related to statistics will be reviewed in future updates to * provide more data and avoid race conditions. They could change or be removed in the current form. */ public int getTotalUploads() { return megaApi.getTotalUploads(); } /** * Get the number of queued uploads since the last call to MegaApiJava.resetTotalDownloads(). * * @return Number of queued uploads since the last call to MegaApiJava.resetTotalDownloads(). * Function related to statistics will be reviewed in future updates. They * could change or be removed in the current form. */ public int getTotalDownloads() { return megaApi.getTotalDownloads(); } /** * Reset the number of total downloads. * <p> * This function resets the number returned by MegaApiJava.getTotalDownloads(). * * Function related to statistics will be reviewed in future updates to * provide more data and avoid race conditions. They could change or be removed in the current form. * */ public void resetTotalDownloads() { megaApi.resetTotalDownloads(); } /** * Reset the number of total uploads. * <p> * This function resets the number returned by MegaApiJava.getTotalUploads(). * * Function related to statistics will be reviewed in future updates to * provide more data and avoid race conditions. They could change or be removed in the current form. */ public void resetTotalUploads() { megaApi.resetTotalUploads(); } /** * Get the total downloaded bytes * @return Total downloaded bytes * * The count starts with the creation of MegaApi and is reset with calls to MegaApi::resetTotalDownloads * or just before a log in or a log out. * * Function related to statistics will be reviewed in future updates to * provide more data and avoid race conditions. They could change or be removed in the current form. */ public long getTotalDownloadedBytes() { return megaApi.getTotalDownloadedBytes(); } /** * Get the total uploaded bytes * @return Total uploaded bytes * * The count starts with the creation of MegaApi and is reset with calls to MegaApi::resetTotalUploads * or just before a log in or a log out. * * Function related to statistics will be reviewed in future updates to * provide more data and avoid race conditions. They could change or be removed in the current form. * */ public long getTotalUploadedBytes() { return megaApi.getTotalUploadedBytes(); } /** * @brief Get the total bytes of started downloads * @return Total bytes of started downloads * * The count starts with the creation of MegaApi and is reset with calls to MegaApi::resetTotalDownloads * or just before a log in or a log out. * * Function related to statistics will be reviewed in future updates to * provide more data and avoid race conditions. They could change or be removed in the current form. */ public long getTotalDownloadBytes(){ return megaApi.getTotalDownloadBytes(); } /** * Get the total bytes of started uploads * @return Total bytes of started uploads * * The count starts with the creation of MegaApi and is reset with calls to MegaApi::resetTotalUploads * or just before a log in or a log out. * * Function related to statistics will be reviewed in future updates to * provide more data and avoid race conditions. They could change or be removed in the current form. * */ public long getTotalUploadBytes(){ return megaApi.getTotalUploadBytes(); } /** * Get the total number of nodes in the account * @return Total number of nodes in the account */ public long getNumNodes() { return megaApi.getNumNodes(); } /** * Starts an unbuffered download of a node (file) from the user's MEGA account. * * @param node The MEGA node to download. * @param startOffset long. The byte to start from. * @param size long. Size of the download. * @param outputStream The output stream object to use for this download. * @param listener MegaRequestListener to track this request. */ public void startUnbufferedDownload(MegaNode node, long startOffset, long size, OutputStream outputStream, MegaTransferListenerInterface listener) { DelegateMegaTransferListener delegateListener = new DelegateOutputMegaTransferListener(this, outputStream, listener, true); activeTransferListeners.add(delegateListener); megaApi.startStreaming(node, startOffset, size, delegateListener); } /** * Starts an unbuffered download of a node (file) from the user's MEGA account. * * @param node The MEGA node to download. * @param outputStream The output stream object to use for this download. * @param listener MegaRequestListener to track this request. */ public void startUnbufferedDownload(MegaNode node, OutputStream outputStream, MegaTransferListenerInterface listener) { startUnbufferedDownload(node, 0, node.getSize(), outputStream, listener); } /****************************************************************************************************/ // FILESYSTEM METHODS /****************************************************************************************************/ /** * Get the number of child nodes. * <p> * If the node does not exist in MEGA or is not a folder, * this function returns 0. * <p> * This function does not search recursively, only returns the direct child nodes. * * @param parent * Parent node. * @return Number of child nodes. */ public int getNumChildren(MegaNode parent) { return megaApi.getNumChildren(parent); } /** * Get the number of child files of a node. * <p> * If the node does not exist in MEGA or is not a folder, * this function returns 0. * <p> * This function does not search recursively, only returns the direct child files. * * @param parent * Parent node. * @return Number of child files. */ public int getNumChildFiles(MegaNode parent) { return megaApi.getNumChildFiles(parent); } /** * Get the number of child folders of a node. * <p> * If the node does not exist in MEGA or is not a folder, * this function returns 0. * <p> * This function does not search recursively, only returns the direct child folders. * * @param parent * Parent node. * @return Number of child folders. */ public int getNumChildFolders(MegaNode parent) { return megaApi.getNumChildFolders(parent); } /** * Get all children of a MegaNode * * If the parent node doesn't exist or it isn't a folder, this function * returns NULL * * You take the ownership of the returned value * * @param parent Parent node * @param order Order for the returned list * Valid values for this parameter are: * - MegaApi::ORDER_NONE = 0 * Undefined order * * - MegaApi::ORDER_DEFAULT_ASC = 1 * Folders first in alphabetical order, then files in the same order * * - MegaApi::ORDER_DEFAULT_DESC = 2 * Files first in reverse alphabetical order, then folders in the same order * * - MegaApi::ORDER_SIZE_ASC = 3 * Sort by size, ascending * * - MegaApi::ORDER_SIZE_DESC = 4 * Sort by size, descending * * - MegaApi::ORDER_CREATION_ASC = 5 * Sort by creation time in MEGA, ascending * * - MegaApi::ORDER_CREATION_DESC = 6 * Sort by creation time in MEGA, descending * * - MegaApi::ORDER_MODIFICATION_ASC = 7 * Sort by modification time of the original file, ascending * * - MegaApi::ORDER_MODIFICATION_DESC = 8 * Sort by modification time of the original file, descending * * - MegaApi::ORDER_ALPHABETICAL_ASC = 9 * Same behavior than MegaApi::ORDER_DEFAULT_ASC * * - MegaApi::ORDER_ALPHABETICAL_DESC = 10 * Same behavior than MegaApi::ORDER_DEFAULT_DESC * * - MegaApi::ORDER_PHOTO_ASC = 11 * Sort with photos first, then by date ascending * * - MegaApi::ORDER_PHOTO_DESC = 12 * Sort with photos first, then by date descending * * - MegaApi::ORDER_VIDEO_ASC = 13 * Sort with videos first, then by date ascending * * - MegaApi::ORDER_VIDEO_DESC = 14 * Sort with videos first, then by date descending * * - MegaApi::ORDER_LABEL_ASC = 17 * Sort by color label, ascending. With this order, folders are returned first, then files * * - MegaApi::ORDER_LABEL_DESC = 18 * Sort by color label, descending. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_ASC = 19 * Sort nodes with favourite attr first. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_DESC = 20 * Sort nodes with favourite attr last. With this order, folders are returned first, then files * * Deprecated: MegaApi::ORDER_ALPHABETICAL_ASC and MegaApi::ORDER_ALPHABETICAL_DESC * are equivalent to MegaApi::ORDER_DEFAULT_ASC and MegaApi::ORDER_DEFAULT_DESC. * They will be eventually removed. * * @return List with all child MegaNode objects */ public ArrayList<MegaNode> getChildren(MegaNode parent, int order) { return nodeListToArray(megaApi.getChildren(parent, order)); } /** * Get all children of a list of MegaNodes * * If any parent node doesn't exist or it isn't a folder, that parent * will be skipped. * * You take the ownership of the returned value * * @param parentNodes List of parent nodes * @param order Order for the returned list * Valid values for this parameter are: * - MegaApi::ORDER_NONE = 0 * Undefined order * * - MegaApi::ORDER_DEFAULT_ASC = 1 * Folders first in alphabetical order, then files in the same order * * - MegaApi::ORDER_DEFAULT_DESC = 2 * Files first in reverse alphabetical order, then folders in the same order * * - MegaApi::ORDER_SIZE_ASC = 3 * Sort by size, ascending * * - MegaApi::ORDER_SIZE_DESC = 4 * Sort by size, descending * * - MegaApi::ORDER_CREATION_ASC = 5 * Sort by creation time in MEGA, ascending * * - MegaApi::ORDER_CREATION_DESC = 6 * Sort by creation time in MEGA, descending * * - MegaApi::ORDER_MODIFICATION_ASC = 7 * Sort by modification time of the original file, ascending * * - MegaApi::ORDER_MODIFICATION_DESC = 8 * Sort by modification time of the original file, descending * * - MegaApi::ORDER_PHOTO_ASC = 11 * Sort with photos first, then by date ascending * * - MegaApi::ORDER_PHOTO_DESC = 12 * Sort with photos first, then by date descending * * - MegaApi::ORDER_VIDEO_ASC = 13 * Sort with videos first, then by date ascending * * - MegaApi::ORDER_VIDEO_DESC = 14 * Sort with videos first, then by date descending * * - MegaApi::ORDER_LABEL_ASC = 17 * Sort by color label, ascending. With this order, folders are returned first, then files * * - MegaApi::ORDER_LABEL_DESC = 18 * Sort by color label, descending. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_ASC = 19 * Sort nodes with favourite attr first. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_DESC = 20 * Sort nodes with favourite attr last. With this order, folders are returned first, then files * @return List with all child MegaNode objects */ public ArrayList<MegaNode> getChildren(MegaNodeList parentNodes, int order) { return nodeListToArray(megaApi.getChildren(parentNodes, order)); } /** * Get all versions of a file * @param node Node to check * @return List with all versions of the node, including the current version */ public ArrayList<MegaNode> getVersions(MegaNode node){ return nodeListToArray(megaApi.getVersions(node)); } /** * Get the number of versions of a file * @param node Node to check * @return Number of versions of the node, including the current version */ public int getNumVersions(MegaNode node){ return megaApi.getNumVersions(node); } /** * Check if a file has previous versions * @param node Node to check * @return true if the node has any previous version */ public boolean hasVersions(MegaNode node){ return megaApi.hasVersions(node); } /** * Get information about the contents of a folder * * The associated request type with this request is MegaRequest::TYPE_FOLDER_INFO * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaFolderInfo - MegaFolderInfo object with the information related to the folder * * @param node Folder node to inspect * @param listener MegaRequestListener to track this request */ public void getFolderInfo(MegaNode node, MegaRequestListenerInterface listener){ megaApi.getFolderInfo(node, createDelegateRequestListener(listener)); } /** * Get file and folder children of a MegaNode separatedly * * If the parent node doesn't exist or it isn't a folder, this function * returns NULL * * You take the ownership of the returned value * * @param parent Parent node * @param order Order for the returned lists * Valid values for this parameter are: * - MegaApi::ORDER_NONE = 0 * Undefined order * * - MegaApi::ORDER_DEFAULT_ASC = 1 * Folders first in alphabetical order, then files in the same order * * - MegaApi::ORDER_DEFAULT_DESC = 2 * Files first in reverse alphabetical order, then folders in the same order * * - MegaApi::ORDER_SIZE_ASC = 3 * Sort by size, ascending * * - MegaApi::ORDER_SIZE_DESC = 4 * Sort by size, descending * * - MegaApi::ORDER_CREATION_ASC = 5 * Sort by creation time in MEGA, ascending * * - MegaApi::ORDER_CREATION_DESC = 6 * Sort by creation time in MEGA, descending * * - MegaApi::ORDER_MODIFICATION_ASC = 7 * Sort by modification time of the original file, ascending * * - MegaApi::ORDER_MODIFICATION_DESC = 8 * Sort by modification time of the original file, descending * * - MegaApi::ORDER_ALPHABETICAL_ASC = 9 * Same behavior than MegaApi::ORDER_DEFAULT_ASC * * - MegaApi::ORDER_ALPHABETICAL_DESC = 10 * Same behavior than MegaApi::ORDER_DEFAULT_DESC * * Deprecated: MegaApi::ORDER_ALPHABETICAL_ASC and MegaApi::ORDER_ALPHABETICAL_DESC * are equivalent to MegaApi::ORDER_DEFAULT_ASC and MegaApi::ORDER_DEFAULT_DESC. * They will be eventually removed. * * - MegaApi::ORDER_PHOTO_ASC = 11 * Sort with photos first, then by date ascending * * - MegaApi::ORDER_PHOTO_DESC = 12 * Sort with photos first, then by date descending * * - MegaApi::ORDER_VIDEO_ASC = 13 * Sort with videos first, then by date ascending * * - MegaApi::ORDER_VIDEO_DESC = 14 * Sort with videos first, then by date descending * * - MegaApi::ORDER_LABEL_ASC = 17 * Sort by color label, ascending. With this order, folders are returned first, then files * * - MegaApi::ORDER_LABEL_DESC = 18 * Sort by color label, descending. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_ASC = 19 * Sort nodes with favourite attr first. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_DESC = 20 * Sort nodes with favourite attr last. With this order, folders are returned first, then files * * @return Lists with files and folders child MegaNode objects */ public MegaChildren getFileFolderChildren(MegaNode parent, int order){ MegaChildren children = new MegaChildren(); MegaChildrenLists childrenList = megaApi.getFileFolderChildren(parent, order); children.setFileList(nodeListToArray(childrenList.getFileList())); children.setFolderList(nodeListToArray(childrenList.getFolderList())); return children; } /** * Get all children of a MegaNode. * <p> * If the parent node does not exist or if it is not a folder, this function. * returns null. * * @param parent * Parent node. * * @return List with all child MegaNode objects. */ public ArrayList<MegaNode> getChildren(MegaNode parent) { return nodeListToArray(megaApi.getChildren(parent)); } /** * Returns true if the node has children * @return true if the node has children */ public boolean hasChildren(MegaNode parent){ return megaApi.hasChildren(parent); } /** * Get the child node with the provided name. * <p> * If the node does not exist, this function returns null. * * @param parent * node. * @param name * of the node. * @return The MegaNode that has the selected parent and name. */ public MegaNode getChildNode(MegaNode parent, String name) { return megaApi.getChildNode(parent, name); } /** * Get the parent node of a MegaNode. * <p> * If the node does not exist in the account or * it is a root node, this function returns null. * * @param node * MegaNode to get the parent. * @return The parent of the provided node. */ public MegaNode getParentNode(MegaNode node) { return megaApi.getParentNode(node); } /** * Get the path of a MegaNode. * <p> * If the node does not exist, this function returns null. * You can recover the node later using MegaApi.getNodeByPath() * unless the path contains names with '/', '\' or ':' characters. * * @param node * MegaNode for which the path will be returned. * @return The path of the node. */ public String getNodePath(MegaNode node) { return megaApi.getNodePath(node); } /** * Get the MegaNode in a specific path in the MEGA account. * <p> * The path separator character is '/'. <br> * The Inbox root node is //in/. <br> * The Rubbish root node is //bin/. * <p> * Paths with names containing '/', '\' or ':' are not compatible * with this function. * * @param path * Path to check. * @param baseFolder * Base node if the path is relative. * @return The MegaNode object in the path, otherwise null. */ public MegaNode getNodeByPath(String path, MegaNode baseFolder) { return megaApi.getNodeByPath(path, baseFolder); } /** * Get the MegaNode in a specific path in the MEGA account. * <p> * The path separator character is '/'. <br> * The Inbox root node is //in/. <br> * The Rubbish root node is //bin/. * <p> * Paths with names containing '/', '\' or ':' are not compatible * with this function. * * @param path * Path to check. * * @return The MegaNode object in the path, otherwise null. */ public MegaNode getNodeByPath(String path) { return megaApi.getNodeByPath(path); } /** * Get the MegaNode that has a specific handle. * <p> * You can get the handle of a MegaNode using MegaNode.getHandle(). The same handle * can be got in a Base64-encoded string using MegaNode.getBase64Handle(). Conversions * between these formats can be done using MegaApiJava.base64ToHandle() and MegaApiJava.handleToBase64(). * * @param handle * Node handle to check. * @return MegaNode object with the handle, otherwise null. */ public MegaNode getNodeByHandle(long handle) { return megaApi.getNodeByHandle(handle); } /** * Get the MegaContactRequest that has a specific handle. * <p> * You can get the handle of a MegaContactRequest using MegaContactRequestgetHandle(). * You take the ownership of the returned value. * * @param handle Contact request handle to check. * @return MegaContactRequest object with the handle, otherwise null. */ public MegaContactRequest getContactRequestByHandle(long handle) { return megaApi.getContactRequestByHandle(handle); } /** * Get all contacts of this MEGA account. * * @return List of MegaUser object with all contacts of this account. */ public ArrayList<MegaUser> getContacts() { return userListToArray(megaApi.getContacts()); } /** * Get the MegaUser that has a specific email address. * <p> * You can get the email of a MegaUser using MegaUser.getEmail(). * * @param email * Email address to check. * @return MegaUser that has the email address, otherwise null. */ public MegaUser getContact(String email) { return megaApi.getContact(email); } /** * Get all MegaUserAlerts for the logged in user * * You take the ownership of the returned value * * @return List of MegaUserAlert objects */ public ArrayList<MegaUserAlert> getUserAlerts(){ return userAlertListToArray(megaApi.getUserAlerts()); } /** * Get the number of unread user alerts for the logged in user * * @return Number of unread user alerts */ public int getNumUnreadUserAlerts(){ return megaApi.getNumUnreadUserAlerts(); } /** * Get a list with all inbound shares from one MegaUser. * * @param user MegaUser sharing folders with this account. * @return List of MegaNode objects that this user is sharing with this account. */ public ArrayList<MegaNode> getInShares(MegaUser user) { return nodeListToArray(megaApi.getInShares(user)); } /** * Get a list with all inbound shares from one MegaUser. * * Valid value for order are: MegaApi::ORDER_NONE, MegaApi::ORDER_DEFAULT_ASC, * MegaApi::ORDER_DEFAULT_DESC * * You take the ownership of the returned value * * @param user MegaUser sharing folders with this account. * @param order Sorting order to use * @return List of MegaNode objects that this user is sharing with this account. */ public ArrayList<MegaNode> getInShares(MegaUser user, int order) { return nodeListToArray(megaApi.getInShares(user, order)); } /** * Get a list with all inbound shares. * * @return List of MegaNode objects that other users are sharing with this account. */ public ArrayList<MegaNode> getInShares() { return nodeListToArray(megaApi.getInShares()); } /** * Get a list with all inbound shares. * * Valid value for order are: MegaApi::ORDER_NONE, MegaApi::ORDER_DEFAULT_ASC, * MegaApi::ORDER_DEFAULT_DESC * * You take the ownership of the returned value * * @param order Sorting order to use * @return List of MegaNode objects that other users are sharing with this account. */ public ArrayList<MegaNode> getInShares(int order) { return nodeListToArray(megaApi.getInShares(order)); } /** * Get a list with all active inboud sharings * * You take the ownership of the returned value * * @return List of MegaShare objects that other users are sharing with this account */ public ArrayList<MegaShare> getInSharesList() { return shareListToArray(megaApi.getInSharesList()); } /** * Get a list with all active inboud sharings * * Valid value for order are: MegaApi::ORDER_NONE, MegaApi::ORDER_DEFAULT_ASC, * MegaApi::ORDER_DEFAULT_DESC * * You take the ownership of the returned value * * @param order Sorting order to use * @return List of MegaShare objects that other users are sharing with this account */ public ArrayList<MegaShare> getInSharesList(int order) { return shareListToArray(megaApi.getInSharesList(order)); } /** * Get the user relative to an incoming share * * This function will return NULL if the node is not found. * * If recurse is true, it will return NULL if the root corresponding to * the node received as argument doesn't represent the root of an incoming share. * Otherwise, it will return NULL if the node doesn't represent * the root of an incoming share. * * You take the ownership of the returned value * * @param node Node to look for inshare user. * @return MegaUser relative to the incoming share */ public MegaUser getUserFromInShare(MegaNode node) { return megaApi.getUserFromInShare(node); } /** * Get the user relative to an incoming share * * This function will return NULL if the node is not found. * * When recurse is true and the root of the specified node is not an incoming share, * this function will return NULL. * When recurse is false and the specified node doesn't represent the root of an * incoming share, this function will return NULL. * * You take the ownership of the returned value * * @param node Node to look for inshare user. * @param recurse use root node corresponding to the node passed * @return MegaUser relative to the incoming share */ public MegaUser getUserFromInShare(MegaNode node, boolean recurse) { return megaApi.getUserFromInShare(node, recurse); } /** * Check if a MegaNode is pending to be shared with another User. This situation * happens when a node is to be shared with a User which is not a contact yet. * * For nodes that are pending to be shared, you can get a list of MegaNode * objects using MegaApi::getPendingShares * * @param node Node to check * @return true is the MegaNode is pending to be shared, otherwise false */ public boolean isPendingShare(MegaNode node) { return megaApi.isPendingShare(node); } /** * Get a list with all active and pending outbound sharings * * @return List of MegaShare objects. */ public ArrayList<MegaShare> getOutShares() { return shareListToArray(megaApi.getOutShares()); } /** * Get a list with the active and pending outbound sharings for a MegaNode * * Valid value for order are: MegaApi::ORDER_NONE, MegaApi::ORDER_DEFAULT_ASC, * MegaApi::ORDER_DEFAULT_DESC * * You take the ownership of the returned value * * @param order Sorting order to use * @return List of MegaShare objects. */ public ArrayList<MegaShare> getOutShares(int order) { return shareListToArray(megaApi.getOutShares(order)); } /** * Get a list with the active and pending outbound sharings for a MegaNode * * If the node doesn't exist in the account, this function returns an empty list. * * You take the ownership of the returned value * * @param node MegaNode to check. * @return List of MegaShare objects. */ public ArrayList<MegaShare> getOutShares(MegaNode node) { return shareListToArray(megaApi.getOutShares(node)); } /** * Check if a node belongs to your own cloud * * @param handle Node to check * @return True if it belongs to your own cloud */ public boolean isPrivateNode(long handle) { return megaApi.isPrivateNode(handle); } /** * Check if a node does NOT belong to your own cloud * * In example, nodes from incoming shared folders do not belong to your cloud. * * @param handle Node to check * @return True if it does NOT belong to your own cloud */ public boolean isForeignNode(long handle) { return megaApi.isForeignNode(handle); } /** * Get a list with all public links * * You take the ownership of the returned value * * @return List of MegaNode objects that are shared with everyone via public link */ public ArrayList<MegaNode> getPublicLinks() { return nodeListToArray(megaApi.getPublicLinks()); } /** * Get a list with all public links * * Valid value for order are: MegaApi::ORDER_NONE, MegaApi::ORDER_DEFAULT_ASC, * MegaApi::ORDER_DEFAULT_DESC, MegaApi::ORDER_LINK_CREATION_ASC, * MegaApi::ORDER_LINK_CREATION_DESC * * You take the ownership of the returned value * * @param order Sorting order to use * @return List of MegaNode objects that are shared with everyone via public link */ public ArrayList<MegaNode> getPublicLinks(int order) { return nodeListToArray(megaApi.getPublicLinks(order)); } /** * Get a list with all incoming contact requests. * * You take the ownership of the returned value * * @return List of MegaContactRequest objects. */ public ArrayList<MegaContactRequest> getIncomingContactRequests() { return contactRequestListToArray(megaApi.getIncomingContactRequests()); } /** * Get a list with all outgoing contact requests. * * You take the ownership of the returned value * * @return List of MegaContactRequest objects. */ public ArrayList<MegaContactRequest> getOutgoingContactRequests() { return contactRequestListToArray(megaApi.getOutgoingContactRequests()); } /** * Get the access level of a MegaNode. * * @param node * MegaNode to check. * @return Access level of the node. * Valid values are: <br> * - MegaShare.ACCESS_OWNER. <br> * - MegaShare.ACCESS_FULL. <br> * - MegaShare.ACCESS_READWRITE. <br> * - MegaShare.ACCESS_READ. <br> * - MegaShare.ACCESS_UNKNOWN. */ public int getAccess(MegaNode node) { return megaApi.getAccess(node); } /** * Get the size of a node tree. * <p> * If the MegaNode is a file, this function returns the size of the file. * If it's a folder, this function returns the sum of the sizes of all nodes * in the node tree. * * @param node * Parent node. * @return Size of the node tree. */ public long getSize(MegaNode node) { return megaApi.getSize(node); } /** * Get a Base64-encoded fingerprint for a local file. * <p> * The fingerprint is created taking into account the modification time of the file * and file contents. This fingerprint can be used to get a corresponding node in MEGA * using MegaApiJava.getNodeByFingerprint(). * <p> * If the file can't be found or can't be opened, this function returns null. * * @param filePath * Local file path. * @return Base64-encoded fingerprint for the file. */ public String getFingerprint(String filePath) { return megaApi.getFingerprint(filePath); } /** * Get a Base64-encoded fingerprint for a node. * <p> * If the node does not exist or does not have a fingerprint, this function returns null. * * @param node * Node for which we want to get the fingerprint. * @return Base64-encoded fingerprint for the file. */ public String getFingerprint(MegaNode node) { return megaApi.getFingerprint(node); } /** * Returns a node with the provided fingerprint. * <p> * If there is not any node in the account with that fingerprint, this function returns null. * * @param fingerprint * Fingerprint to check. * @return MegaNode object with the provided fingerprint. */ public MegaNode getNodeByFingerprint(String fingerprint) { return megaApi.getNodeByFingerprint(fingerprint); } /** * Returns a node with the provided fingerprint in a preferred parent folder. * <p> * If there is not any node in the account with that fingerprint, this function returns null. * * @param fingerprint * Fingerprint to check. * @param preferredParent * Preferred parent if several matches are found. * @return MegaNode object with the provided fingerprint. */ public MegaNode getNodeByFingerprint(String fingerprint, MegaNode preferredParent) { return megaApi.getNodeByFingerprint(fingerprint, preferredParent); } /** * Returns all nodes that have a fingerprint * * If there isn't any node in the account with that fingerprint, this function returns an empty MegaNodeList. * * @param fingerprint Fingerprint to check * @return List of nodes with the same fingerprint */ public ArrayList<MegaNode> getNodesByFingerprint(String fingerprint) { return nodeListToArray(megaApi.getNodesByFingerprint(fingerprint)); } /** * Returns a node with the provided fingerprint that can be exported * * If there isn't any node in the account with that fingerprint, this function returns null. * If a file name is passed in the second parameter, it's also checked if nodes with a matching * fingerprint has that name. If there isn't any matching node, this function returns null. * This function ignores nodes that are inside the Rubbish Bin because public links to those nodes * can't be downloaded. * * @param fingerprint Fingerprint to check * @param name Name that the node should have * @return Exportable node that meet the requirements */ public MegaNode getExportableNodeByFingerprint(String fingerprint, String name) { return megaApi.getExportableNodeByFingerprint(fingerprint, name); } /** * Returns a node with the provided fingerprint that can be exported * * If there isn't any node in the account with that fingerprint, this function returns null. * This function ignores nodes that are inside the Rubbish Bin because public links to those nodes * can't be downloaded. * * @param fingerprint Fingerprint to check * @return Exportable node that meet the requirements */ public MegaNode getExportableNodeByFingerprint(String fingerprint) { return megaApi.getExportableNodeByFingerprint(fingerprint); } /** * Check if the account already has a node with the provided fingerprint. * <p> * A fingerprint for a local file can be generated using MegaApiJava.getFingerprint(). * * @param fingerprint * Fingerprint to check. * @return true if the account contains a node with the same fingerprint. */ public boolean hasFingerprint(String fingerprint) { return megaApi.hasFingerprint(fingerprint); } /** * getCRC Get the CRC of a file * * The CRC of a file is a hash of its contents. * If you need a more realiable method to check files, use fingerprint functions * (MegaApi::getFingerprint, MegaApi::getNodeByFingerprint) that also takes into * account the size and the modification time of the file to create the fingerprint. * * @param filePath Local file path * @return Base64-encoded CRC of the file */ public String getCRC(String filePath) { return megaApi.getCRC(filePath); } /** * Get the CRC from a fingerprint * * @param fingerprint fingerprint from which we want to get the CRC * @return Base64-encoded CRC from the fingerprint */ public String getCRCFromFingerprint(String fingerprint) { return megaApi.getCRCFromFingerprint(fingerprint); } /** * getCRC Get the CRC of a node * * The CRC of a node is a hash of its contents. * If you need a more realiable method to check files, use fingerprint functions * (MegaApi::getFingerprint, MegaApi::getNodeByFingerprint) that also takes into * account the size and the modification time of the node to create the fingerprint. * * @param node Node for which we want to get the CRC * @return Base64-encoded CRC of the node */ public String getCRC(MegaNode node) { return megaApi.getCRC(node); } /** * getNodeByCRC Returns a node with the provided CRC * * If there isn't any node in the selected folder with that CRC, this function returns NULL. * If there are several nodes with the same CRC, anyone can be returned. * * @param crc CRC to check * @param parent Parent node to scan. It must be a folder. * @return Node with the selected CRC in the selected folder, or NULL * if it's not found. */ public MegaNode getNodeByCRC(String crc, MegaNode parent) { return megaApi.getNodeByCRC(crc, parent); } /** * Check if a node has an access level. * * @param node * Node to check. * @param level * Access level to check. * Valid values for this parameter are: <br> * - MegaShare.ACCESS_OWNER. <br> * - MegaShare.ACCESS_FULL. <br> * - MegaShare.ACCESS_READWRITE. <br> * - MegaShare.ACCESS_READ. * @return MegaError object with the result. * Valid values for the error code are: <br> * - MegaError.API_OK - The node has the required access level. <br> * - MegaError.API_EACCESS - The node does not have the required access level. <br> * - MegaError.API_ENOENT - The node does not exist in the account. <br> * - MegaError.API_EARGS - Invalid parameters. */ public MegaError checkAccess(MegaNode node, int level) { return megaApi.checkAccess(node, level); } /** * Check if a node can be moved to a target node. * * @param node * Node to check. * @param target * Target for the move operation. * @return MegaError object with the result. * Valid values for the error code are: <br> * - MegaError.API_OK - The node can be moved to the target. <br> * - MegaError.API_EACCESS - The node can't be moved because of permissions problems. <br> * - MegaError.API_ECIRCULAR - The node can't be moved because that would create a circular linkage. <br> * - MegaError.API_ENOENT - The node or the target does not exist in the account. <br> * - MegaError.API_EARGS - Invalid parameters. */ public MegaError checkMove(MegaNode node, MegaNode target) { return megaApi.checkMove(node, target); } /** * Check if the MEGA filesystem is available in the local computer * * This function returns true after a successful call to MegaApi::fetchNodes, * otherwise it returns false * * @return True if the MEGA filesystem is available */ public boolean isFilesystemAvailable() { return megaApi.isFilesystemAvailable(); } /** * Returns the root node of the account. * <p> * If you haven't successfully called MegaApiJava.fetchNodes() before, * this function returns null. * * @return Root node of the account. */ public MegaNode getRootNode() { return megaApi.getRootNode(); } /** * Check if a node is in the Cloud Drive tree * * @param node Node to check * @return True if the node is in the cloud drive */ public boolean isInCloud(MegaNode node){ return megaApi.isInCloud(node); } /** * Check if a node is in the Rubbish bin tree * * @param node Node to check * @return True if the node is in the Rubbish bin */ public boolean isInRubbish(MegaNode node){ return megaApi.isInRubbish(node); } /** * Check if a node is in the Inbox tree * * @param node Node to check * @return True if the node is in the Inbox */ public boolean isInInbox(MegaNode node){ return megaApi.isInInbox(node); } /** * Returns the inbox node of the account. * <p> * If you haven't successfully called MegaApiJava.fetchNodes() before, * this function returns null. * * @return Inbox node of the account. */ public MegaNode getInboxNode() { return megaApi.getInboxNode(); } /** * Returns the rubbish node of the account. * <p> * If you haven't successfully called MegaApiJava.fetchNodes() before, * this function returns null. * * @return Rubbish node of the account. */ public MegaNode getRubbishNode() { return megaApi.getRubbishNode(); } /** * Get the time (in seconds) during which transfers will be stopped due to a bandwidth overquota * @return Time (in seconds) during which transfers will be stopped, otherwise 0 */ public long getBandwidthOverquotaDelay() { return megaApi.getBandwidthOverquotaDelay(); } /** * Search nodes containing a search string in their name * * The search is case-insensitive. * * You take the ownership of the returned value. * * This function allows to cancel the processing at any time by passing a MegaCancelToken and calling * to MegaCancelToken::setCancelFlag(true). If a valid object is passed, it must be kept alive until * this method returns. * * @param node The parent node of the tree to explore * @param searchString Search string. The search is case-insensitive * @param cancelToken MegaCancelToken to be able to cancel the processing at any time. * @param recursive True if you want to search recursively in the node tree. * False if you want to search in the children of the node only * @param order Order for the returned list * Valid values for this parameter are: * - MegaApi::ORDER_NONE = 0 * Undefined order * * - MegaApi::ORDER_DEFAULT_ASC = 1 * Folders first in alphabetical order, then files in the same order * * - MegaApi::ORDER_DEFAULT_DESC = 2 * Files first in reverse alphabetical order, then folders in the same order * * - MegaApi::ORDER_SIZE_ASC = 3 * Sort by size, ascending * * - MegaApi::ORDER_SIZE_DESC = 4 * Sort by size, descending * * - MegaApi::ORDER_CREATION_ASC = 5 * Sort by creation time in MEGA, ascending * * - MegaApi::ORDER_CREATION_DESC = 6 * Sort by creation time in MEGA, descending * * - MegaApi::ORDER_MODIFICATION_ASC = 7 * Sort by modification time of the original file, ascending * * - MegaApi::ORDER_MODIFICATION_DESC = 8 * Sort by modification time of the original file, descending * * - MegaApi::ORDER_ALPHABETICAL_ASC = 9 * Same behavior than MegaApi::ORDER_DEFAULT_ASC * * - MegaApi::ORDER_ALPHABETICAL_DESC = 10 * Same behavior than MegaApi::ORDER_DEFAULT_DESC * * Deprecated: MegaApi::ORDER_ALPHABETICAL_ASC and MegaApi::ORDER_ALPHABETICAL_DESC * are equivalent to MegaApi::ORDER_DEFAULT_ASC and MegaApi::ORDER_DEFAULT_DESC. * They will be eventually removed. * * - MegaApi::ORDER_PHOTO_ASC = 11 * Sort with photos first, then by date ascending * * - MegaApi::ORDER_PHOTO_DESC = 12 * Sort with photos first, then by date descending * * - MegaApi::ORDER_VIDEO_ASC = 13 * Sort with videos first, then by date ascending * * - MegaApi::ORDER_VIDEO_DESC = 14 * Sort with videos first, then by date descending * * - MegaApi::ORDER_LABEL_ASC = 17 * Sort by color label, ascending. With this order, folders are returned first, then files * * - MegaApi::ORDER_LABEL_DESC = 18 * Sort by color label, descending. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_ASC = 19 * Sort nodes with favourite attr first. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_DESC = 20 * Sort nodes with favourite attr last. With this order, folders are returned first, then files * * @return List of nodes that contain the desired string in their name */ public ArrayList<MegaNode> search(MegaNode node, String searchString, @NotNull MegaCancelToken cancelToken, boolean recursive, int order) { return nodeListToArray(megaApi.search(node, searchString, cancelToken, recursive, order)); } /** * Search nodes containing a search string in their name * * The search is case-insensitive. * * The search will consider every accessible node for the account: * - Cloud drive * - Inbox * - Rubbish bin * - Incoming shares from other users * * This function allows to cancel the processing at any time by passing a MegaCancelToken and calling * to MegaCancelToken::setCancelFlag(true). If a valid object is passed, it must be kept alive until * this method returns. * * You take the ownership of the returned value. * * @param searchString Search string. The search is case-insensitive * @param cancelToken MegaCancelToken to be able to cancel the processing at any time. * @param order Order for the returned list * Valid values for this parameter are: * - MegaApi::ORDER_NONE = 0 * Undefined order * * - MegaApi::ORDER_DEFAULT_ASC = 1 * Folders first in alphabetical order, then files in the same order * * - MegaApi::ORDER_DEFAULT_DESC = 2 * Files first in reverse alphabetical order, then folders in the same order * * - MegaApi::ORDER_SIZE_ASC = 3 * Sort by size, ascending * * - MegaApi::ORDER_SIZE_DESC = 4 * Sort by size, descending * * - MegaApi::ORDER_CREATION_ASC = 5 * Sort by creation time in MEGA, ascending * * - MegaApi::ORDER_CREATION_DESC = 6 * Sort by creation time in MEGA, descending * * - MegaApi::ORDER_MODIFICATION_ASC = 7 * Sort by modification time of the original file, ascending * * - MegaApi::ORDER_MODIFICATION_DESC = 8 * Sort by modification time of the original file, descending * * - MegaApi::ORDER_ALPHABETICAL_ASC = 9 * Same behavior than MegaApi::ORDER_DEFAULT_ASC * * - MegaApi::ORDER_ALPHABETICAL_DESC = 10 * Same behavior than MegaApi::ORDER_DEFAULT_DESC * * Deprecated: MegaApi::ORDER_ALPHABETICAL_ASC and MegaApi::ORDER_ALPHABETICAL_DESC * are equivalent to MegaApi::ORDER_DEFAULT_ASC and MegaApi::ORDER_DEFAULT_DESC. * They will be eventually removed. * * - MegaApi::ORDER_PHOTO_ASC = 11 * Sort with photos first, then by date ascending * * - MegaApi::ORDER_PHOTO_DESC = 12 * Sort with photos first, then by date descending * * - MegaApi::ORDER_VIDEO_ASC = 13 * Sort with videos first, then by date ascending * * - MegaApi::ORDER_VIDEO_DESC = 14 * Sort with videos first, then by date descending * * - MegaApi::ORDER_LABEL_ASC = 17 * Sort by color label, ascending. With this order, folders are returned first, then files * * - MegaApi::ORDER_LABEL_DESC = 18 * Sort by color label, descending. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_ASC = 19 * Sort nodes with favourite attr first. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_DESC = 20 * Sort nodes with favourite attr last. With this order, folders are returned first, then files * * @return List of nodes that contain the desired string in their name */ public ArrayList<MegaNode> search(String searchString, @NotNull MegaCancelToken cancelToken, int order) { return nodeListToArray(megaApi.search(searchString, cancelToken, order)); } /** * Search nodes on incoming shares containing a search string in their name * * The search is case-insensitive. * * The method will search exclusively on incoming shares * * This function allows to cancel the processing at any time by passing a MegaCancelToken and calling * to MegaCancelToken::setCancelFlag(true). If a valid object is passed, it must be kept alive until * this method returns. * * You take the ownership of the returned value. * * @param searchString Search string. The search is case-insensitive * @param cancelToken MegaCancelToken to be able to cancel the processing at any time. * @param order Order for the returned list * Valid values for this parameter are: * - MegaApi::ORDER_NONE = 0 * Undefined order * * - MegaApi::ORDER_DEFAULT_ASC = 1 * Folders first in alphabetical order, then files in the same order * * - MegaApi::ORDER_DEFAULT_DESC = 2 * Files first in reverse alphabetical order, then folders in the same order * * - MegaApi::ORDER_SIZE_ASC = 3 * Sort by size, ascending * * - MegaApi::ORDER_SIZE_DESC = 4 * Sort by size, descending * * - MegaApi::ORDER_CREATION_ASC = 5 * Sort by creation time in MEGA, ascending * * - MegaApi::ORDER_CREATION_DESC = 6 * Sort by creation time in MEGA, descending * * - MegaApi::ORDER_MODIFICATION_ASC = 7 * Sort by modification time of the original file, ascending * * - MegaApi::ORDER_MODIFICATION_DESC = 8 * Sort by modification time of the original file, descending * * - MegaApi::ORDER_ALPHABETICAL_ASC = 9 * Same behavior than MegaApi::ORDER_DEFAULT_ASC * * - MegaApi::ORDER_ALPHABETICAL_DESC = 10 * Same behavior than MegaApi::ORDER_DEFAULT_DESC * * Deprecated: MegaApi::ORDER_ALPHABETICAL_ASC and MegaApi::ORDER_ALPHABETICAL_DESC * are equivalent to MegaApi::ORDER_DEFAULT_ASC and MegaApi::ORDER_DEFAULT_DESC. * They will be eventually removed. * * - MegaApi::ORDER_PHOTO_ASC = 11 * Sort with photos first, then by date ascending * * - MegaApi::ORDER_PHOTO_DESC = 12 * Sort with photos first, then by date descending * * - MegaApi::ORDER_VIDEO_ASC = 13 * Sort with videos first, then by date ascending * * - MegaApi::ORDER_VIDEO_DESC = 14 * Sort with videos first, then by date descending * * - MegaApi::ORDER_LABEL_ASC = 17 * Sort by color label, ascending. With this order, folders are returned first, then files * * - MegaApi::ORDER_LABEL_DESC = 18 * Sort by color label, descending. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_ASC = 19 * Sort nodes with favourite attr first. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_DESC = 20 * Sort nodes with favourite attr last. With this order, folders are returned first, then files * * @return List of nodes that contain the desired string in their name */ public ArrayList<MegaNode> searchOnInShares(String searchString, @NotNull MegaCancelToken cancelToken, int order) { return nodeListToArray(megaApi.searchOnInShares(searchString, cancelToken, order)); } /** * Search nodes on outbound shares containing a search string in their name * * The search is case-insensitive. * * The method will search exclusively on outbound shares * * This function allows to cancel the processing at any time by passing a MegaCancelToken and calling * to MegaCancelToken::setCancelFlag(true). If a valid object is passed, it must be kept alive until * this method returns. * * You take the ownership of the returned value. * * @param searchString Search string. The search is case-insensitive * @param cancelToken MegaCancelToken to be able to cancel the processing at any time. * @param order Order for the returned list * Valid values for this parameter are: * - MegaApi::ORDER_NONE = 0 * Undefined order * * - MegaApi::ORDER_DEFAULT_ASC = 1 * Folders first in alphabetical order, then files in the same order * * - MegaApi::ORDER_DEFAULT_DESC = 2 * Files first in reverse alphabetical order, then folders in the same order * * - MegaApi::ORDER_SIZE_ASC = 3 * Sort by size, ascending * * - MegaApi::ORDER_SIZE_DESC = 4 * Sort by size, descending * * - MegaApi::ORDER_CREATION_ASC = 5 * Sort by creation time in MEGA, ascending * * - MegaApi::ORDER_CREATION_DESC = 6 * Sort by creation time in MEGA, descending * * - MegaApi::ORDER_MODIFICATION_ASC = 7 * Sort by modification time of the original file, ascending * * - MegaApi::ORDER_MODIFICATION_DESC = 8 * Sort by modification time of the original file, descending * * - MegaApi::ORDER_ALPHABETICAL_ASC = 9 * Same behavior than MegaApi::ORDER_DEFAULT_ASC * * - MegaApi::ORDER_ALPHABETICAL_DESC = 10 * Same behavior than MegaApi::ORDER_DEFAULT_DESC * * Deprecated: MegaApi::ORDER_ALPHABETICAL_ASC and MegaApi::ORDER_ALPHABETICAL_DESC * are equivalent to MegaApi::ORDER_DEFAULT_ASC and MegaApi::ORDER_DEFAULT_DESC. * They will be eventually removed. * * - MegaApi::ORDER_PHOTO_ASC = 11 * Sort with photos first, then by date ascending * * - MegaApi::ORDER_PHOTO_DESC = 12 * Sort with photos first, then by date descending * * - MegaApi::ORDER_VIDEO_ASC = 13 * Sort with videos first, then by date ascending * * - MegaApi::ORDER_VIDEO_DESC = 14 * Sort with videos first, then by date descending * * - MegaApi::ORDER_LABEL_ASC = 17 * Sort by color label, ascending. With this order, folders are returned first, then files * * - MegaApi::ORDER_LABEL_DESC = 18 * Sort by color label, descending. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_ASC = 19 * Sort nodes with favourite attr first. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_DESC = 20 * Sort nodes with favourite attr last. With this order, folders are returned first, then files * * @return List of nodes that contain the desired string in their name */ public ArrayList<MegaNode> searchOnOutShares(String searchString, @NotNull MegaCancelToken cancelToken, int order) { return nodeListToArray(megaApi.searchOnOutShares(searchString, cancelToken, order)); } /** * Search nodes on public links containing a search string in their name * * The search is case-insensitive. * * The method will search exclusively on public links * * This function allows to cancel the processing at any time by passing a MegaCancelToken and calling * to MegaCancelToken::setCancelFlag(true). If a valid object is passed, it must be kept alive until * this method returns. * * You take the ownership of the returned value. * * @param searchString Search string. The search is case-insensitive * @param cancelToken MegaCancelToken to be able to cancel the processing at any time. * @param order Order for the returned list * Valid values for this parameter are: * - MegaApi::ORDER_NONE = 0 * Undefined order * * - MegaApi::ORDER_DEFAULT_ASC = 1 * Folders first in alphabetical order, then files in the same order * * - MegaApi::ORDER_DEFAULT_DESC = 2 * Files first in reverse alphabetical order, then folders in the same order * * - MegaApi::ORDER_SIZE_ASC = 3 * Sort by size, ascending * * - MegaApi::ORDER_SIZE_DESC = 4 * Sort by size, descending * * - MegaApi::ORDER_CREATION_ASC = 5 * Sort by creation time in MEGA, ascending * * - MegaApi::ORDER_CREATION_DESC = 6 * Sort by creation time in MEGA, descending * * - MegaApi::ORDER_MODIFICATION_ASC = 7 * Sort by modification time of the original file, ascending * * - MegaApi::ORDER_MODIFICATION_DESC = 8 * Sort by modification time of the original file, descending * * - MegaApi::ORDER_ALPHABETICAL_ASC = 9 * Same behavior than MegaApi::ORDER_DEFAULT_ASC * * - MegaApi::ORDER_ALPHABETICAL_DESC = 10 * Same behavior than MegaApi::ORDER_DEFAULT_DESC * * Deprecated: MegaApi::ORDER_ALPHABETICAL_ASC and MegaApi::ORDER_ALPHABETICAL_DESC * are equivalent to MegaApi::ORDER_DEFAULT_ASC and MegaApi::ORDER_DEFAULT_DESC. * They will be eventually removed. * * - MegaApi::ORDER_PHOTO_ASC = 11 * Sort with photos first, then by date ascending * * - MegaApi::ORDER_PHOTO_DESC = 12 * Sort with photos first, then by date descending * * - MegaApi::ORDER_VIDEO_ASC = 13 * Sort with videos first, then by date ascending * * - MegaApi::ORDER_VIDEO_DESC = 14 * Sort with videos first, then by date descending * * - MegaApi::ORDER_LABEL_ASC = 17 * Sort by color label, ascending. With this order, folders are returned first, then files * * - MegaApi::ORDER_LABEL_DESC = 18 * Sort by color label, descending. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_ASC = 19 * Sort nodes with favourite attr first. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_DESC = 20 * Sort nodes with favourite attr last. With this order, folders are returned first, then files * * @return List of nodes that contain the desired string in their name */ public ArrayList<MegaNode> searchOnPublicLinks(String searchString, @NotNull MegaCancelToken cancelToken, int order) { return nodeListToArray(megaApi.searchOnPublicLinks(searchString, cancelToken, order)); } /** * Allow to search nodes with the following options: * - Search given a parent node of the tree to explore, or on the contrary search in a * specific target (root nodes, inshares, outshares, public links) * - Search recursively * - Containing a search string in their name * - Filter by the type of the node * - Order the returned list * * If node is provided, it will be the parent node of the tree to explore, * search string and/or nodeType can be added to search parameters * * If node and searchString are not provided, and node type is not valid, this method will * return an empty list. * * If parameter type is different of MegaApi::FILE_TYPE_DEFAULT, the following values for parameter * order are invalid: MegaApi::ORDER_PHOTO_ASC, MegaApi::ORDER_PHOTO_DESC, * MegaApi::ORDER_VIDEO_ASC, MegaApi::ORDER_VIDEO_DESC * * The search is case-insensitive. If the search string is not provided but type has any value * defined at nodefiletype_t (except FILE_TYPE_DEFAULT), * this method will return a list that contains nodes of the same type as provided. * * You take the ownership of the returned value. * * This function allows to cancel the processing at any time by passing a MegaCancelToken and calling * to MegaCancelToken::setCancelFlag(true). If a valid object is passed, it must be kept alive until * this method returns. * * @param node The parent node of the tree to explore * @param searchString Search string. The search is case-insensitive * @param cancelToken MegaCancelToken to be able to cancel the processing at any time. * @param recursive True if you want to search recursively in the node tree. * False if you want to search in the children of the node only * @param order Order for the returned list * Valid values for this parameter are: * - MegaApi::ORDER_NONE = 0 * Undefined order * * - MegaApi::ORDER_DEFAULT_ASC = 1 * Folders first in alphabetical order, then files in the same order * * - MegaApi::ORDER_DEFAULT_DESC = 2 * Files first in reverse alphabetical order, then folders in the same order * * - MegaApi::ORDER_SIZE_ASC = 3 * Sort by size, ascending * * - MegaApi::ORDER_SIZE_DESC = 4 * Sort by size, descending * * - MegaApi::ORDER_CREATION_ASC = 5 * Sort by creation time in MEGA, ascending * * - MegaApi::ORDER_CREATION_DESC = 6 * Sort by creation time in MEGA, descending * * - MegaApi::ORDER_MODIFICATION_ASC = 7 * Sort by modification time of the original file, ascending * * - MegaApi::ORDER_MODIFICATION_DESC = 8 * Sort by modification time of the original file, descending * * - MegaApi::ORDER_PHOTO_ASC = 11 * Sort with photos first, then by date ascending * * - MegaApi::ORDER_PHOTO_DESC = 12 * Sort with photos first, then by date descending * * - MegaApi::ORDER_VIDEO_ASC = 13 * Sort with videos first, then by date ascending * * - MegaApi::ORDER_VIDEO_DESC = 14 * Sort with videos first, then by date descending * * - MegaApi::ORDER_LABEL_ASC = 17 * Sort by color label, ascending. With this order, folders are returned first, then files * * - MegaApi::ORDER_LABEL_DESC = 18 * Sort by color label, descending. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_ASC = 19 * Sort nodes with favourite attr first. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_DESC = 20 * Sort nodes with favourite attr last. With this order, folders are returned first, then files * * @param type Type of nodes requested in the search * Valid values for this parameter are: * - MegaApi::FILE_TYPE_DEFAULT = 0 --> all types * - MegaApi::FILE_TYPE_PHOTO = 1 * - MegaApi::FILE_TYPE_AUDIO = 2 * - MegaApi::FILE_TYPE_VIDEO = 3 * - MegaApi::FILE_TYPE_DOCUMENT = 4 * @param target Target type where this method will search * Valid values for this parameter are * - SEARCH_TARGET_INSHARE = 0 * - SEARCH_TARGET_OUTSHARE = 1 * - SEARCH_TARGET_PUBLICLINK = 2 * - SEARCH_TARGET_ROOTNODE = 3 * - SEARCH_TARGET_ALL = 4 * @return List of nodes that match with the search parameters */ public ArrayList<MegaNode> searchByType(MegaNode node, String searchString, @NotNull MegaCancelToken cancelToken, boolean recursive, int order, int type, int target) { return nodeListToArray(megaApi.searchByType(node, searchString, cancelToken, recursive, order, type, target)); } /** * Allow to search nodes with the following options: * - Search in a specific target (root nodes, inshares, outshares, public links) * - Filter by the type of the node * - Order the returned list * * If node type is not valid, this method will return an empty list. * * If parameter type is different of MegaApi::FILE_TYPE_DEFAULT, the following values for parameter * order are invalid: MegaApi::ORDER_PHOTO_ASC, MegaApi::ORDER_PHOTO_DESC, * MegaApi::ORDER_VIDEO_ASC, MegaApi::ORDER_VIDEO_DESC * * The search is case-insensitive. If the type has any value defined at nodefiletype_t * (except FILE_TYPE_DEFAULT), this method will return a list * that contains nodes of the same type as provided. * * You take the ownership of the returned value. * * @param order Order for the returned list * Valid values for this parameter are: * - MegaApi::ORDER_NONE = 0 * Undefined order * * - MegaApi::ORDER_DEFAULT_ASC = 1 * Folders first in alphabetical order, then files in the same order * * - MegaApi::ORDER_DEFAULT_DESC = 2 * Files first in reverse alphabetical order, then folders in the same order * * - MegaApi::ORDER_SIZE_ASC = 3 * Sort by size, ascending * * - MegaApi::ORDER_SIZE_DESC = 4 * Sort by size, descending * * - MegaApi::ORDER_CREATION_ASC = 5 * Sort by creation time in MEGA, ascending * * - MegaApi::ORDER_CREATION_DESC = 6 * Sort by creation time in MEGA, descending * * - MegaApi::ORDER_MODIFICATION_ASC = 7 * Sort by modification time of the original file, ascending * * - MegaApi::ORDER_MODIFICATION_DESC = 8 * Sort by modification time of the original file, descending * * - MegaApi::ORDER_PHOTO_ASC = 11 * Sort with photos first, then by date ascending * * - MegaApi::ORDER_PHOTO_DESC = 12 * Sort with photos first, then by date descending * * - MegaApi::ORDER_VIDEO_ASC = 13 * Sort with videos first, then by date ascending * * - MegaApi::ORDER_VIDEO_DESC = 14 * Sort with videos first, then by date descending * * - MegaApi::ORDER_LABEL_ASC = 17 * Sort by color label, ascending. With this order, folders are returned first, then files * * - MegaApi::ORDER_LABEL_DESC = 18 * Sort by color label, descending. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_ASC = 19 * Sort nodes with favourite attr first. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_DESC = 20 * Sort nodes with favourite attr last. With this order, folders are returned first, then files * * @param type Type of nodes requested in the search * Valid values for this parameter are: * - MegaApi::FILE_TYPE_DEFAULT = 0 --> all types * - MegaApi::FILE_TYPE_PHOTO = 1 * - MegaApi::FILE_TYPE_AUDIO = 2 * - MegaApi::FILE_TYPE_VIDEO = 3 * - MegaApi::FILE_TYPE_DOCUMENT = 4 * * @param target Target type where this method will search * Valid values for this parameter are * - SEARCH_TARGET_INSHARE = 0 * - SEARCH_TARGET_OUTSHARE = 1 * - SEARCH_TARGET_PUBLICLINK = 2 * - SEARCH_TARGET_ROOTNODE = 3 * - SEARCH_TARGET_ALL = 4 * * @return List of nodes that match with the search parameters */ public ArrayList<MegaNode> searchByType(@NotNull MegaCancelToken cancelToken, int order, int type, int target) { return nodeListToArray(megaApi.searchByType(null, null, cancelToken, true, order, type, target)); } /** * Allow to search nodes with the following options: * - Search given a parent node of the tree to explore * - Search recursively * - Containing a search string in their name * - Filter by the type of the node * - Order the returned list * * If node is provided, it will be the parent node of the tree to explore, * search string and/or nodeType can be added to search parameters * * If node and searchString are not provided, and node type is not valid, this method will * return an empty list. * * If parameter type is different of MegaApi::FILE_TYPE_DEFAULT, the following values for parameter * order are invalid: MegaApi::ORDER_PHOTO_ASC, MegaApi::ORDER_PHOTO_DESC, * MegaApi::ORDER_VIDEO_ASC, MegaApi::ORDER_VIDEO_DESC * * The search is case-insensitive. If the search string is not provided but type has any value * defined at nodefiletype_t (except FILE_TYPE_DEFAULT), * this method will return a list that contains nodes of the same type as provided. * * You take the ownership of the returned value. * * This function allows to cancel the processing at any time by passing a MegaCancelToken and calling * to MegaCancelToken::setCancelFlag(true). If a valid object is passed, it must be kept alive until * this method returns. * * @param node The parent node of the tree to explore * @param searchString Search string. The search is case-insensitive * @param cancelToken MegaCancelToken to be able to cancel the processing at any time. * @param recursive True if you want to seach recursively in the node tree. * False if you want to seach in the children of the node only * @param order Order for the returned list * Valid values for this parameter are: * - MegaApi::ORDER_NONE = 0 * Undefined order * * - MegaApi::ORDER_DEFAULT_ASC = 1 * Folders first in alphabetical order, then files in the same order * * - MegaApi::ORDER_DEFAULT_DESC = 2 * Files first in reverse alphabetical order, then folders in the same order * * - MegaApi::ORDER_SIZE_ASC = 3 * Sort by size, ascending * * - MegaApi::ORDER_SIZE_DESC = 4 * Sort by size, descending * * - MegaApi::ORDER_CREATION_ASC = 5 * Sort by creation time in MEGA, ascending * * - MegaApi::ORDER_CREATION_DESC = 6 * Sort by creation time in MEGA, descending * * - MegaApi::ORDER_MODIFICATION_ASC = 7 * Sort by modification time of the original file, ascending * * - MegaApi::ORDER_MODIFICATION_DESC = 8 * Sort by modification time of the original file, descending * * - MegaApi::ORDER_PHOTO_ASC = 11 * Sort with photos first, then by date ascending * * - MegaApi::ORDER_PHOTO_DESC = 12 * Sort with photos first, then by date descending * * - MegaApi::ORDER_VIDEO_ASC = 13 * Sort with videos first, then by date ascending * * - MegaApi::ORDER_VIDEO_DESC = 14 * Sort with videos first, then by date descending * * - MegaApi::ORDER_LABEL_ASC = 17 * Sort by color label, ascending. With this order, folders are returned first, then files * * - MegaApi::ORDER_LABEL_DESC = 18 * Sort by color label, descending. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_ASC = 19 * Sort nodes with favourite attr first. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_DESC = 20 * Sort nodes with favourite attr last. With this order, folders are returned first, then files * * @param type Type of nodes requested in the search * Valid values for this parameter are: * - MegaApi::FILE_TYPE_DEFAULT = 0 --> all types * - MegaApi::FILE_TYPE_PHOTO = 1 * - MegaApi::FILE_TYPE_AUDIO = 2 * - MegaApi::FILE_TYPE_VIDEO = 3 * - MegaApi::FILE_TYPE_DOCUMENT = 4 * * @return List of nodes that match with the search parameters */ public ArrayList<MegaNode> searchByType(MegaNode node, String searchString, @NotNull MegaCancelToken cancelToken, boolean recursive, int order, int type) { return nodeListToArray(megaApi.searchByType(node, searchString, cancelToken, recursive, order, type)); } /** * Allow to search nodes with the following options: * - Search given a parent node of the tree to explore * - Search recursively * - Containing a search string in their name * - Order the returned list * * If node is provided, it will be the parent node of the tree to explore, * search string can be added to search parameters * * If node and searchString are not provided, this method will * return an empty list. * * You take the ownership of the returned value. * * This function allows to cancel the processing at any time by passing a MegaCancelToken and calling * to MegaCancelToken::setCancelFlag(true). If a valid object is passed, it must be kept alive until * this method returns. * * @param node The parent node of the tree to explore * @param searchString Search string. The search is case-insensitive * @param cancelToken MegaCancelToken to be able to cancel the processing at any time. * @param recursive True if you want to seach recursively in the node tree. * False if you want to seach in the children of the node only * @param order Order for the returned list * Valid values for this parameter are: * - MegaApi::ORDER_NONE = 0 * Undefined order * * - MegaApi::ORDER_DEFAULT_ASC = 1 * Folders first in alphabetical order, then files in the same order * * - MegaApi::ORDER_DEFAULT_DESC = 2 * Files first in reverse alphabetical order, then folders in the same order * * - MegaApi::ORDER_SIZE_ASC = 3 * Sort by size, ascending * * - MegaApi::ORDER_SIZE_DESC = 4 * Sort by size, descending * * - MegaApi::ORDER_CREATION_ASC = 5 * Sort by creation time in MEGA, ascending * * - MegaApi::ORDER_CREATION_DESC = 6 * Sort by creation time in MEGA, descending * * - MegaApi::ORDER_MODIFICATION_ASC = 7 * Sort by modification time of the original file, ascending * * - MegaApi::ORDER_MODIFICATION_DESC = 8 * Sort by modification time of the original file, descending * * - MegaApi::ORDER_PHOTO_ASC = 11 * Sort with photos first, then by date ascending * * - MegaApi::ORDER_PHOTO_DESC = 12 * Sort with photos first, then by date descending * * - MegaApi::ORDER_VIDEO_ASC = 13 * Sort with videos first, then by date ascending * * - MegaApi::ORDER_VIDEO_DESC = 14 * Sort with videos first, then by date descending * * - MegaApi::ORDER_LABEL_ASC = 17 * Sort by color label, ascending. With this order, folders are returned first, then files * * - MegaApi::ORDER_LABEL_DESC = 18 * Sort by color label, descending. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_ASC = 19 * Sort nodes with favourite attr first. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_DESC = 20 * Sort nodes with favourite attr last. With this order, folders are returned first, then files * * @return List of nodes that match with the search parameters */ public ArrayList<MegaNode> searchByType(MegaNode node, String searchString, @NotNull MegaCancelToken cancelToken, boolean recursive, int order) { return nodeListToArray(megaApi.searchByType(node, searchString, cancelToken, recursive, order)); } /** * Allow to search nodes with the following options: * - Search given a parent node of the tree to explore * - Search recursively * - Containing a search string in their name * * If node is provided, it will be the parent node of the tree to explore, * search string can be added to search parameters * * If node and searchString are not provided, this method will * return an empty list. * * You take the ownership of the returned value. * * This function allows to cancel the processing at any time by passing a MegaCancelToken and calling * to MegaCancelToken::setCancelFlag(true). If a valid object is passed, it must be kept alive until * this method returns. * * @param node The parent node of the tree to explore * @param searchString Search string. The search is case-insensitive * @param cancelToken MegaCancelToken to be able to cancel the processing at any time. * @param recursive True if you want to seach recursively in the node tree. * False if you want to seach in the children of the node only * * @return List of nodes that match with the search parameters */ public ArrayList<MegaNode> searchByType(MegaNode node, String searchString, @NotNull MegaCancelToken cancelToken, boolean recursive) { return nodeListToArray(megaApi.searchByType(node, searchString, cancelToken, recursive)); } /** * Allow to search nodes with the following options: * - Search given a parent node of the tree to explore * - Containing a search string in their name * * If node is provided, it will be the parent node of the tree to explore, * search string can be added to search parameters * * If node and searchString are not provided, this method will * return an empty list. * * You take the ownership of the returned value. * * This function allows to cancel the processing at any time by passing a MegaCancelToken and calling * to MegaCancelToken::setCancelFlag(true). If a valid object is passed, it must be kept alive until * this method returns. * * @param node The parent node of the tree to explore * @param searchString Search string. The search is case-insensitive * @param cancelToken MegaCancelToken to be able to cancel the processing at any time. * * @return List of nodes that match with the search parameters */ public ArrayList<MegaNode> searchByType(MegaNode node, String searchString, @NotNull MegaCancelToken cancelToken) { return nodeListToArray(megaApi.searchByType(node, searchString, cancelToken)); } /** * Return a list of buckets, each bucket containing a list of recently added/modified nodes * * Each bucket contains files that were added/modified in a set, by a single user. * * @param days Age of actions since added/modified nodes will be considered (in days) * @param maxnodes Maximum amount of nodes to be considered * * @return List of buckets containing nodes that were added/modifed as a set */ public ArrayList<MegaRecentActionBucket> getRecentActions (long days, long maxnodes) { return recentActionsToArray(megaApi.getRecentActions(days, maxnodes)); } /** * Return a list of buckets, each bucket containing a list of recently added/modified nodes * * Each bucket contains files that were added/modified in a set, by a single user. * * This function uses the default parameters for the MEGA apps, which consider (currently) * interactions during the last 90 days and max 10.000 nodes. * * @return List of buckets containing nodes that were added/modifed as a set */ public ArrayList<MegaRecentActionBucket> getRecentActions () { return recentActionsToArray(megaApi.getRecentActions()); } /** * Process a node tree using a MegaTreeProcessor implementation. * * @param parent * The parent node of the tree to explore. * @param processor * MegaTreeProcessor that will receive callbacks for every node in the tree. * @param recursive * true if you want to recursively process the whole node tree. * false if you want to process the children of the node only. * * @return true if all nodes were processed. false otherwise (the operation can be * cancelled by MegaTreeProcessor.processMegaNode()). */ public boolean processMegaTree(MegaNode parent, MegaTreeProcessorInterface processor, boolean recursive) { DelegateMegaTreeProcessor delegateListener = new DelegateMegaTreeProcessor(this, processor); activeMegaTreeProcessors.add(delegateListener); boolean result = megaApi.processMegaTree(parent, delegateListener, recursive); activeMegaTreeProcessors.remove(delegateListener); return result; } /** * Process a node tree using a MegaTreeProcessor implementation. * * @param parent * The parent node of the tree to explore. * @param processor * MegaTreeProcessor that will receive callbacks for every node in the tree. * * @return true if all nodes were processed. false otherwise (the operation can be * cancelled by MegaTreeProcessor.processMegaNode()). */ public boolean processMegaTree(MegaNode parent, MegaTreeProcessorInterface processor) { DelegateMegaTreeProcessor delegateListener = new DelegateMegaTreeProcessor(this, processor); activeMegaTreeProcessors.add(delegateListener); boolean result = megaApi.processMegaTree(parent, delegateListener); activeMegaTreeProcessors.remove(delegateListener); return result; } /** * Returns a MegaNode that can be downloaded with any instance of MegaApi * * This function only allows to authorize file nodes. * * You can use MegaApi::startDownload with the resulting node with any instance * of MegaApi, even if it's logged into another account, a public folder, or not * logged in. * * If the first parameter is a public node or an already authorized node, this * function returns a copy of the node, because it can be already downloaded * with any MegaApi instance. * * If the node in the first parameter belongs to the account or public folder * in which the current MegaApi object is logged in, this funtion returns an * authorized node. * * If the first parameter is NULL or a node that is not a public node, is not * already authorized and doesn't belong to the current MegaApi, this function * returns NULL. * * You take the ownership of the returned value. * * @param node MegaNode to authorize * @return Authorized node, or NULL if the node can't be authorized or is not a file */ public MegaNode authorizeNode(MegaNode node){ return megaApi.authorizeNode(node); } /** * * Returns a MegaNode that can be downloaded/copied with a chat-authorization * * During preview of chat-links, you need to call this method to authorize the MegaNode * from a node-attachment message, so the API allows to access to it. The parameter to * authorize the access can be retrieved from MegaChatRoom::getAuthorizationToken when * the chatroom in in preview mode. * * You can use MegaApi::startDownload and/or MegaApi::copyNode with the resulting * node with any instance of MegaApi, even if it's logged into another account, * a public folder, or not logged in. * * You take the ownership of the returned value. * * @param node MegaNode to authorize * @param cauth Authorization token (public handle of the chatroom in B64url encoding) * @return Authorized node, or NULL if the node can't be authorized */ public MegaNode authorizeChatNode(MegaNode node, String cauth){ return megaApi.authorizeChatNode(node, cauth); } /** * Get the SDK version. * * @return SDK version. */ public String getVersion() { return megaApi.getVersion(); } /** * Get the User-Agent header used by the SDK. * * @return User-Agent used by the SDK. */ public String getUserAgent() { return megaApi.getUserAgent(); } /** * Changes the API URL. * * @param apiURL The API URL to change. * @param disablepkp boolean. Disable public key pinning if true. Do not disable public key pinning if false. */ public void changeApiUrl(String apiURL, boolean disablepkp) { megaApi.changeApiUrl(apiURL, disablepkp); } /** * Changes the API URL. * <p> * Please note, this method does not disable public key pinning. * * @param apiURL The API URL to change. */ public void changeApiUrl(String apiURL) { megaApi.changeApiUrl(apiURL); } /** * Set the language code used by the app * @param languageCode code used by the app * * @return True if the language code is known for the SDK, otherwise false */ public boolean setLanguage(String languageCode){ return megaApi.setLanguage(languageCode); } /** * Set the preferred language of the user * * Valid data in the MegaRequest object received in onRequestFinish: * - MegaRequest::getText - Return the language code * * If the language code is unknown for the SDK, the error code will be MegaError::API_ENOENT * * This attribute is automatically created by the server. Apps only need * to set the new value when the user changes the language. * * @param Language code to be set * @param listener MegaRequestListener to track this request */ public void setLanguagePreference(String languageCode, MegaRequestListenerInterface listener){ megaApi.setLanguagePreference(languageCode, createDelegateRequestListener(listener)); } /** * Get the preferred language of the user * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Return the language code * * @param listener MegaRequestListener to track this request */ public void getLanguagePreference(MegaRequestListenerInterface listener){ megaApi.getLanguagePreference(createDelegateRequestListener(listener)); } /** * Enable or disable file versioning * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the value MegaApi::USER_ATTR_DISABLE_VERSIONS * * Valid data in the MegaRequest object received in onRequestFinish: * - MegaRequest::getText - "1" for disable, "0" for enable * * @param disable True to disable file versioning. False to enable it * @param listener MegaRequestListener to track this request */ public void setFileVersionsOption(boolean disable, MegaRequestListenerInterface listener){ megaApi.setFileVersionsOption(disable, createDelegateRequestListener(listener)); } /** * Enable or disable the automatic approval of incoming contact requests using a contact link * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the value MegaApi::USER_ATTR_CONTACT_LINK_VERIFICATION * * Valid data in the MegaRequest object received in onRequestFinish: * - MegaRequest::getText - "0" for disable, "1" for enable * * @param disable True to disable the automatic approval of incoming contact requests using a contact link * @param listener MegaRequestListener to track this request */ public void setContactLinksOption(boolean disable, MegaRequestListenerInterface listener){ megaApi.setContactLinksOption(disable, createDelegateRequestListener(listener)); } /** * Check if file versioning is enabled or disabled * * If the option has never been set, the error code will be MegaError::API_ENOENT. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the value MegaApi::USER_ATTR_DISABLE_VERSIONS * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - "1" for disable, "0" for enable * - MegaRequest::getFlag - True if disabled, false if enabled * * @param listener MegaRequestListener to track this request */ public void getFileVersionsOption(MegaRequestListenerInterface listener){ megaApi.getFileVersionsOption(createDelegateRequestListener(listener)); } /** * Check if the automatic approval of incoming contact requests using contact links is enabled or disabled * * If the option has never been set, the error code will be MegaError::API_ENOENT. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the value MegaApi::USER_ATTR_CONTACT_LINK_VERIFICATION * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - "0" for disable, "1" for enable * - MegaRequest::getFlag - false if disabled, true if enabled * * @param listener MegaRequestListener to track this request */ public void getContactLinksOption(MegaRequestListenerInterface listener){ megaApi.getContactLinksOption(createDelegateRequestListener(listener)); } /** * Keep retrying when public key pinning fails * * By default, when the check of the MEGA public key fails, it causes an automatic * logout. Pass false to this function to disable that automatic logout and * keep the SDK retrying the request. * * Even if the automatic logout is disabled, a request of the type MegaRequest::TYPE_LOGOUT * will be automatically created and callbacks (onRequestStart, onRequestFinish) will * be sent. However, logout won't be really executed and in onRequestFinish the error code * for the request will be MegaError::API_EINCOMPLETE * * @param enable true to keep retrying failed requests due to a fail checking the MEGA public key * or false to perform an automatic logout in that case */ public void retrySSLerrors(boolean enable) { megaApi.retrySSLerrors(enable); } /** * Enable / disable the public key pinning * * Public key pinning is enabled by default for all sensible communications. * It is strongly discouraged to disable this feature. * * @param enable true to keep public key pinning enabled, false to disable it */ public void setPublicKeyPinning(boolean enable) { megaApi.setPublicKeyPinning(enable); } /** * Make a name suitable for a file name in the local filesystem * * This function escapes (%xx) forbidden characters in the local filesystem if needed. * You can revert this operation using MegaApi::unescapeFsIncompatible * * If no dstPath is provided or filesystem type it's not supported this method will * escape characters contained in the following list: \/:?\"<>|* * Otherwise it will check forbidden characters for local filesystem type * * The input string must be UTF8 encoded. The returned value will be UTF8 too. * * You take the ownership of the returned value * * @param filename Name to convert (UTF8) * @param dstPath Destination path * @return Converted name (UTF8) */ public String escapeFsIncompatible(String filename, String dstPath) { return megaApi.escapeFsIncompatible(filename, dstPath); } /** * Unescape a file name escaped with MegaApi::escapeFsIncompatible * * If no localPath is provided or filesystem type it's not supported, this method will * unescape those sequences that once has been unescaped results in any character * of the following list: \/:?\"<>|* * Otherwise it will unescape those characters forbidden in local filesystem type * * The input string must be UTF8 encoded. The returned value will be UTF8 too. * You take the ownership of the returned value * * @param name Escaped name to convert (UTF8) * @param localPath Local path * @return Converted name (UTF8) */ String unescapeFsIncompatible(String name, String localPath) { return megaApi.unescapeFsIncompatible(name, localPath); } /** * Create a thumbnail for an image. * * @param imagePath Image path. * @param dstPath Destination path for the thumbnail (including the file name). * @return true if the thumbnail was successfully created, otherwise false. */ public boolean createThumbnail(String imagePath, String dstPath) { return megaApi.createThumbnail(imagePath, dstPath); } /** * Create a preview for an image. * * @param imagePath Image path. * @param dstPath Destination path for the preview (including the file name). * @return true if the preview was successfully created, otherwise false. */ public boolean createPreview(String imagePath, String dstPath) { return megaApi.createPreview(imagePath, dstPath); } /** * Convert a Base64 string to Base32. * <p> * If the input pointer is null, this function will return null. * If the input character array is not a valid base64 string * the effect is undefined. * * @param base64 * null-terminated Base64 character array. * @return null-terminated Base32 character array. */ public static String base64ToBase32(String base64) { return MegaApi.base64ToBase32(base64); } /** * Convert a Base32 string to Base64. * * If the input pointer is null, this function will return null. * If the input character array is not a valid base32 string * the effect is undefined. * * @param base32 * null-terminated Base32 character array. * @return null-terminated Base64 character array. */ public static String base32ToBase64(String base32) { return MegaApi.base32ToBase64(base32); } /** * Recursively remove all local files/folders inside a local path * @param path Local path of a folder to start the recursive deletion * The folder itself is not deleted */ public static void removeRecursively(String localPath) { MegaApi.removeRecursively(localPath); } /** * Check if the connection with MEGA servers is OK * * It can briefly return false even if the connection is good enough when * some storage servers are temporarily not available or the load of API * servers is high. * * @return true if the connection is perfectly OK, otherwise false */ public boolean isOnline() { return megaApi.isOnline(); } /** * Start an HTTP proxy server in specified port * * If this function returns true, that means that the server is * ready to accept connections. The initialization is synchronous. * * The server will serve files using this URL format: * http://127.0.0.1/<NodeHandle>/<NodeName> * * The node name must be URL encoded and must match with the node handle. * You can generate a correct link for a MegaNode using MegaApi::httpServerGetLocalLink * * If the node handle belongs to a folder node, a web with the list of files * inside the folder is returned. * * It's important to know that the HTTP proxy server has several configuration options * that can restrict the nodes that will be served and the connections that will be accepted. * * These are the default options: * - The restricted mode of the server is set to MegaApi::HTTP_SERVER_ALLOW_CREATED_LOCAL_LINKS * (see MegaApi::httpServerSetRestrictedMode) * * - Folder nodes are NOT allowed to be served (see MegaApi::httpServerEnableFolderServer) * - File nodes are allowed to be served (see MegaApi::httpServerEnableFileServer) * - Subtitles support is disabled (see MegaApi::httpServerEnableSubtitlesSupport) * * The HTTP server will only stream a node if it's allowed by all configuration options. * * @param localOnly true to listen on 127.0.0.1 only, false to listen on all network interfaces * @param port Port in which the server must accept connections * @return True is the server is ready, false if the initialization failed */ public boolean httpServerStart(boolean localOnly, int port) { return megaApi.httpServerStart(localOnly, port); } /** * Start an HTTP proxy server in specified port * * If this function returns true, that means that the server is * ready to accept connections. The initialization is synchronous. * * The server will serve files using this URL format: * http://127.0.0.1/<NodeHandle>/<NodeName> * * The node name must be URL encoded and must match with the node handle. * You can generate a correct link for a MegaNode using MegaApi::httpServerGetLocalLink * * If the node handle belongs to a folder node, a web with the list of files * inside the folder is returned. * * It's important to know that the HTTP proxy server has several configuration options * that can restrict the nodes that will be served and the connections that will be accepted. * * These are the default options: * - The restricted mode of the server is set to MegaApi::HTTP_SERVER_ALLOW_CREATED_LOCAL_LINKS * (see MegaApi::httpServerSetRestrictedMode) * * - Folder nodes are NOT allowed to be served (see MegaApi::httpServerEnableFolderServer) * - File nodes are allowed to be served (see MegaApi::httpServerEnableFileServer) * - Subtitles support is disabled (see MegaApi::httpServerEnableSubtitlesSupport) * * The HTTP server will only stream a node if it's allowed by all configuration options. * * @param localOnly true to listen on 127.0.0.1 only, false to listen on all network interfaces * @return True is the server is ready, false if the initialization failed */ public boolean httpServerStart(boolean localOnly) { return megaApi.httpServerStart(localOnly); } /** * Start an HTTP proxy server in specified port * * If this function returns true, that means that the server is * ready to accept connections. The initialization is synchronous. * * The server will serve files using this URL format: * http://127.0.0.1/<NodeHandle>/<NodeName> * * The node name must be URL encoded and must match with the node handle. * You can generate a correct link for a MegaNode using MegaApi::httpServerGetLocalLink * * If the node handle belongs to a folder node, a web with the list of files * inside the folder is returned. * * It's important to know that the HTTP proxy server has several configuration options * that can restrict the nodes that will be served and the connections that will be accepted. * * These are the default options: * - The restricted mode of the server is set to MegaApi::HTTP_SERVER_ALLOW_CREATED_LOCAL_LINKS * (see MegaApi::httpServerSetRestrictedMode) * * - Folder nodes are NOT allowed to be served (see MegaApi::httpServerEnableFolderServer) * - File nodes are allowed to be served (see MegaApi::httpServerEnableFileServer) * - Subtitles support is disabled (see MegaApi::httpServerEnableSubtitlesSupport) * * The HTTP server will only stream a node if it's allowed by all configuration options. * * @return True is the server is ready, false if the initialization failed */ public boolean httpServerStart() { return megaApi.httpServerStart(); } /** * Stop the HTTP proxy server * * When this function returns, the server is already shutdown. * If the HTTP proxy server isn't running, this functions does nothing */ public void httpServerStop(){ megaApi.httpServerStop(); } /** * Check if the HTTP proxy server is running * @return 0 if the server is not running. Otherwise the port in which it's listening to */ public int httpServerIsRunning(){ return megaApi.httpServerIsRunning(); } /** * Check if the HTTP proxy server is listening on all network interfaces * @return true if the HTTP proxy server is listening on 127.0.0.1 only, or it's not started. * If it's started and listening on all network interfaces, this function returns false */ public boolean httpServerIsLocalOnly() { return megaApi.httpServerIsLocalOnly(); } /** * Allow/forbid to serve files * * By default, files are served (when the server is running) * * Even if files are allowed to be served by this function, restrictions related to * other configuration options (MegaApi::httpServerSetRestrictedMode) are still applied. * * @param enable true to allow to server files, false to forbid it */ public void httpServerEnableFileServer(boolean enable) { megaApi.httpServerEnableFileServer(enable); } /** * Check if it's allowed to serve files * * This function can return true even if the HTTP proxy server is not running * * Even if files are allowed to be served by this function, restrictions related to * other configuration options (MegaApi::httpServerSetRestrictedMode) are still applied. * * @return true if it's allowed to serve files, otherwise false */ public boolean httpServerIsFileServerEnabled() { return megaApi.httpServerIsFileServerEnabled(); } /** * Allow/forbid to serve folders * * By default, folders are NOT served * * Even if folders are allowed to be served by this function, restrictions related to * other configuration options (MegaApi::httpServerSetRestrictedMode) are still applied. * * @param enable true to allow to server folders, false to forbid it */ public void httpServerEnableFolderServer(boolean enable) { megaApi.httpServerEnableFolderServer(enable); } /** * Check if it's allowed to serve folders * * This function can return true even if the HTTP proxy server is not running * * Even if folders are allowed to be served by this function, restrictions related to * other configuration options (MegaApi::httpServerSetRestrictedMode) are still applied. * * @return true if it's allowed to serve folders, otherwise false */ public boolean httpServerIsFolderServerEnabled() { return megaApi.httpServerIsFolderServerEnabled(); } /** * Enable/disable the restricted mode of the HTTP server * * This function allows to restrict the nodes that are allowed to be served. * For not allowed links, the server will return "407 Forbidden". * * Possible values are: * - HTTP_SERVER_DENY_ALL = -1 * All nodes are forbidden * * - HTTP_SERVER_ALLOW_ALL = 0 * All nodes are allowed to be served * * - HTTP_SERVER_ALLOW_CREATED_LOCAL_LINKS = 1 (default) * Only links created with MegaApi::httpServerGetLocalLink are allowed to be served * * - HTTP_SERVER_ALLOW_LAST_LOCAL_LINK = 2 * Only the last link created with MegaApi::httpServerGetLocalLink is allowed to be served * * If a different value from the list above is passed to this function, it won't have any effect and the previous * state of this option will be preserved. * * The default value of this property is MegaApi::HTTP_SERVER_ALLOW_CREATED_LOCAL_LINKS * * The state of this option is preserved even if the HTTP server is restarted, but the * the HTTP proxy server only remembers the generated links since the last call to * MegaApi::httpServerStart * * Even if nodes are allowed to be served by this function, restrictions related to * other configuration options (MegaApi::httpServerEnableFileServer, * MegaApi::httpServerEnableFolderServer) are still applied. * * @param mode Required state for the restricted mode of the HTTP proxy server */ public void httpServerSetRestrictedMode(int mode) { megaApi.httpServerSetRestrictedMode(mode); } /** * Check if the HTTP proxy server is working in restricted mode * * Possible return values are: * - HTTP_SERVER_DENY_ALL = -1 * All nodes are forbidden * * - HTTP_SERVER_ALLOW_ALL = 0 * All nodes are allowed to be served * * - HTTP_SERVER_ALLOW_CREATED_LOCAL_LINKS = 1 * Only links created with MegaApi::httpServerGetLocalLink are allowed to be served * * - HTTP_SERVER_ALLOW_LAST_LOCAL_LINK = 2 * Only the last link created with MegaApi::httpServerGetLocalLink is allowed to be served * * The default value of this property is MegaApi::HTTP_SERVER_ALLOW_CREATED_LOCAL_LINKS * * See MegaApi::httpServerEnableRestrictedMode and MegaApi::httpServerStart * * Even if nodes are allowed to be served by this function, restrictions related to * other configuration options (MegaApi::httpServerEnableFileServer, * MegaApi::httpServerEnableFolderServer) are still applied. * * @return State of the restricted mode of the HTTP proxy server */ public int httpServerGetRestrictedMode() { return megaApi.httpServerGetRestrictedMode(); } /** * Enable/disable the support for subtitles * * Subtitles support allows to stream some special links that otherwise wouldn't be valid. * For example, let's suppose that the server is streaming this video: * http://120.0.0.1:4443/<Base64Handle>/MyHolidays.avi * * Some media players scan HTTP servers looking for subtitle files and request links like these ones: * http://120.0.0.1:4443/<Base64Handle>/MyHolidays.txt * http://120.0.0.1:4443/<Base64Handle>/MyHolidays.srt * * Even if a file with that name is in the same folder of the MEGA account, the node wouldn't be served because * the node handle wouldn't match. * * When this feature is enabled, the HTTP proxy server will check if there are files with that name * in the same folder as the node corresponding to the handle in the link. * * If a matching file is found, the name is exactly the same as the the node with the specified handle * (except the extension), the node with that handle is allowed to be streamed and this feature is enabled * the HTTP proxy server will serve that file. * * This feature is disabled by default. * * @param enable True to enable subtitles support, false to disable it */ public void httpServerEnableSubtitlesSupport(boolean enable) { megaApi.httpServerEnableSubtitlesSupport(enable); } /** * Check if the support for subtitles is enabled * * See MegaApi::httpServerEnableSubtitlesSupport. * * This feature is disabled by default. * * @return true of the support for subtibles is enables, otherwise false */ public boolean httpServerIsSubtitlesSupportEnabled() { return megaApi.httpServerIsSubtitlesSupportEnabled(); } /** * Add a listener to receive information about the HTTP proxy server * * This is the valid data that will be provided on callbacks: * - MegaTransfer::getType - It will be MegaTransfer::TYPE_LOCAL_HTTP_DOWNLOAD * - MegaTransfer::getPath - URL requested to the HTTP proxy server * - MegaTransfer::getFileName - Name of the requested file (if any, otherwise NULL) * - MegaTransfer::getNodeHandle - Handle of the requested file (if any, otherwise NULL) * - MegaTransfer::getTotalBytes - Total bytes of the response (response headers + file, if required) * - MegaTransfer::getStartPos - Start position (for range requests only, otherwise -1) * - MegaTransfer::getEndPos - End position (for range requests only, otherwise -1) * * On the onTransferFinish error, the error code associated to the MegaError can be: * - MegaError::API_EINCOMPLETE - If the whole response wasn't sent * (it's normal to get this error code sometimes because media players close connections when they have * the data that they need) * * - MegaError::API_EREAD - If the connection with MEGA storage servers failed * - MegaError::API_EAGAIN - If the download speed is too slow for streaming * - A number > 0 means an HTTP error code returned to the client * * @param listener Listener to receive information about the HTTP proxy server */ public void httpServerAddListener(MegaTransferListenerInterface listener) { megaApi.httpServerAddListener(createDelegateHttpServerListener(listener, false)); } /** * Stop the reception of callbacks related to the HTTP proxy server on this listener * @param listener Listener that won't continue receiving information */ public void httpServerRemoveListener(MegaTransferListenerInterface listener) { ArrayList<DelegateMegaTransferListener> listenersToRemove = new ArrayList<DelegateMegaTransferListener>(); synchronized (activeHttpServerListeners) { Iterator<DelegateMegaTransferListener> it = activeHttpServerListeners.iterator(); while (it.hasNext()) { DelegateMegaTransferListener delegate = it.next(); if (delegate.getUserListener() == listener) { listenersToRemove.add(delegate); it.remove(); } } } for (int i=0;i<listenersToRemove.size();i++){ megaApi.httpServerRemoveListener(listenersToRemove.get(i)); } } /** * Returns a URL to a node in the local HTTP proxy server * * The HTTP proxy server must be running before using this function, otherwise * it will return NULL. * * You take the ownership of the returned value * * @param node Node to generate the local HTTP link * @return URL to the node in the local HTTP proxy server, otherwise NULL */ public String httpServerGetLocalLink(MegaNode node) { return megaApi.httpServerGetLocalLink(node); } /** * Set the maximum buffer size for the internal buffer * * The HTTP proxy server has an internal buffer to store the data received from MEGA * while it's being sent to clients. When the buffer is full, the connection with * the MEGA storage server is closed, when the buffer has few data, the connection * with the MEGA storage server is started again. * * Even with very fast connections, due to the possible latency starting new connections, * if this buffer is small the streaming can have problems due to the overhead caused by * the excessive number of POST requests. * * It's recommended to set this buffer at least to 1MB * * For connections that request less data than the buffer size, the HTTP proxy server * will only allocate the required memory to complete the request to minimize the * memory usage. * * The new value will be taken into account since the next request received by * the HTTP proxy server, not for ongoing requests. It's possible and effective * to call this function even before the server has been started, and the value * will be still active even if the server is stopped and started again. * * @param bufferSize Maximum buffer size (in bytes) or a number <= 0 to use the * internal default value */ public void httpServerSetMaxBufferSize(int bufferSize) { megaApi.httpServerSetMaxBufferSize(bufferSize); } /** * Get the maximum size of the internal buffer size * * See MegaApi::httpServerSetMaxBufferSize * * @return Maximum size of the internal buffer size (in bytes) */ public int httpServerGetMaxBufferSize() { return megaApi.httpServerGetMaxBufferSize(); } /** * Set the maximum size of packets sent to clients * * For each connection, the HTTP proxy server only sends one write to the underlying * socket at once. This parameter allows to set the size of that write. * * A small value could cause a lot of writes and would lower the performance. * * A big value could send too much data to the output buffer of the socket. That could * keep the internal buffer full of data that hasn't been sent to the client yet, * preventing the retrieval of additional data from the MEGA storage server. In that * circumstances, the client could read a lot of data at once and the HTTP server * could not have enough time to get more data fast enough. * * It's recommended to set this value to at least 8192 and no more than the 25% of * the maximum buffer size (MegaApi::httpServerSetMaxBufferSize). * * The new value will be takein into account since the next request received by * the HTTP proxy server, not for ongoing requests. It's possible and effective * to call this function even before the server has been started, and the value * will be still active even if the server is stopped and started again. * * @param outputSize Maximun size of data packets sent to clients (in bytes) or * a number <= 0 to use the internal default value */ public void httpServerSetMaxOutputSize(int outputSize) { megaApi.httpServerSetMaxOutputSize(outputSize); } /** * Get the maximum size of the packets sent to clients * * See MegaApi::httpServerSetMaxOutputSize * * @return Maximum size of the packets sent to clients (in bytes) */ public int httpServerGetMaxOutputSize() { return megaApi.httpServerGetMaxOutputSize(); } /** * Get the MIME type associated with the extension * * You take the ownership of the returned value * * @param extension File extension (with or without a leading dot) * @return MIME type associated with the extension */ public static String getMimeType(String extension) { return MegaApi.getMimeType(extension); } /** * Register a token for push notifications * * This function attach a token to the current session, which is intended to get push notifications * on mobile platforms like Android and iOS. * * The associated request type with this request is MegaRequest::TYPE_REGISTER_PUSH_NOTIFICATION * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getText - Returns the token provided. * - MegaRequest::getNumber - Returns the device type provided. * * @param deviceType Integer id for the provider. 1 for Android, 2 for iOS * @param token Character array representing the token to be registered. * @param listener MegaRequestListenerInterface to track this request */ public void registerPushNotifications(int deviceType, String token, MegaRequestListenerInterface listener) { megaApi.registerPushNotifications(deviceType, token, createDelegateRequestListener(listener)); } /** * Register a token for push notifications * * This function attach a token to the current session, which is intended to get push notifications * on mobile platforms like Android and iOS. * * @param deviceType Integer id for the provider. 1 for Android, 2 for iOS * @param token Character array representing the token to be registered. */ public void registerPushNotifications(int deviceType, String token) { megaApi.registerPushNotifications(deviceType, token); } /** * Get the MEGA Achievements of the account logged in * * The associated request type with this request is MegaRequest::TYPE_GET_ACHIEVEMENTS * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getFlag - Always false * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaAchievementsDetails - Details of the MEGA Achievements of this account * * @param listener MegaRequestListenerInterface to track this request */ public void getAccountAchievements(MegaRequestListenerInterface listener) { megaApi.getAccountAchievements(createDelegateRequestListener(listener)); } /** * Get the MEGA Achievements of the account logged in * * The associated request type with this request is MegaRequest::TYPE_GET_ACHIEVEMENTS * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getFlag - Always false * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaAchievementsDetails - Details of the MEGA Achievements of this account */ public void getAccountAchievements(){ megaApi.getAccountAchievements(); } /** * Get the list of existing MEGA Achievements * * Similar to MegaApi::getAccountAchievements, this method returns only the base storage and * the details for the different achievement classes, but not awards or rewards related to the * account that is logged in. * This function can be used to give an indication of what is available for advertising * for unregistered users, despite it can be used with a logged in account with no difference. * * @note: if the IP address is not achievement enabled (it belongs to a country where MEGA * Achievements are not enabled), the request will fail with MegaError::API_EACCESS. * * The associated request type with this request is MegaRequest::TYPE_GET_ACHIEVEMENTS * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getFlag - Always true * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaAchievementsDetails - Details of the list of existing MEGA Achievements * * @param listener MegaRequestListenerInterface to track this request */ public void getMegaAchievements(MegaRequestListenerInterface listener) { megaApi.getMegaAchievements(createDelegateRequestListener(listener)); } /** * Get the list of existing MEGA Achievements * * Similar to MegaApi::getAccountAchievements, this method returns only the base storage and * the details for the different achievement classes, but not awards or rewards related to the * account that is logged in. * This function can be used to give an indication of what is available for advertising * for unregistered users, despite it can be used with a logged in account with no difference. * * @note: if the IP address is not achievement enabled (it belongs to a country where MEGA * Achievements are not enabled), the request will fail with MegaError::API_EACCESS. * * The associated request type with this request is MegaRequest::TYPE_GET_ACHIEVEMENTS * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getFlag - Always true * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaAchievementsDetails - Details of the list of existing MEGA Achievements */ public void getMegaAchievements() { megaApi.getMegaAchievements(); } /** * Set original fingerprint for MegaNode * * @param node * @param fingerprint * @param listener */ public void setOriginalFingerprint(MegaNode node, String fingerprint, MegaRequestListenerInterface listener){ megaApi.setOriginalFingerprint(node,fingerprint,createDelegateRequestListener(listener)); } /** * Get MegaNode list by original fingerprint * * @param originalfingerprint * @param parent */ public MegaNodeList getNodesByOriginalFingerprint(String originalfingerprint, MegaNode parent){ return megaApi.getNodesByOriginalFingerprint(originalfingerprint, parent); } /** * @brief Retrieve basic information about a folder link * * This function retrieves basic information from a folder link, like the number of files / folders * and the name of the folder. For folder links containing a lot of files/folders, * this function is more efficient than a fetchnodes. * * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getLink() - Returns the public link to the folder * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaFolderInfo() - Returns information about the contents of the folder * - MegaRequest::getNodeHandle() - Returns the public handle of the folder * - MegaRequest::getParentHandle() - Returns the handle of the owner of the folder * - MegaRequest::getText() - Returns the name of the folder. * If there's no name, it returns the special status string "CRYPTO_ERROR". * If the length of the name is zero, it returns the special status string "BLANK". * * On the onRequestFinish error, the error code associated to the MegaError can be: * - MegaError::API_EARGS - If the link is not a valid folder link * - MegaError::API_EKEY - If the public link does not contain the key or it is invalid * * @param megaFolderLink Public link to a folder in MEGA * @param listener MegaRequestListener to track this request */ public void getPublicLinkInformation(String megaFolderLink, MegaRequestListenerInterface listener) { megaApi.getPublicLinkInformation(megaFolderLink, createDelegateRequestListener(listener)); } /** * @brief Retrieve basic information about a folder link * * This function retrieves basic information from a folder link, like the number of files / folders * and the name of the folder. For folder links containing a lot of files/folders, * this function is more efficient than a fetchnodes. * * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getLink() - Returns the public link to the folder * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaFolderInfo() - Returns information about the contents of the folder * - MegaRequest::getNodeHandle() - Returns the public handle of the folder * - MegaRequest::getParentHandle() - Returns the handle of the owner of the folder * - MegaRequest::getText() - Returns the name of the folder. * If there's no name, it returns the special status string "CRYPTO_ERROR". * If the length of the name is zero, it returns the special status string "BLANK". * * On the onRequestFinish error, the error code associated to the MegaError can be: * - MegaError::API_EARGS - If the link is not a valid folder link * - MegaError::API_EKEY - If the public link does not contain the key or it is invalid * * @param megaFolderLink Public link to a folder in MEGA */ public void getPublicLinkInformation(String megaFolderLink) { megaApi.getPublicLinkInformation(megaFolderLink); } /** * Call the low level function getrlimit() for NOFILE, needed for some platforms. * * @return The current limit for the number of open files (and sockets) for the app, or -1 if error. */ public int platformGetRLimitNumFile() { return megaApi.platformGetRLimitNumFile(); } /** * Call the low level function setrlimit() for NOFILE, needed for some platforms. * * Particularly on phones, the system default limit for the number of open files (and sockets) * is quite low. When the SDK can be working on many files and many sockets at once, * we need a higher limit. Those limits need to take into account the needs of the whole * app and not just the SDK, of course. This function is provided in order that the app * can make that call and set appropriate limits. * * @param newNumFileLimit The new limit of file and socket handles for the whole app. * * @return True when there were no errors setting the new limit (even when clipped to the maximum * allowed value). It returns false when setting a new limit failed. */ public boolean platformSetRLimitNumFile(int newNumFileLimit) { return megaApi.platformSetRLimitNumFile(newNumFileLimit); } /** * Requests a list of all Smart Banners available for current user. * * The response value is stored as a MegaBannerList. * * The associated request type with this request is MegaRequest::TYPE_GET_BANNERS * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaBannerList: the list of banners * * On the onRequestFinish error, the error code associated to the MegaError can be: * - MegaError::API_EACCESS - If called with no user being logged in. * - MegaError::API_EINTERNAL - If the internally used user attribute exists but can't be decoded. * - MegaError::API_ENOENT if there are no banners to return to the user. * * @param listener MegaRequestListener to track this request */ public void getBanners(MegaRequestListenerInterface listener) { megaApi.getBanners(createDelegateRequestListener(listener)); } /** * Requests a list of all Smart Banners available for current user. * * The response value is stored as a MegaBannerList. * * The associated request type with this request is MegaRequest::TYPE_GET_BANNERS * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaBannerList: the list of banners * * On the onRequestFinish error, the error code associated to the MegaError can be: * - MegaError::API_EACCESS - If called with no user being logged in. * - MegaError::API_EINTERNAL - If the internally used user attribute exists but can't be decoded. * - MegaError::API_ENOENT if there are no banners to return to the user. */ public void getBanners() { megaApi.getBanners(); } /** * No longer show the Smart Banner with the specified id to the current user. * * @param listener MegaRequestListener to track this request */ public void dismissBanner(int id, MegaRequestListenerInterface listener) { megaApi.dismissBanner(id, createDelegateRequestListener(listener)); } /** * No longer show the Smart Banner with the specified id to the current user. */ public void dismissBanner(int id) { megaApi.dismissBanner(id); } /****************************************************************************************************/ // INTERNAL METHODS /****************************************************************************************************/ private MegaRequestListener createDelegateRequestListener(MegaRequestListenerInterface listener) { DelegateMegaRequestListener delegateListener = new DelegateMegaRequestListener(this, listener, true); activeRequestListeners.add(delegateListener); return delegateListener; } private MegaRequestListener createDelegateRequestListener(MegaRequestListenerInterface listener, boolean singleListener) { DelegateMegaRequestListener delegateListener = new DelegateMegaRequestListener(this, listener, singleListener); activeRequestListeners.add(delegateListener); return delegateListener; } private MegaTransferListener createDelegateTransferListener(MegaTransferListenerInterface listener) { DelegateMegaTransferListener delegateListener = new DelegateMegaTransferListener(this, listener, true); activeTransferListeners.add(delegateListener); return delegateListener; } private MegaTransferListener createDelegateTransferListener(MegaTransferListenerInterface listener, boolean singleListener) { DelegateMegaTransferListener delegateListener = new DelegateMegaTransferListener(this, listener, singleListener); activeTransferListeners.add(delegateListener); return delegateListener; } private MegaGlobalListener createDelegateGlobalListener(MegaGlobalListenerInterface listener) { DelegateMegaGlobalListener delegateListener = new DelegateMegaGlobalListener(this, listener); activeGlobalListeners.add(delegateListener); return delegateListener; } private MegaListener createDelegateMegaListener(MegaListenerInterface listener) { DelegateMegaListener delegateListener = new DelegateMegaListener(this, listener); activeMegaListeners.add(delegateListener); return delegateListener; } private static MegaLogger createDelegateMegaLogger(MegaLoggerInterface listener){ DelegateMegaLogger delegateLogger = new DelegateMegaLogger(listener); activeMegaLoggers.add(delegateLogger); return delegateLogger; } private MegaTransferListener createDelegateHttpServerListener(MegaTransferListenerInterface listener) { DelegateMegaTransferListener delegateListener = new DelegateMegaTransferListener(this, listener, true); activeHttpServerListeners.add(delegateListener); return delegateListener; } private MegaTransferListener createDelegateHttpServerListener(MegaTransferListenerInterface listener, boolean singleListener) { DelegateMegaTransferListener delegateListener = new DelegateMegaTransferListener(this, listener, singleListener); activeHttpServerListeners.add(delegateListener); return delegateListener; } void privateFreeRequestListener(DelegateMegaRequestListener listener) { activeRequestListeners.remove(listener); } void privateFreeTransferListener(DelegateMegaTransferListener listener) { activeTransferListeners.remove(listener); } static public ArrayList<MegaNode> nodeListToArray(MegaNodeList nodeList) { if (nodeList == null) { return null; } ArrayList<MegaNode> result = new ArrayList<MegaNode>(nodeList.size()); for (int i = 0; i < nodeList.size(); i++) { result.add(nodeList.get(i).copy()); } return result; } static ArrayList<MegaShare> shareListToArray(MegaShareList shareList) { if (shareList == null) { return null; } ArrayList<MegaShare> result = new ArrayList<MegaShare>(shareList.size()); for (int i = 0; i < shareList.size(); i++) { result.add(shareList.get(i).copy()); } return result; } static ArrayList<MegaContactRequest> contactRequestListToArray(MegaContactRequestList contactRequestList) { if (contactRequestList == null) { return null; } ArrayList<MegaContactRequest> result = new ArrayList<MegaContactRequest>(contactRequestList.size()); for(int i=0; i<contactRequestList.size(); i++) { result.add(contactRequestList.get(i).copy()); } return result; } static ArrayList<MegaTransfer> transferListToArray(MegaTransferList transferList) { if (transferList == null) { return null; } ArrayList<MegaTransfer> result = new ArrayList<MegaTransfer>(transferList.size()); for (int i = 0; i < transferList.size(); i++) { result.add(transferList.get(i).copy()); } return result; } static ArrayList<MegaUser> userListToArray(MegaUserList userList) { if (userList == null) { return null; } ArrayList<MegaUser> result = new ArrayList<MegaUser>(userList.size()); for (int i = 0; i < userList.size(); i++) { result.add(userList.get(i).copy()); } return result; } static ArrayList<MegaUserAlert> userAlertListToArray(MegaUserAlertList userAlertList){ if (userAlertList == null){ return null; } ArrayList<MegaUserAlert> result = new ArrayList<MegaUserAlert>(userAlertList.size()); for (int i = 0; i < userAlertList.size(); i++){ result.add(userAlertList.get(i).copy()); } return result; } static ArrayList<MegaRecentActionBucket> recentActionsToArray(MegaRecentActionBucketList recentActionList) { if (recentActionList == null) { return null; } ArrayList<MegaRecentActionBucket> result = new ArrayList<>(recentActionList.size()); for (int i = 0; i< recentActionList.size(); i++) { result.add(recentActionList.get(i).copy()); } return result; } /** * Returns whether notifications about a chat have to be generated. * * @param chatid MegaHandle that identifies the chat room. * @return true if notification has to be created. */ public boolean isChatNotifiable(long chatid) { return megaApi.isChatNotifiable(chatid); } /** * Provide a phone number to get verification code. * * @param phoneNumber the phone number to receive the txt with verification code. * @param listener callback of this request. */ public void sendSMSVerificationCode(String phoneNumber,nz.mega.sdk.MegaRequestListenerInterface listener) { megaApi.sendSMSVerificationCode(phoneNumber,createDelegateRequestListener(listener)); } public void sendSMSVerificationCode(String phoneNumber,nz.mega.sdk.MegaRequestListenerInterface listener,boolean reverifying_whitelisted) { megaApi.sendSMSVerificationCode(phoneNumber,createDelegateRequestListener(listener),reverifying_whitelisted); } /** * Send the verification code to verifiy phone number. * * @param verificationCode received 6 digits verification code. * @param listener callback of this request. */ public void checkSMSVerificationCode(String verificationCode,nz.mega.sdk.MegaRequestListenerInterface listener) { megaApi.checkSMSVerificationCode(verificationCode,createDelegateRequestListener(listener)); } /** * Get the verified phone number of the mega account. * * @return verified phone number. */ public String smsVerifiedPhoneNumber() { return megaApi.smsVerifiedPhoneNumber(); } /** * Requests the contacts that are registered at MEGA (currently verified through SMS) * * @param contacts The map of contacts to get registered contacts from * @param listener MegaRequestListener to track this request */ public void getRegisteredContacts(MegaStringMap contacts, nz.mega.sdk.MegaRequestListenerInterface listener) { megaApi.getRegisteredContacts(contacts, createDelegateRequestListener(listener)); } /** * Requests the currently available country calling codes * * @param listener MegaRequestListener to track this request */ public void getCountryCallingCodes(nz.mega.sdk.MegaRequestListenerInterface listener) { megaApi.getCountryCallingCodes(createDelegateRequestListener(listener)); } /** * Get the state to see whether blocked account could do SMS verification * * @return the state */ public int smsAllowedState() { return megaApi.smsAllowedState(); } /** * Returns the email of the user who made the changes * * The SDK retains the ownership of the returned value. It will be valid until * the MegaRecentActionBucket object is deleted. * * @return The associated user's email */ public void getUserEmail(long handle, nz.mega.sdk.MegaRequestListenerInterface listener) { megaApi.getUserEmail(handle, createDelegateRequestListener(listener)); } /** * Resume a registration process for an Ephemeral++ account * * When a user begins the account registration process by calling * MegaApi::createEphemeralAccountPlusPlus an ephemeral++ account is created. * * Until the user successfully confirms the signup link sent to the provided email address, * you can resume the ephemeral session in order to change the email address, resend the * signup link (@see MegaApi::sendSignupLink) and also to receive notifications in case the * user confirms the account using another client (MegaGlobalListener::onAccountUpdate or * MegaListener::onAccountUpdate). It is also possible to cancel the registration process by * MegaApi::cancelCreateAccount, which invalidates the signup link associated to the ephemeral * session (the session will be still valid). * * The associated request type with this request is MegaRequest::TYPE_CREATE_ACCOUNT. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getSessionKey - Returns the session id to resume the process * - MegaRequest::getParamType - Returns the value MegaApi::RESUME_EPLUSPLUS_ACCOUNT * * In case the account is already confirmed, the associated request will fail with * error MegaError::API_EARGS. * * @param sid Session id valid for the ephemeral++ account (@see MegaApi::createEphemeralAccountPlusPlus) * @param listener MegaRequestListener to track this request */ public void resumeCreateAccountEphemeralPlusPlus(String sid, MegaRequestListenerInterface listener) { megaApi.resumeCreateAccountEphemeralPlusPlus(sid, createDelegateRequestListener(listener)); } /** * Cancel a registration process * * If a signup link has been generated during registration process, call this function * to invalidate it. The ephemeral session will not be invalidated, only the signup link. * * The associated request type with this request is MegaRequest::TYPE_CREATE_ACCOUNT. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the value MegaApi::CANCEL_ACCOUNT * * @param listener MegaRequestListener to track this request */ public void cancelCreateAccount(MegaRequestListenerInterface listener){ megaApi.cancelCreateAccount(createDelegateRequestListener(listener)); } /** * @brief Registers a backup to display in Backup Centre * * Apps should register backups, like CameraUploads, in order to be listed in the * BackupCentre. The client should send heartbeats to indicate the progress of the * backup (see \c MegaApi::sendBackupHeartbeats). * * Possible types of backups: * BACKUP_TYPE_CAMERA_UPLOADS = 3, * BACKUP_TYPE_MEDIA_UPLOADS = 4, // Android has a secondary CU * * Note that the backup name is not registered in the API as part of the data of this * backup. It will be stored in a user's attribute after this request finished. For * more information, see \c MegaApi::setBackupName and MegaApi::getBackupName. * * The associated request type with this request is MegaRequest::TYPE_BACKUP_PUT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParentHandle - Returns the backupId * - MegaRequest::getNodeHandle - Returns the target node of the backup * - MegaRequest::getName - Returns the backup name of the remote location * - MegaRequest::getAccess - Returns the backup state * - MegaRequest::getFile - Returns the path of the local folder * - MegaRequest::getTotalBytes - Returns the backup type * - MegaRequest::getNumDetails - Returns the backup substate * - MegaRequest::getFlag - Returns true * - MegaRequest::getListener - Returns the MegaRequestListener to track this request * * @param backupType back up type requested for the service * @param targetNode MEGA folder to hold the backups * @param localFolder Local path of the folder * @param backupName Name of the backup * @param state state * @param subState subState * @param listener MegaRequestListener to track this request */ public void setBackup(int backupType, long targetNode, String localFolder, String backupName, int state, int subState, MegaRequestListenerInterface listener) { megaApi.setBackup(backupType, targetNode, localFolder, backupName, state, subState, createDelegateRequestListener(listener)); } /** * @brief Update the information about a registered backup for Backup Centre * * Possible types of backups: * BACKUP_TYPE_INVALID = -1, * BACKUP_TYPE_CAMERA_UPLOADS = 3, * BACKUP_TYPE_MEDIA_UPLOADS = 4, // Android has a secondary CU * * Params that keep the same value are passed with invalid value to avoid to send to the server * Invalid values: * - type: BACKUP_TYPE_INVALID * - nodeHandle: UNDEF * - localFolder: nullptr * - deviceId: nullptr * - state: -1 * - subState: -1 * - extraData: nullptr * * If you want to update the backup name, use \c MegaApi::setBackupName. * * The associated request type with this request is MegaRequest::TYPE_BACKUP_PUT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParentHandle - Returns the backupId * - MegaRequest::getTotalBytes - Returns the backup type * - MegaRequest::getNodeHandle - Returns the target node of the backup * - MegaRequest::getFile - Returns the path of the local folder * - MegaRequest::getAccess - Returns the backup state * - MegaRequest::getNumDetails - Returns the backup substate * - MegaRequest::getListener - Returns the MegaRequestListener to track this request * * @param backupId backup id identifying the backup to be updated * @param backupType back up type requested for the service * @param targetNode MEGA folder to hold the backups * @param localFolder Local path of the folder * @param state backup state * @param subState backup subState * @param listener MegaRequestListener to track this request */ public void updateBackup(long backupId, int backupType, long targetNode, String localFolder, String backupName, int state, int subState, MegaRequestListenerInterface listener) { megaApi.updateBackup(backupId, backupType, targetNode, localFolder, backupName, state, subState, createDelegateRequestListener(listener)); } /** * @brief Unregister a backup already registered for the Backup Centre * * This method allows to remove a backup from the list of backups displayed in the * Backup Centre. @see \c MegaApi::setBackup. * * The associated request type with this request is MegaRequest::TYPE_BACKUP_REMOVE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParentHandle - Returns the backupId * - MegaRequest::getListener - Returns the MegaRequestListener to track this request * * @param backupId backup id identifying the backup to be removed * @param listener MegaRequestListener to track this request */ public void removeBackup(long backupId, MegaRequestListenerInterface listener) { megaApi.removeBackup(backupId, createDelegateRequestListener(listener)); } /** * @brief Send heartbeat associated with an existing backup * * The client should call this method regularly for every registered backup, in order to * inform about the status of the backup. * * Progress, last timestamp and last node are not always meaningful (ie. when the Camera * Uploads starts a new batch, there isn't a last node, or when the CU up to date and * inactive for long time, the progress doesn't make sense). In consequence, these parameters * are optional. They will not be sent to API if they take the following values: * - lastNode = INVALID_HANDLE * - lastTs = -1 * - progress = -1 * * The associated request type with this request is MegaRequest::TYPE_BACKUP_PUT_HEART_BEAT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParentHandle - Returns the backupId * - MegaRequest::getAccess - Returns the backup state * - MegaRequest::getNumDetails - Returns the backup substate * - MegaRequest::getParamType - Returns the number of pending upload transfers * - MegaRequest::getTransferTag - Returns the number of pending download transfers * - MegaRequest::getNumber - Returns the last action timestamp * - MegaRequest::getNodeHandle - Returns the last node handle to be synced * * @param backupId backup id identifying the backup * @param state backup state * @param progress backup progress * @param ups Number of pending upload transfers * @param downs Number of pending download transfers * @param ts Last action timestamp * @param lastNode Last node handle to be synced * @param listener MegaRequestListener to track this request */ public void sendBackupHeartbeat(long backupId, int status, int progress, int ups, int downs, long ts, long lastNode, MegaRequestListenerInterface listener) { megaApi.sendBackupHeartbeat(backupId, status, progress, ups, downs, ts, lastNode, createDelegateRequestListener(listener)); } /** * @brief Fetch Google ads * * The associated request type with this request is MegaRequest::TYPE_FETCH_GOOGLE_ADS * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNumber A bitmap flag used to communicate with the API * - MegaRequest::getMegaStringList List of the adslot ids to fetch * - MegaRequest::getNodeHandle Public handle that the user is visiting * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaStringMap: map with relationship between ids and ius * * @param adFlags A bitmap flag used to communicate with the API * Valid values are: * - GOOGLE_ADS_DEFAULT = 0x0 * - GOOGLE_ADS_FORCE_ADS = 0x200 * - GOOGLE_ADS_IGNORE_MEGA = 0x400 * - GOOGLE_ADS_IGNORE_COUNTRY = 0x800 * - GOOGLE_ADS_IGNORE_IP = 0x1000 * - GOOGLE_ADS_IGNORE_PRO = 0x2000 * - GOOGLE_ADS_FLAG_IGNORE_ROLLOUT = 0x4000 * @param adUnits A list of the adslot ids to fetch * @param publicHandle Provide the public handle that the user is visiting * @param listener MegaRequestListener to track this request */ public void fetchGoogleAds(int adFlags, MegaStringList adUnits, long publicHandle, MegaRequestListenerInterface listener) { megaApi.fetchGoogleAds(adFlags, adUnits, publicHandle, createDelegateRequestListener(listener)); } /** * @brief Fetch Google ads * * The associated request type with this request is MegaRequest::TYPE_FETCH_GOOGLE_ADS * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNumber A bitmap flag used to communicate with the API * - MegaRequest::getMegaStringList List of the adslot ids to fetch * - MegaRequest::getNodeHandle Public handle that the user is visiting * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaStringMap: map with relationship between ids and ius * * @param adFlags A bitmap flag used to communicate with the API * Valid values are: * - GOOGLE_ADS_DEFAULT = 0x0 * - GOOGLE_ADS_FORCE_ADS = 0x200 * - GOOGLE_ADS_IGNORE_MEGA = 0x400 * - GOOGLE_ADS_IGNORE_COUNTRY = 0x800 * - GOOGLE_ADS_IGNORE_IP = 0x1000 * - GOOGLE_ADS_IGNORE_PRO = 0x2000 * - GOOGLE_ADS_FLAG_IGNORE_ROLLOUT = 0x4000 * @param adUnits A list of the adslot ids to fetch * @param publicHandle Provide the public handle that the user is visiting */ public void fetchGoogleAds(int adFlags, MegaStringList adUnits, long publicHandle) { megaApi.fetchGoogleAds(adFlags, adUnits, publicHandle); } /** * @brief Fetch Google ads * * The associated request type with this request is MegaRequest::TYPE_FETCH_GOOGLE_ADS * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNumber A bitmap flag used to communicate with the API * - MegaRequest::getMegaStringList List of the adslot ids to fetch * - MegaRequest::getNodeHandle Public handle that the user is visiting * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaStringMap: map with relationship between ids and ius * * @param adFlags A bitmap flag used to communicate with the API * Valid values are: * - GOOGLE_ADS_DEFAULT = 0x0 * - GOOGLE_ADS_FORCE_ADS = 0x200 * - GOOGLE_ADS_IGNORE_MEGA = 0x400 * - GOOGLE_ADS_IGNORE_COUNTRY = 0x800 * - GOOGLE_ADS_IGNORE_IP = 0x1000 * - GOOGLE_ADS_IGNORE_PRO = 0x2000 * - GOOGLE_ADS_FLAG_IGNORE_ROLLOUT = 0x4000 * @param adUnits A list of the adslot ids to fetch */ public void fetchGoogleAds(int adFlags, MegaStringList adUnits) { megaApi.fetchGoogleAds(adFlags, adUnits); } /** * @brief Check if Google ads should show or not * * The associated request type with this request is MegaRequest::TYPE_QUERY_GOOGLE_ADS * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNumber A bitmap flag used to communicate with the API * - MegaRequest::getNodeHandle Public handle that the user is visiting * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNumDetails Return if ads should be show or not * * @param adFlags A bitmap flag used to communicate with the API * Valid values are: * - GOOGLE_ADS_DEFAULT = 0x0 * - GOOGLE_ADS_FORCE_ADS = 0x200 * - GOOGLE_ADS_IGNORE_MEGA = 0x400 * - GOOGLE_ADS_IGNORE_COUNTRY = 0x800 * - GOOGLE_ADS_IGNORE_IP = 0x1000 * - GOOGLE_ADS_IGNORE_PRO = 0x2000 * - GOOGLE_ADS_FLAG_IGNORE_ROLLOUT 0x4000 * @param publicHandle Provide the public handle that the user is visiting * @param listener MegaRequestListener to track this request */ public void queryGoogleAds(int adFlags, long publicHandle, MegaRequestListenerInterface listener) { megaApi.queryGoogleAds(adFlags, publicHandle, createDelegateRequestListener(listener)); } /** * @brief Check if Google ads should show or not * * The associated request type with this request is MegaRequest::TYPE_QUERY_GOOGLE_ADS * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNumber A bitmap flag used to communicate with the API * - MegaRequest::getNodeHandle Public handle that the user is visiting * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNumDetails Return if ads should be show or not * * @param adFlags A bitmap flag used to communicate with the API * Valid values are: * - GOOGLE_ADS_DEFAULT = 0x0 * - GOOGLE_ADS_FORCE_ADS = 0x200 * - GOOGLE_ADS_IGNORE_MEGA = 0x400 * - GOOGLE_ADS_IGNORE_COUNTRY = 0x800 * - GOOGLE_ADS_IGNORE_IP = 0x1000 * - GOOGLE_ADS_IGNORE_PRO = 0x2000 * - GOOGLE_ADS_FLAG_IGNORE_ROLLOUT 0x4000 * @param publicHandle Provide the public handle that the user is visiting */ public void queryGoogleAds(int adFlags, long publicHandle) { megaApi.queryGoogleAds(adFlags, publicHandle); } /** * @brief Check if Google ads should show or not * * The associated request type with this request is MegaRequest::TYPE_QUERY_GOOGLE_ADS * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNumber A bitmap flag used to communicate with the API * - MegaRequest::getNodeHandle Public handle that the user is visiting * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNumDetails Return if ads should be show or not * * @param adFlags A bitmap flag used to communicate with the API * Valid values are: * - GOOGLE_ADS_DEFAULT = 0x0 * - GOOGLE_ADS_FORCE_ADS = 0x200 * - GOOGLE_ADS_IGNORE_MEGA = 0x400 * - GOOGLE_ADS_IGNORE_COUNTRY = 0x800 * - GOOGLE_ADS_IGNORE_IP = 0x1000 * - GOOGLE_ADS_IGNORE_PRO = 0x2000 * - GOOGLE_ADS_FLAG_IGNORE_ROLLOUT 0x4000 */ public void queryGoogleAds(int adFlags) { megaApi.queryGoogleAds(adFlags); } /** * @brief Set a bitmap to indicate whether some cookies are enabled or not * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_COOKIE_SETTINGS * - MegaRequest::getNumDetails - Return a bitmap with cookie settings * - MegaRequest::getListener - Returns the MegaRequestListener to track this request * * @param settings A bitmap with cookie settings * Valid bits are: * - Bit 0: essential * - Bit 1: preference * - Bit 2: analytics * - Bit 3: ads * - Bit 4: thirdparty * @param listener MegaRequestListener to track this request */ public void setCookieSettings(int settings, MegaRequestListenerInterface listener) { megaApi.setCookieSettings(settings, createDelegateRequestListener(listener)); } /** * @brief Set a bitmap to indicate whether some cookies are enabled or not * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_COOKIE_SETTINGS * - MegaRequest::getNumDetails - Return a bitmap with cookie settings * - MegaRequest::getListener - Returns the MegaRequestListener to track this request * * @param settings A bitmap with cookie settings * Valid bits are: * - Bit 0: essential * - Bit 1: preference * - Bit 2: analytics * - Bit 3: ads * - Bit 4: thirdparty */ public void setCookieSettings(int settings) { megaApi.setCookieSettings(settings); } /** * @brief Get a bitmap to indicate whether some cookies are enabled or not * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the value USER_ATTR_COOKIE_SETTINGS * - MegaRequest::getListener - Returns the MegaRequestListener to track this request * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNumDetails Return the bitmap with cookie settings * Valid bits are: * - Bit 0: essential * - Bit 1: preference * - Bit 2: analytics * - Bit 3: ads * - Bit 4: thirdparty * * On the onRequestFinish error, the error code associated to the MegaError can be: * - MegaError::API_EINTERNAL - If the value for cookie settings bitmap was invalid * * @param listener MegaRequestListener to track this request */ public void getCookieSettings(MegaRequestListenerInterface listener) { megaApi.getCookieSettings(createDelegateRequestListener(listener)); } /** * @brief Get a bitmap to indicate whether some cookies are enabled or not * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the value USER_ATTR_COOKIE_SETTINGS * - MegaRequest::getListener - Returns the MegaRequestListener to track this request * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNumDetails Return the bitmap with cookie settings * Valid bits are: * - Bit 0: essential * - Bit 1: preference * - Bit 2: analytics * - Bit 3: ads * - Bit 4: thirdparty * * On the onRequestFinish error, the error code associated to the MegaError can be: * - MegaError::API_EINTERNAL - If the value for cookie settings bitmap was invalid */ public void getCookieSettings() { megaApi.getCookieSettings(); } /** * @brief Check if the app can start showing the cookie banner * * This function will NOT return a valid value until the callback onEvent with * type MegaApi::EVENT_MISC_FLAGS_READY is received. You can also rely on the completion of * a fetchnodes to check this value, but only when it follows a login with user and password, * not when an existing session is resumed. * * For not logged-in mode, you need to call MegaApi::getMiscFlags first. * * @return True if this feature is enabled. Otherwise, false. */ public boolean isCookieBannerEnabled() { return megaApi.cookieBannerEnabled(); } /** * @brief Set My Backups folder. * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_MY_BACKUPS_FOLDER * - MegaRequest::getFlag - Returns false * - MegaRequest::getNodehandle - Returns the provided node handle * - MegaRequest::getMegaStringMap - Returns a MegaStringMap. * The key "h" in the map contains the nodehandle specified as parameter encoded in B64 * * If the folder is not private to the current account, or is in Rubbish, or is in a synced folder, * the request will fail with the error code MegaError::API_EACCESS. * * @param handle MegaHandle of the node to be used as target folder * @param listener MegaRequestListener to track this request */ public void setMyBackupsFolder(long handle, MegaRequestListenerInterface listener) { megaApi.setMyBackupsFolder(handle, createDelegateRequestListener(listener)); } /** * @brief Set My Backups folder. * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_MY_BACKUPS_FOLDER * - MegaRequest::getFlag - Returns false * - MegaRequest::getNodehandle - Returns the provided node handle * - MegaRequest::getMegaStringMap - Returns a MegaStringMap. * The key "h" in the map contains the nodehandle specified as parameter encoded in B64 * * If the folder is not private to the current account, or is in Rubbish, or is in a synced folder, * the request will fail with the error code MegaError::API_EACCESS. * * @param handle MegaHandle of the node to be used as target folder */ public void setMyBackupsFolder(long handle) { megaApi.setMyBackupsFolder(handle); } /** * @brief Gets My Backups target folder. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_MY_BACKUPS_FOLDER * - MegaRequest::getFlag - Returns false * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodehandle - Returns the handle of the node where My Backups files are stored * * If the folder was not set, the request will fail with the error code MegaError::API_ENOENT. * * @param listener MegaRequestListener to track this request */ public void getMyBackupsFolder(MegaRequestListenerInterface listener) { megaApi.getMyBackupsFolder(createDelegateRequestListener(listener)); } /** * @brief Gets My Backups target folder. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_MY_BACKUPS_FOLDER * - MegaRequest::getFlag - Returns false * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodehandle - Returns the handle of the node where My Backups files are stored * * If the folder was not set, the request will fail with the error code MegaError::API_ENOENT. */ public void getMyBackupsFolder() { megaApi.getMyBackupsFolder(); } /** * @brief Get a list of favourite nodes. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_NODE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node provided * - MegaRequest::getParamType - Returns MegaApi::NODE_ATTR_FAV * - MegaRequest::getNumDetails - Returns the count requested * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaHandleList - List of handles of favourite nodes * * @param node Node and its children that will be searched for favourites. Search all nodes if null * @param count if count is zero return all favourite nodes, otherwise return only 'count' favourite nodes * @param listener MegaRequestListener to track this request */ public void getFavourites(MegaNode node, int count, MegaRequestListenerInterface listener) { megaApi.getFavourites(node, count, createDelegateRequestListener(listener)); } }
bindings/java/nz/mega/sdk/MegaApiJava.java
/* * (c) 2013-2015 by Mega Limited, Auckland, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK is distributed in the hope that it will be useful,\ * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * @copyright Simplified (2-clause) BSD License. * You should have received a copy of the license along with this * program. */ package nz.mega.sdk; import org.jetbrains.annotations.NotNull; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; /** * Java Application Programming Interface (API) to access MEGA SDK services on a MEGA account or shared public folder. * <p> * An appKey must be specified to use the MEGA SDK. Generate an appKey for free here: <br> * - https://mega.co.nz/#sdk * <p> * Save on data usage and start up time by enabling local node caching. This can be enabled by passing a local path * in the constructor. Local node caching prevents the need to download the entire file system each time the MegaApiJava * object is logged in. * <p> * To take advantage of local node caching, the application needs to save the session key after login * (MegaApiJava.dumpSession()) and use it to login during the next session. A persistent local node cache will only be * loaded if logging in with a session key. * Local node caching is also recommended in order to enhance security as it prevents the account password from being * stored by the application. * <p> * To access MEGA services using the MEGA SDK, an object of this class (MegaApiJava) needs to be created and one of the * MegaApiJava.login() options used to log into a MEGA account or a public folder. If the login request succeeds, * call MegaApiJava.fetchNodes() to get the account's file system from MEGA. Once the file system is retrieved, all other * requests including file management and transfers can be used. * <p> * After using MegaApiJava.logout() you can reuse the same MegaApi object to log in to another MEGA account or a public * folder. */ public class MegaApiJava { MegaApi megaApi; MegaGfxProcessor gfxProcessor; void runCallback(Runnable runnable) { runnable.run(); } static Set<DelegateMegaRequestListener> activeRequestListeners = Collections.synchronizedSet(new LinkedHashSet<DelegateMegaRequestListener>()); static Set<DelegateMegaTransferListener> activeTransferListeners = Collections.synchronizedSet(new LinkedHashSet<DelegateMegaTransferListener>()); static Set<DelegateMegaGlobalListener> activeGlobalListeners = Collections.synchronizedSet(new LinkedHashSet<DelegateMegaGlobalListener>()); static Set<DelegateMegaListener> activeMegaListeners = Collections.synchronizedSet(new LinkedHashSet<DelegateMegaListener>()); static Set<DelegateMegaLogger> activeMegaLoggers = Collections.synchronizedSet(new LinkedHashSet<DelegateMegaLogger>()); static Set<DelegateMegaTreeProcessor> activeMegaTreeProcessors = Collections.synchronizedSet(new LinkedHashSet<DelegateMegaTreeProcessor>()); static Set<DelegateMegaTransferListener> activeHttpServerListeners = Collections.synchronizedSet(new LinkedHashSet<DelegateMegaTransferListener>()); /** * INVALID_HANDLE Invalid value for a handle * * This value is used to represent an invalid handle. Several MEGA objects can have * a handle but it will never be INVALID_HANDLE. */ public final static long INVALID_HANDLE = ~(long)0; // Very severe error event that will presumably lead the application to abort. public final static int LOG_LEVEL_FATAL = MegaApi.LOG_LEVEL_FATAL; // Error information but application will continue run. public final static int LOG_LEVEL_ERROR = MegaApi.LOG_LEVEL_ERROR; // Information representing errors in application but application will keep running public final static int LOG_LEVEL_WARNING = MegaApi.LOG_LEVEL_WARNING; // Mainly useful to represent current progress of application. public final static int LOG_LEVEL_INFO = MegaApi.LOG_LEVEL_INFO; // Informational logs, that are useful for developers. Only applicable if DEBUG is defined. public final static int LOG_LEVEL_DEBUG = MegaApi.LOG_LEVEL_DEBUG; public final static int LOG_LEVEL_MAX = MegaApi.LOG_LEVEL_MAX; public final static int ATTR_TYPE_THUMBNAIL = MegaApi.ATTR_TYPE_THUMBNAIL; public final static int ATTR_TYPE_PREVIEW = MegaApi.ATTR_TYPE_PREVIEW; public final static int USER_ATTR_AVATAR = MegaApi.USER_ATTR_AVATAR; public final static int USER_ATTR_FIRSTNAME = MegaApi.USER_ATTR_FIRSTNAME; public final static int USER_ATTR_LASTNAME = MegaApi.USER_ATTR_LASTNAME; public final static int USER_ATTR_AUTHRING = MegaApi.USER_ATTR_AUTHRING; public final static int USER_ATTR_LAST_INTERACTION = MegaApi.USER_ATTR_LAST_INTERACTION; public final static int USER_ATTR_ED25519_PUBLIC_KEY = MegaApi.USER_ATTR_ED25519_PUBLIC_KEY; public final static int USER_ATTR_CU25519_PUBLIC_KEY = MegaApi.USER_ATTR_CU25519_PUBLIC_KEY; public final static int USER_ATTR_KEYRING = MegaApi.USER_ATTR_KEYRING; public final static int USER_ATTR_SIG_RSA_PUBLIC_KEY = MegaApi.USER_ATTR_SIG_RSA_PUBLIC_KEY; public final static int USER_ATTR_SIG_CU255_PUBLIC_KEY = MegaApi.USER_ATTR_SIG_CU255_PUBLIC_KEY; public final static int USER_ATTR_LANGUAGE = MegaApi.USER_ATTR_LANGUAGE; public final static int USER_ATTR_PWD_REMINDER = MegaApi.USER_ATTR_PWD_REMINDER; public final static int USER_ATTR_DISABLE_VERSIONS = MegaApi.USER_ATTR_DISABLE_VERSIONS; public final static int USER_ATTR_CONTACT_LINK_VERIFICATION = MegaApi.USER_ATTR_CONTACT_LINK_VERIFICATION; public final static int USER_ATTR_RICH_PREVIEWS = MegaApi.USER_ATTR_RICH_PREVIEWS; public final static int USER_ATTR_RUBBISH_TIME = MegaApi.USER_ATTR_RUBBISH_TIME; public final static int USER_ATTR_LAST_PSA = MegaApi.USER_ATTR_LAST_PSA; public final static int USER_ATTR_STORAGE_STATE = MegaApi.USER_ATTR_STORAGE_STATE; public final static int USER_ATTR_GEOLOCATION = MegaApi.USER_ATTR_GEOLOCATION; public final static int USER_ATTR_CAMERA_UPLOADS_FOLDER = MegaApi.USER_ATTR_CAMERA_UPLOADS_FOLDER; public final static int USER_ATTR_MY_CHAT_FILES_FOLDER = MegaApi.USER_ATTR_MY_CHAT_FILES_FOLDER; public final static int USER_ATTR_PUSH_SETTINGS = MegaApi.USER_ATTR_PUSH_SETTINGS; public final static int USER_ATTR_ALIAS = MegaApi.USER_ATTR_ALIAS; public final static int USER_ATTR_DEVICE_NAMES = MegaApi.USER_ATTR_DEVICE_NAMES; public final static int USER_ATTR_MY_BACKUPS_FOLDER = MegaApi.USER_ATTR_MY_BACKUPS_FOLDER; // deprecated: public final static int USER_ATTR_BACKUP_NAMES = MegaApi.USER_ATTR_BACKUP_NAMES; public final static int USER_ATTR_COOKIE_SETTINGS = MegaApi.USER_ATTR_COOKIE_SETTINGS; public final static int NODE_ATTR_DURATION = MegaApi.NODE_ATTR_DURATION; public final static int NODE_ATTR_COORDINATES = MegaApi.NODE_ATTR_COORDINATES; public final static int NODE_ATTR_LABEL = MegaApi.NODE_ATTR_LABEL; public final static int NODE_ATTR_FAV = MegaApi.NODE_ATTR_FAV; public final static int PAYMENT_METHOD_BALANCE = MegaApi.PAYMENT_METHOD_BALANCE; public final static int PAYMENT_METHOD_PAYPAL = MegaApi.PAYMENT_METHOD_PAYPAL; public final static int PAYMENT_METHOD_ITUNES = MegaApi.PAYMENT_METHOD_ITUNES; public final static int PAYMENT_METHOD_GOOGLE_WALLET = MegaApi.PAYMENT_METHOD_GOOGLE_WALLET; public final static int PAYMENT_METHOD_BITCOIN = MegaApi.PAYMENT_METHOD_BITCOIN; public final static int PAYMENT_METHOD_UNIONPAY = MegaApi.PAYMENT_METHOD_UNIONPAY; public final static int PAYMENT_METHOD_FORTUMO = MegaApi.PAYMENT_METHOD_FORTUMO; public final static int PAYMENT_METHOD_STRIPE = MegaApi.PAYMENT_METHOD_STRIPE; public final static int PAYMENT_METHOD_CREDIT_CARD = MegaApi.PAYMENT_METHOD_CREDIT_CARD; public final static int PAYMENT_METHOD_CENTILI = MegaApi.PAYMENT_METHOD_CENTILI; public final static int PAYMENT_METHOD_PAYSAFE_CARD = MegaApi.PAYMENT_METHOD_PAYSAFE_CARD; public final static int PAYMENT_METHOD_ASTROPAY = MegaApi.PAYMENT_METHOD_ASTROPAY; public final static int PAYMENT_METHOD_RESERVED = MegaApi.PAYMENT_METHOD_RESERVED; public final static int PAYMENT_METHOD_WINDOWS_STORE = MegaApi.PAYMENT_METHOD_WINDOWS_STORE; public final static int PAYMENT_METHOD_TPAY = MegaApi.PAYMENT_METHOD_TPAY; public final static int PAYMENT_METHOD_DIRECT_RESELLER = MegaApi.PAYMENT_METHOD_DIRECT_RESELLER; public final static int PAYMENT_METHOD_ECP = MegaApi.PAYMENT_METHOD_ECP; public final static int PAYMENT_METHOD_SABADELL = MegaApi.PAYMENT_METHOD_SABADELL; public final static int PAYMENT_METHOD_HUAWEI_WALLET = MegaApi.PAYMENT_METHOD_HUAWEI_WALLET; public final static int PAYMENT_METHOD_STRIPE2 = MegaApi.PAYMENT_METHOD_STRIPE2; public final static int PAYMENT_METHOD_WIRE_TRANSFER = MegaApi.PAYMENT_METHOD_WIRE_TRANSFER; public final static int TRANSFER_METHOD_NORMAL = MegaApi.TRANSFER_METHOD_NORMAL; public final static int TRANSFER_METHOD_ALTERNATIVE_PORT = MegaApi.TRANSFER_METHOD_ALTERNATIVE_PORT; public final static int TRANSFER_METHOD_AUTO = MegaApi.TRANSFER_METHOD_AUTO; public final static int TRANSFER_METHOD_AUTO_NORMAL = MegaApi.TRANSFER_METHOD_AUTO_NORMAL; public final static int TRANSFER_METHOD_AUTO_ALTERNATIVE = MegaApi.TRANSFER_METHOD_AUTO_ALTERNATIVE; public final static int PUSH_NOTIFICATION_ANDROID = MegaApi.PUSH_NOTIFICATION_ANDROID; public final static int PUSH_NOTIFICATION_IOS_VOIP = MegaApi.PUSH_NOTIFICATION_IOS_VOIP; public final static int PUSH_NOTIFICATION_IOS_STD = MegaApi.PUSH_NOTIFICATION_IOS_STD; public final static int PASSWORD_STRENGTH_VERYWEAK = MegaApi.PASSWORD_STRENGTH_VERYWEAK; public final static int PASSWORD_STRENGTH_WEAK = MegaApi.PASSWORD_STRENGTH_WEAK; public final static int PASSWORD_STRENGTH_MEDIUM = MegaApi.PASSWORD_STRENGTH_MEDIUM; public final static int PASSWORD_STRENGTH_GOOD = MegaApi.PASSWORD_STRENGTH_GOOD; public final static int PASSWORD_STRENGTH_STRONG = MegaApi.PASSWORD_STRENGTH_STRONG; public final static int RETRY_NONE = MegaApi.RETRY_NONE; public final static int RETRY_CONNECTIVITY = MegaApi.RETRY_CONNECTIVITY; public final static int RETRY_SERVERS_BUSY = MegaApi.RETRY_SERVERS_BUSY; public final static int RETRY_API_LOCK = MegaApi.RETRY_API_LOCK; public final static int RETRY_RATE_LIMIT = MegaApi.RETRY_RATE_LIMIT; public final static int RETRY_LOCAL_LOCK = MegaApi.RETRY_LOCAL_LOCK; public final static int RETRY_UNKNOWN = MegaApi.RETRY_UNKNOWN; public final static int KEEP_ALIVE_CAMERA_UPLOADS = MegaApi.KEEP_ALIVE_CAMERA_UPLOADS; public final static int STORAGE_STATE_UNKNOWN = MegaApi.STORAGE_STATE_UNKNOWN; public final static int STORAGE_STATE_GREEN = MegaApi.STORAGE_STATE_GREEN; public final static int STORAGE_STATE_ORANGE = MegaApi.STORAGE_STATE_ORANGE; public final static int STORAGE_STATE_RED = MegaApi.STORAGE_STATE_RED; public final static int STORAGE_STATE_CHANGE = MegaApi.STORAGE_STATE_CHANGE; public final static int STORAGE_STATE_PAYWALL = MegaApi.STORAGE_STATE_PAYWALL; public final static int BUSINESS_STATUS_EXPIRED = MegaApi.BUSINESS_STATUS_EXPIRED; public final static int BUSINESS_STATUS_INACTIVE = MegaApi.BUSINESS_STATUS_INACTIVE; public final static int BUSINESS_STATUS_ACTIVE = MegaApi.BUSINESS_STATUS_ACTIVE; public final static int BUSINESS_STATUS_GRACE_PERIOD = MegaApi.BUSINESS_STATUS_GRACE_PERIOD; public final static int AFFILIATE_TYPE_INVALID = MegaApi.AFFILIATE_TYPE_INVALID; public final static int AFFILIATE_TYPE_ID = MegaApi.AFFILIATE_TYPE_ID; public final static int AFFILIATE_TYPE_FILE_FOLDER = MegaApi.AFFILIATE_TYPE_FILE_FOLDER; public final static int AFFILIATE_TYPE_CHAT = MegaApi.AFFILIATE_TYPE_CHAT; public final static int AFFILIATE_TYPE_CONTACT = MegaApi.AFFILIATE_TYPE_CONTACT; public final static int CREATE_ACCOUNT = MegaApi.CREATE_ACCOUNT; public final static int RESUME_ACCOUNT = MegaApi.RESUME_ACCOUNT; public final static int CANCEL_ACCOUNT = MegaApi.CANCEL_ACCOUNT; public final static int CREATE_EPLUSPLUS_ACCOUNT = MegaApi.CREATE_EPLUSPLUS_ACCOUNT; public final static int RESUME_EPLUSPLUS_ACCOUNT = MegaApi.RESUME_EPLUSPLUS_ACCOUNT; public final static int ORDER_NONE = MegaApi.ORDER_NONE; public final static int ORDER_DEFAULT_ASC = MegaApi.ORDER_DEFAULT_ASC; public final static int ORDER_DEFAULT_DESC = MegaApi.ORDER_DEFAULT_DESC; public final static int ORDER_SIZE_ASC = MegaApi.ORDER_SIZE_ASC; public final static int ORDER_SIZE_DESC = MegaApi.ORDER_SIZE_DESC; public final static int ORDER_CREATION_ASC = MegaApi.ORDER_CREATION_ASC; public final static int ORDER_CREATION_DESC = MegaApi.ORDER_CREATION_DESC; public final static int ORDER_MODIFICATION_ASC = MegaApi.ORDER_MODIFICATION_ASC; public final static int ORDER_MODIFICATION_DESC = MegaApi.ORDER_MODIFICATION_DESC; public final static int ORDER_ALPHABETICAL_ASC = MegaApi.ORDER_ALPHABETICAL_ASC; public final static int ORDER_ALPHABETICAL_DESC = MegaApi.ORDER_ALPHABETICAL_DESC; public final static int ORDER_PHOTO_ASC = MegaApi.ORDER_PHOTO_ASC; public final static int ORDER_PHOTO_DESC = MegaApi.ORDER_PHOTO_DESC; public final static int ORDER_VIDEO_ASC = MegaApi.ORDER_VIDEO_ASC; public final static int ORDER_VIDEO_DESC = MegaApi.ORDER_VIDEO_DESC; public final static int ORDER_LINK_CREATION_ASC = MegaApi.ORDER_LINK_CREATION_ASC; public final static int ORDER_LINK_CREATION_DESC = MegaApi.ORDER_LINK_CREATION_DESC; public final static int ORDER_LABEL_ASC = MegaApi.ORDER_LABEL_ASC; public final static int ORDER_LABEL_DESC = MegaApi.ORDER_LABEL_DESC; public final static int ORDER_FAV_ASC = MegaApi.ORDER_FAV_ASC; public final static int ORDER_FAV_DESC = MegaApi.ORDER_FAV_DESC; public final static int TCP_SERVER_DENY_ALL = MegaApi.TCP_SERVER_DENY_ALL; public final static int TCP_SERVER_ALLOW_ALL = MegaApi.TCP_SERVER_ALLOW_ALL; public final static int TCP_SERVER_ALLOW_CREATED_LOCAL_LINKS = MegaApi.TCP_SERVER_ALLOW_CREATED_LOCAL_LINKS; public final static int TCP_SERVER_ALLOW_LAST_LOCAL_LINK = MegaApi.TCP_SERVER_ALLOW_LAST_LOCAL_LINK; public final static int HTTP_SERVER_DENY_ALL = MegaApi.HTTP_SERVER_DENY_ALL; public final static int HTTP_SERVER_ALLOW_ALL = MegaApi.HTTP_SERVER_ALLOW_ALL; public final static int HTTP_SERVER_ALLOW_CREATED_LOCAL_LINKS = MegaApi.HTTP_SERVER_ALLOW_CREATED_LOCAL_LINKS; public final static int HTTP_SERVER_ALLOW_LAST_LOCAL_LINK = MegaApi.HTTP_SERVER_ALLOW_LAST_LOCAL_LINK; public final static int FILE_TYPE_DEFAULT = MegaApi.FILE_TYPE_DEFAULT; public final static int FILE_TYPE_PHOTO = MegaApi.FILE_TYPE_PHOTO; public final static int FILE_TYPE_AUDIO = MegaApi.FILE_TYPE_AUDIO; public final static int FILE_TYPE_VIDEO = MegaApi.FILE_TYPE_VIDEO; public final static int FILE_TYPE_DOCUMENT = MegaApi.FILE_TYPE_DOCUMENT; public final static int SEARCH_TARGET_INSHARE = MegaApi.SEARCH_TARGET_INSHARE; public final static int SEARCH_TARGET_OUTSHARE = MegaApi.SEARCH_TARGET_OUTSHARE; public final static int SEARCH_TARGET_PUBLICLINK = MegaApi.SEARCH_TARGET_PUBLICLINK; public final static int SEARCH_TARGET_ROOTNODE = MegaApi.SEARCH_TARGET_ROOTNODE; public final static int SEARCH_TARGET_ALL = MegaApi.SEARCH_TARGET_ALL; public final static int BACKUP_TYPE_INVALID = MegaApi.BACKUP_TYPE_INVALID; public final static int BACKUP_TYPE_TWO_WAY_SYNC = MegaApi.BACKUP_TYPE_TWO_WAY_SYNC; public final static int BACKUP_TYPE_UP_SYNC = MegaApi.BACKUP_TYPE_UP_SYNC; public final static int BACKUP_TYPE_DOWN_SYNC = MegaApi.BACKUP_TYPE_DOWN_SYNC; public final static int BACKUP_TYPE_CAMERA_UPLOADS = MegaApi.BACKUP_TYPE_CAMERA_UPLOADS; public final static int BACKUP_TYPE_MEDIA_UPLOADS = MegaApi.BACKUP_TYPE_MEDIA_UPLOADS; public final static int GOOGLE_ADS_DEFAULT = MegaApi.GOOGLE_ADS_DEFAULT; public final static int GOOGLE_ADS_FORCE_ADS = MegaApi.GOOGLE_ADS_FORCE_ADS; public final static int GOOGLE_ADS_IGNORE_MEGA = MegaApi.GOOGLE_ADS_IGNORE_MEGA; public final static int GOOGLE_ADS_IGNORE_COUNTRY = MegaApi.GOOGLE_ADS_IGNORE_COUNTRY; public final static int GOOGLE_ADS_IGNORE_IP = MegaApi.GOOGLE_ADS_IGNORE_IP; public final static int GOOGLE_ADS_IGNORE_PRO = MegaApi.GOOGLE_ADS_IGNORE_PRO; public final static int GOOGLE_ADS_FLAG_IGNORE_ROLLOUT = MegaApi.GOOGLE_ADS_FLAG_IGNORE_ROLLOUT; MegaApi getMegaApi() { return megaApi; } /** * Constructor suitable for most applications. * * @param appKey * AppKey of your application. * Generate an AppKey for free here: https://mega.co.nz/#sdk * * @param basePath * Base path to store the local cache. * If you pass null to this parameter, the SDK won't use any local cache. */ public MegaApiJava(String appKey, String basePath) { megaApi = new MegaApi(appKey, basePath); } /** * MegaApi Constructor that allows use of a custom GFX processor. * <p> * The SDK attaches thumbnails and previews to all uploaded images. To generate them, it needs a graphics processor. * You can build the SDK with one of the provided built-in graphics processors. If none are available * in your app, you can implement the MegaGfxProcessor interface to provide a custom processor. Please * read the documentation of MegaGfxProcessor carefully to ensure that your implementation is valid. * * @param appKey * AppKey of your application. * Generate an AppKey for free here: https://mega.co.nz/#sdk * * @param userAgent * User agent to use in network requests. * If you pass null to this parameter, a default user agent will be used. * * @param basePath * Base path to store the local cache. * If you pass null to this parameter, the SDK won't use any local cache. * * @param gfxProcessor * Image processor. The SDK will use it to generate previews and thumbnails. * If you pass null to this parameter, the SDK will try to use the built-in image processors. * */ public MegaApiJava(String appKey, String userAgent, String basePath, MegaGfxProcessor gfxProcessor) { this.gfxProcessor = gfxProcessor; megaApi = new MegaApi(appKey, gfxProcessor, basePath, userAgent); } /** * Constructor suitable for most applications. * * @param appKey * AppKey of your application. * Generate an AppKey for free here: https://mega.co.nz/#sdk */ public MegaApiJava(String appKey) { megaApi = new MegaApi(appKey); } /****************************************************************************************************/ // LISTENER MANAGEMENT /****************************************************************************************************/ /** * Register a listener to receive all events (requests, transfers, global, synchronization). * <p> * You can use MegaApiJava.removeListener() to stop receiving events. * * @param listener * Listener that will receive all events (requests, transfers, global, synchronization). */ public void addListener(MegaListenerInterface listener) { megaApi.addListener(createDelegateMegaListener(listener)); } /** * Register a listener to receive all events about requests. * <p> * You can use MegaApiJava.removeRequestListener() to stop receiving events. * * @param listener * Listener that will receive all events about requests. */ public void addRequestListener(MegaRequestListenerInterface listener) { megaApi.addRequestListener(createDelegateRequestListener(listener, false)); } /** * Register a listener to receive all events about transfers. * <p> * You can use MegaApiJava.removeTransferListener() to stop receiving events. * * @param listener * Listener that will receive all events about transfers. */ public void addTransferListener(MegaTransferListenerInterface listener) { megaApi.addTransferListener(createDelegateTransferListener(listener, false)); } /** * Register a listener to receive global events. * <p> * You can use MegaApiJava.removeGlobalListener() to stop receiving events. * * @param listener * Listener that will receive global events. */ public void addGlobalListener(MegaGlobalListenerInterface listener) { megaApi.addGlobalListener(createDelegateGlobalListener(listener)); } /** * Unregister a listener. * <p> * Stop receiving events from the specified listener. * * @param listener * Object that is unregistered. */ public void removeListener(MegaListenerInterface listener) { ArrayList<DelegateMegaListener> listenersToRemove = new ArrayList<DelegateMegaListener>(); synchronized (activeMegaListeners) { Iterator<DelegateMegaListener> it = activeMegaListeners.iterator(); while (it.hasNext()) { DelegateMegaListener delegate = it.next(); if (delegate.getUserListener() == listener) { listenersToRemove.add(delegate); it.remove(); } } } for (int i=0;i<listenersToRemove.size();i++){ megaApi.removeListener(listenersToRemove.get(i)); } } /** * Unregister a MegaRequestListener. * <p> * Stop receiving events from the specified listener. * * @param listener * Object that is unregistered. */ public void removeRequestListener(MegaRequestListenerInterface listener) { ArrayList<DelegateMegaRequestListener> listenersToRemove = new ArrayList<DelegateMegaRequestListener>(); synchronized (activeRequestListeners) { Iterator<DelegateMegaRequestListener> it = activeRequestListeners.iterator(); while (it.hasNext()) { DelegateMegaRequestListener delegate = it.next(); if (delegate.getUserListener() == listener) { listenersToRemove.add(delegate); it.remove(); } } } for (int i=0;i<listenersToRemove.size();i++){ megaApi.removeRequestListener(listenersToRemove.get(i)); } } /** * Unregister a MegaTransferListener. * <p> * Stop receiving events from the specified listener. * * @param listener * Object that is unregistered. */ public void removeTransferListener(MegaTransferListenerInterface listener) { ArrayList<DelegateMegaTransferListener> listenersToRemove = new ArrayList<DelegateMegaTransferListener>(); synchronized (activeTransferListeners) { Iterator<DelegateMegaTransferListener> it = activeTransferListeners.iterator(); while (it.hasNext()) { DelegateMegaTransferListener delegate = it.next(); if (delegate.getUserListener() == listener) { listenersToRemove.add(delegate); it.remove(); } } } for (int i=0;i<listenersToRemove.size();i++){ megaApi.removeTransferListener(listenersToRemove.get(i)); } } /** * Unregister a MegaGlobalListener. * <p> * Stop receiving events from the specified listener. * * @param listener * Object that is unregistered. */ public void removeGlobalListener(MegaGlobalListenerInterface listener) { ArrayList<DelegateMegaGlobalListener> listenersToRemove = new ArrayList<DelegateMegaGlobalListener>(); synchronized (activeGlobalListeners) { Iterator<DelegateMegaGlobalListener> it = activeGlobalListeners.iterator(); while (it.hasNext()) { DelegateMegaGlobalListener delegate = it.next(); if (delegate.getUserListener() == listener) { listenersToRemove.add(delegate); it.remove(); } } } for (int i=0;i<listenersToRemove.size();i++){ megaApi.removeGlobalListener(listenersToRemove.get(i)); } } /****************************************************************************************************/ // UTILS /****************************************************************************************************/ /** * Get an URL to transfer the current session to the webclient * * This function creates a new session for the link so logging out in the web client won't log out * the current session. * * The associated request type with this request is MegaRequest::TYPE_GET_SESSION_TRANSFER_URL * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getLink - URL to open the desired page with the same account * * You take the ownership of the returned value. * * @param path Path inside https://mega.nz/# that we want to open with the current session * * For example, if you want to open https://mega.nz/#pro, the parameter of this function should be "pro". * * @param listener MegaRequestListener to track this request */ public void getSessionTransferURL(String path, MegaRequestListenerInterface listener){ megaApi.getSessionTransferURL(path, createDelegateRequestListener(listener)); } /** * Get an URL to transfer the current session to the webclient * * This function creates a new session for the link so logging out in the web client won't log out * the current session. * * The associated request type with this request is MegaRequest::TYPE_GET_SESSION_TRANSFER_URL * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getLink - URL to open the desired page with the same account * * You take the ownership of the returned value. * * @param path Path inside https://mega.nz/# that we want to open with the current session * * For example, if you want to open https://mega.nz/#pro, the parameter of this function should be "pro". */ public void getSessionTransferURL(String path){ megaApi.getSessionTransferURL(path); } /** * Converts a Base32-encoded user handle (JID) to a MegaHandle. * <p> * @param base32Handle * Base32-encoded handle (JID). * @return User handle. */ public static long base32ToHandle(String base32Handle) { return MegaApi.base32ToHandle(base32Handle); } /** * Converts a Base64-encoded node handle to a MegaHandle. * <p> * The returned value can be used to recover a MegaNode using MegaApiJava.getNodeByHandle(). * You can revert this operation using MegaApiJava.handleToBase64(). * * @param base64Handle * Base64-encoded node handle. * @return Node handle. */ public static long base64ToHandle(String base64Handle) { return MegaApi.base64ToHandle(base64Handle); } /** * Converts a Base64-encoded user handle to a MegaHandle * * You can revert this operation using MegaApi::userHandleToBase64 * * @param base64Handle Base64-encoded node handle * @return Node handle */ public static long base64ToUserHandle(String base64Handle){ return MegaApi.base64ToUserHandle(base64Handle); } /** * Converts a MegaHandle to a Base64-encoded string. * <p> * You can revert this operation using MegaApiJava.base64ToHandle(). * * @param handle * to be converted. * @return Base64-encoded node handle. */ public static String handleToBase64(long handle) { return MegaApi.handleToBase64(handle); } /** * Converts a MegaHandle to a Base64-encoded string. * <p> * You take the ownership of the returned value. * You can revert this operation using MegaApiJava.base64ToHandle(). * * @param handle * handle to be converted. * @return Base64-encoded user handle. */ public static String userHandleToBase64(long handle) { return MegaApi.userHandleToBase64(handle); } /** * Add entropy to internal random number generators. * <p> * It's recommended to call this function with random data to * enhance security. * * @param data * Byte array with random data. * @param size * Size of the byte array (in bytes). */ public void addEntropy(String data, long size) { megaApi.addEntropy(data, size); } /** * Reconnect and retry all transfers. */ public void reconnect() { megaApi.retryPendingConnections(true, true); } /** * Retry all pending requests. * <p> * When requests fails they wait some time before being retried. That delay grows exponentially if the request * fails again. For this reason, and since this request is very lightweight, it's recommended to call it with * the default parameters on every user interaction with the application. This will prevent very big delays * completing requests. */ public void retryPendingConnections() { megaApi.retryPendingConnections(); } /** * Check if server-side Rubbish Bin autopurging is enabled for the current account * * Before using this function, it's needed to: * - If you are logged-in: call to MegaApi::login and MegaApi::fetchNodes. * * @return True if this feature is enabled. Otherwise false. */ public boolean serverSideRubbishBinAutopurgeEnabled(){ return megaApi.serverSideRubbishBinAutopurgeEnabled(); } /** * Check if the new format for public links is enabled * * Before using this function, it's needed to: * - If you are logged-in: call to MegaApi::login and MegaApi::fetchNodes. * - If you are not logged-in: call to MegaApi::getMiscFlags. * * @return True if this feature is enabled. Otherwise, false. */ public boolean newLinkFormatEnabled() { return megaApi.newLinkFormatEnabled(); } /** * Check if multi-factor authentication can be enabled for the current account. * * Before using this function, it's needed to: * - If you are logged-in: call to MegaApi::login and MegaApi::fetchNodes. * - If you are not logged-in: call to MegaApi::getMiscFlags. * * @return True if multi-factor authentication can be enabled for the current account, otherwise false. */ public boolean multiFactorAuthAvailable () { return megaApi.multiFactorAuthAvailable(); } /** * Reset the verified phone number for the account logged in. * * The associated request type with this request is MegaRequest::TYPE_RESET_SMS_VERIFIED_NUMBER * If there's no verified phone number associated for the account logged in, the error code * provided in onRequestFinish is MegaError::API_ENOENT. * * @param listener MegaRequestListener to track this request */ public void resetSmsVerifiedPhoneNumber(MegaRequestListenerInterface listener) { megaApi.resetSmsVerifiedPhoneNumber(createDelegateRequestListener(listener)); } /** * Reset the verified phone number for the account logged in. * * The associated request type with this request is MegaRequest::TYPE_RESET_SMS_VERIFIED_NUMBER * If there's no verified phone number associated for the account logged in, the error code * provided in onRequestFinish is MegaError::API_ENOENT. */ public void resetSmsVerifiedPhoneNumber() { megaApi.resetSmsVerifiedPhoneNumber(); } /** * Check if multi-factor authentication is enabled for an account * * The associated request type with this request is MegaRequest::TYPE_MULTI_FACTOR_AUTH_CHECK * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getEmail - Returns the email sent in the first parameter * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getFlag - Returns true if multi-factor authentication is enabled or false if it's disabled. * * @param email Email to check * @param listener MegaRequestListener to track this request */ public void multiFactorAuthCheck(String email, MegaRequestListenerInterface listener){ megaApi.multiFactorAuthCheck(email, createDelegateRequestListener(listener)); } /** * Check if multi-factor authentication is enabled for an account * * The associated request type with this request is MegaRequest::TYPE_MULTI_FACTOR_AUTH_CHECK * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getEmail - Returns the email sent in the first parameter * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getFlag - Returns true if multi-factor authentication is enabled or false if it's disabled. * * @param email Email to check */ public void multiFactorAuthCheck(String email){ megaApi.multiFactorAuthCheck(email); } /** * Get the secret code of the account to enable multi-factor authentication * The MegaApi object must be logged into an account to successfully use this function. * * The associated request type with this request is MegaRequest::TYPE_MULTI_FACTOR_AUTH_GET * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Returns the Base32 secret code needed to configure multi-factor authentication. * * @param listener MegaRequestListener to track this request */ public void multiFactorAuthGetCode(MegaRequestListenerInterface listener){ megaApi.multiFactorAuthGetCode(createDelegateRequestListener(listener)); } /** * Get the secret code of the account to enable multi-factor authentication * The MegaApi object must be logged into an account to successfully use this function. * * The associated request type with this request is MegaRequest::TYPE_MULTI_FACTOR_AUTH_GET * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Returns the Base32 secret code needed to configure multi-factor authentication. */ public void multiFactorAuthGetCode(){ megaApi.multiFactorAuthGetCode(); } /** * Enable multi-factor authentication for the account * The MegaApi object must be logged into an account to successfully use this function. * * The associated request type with this request is MegaRequest::TYPE_MULTI_FACTOR_AUTH_SET * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getFlag - Returns true * - MegaRequest::getPassword - Returns the pin sent in the first parameter * * @param pin Valid pin code for multi-factor authentication * @param listener MegaRequestListener to track this request */ public void multiFactorAuthEnable(String pin, MegaRequestListenerInterface listener){ megaApi.multiFactorAuthEnable(pin, createDelegateRequestListener(listener)); } /** * Enable multi-factor authentication for the account * The MegaApi object must be logged into an account to successfully use this function. * * The associated request type with this request is MegaRequest::TYPE_MULTI_FACTOR_AUTH_SET * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getFlag - Returns true * - MegaRequest::getPassword - Returns the pin sent in the first parameter * * @param pin Valid pin code for multi-factor authentication */ public void multiFactorAuthEnable(String pin){ megaApi.multiFactorAuthEnable(pin); } /** * Disable multi-factor authentication for the account * The MegaApi object must be logged into an account to successfully use this function. * * The associated request type with this request is MegaRequest::TYPE_MULTI_FACTOR_AUTH_SET * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getFlag - Returns false * - MegaRequest::getPassword - Returns the pin sent in the first parameter * * @param pin Valid pin code for multi-factor authentication * @param listener MegaRequestListener to track this request */ public void multiFactorAuthDisable(String pin, MegaRequestListenerInterface listener){ megaApi.multiFactorAuthDisable(pin, createDelegateRequestListener(listener)); } /** * Disable multi-factor authentication for the account * The MegaApi object must be logged into an account to successfully use this function. * * The associated request type with this request is MegaRequest::TYPE_MULTI_FACTOR_AUTH_SET * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getFlag - Returns false * - MegaRequest::getPassword - Returns the pin sent in the first parameter * * @param pin Valid pin code for multi-factor authentication */ public void multiFactorAuthDisable(String pin){ megaApi.multiFactorAuthDisable(pin); } /** * Log in to a MEGA account with multi-factor authentication enabled * * The associated request type with this request is MegaRequest::TYPE_LOGIN. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getEmail - Returns the first parameter * - MegaRequest::getPassword - Returns the second parameter * - MegaRequest::getText - Returns the third parameter * * If the email/password aren't valid the error code provided in onRequestFinish is * MegaError::API_ENOENT. * * @param email Email of the user * @param password Password * @param pin Pin code for multi-factor authentication * @param listener MegaRequestListener to track this request */ public void multiFactorAuthLogin(String email, String password, String pin, MegaRequestListenerInterface listener){ megaApi.multiFactorAuthLogin(email, password, pin, createDelegateRequestListener(listener)); } /** * Log in to a MEGA account with multi-factor authentication enabled * * The associated request type with this request is MegaRequest::TYPE_LOGIN. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getEmail - Returns the first parameter * - MegaRequest::getPassword - Returns the second parameter * - MegaRequest::getText - Returns the third parameter * * If the email/password aren't valid the error code provided in onRequestFinish is * MegaError::API_ENOENT. * * @param email Email of the user * @param password Password * @param pin Pin code for multi-factor authentication */ public void multiFactorAuthLogin(String email, String password, String pin){ megaApi.multiFactorAuthLogin(email, password, pin); } /** * Change the password of a MEGA account with multi-factor authentication enabled * * The associated request type with this request is MegaRequest::TYPE_CHANGE_PW * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getPassword - Returns the old password (if it was passed as parameter) * - MegaRequest::getNewPassword - Returns the new password * - MegaRequest::getText - Returns the pin code for multi-factor authentication * * @param oldPassword Old password (optional, it can be NULL to not check the old password) * @param newPassword New password * @param pin Pin code for multi-factor authentication * @param listener MegaRequestListener to track this request */ public void multiFactorAuthChangePassword(String oldPassword, String newPassword, String pin, MegaRequestListenerInterface listener){ megaApi.multiFactorAuthChangePassword(oldPassword, newPassword, pin, createDelegateRequestListener(listener)); } /** * Change the password of a MEGA account with multi-factor authentication enabled * * The associated request type with this request is MegaRequest::TYPE_CHANGE_PW * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getPassword - Returns the old password (if it was passed as parameter) * - MegaRequest::getNewPassword - Returns the new password * - MegaRequest::getText - Returns the pin code for multi-factor authentication * * @param oldPassword Old password (optional, it can be NULL to not check the old password) * @param newPassword New password * @param pin Pin code for multi-factor authentication */ public void multiFactorAuthChangePassword(String oldPassword, String newPassword, String pin){ megaApi.multiFactorAuthChangePassword(oldPassword, newPassword, pin); } /** * Initialize the change of the email address associated to an account with multi-factor authentication enabled. * * The associated request type with this request is MegaRequest::TYPE_GET_CHANGE_EMAIL_LINK. * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getEmail - Returns the email for the account * - MegaRequest::getText - Returns the pin code for multi-factor authentication * * If this request succeeds, a change-email link will be sent to the specified email address. * If no user is logged in, you will get the error code MegaError::API_EACCESS in onRequestFinish(). * * If the MEGA account is a sub-user business account, onRequestFinish will * be called with the error code MegaError::API_EMASTERONLY. * * @param email The new email to be associated to the account. * @param pin Pin code for multi-factor authentication * @param listener MegaRequestListener to track this request */ public void multiFactorAuthChangeEmail(String email, String pin, MegaRequestListenerInterface listener){ megaApi.multiFactorAuthChangeEmail(email, pin, createDelegateRequestListener(listener)); } /** * Initialize the change of the email address associated to an account with multi-factor authentication enabled. * * The associated request type with this request is MegaRequest::TYPE_GET_CHANGE_EMAIL_LINK. * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getEmail - Returns the email for the account * - MegaRequest::getText - Returns the pin code for multi-factor authentication * * If this request succeeds, a change-email link will be sent to the specified email address. * If no user is logged in, you will get the error code MegaError::API_EACCESS in onRequestFinish(). * * If the MEGA account is a sub-user business account, onRequestFinish will * be called with the error code MegaError::API_EMASTERONLY. * * @param email The new email to be associated to the account. * @param pin Pin code for multi-factor authentication */ public void multiFactorAuthChangeEmail(String email, String pin){ megaApi.multiFactorAuthChangeEmail(email, pin); } /** * Initialize the cancellation of an account. * * The associated request type with this request is MegaRequest::TYPE_GET_CANCEL_LINK. * * If this request succeeds, a cancellation link will be sent to the email address of the user. * If no user is logged in, you will get the error code MegaError::API_EACCESS in onRequestFinish(). * * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getText - Returns the pin code for multi-factor authentication * * If the MEGA account is a sub-user business account, onRequestFinish will * be called with the error code MegaError::API_EMASTERONLY. * * @see MegaApi::confirmCancelAccount * * @param pin Pin code for multi-factor authentication * @param listener MegaRequestListener to track this request */ public void multiFactorAuthCancelAccount(String pin, MegaRequestListenerInterface listener){ megaApi.multiFactorAuthCancelAccount(pin, createDelegateRequestListener(listener)); } /** * Initialize the cancellation of an account. * * The associated request type with this request is MegaRequest::TYPE_GET_CANCEL_LINK. * * If this request succeeds, a cancellation link will be sent to the email address of the user. * If no user is logged in, you will get the error code MegaError::API_EACCESS in onRequestFinish(). * * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getText - Returns the pin code for multi-factor authentication * * If the MEGA account is a sub-user business account, onRequestFinish will * be called with the error code MegaError::API_EMASTERONLY. * * @see MegaApi::confirmCancelAccount * * @param pin Pin code for multi-factor authentication */ public void multiFactorAuthCancelAccount(String pin){ megaApi.multiFactorAuthCancelAccount(pin); } /** * Fetch details related to time zones and the current default * * The associated request type with this request is MegaRequest::TYPE_FETCH_TIMEZONE. * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaTimeZoneDetails - Returns details about timezones and the current default * * @param listener MegaRequestListener to track this request */ void fetchTimeZone(MegaRequestListenerInterface listener){ megaApi.fetchTimeZone(createDelegateRequestListener(listener)); } /** * Fetch details related to time zones and the current default * * The associated request type with this request is MegaRequest::TYPE_FETCH_TIMEZONE. * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaTimeZoneDetails - Returns details about timezones and the current default * */ void fetchTimeZone(){ megaApi.fetchTimeZone(); } /** * Log in to a MEGA account. * <p> * The associated request type with this request is MegaRequest.TYPE_LOGIN. * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getEmail() - Returns the first parameter. <br> * - MegaRequest.getPassword() - Returns the second parameter. * <p> * If the email/password are not valid the error code provided in onRequestFinish() is * MegaError.API_ENOENT. * * @param email * Email of the user. * @param password * Password. * @param listener * MegaRequestListener to track this request. */ public void login(String email, String password, MegaRequestListenerInterface listener) { megaApi.login(email, password, createDelegateRequestListener(listener)); } /** * Log in to a MEGA account. * <p> * @param email * Email of the user. * @param password * Password. */ public void login(String email, String password) { megaApi.login(email, password); } /** * Log in to a public folder using a folder link. * <p> * After a successful login, you should call MegaApiJava.fetchNodes() to get filesystem and * start working with the folder. * <p> * The associated request type with this request is MegaRequest.TYPE_LOGIN. * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getEmail() - Returns the string "FOLDER". <br> * - MegaRequest.getLink() - Returns the public link to the folder. * * @param megaFolderLink * link to a folder in MEGA. * @param listener * MegaRequestListener to track this request. */ public void loginToFolder(String megaFolderLink, MegaRequestListenerInterface listener) { megaApi.loginToFolder(megaFolderLink, createDelegateRequestListener(listener)); } /** * Log in to a public folder using a folder link. * <p> * After a successful login, you should call MegaApiJava.fetchNodes() to get filesystem and * start working with the folder. * * @param megaFolderLink * link to a folder in MEGA. */ public void loginToFolder(String megaFolderLink) { megaApi.loginToFolder(megaFolderLink); } /** * Log in to a MEGA account using precomputed keys. * <p> * The associated request type with this request is MegaRequest.TYPE_LOGIN. * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getEmail() - Returns the first parameter. <br> * - MegaRequest.getPassword() - Returns the second parameter. <br> * - MegaRequest.getPrivateKey() - Returns the third parameter. * <p> * If the email/stringHash/base64pwKey are not valid the error code provided in onRequestFinish() is * MegaError.API_ENOENT. * * @param email * Email of the user. * @param stringHash * Hash of the email returned by MegaApiJava.getStringHash(). * @param base64pwkey * Private key calculated using MegaApiJava.getBase64PwKey(). * @param listener * MegaRequestListener to track this request. */ public void fastLogin(String email, String stringHash, String base64pwkey, MegaRequestListenerInterface listener) { megaApi.fastLogin(email, stringHash, base64pwkey, createDelegateRequestListener(listener)); } /** * Log in to a MEGA account using precomputed keys. * * @param email * Email of the user. * @param stringHash * Hash of the email returned by MegaApiJava.getStringHash(). * @param base64pwkey * Private key calculated using MegaApiJava.getBase64PwKey(). */ public void fastLogin(String email, String stringHash, String base64pwkey) { megaApi.fastLogin(email, stringHash, base64pwkey); } /** * Log in to a MEGA account using a session key. * <p> * The associated request type with this request is MegaRequest.TYPE_LOGIN. * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getSessionKey() - Returns the session key. * * @param session * Session key previously dumped with MegaApiJava.dumpSession(). * @param listener * MegaRequestListener to track this request. */ public void fastLogin(String session, MegaRequestListenerInterface listener) { megaApi.fastLogin(session, createDelegateRequestListener(listener)); } /** * Log in to a MEGA account using a session key. * * @param session * Session key previously dumped with MegaApiJava.dumpSession(). */ public void fastLogin(String session) { megaApi.fastLogin(session); } /** * Close a MEGA session. * * All clients using this session will be automatically logged out. * <p> * You can get session information using MegaApiJava.getExtendedAccountDetails(). * Then use MegaAccountDetails.getNumSessions and MegaAccountDetails.getSession * to get session info. * MegaAccountSession.getHandle provides the handle that this function needs. * <p> * If you use mega.INVALID_HANDLE, all sessions except the current one will be closed. * * @param sessionHandle * of the session. Use mega.INVALID_HANDLE to cancel all sessions except the current one. * @param listener * MegaRequestListenerInterface to track this request. */ public void killSession(long sessionHandle, MegaRequestListenerInterface listener) { megaApi.killSession(sessionHandle, createDelegateRequestListener(listener)); } /** * Close a MEGA session. * <p> * All clients using this session will be automatically logged out. * <p> * You can get session information using MegaApiJava.getExtendedAccountDetails(). * Then use MegaAccountDetails.getNumSessions and MegaAccountDetails.getSession * to get session info. * MegaAccountSession.getHandle provides the handle that this function needs. * <p> * If you use mega.INVALID_HANDLE, all sessions except the current one will be closed. * * @param sessionHandle * of the session. Use mega.INVALID_HANDLE to cancel all sessions except the current one. */ public void killSession(long sessionHandle) { megaApi.killSession(sessionHandle); } /** * Get data about the logged account. * <p> * The associated request type with this request is MegaRequest.TYPE_GET_USER_DATA. * <p> * Valid data in the MegaRequest object received in onRequestFinish() when the error code * is MegaError.API_OK: <br> * - MegaRequest.getName() - Returns the name of the logged user. <br> * - MegaRequest.getPassword() - Returns the the public RSA key of the account, Base64-encoded. <br> * - MegaRequest.getPrivateKey() - Returns the private RSA key of the account, Base64-encoded. * * @param listener * MegaRequestListenerInterface to track this request. */ public void getUserData(MegaRequestListenerInterface listener) { megaApi.getUserData(createDelegateRequestListener(listener)); } /** * Get data about the logged account. * */ public void getUserData() { megaApi.getUserData(); } /** * Get data about a contact. * <p> * The associated request type with this request is MegaRequest.TYPE_GET_USER_DATA. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest.getEmail - Returns the email of the contact * <p> * Valid data in the MegaRequest object received in onRequestFinish() when the error code * is MegaError.API_OK: <br> * - MegaRequest.getText() - Returns the XMPP ID of the contact. <br> * - MegaRequest.getPassword() - Returns the public RSA key of the contact, Base64-encoded. * * @param user * Contact to get the data. * @param listener * MegaRequestListenerInterface to track this request. */ public void getUserData(MegaUser user, MegaRequestListenerInterface listener) { megaApi.getUserData(user, createDelegateRequestListener(listener)); } /** * Get data about a contact. * * @param user * Contact to get the data. */ public void getUserData(MegaUser user) { megaApi.getUserData(user); } /** * Get data about a contact. * <p> * The associated request type with this request is MegaRequest.TYPE_GET_USER_DATA. * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getEmail() - Returns the email or the Base64 handle of the contact. * <p> * Valid data in the MegaRequest object received in onRequestFinish() when the error code * is MegaError.API_OK: <br> * - MegaRequest.getText() - Returns the XMPP ID of the contact. <br> * - MegaRequest.getPassword() - Returns the public RSA key of the contact, Base64-encoded. * * @param user * Email or Base64 handle of the contact. * @param listener * MegaRequestListenerInterface to track this request. */ public void getUserData(String user, MegaRequestListenerInterface listener) { megaApi.getUserData(user, createDelegateRequestListener(listener)); } /** * Get data about a contact. * * @param user * Email or Base64 handle of the contact. */ public void getUserData(String user) { megaApi.getUserData(user); } /** * Fetch miscellaneous flags when not logged in * * The associated request type with this request is MegaRequest::TYPE_GET_MISC_FLAGS. * * When onRequestFinish is called with MegaError::API_OK, the global flags are available. * If you are logged in into an account, the error code provided in onRequestFinish is * MegaError::API_EACCESS. * * @see MegaApi::multiFactorAuthAvailable * @see MegaApi::newLinkFormatEnabled * @see MegaApi::smsAllowedState * * @param listener MegaRequestListener to track this request */ public void getMiscFlags(MegaRequestListenerInterface listener) { megaApi.getMiscFlags(createDelegateRequestListener(listener)); } /** * Fetch miscellaneous flags when not logged in * * The associated request type with this request is MegaRequest::TYPE_GET_MISC_FLAGS. * * When onRequestFinish is called with MegaError::API_OK, the global flags are available. * If you are logged in into an account, the error code provided in onRequestFinish is * MegaError::API_EACCESS. * * @see MegaApi::multiFactorAuthAvailable * @see MegaApi::newLinkFormatEnabled * @see MegaApi::smsAllowedState */ public void getMiscFlags() { megaApi.getMiscFlags(); } /** * Trigger special account state changes for own accounts, for testing * * Because the dev API command allows a wide variety of state changes including suspension and unsuspension, * it has restrictions on which accounts you can target, and where it can be called from. * * Your client must be on a company VPN IP address. * * The target account must be an @mega email address. The target account must either be the calling account, * OR a related account via a prefix and + character. For example if the calling account is name1+test@mega.co.nz * then it can perform a dev command on itself or on name1@mega.co.nz, name1+bob@mega.co.nz etc, but NOT on * name2@mega.co.nz or name2+test@meg.co.nz. * * The associated request type with this request is MegaRequest::TYPE_SEND_DEV_COMMAND. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getName - Returns the first parameter * - MegaRequest::getEmail - Returns the second parameter * * Possible errors are: * - EACCESS if the calling account is not allowed to perform this method (not a mega email account, not the right IP, etc). * - EARGS if the subcommand is not present or is invalid * - EBLOCKED if the target account is not allowed (this could also happen if the target account does not exist) * * Possible commands: * - "aodq" - Advance ODQ Warning State * If called, this will advance your ODQ warning state until the final warning state, * at which point it will turn on the ODQ paywall for your account. It requires an account lock on the target account. * This subcommand will return the 'step' of the warning flow you have advanced to - 1, 2, 3 or 4 * (the paywall is turned on at step 4) * * Valid data in the MegaRequest object received in onRequestFinish when the error code is MegaError::API_OK: * + MegaRequest::getNumber - Returns the number of warnings (1, 2, 3 or 4). * * Possible errors in addition to the standard dev ones are: * + EFAILED - your account is not in the RED stoplight state * * @param command The subcommand for the specific operation * @param email Optional email of the target email's account. If null, it will use the logged-in account * @param listener MegaRequestListener to track this request */ public void sendDevCommand(String command, String email, MegaRequestListenerInterface listener) { megaApi.sendDevCommand(command, email, createDelegateRequestListener(listener)); } /** * Returns the current session key. * <p> * You have to be logged in to get a valid session key. Otherwise, * this function returns null. * * @return Current session key. */ public String dumpSession() { return megaApi.dumpSession(); } /** * Get an authentication token that can be used to identify the user account * * If this MegaApi object is not logged into an account, this function will return NULL * * The value returned by this function can be used in other instances of MegaApi * thanks to the function MegaApi::setAccountAuth. * * You take the ownership of the returned value * * @return Authentication token */ public String getAccountAuth() { return megaApi.getAccountAuth(); } /** * Use an authentication token to identify an account while accessing public folders * * This function is useful to preserve the PRO status when a public folder is being * used. The identifier will be sent in all API requests made after the call to this function. * * To stop using the current authentication token, it's needed to explicitly call * this function with NULL as parameter. Otherwise, the value set would continue * being used despite this MegaApi object is logged in or logged out. * * It's recommended to call this function before the usage of MegaApi::loginToFolder * * @param auth Authentication token used to identify the account of the user. * You can get it using MegaApi::getAccountAuth with an instance of MegaApi logged into * an account. */ public void setAccountAuth(String auth) { megaApi.setAccountAuth(auth); } /** * Create Ephemeral++ account * * This kind of account allows to join chat links and to keep the session in the device * where it was created. * * The associated request type with this request is MegaRequest::TYPE_CREATE_ACCOUNT. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getName - Returns the firstname of the user * - MegaRequest::getText - Returns the lastname of the user * - MegaRequest::getParamType - Returns the value MegaApi:CREATE_EPLUSPLUS_ACCOUNT * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * MegaRequest::getSessionKey - Returns the session id to resume the process * * If this request succeeds, a new ephemeral++ account will be created for the new user. * The app may resume the create-account process by using MegaApi::resumeCreateAccountEphemeralPlusPlus. * * @note This account should be confirmed in same device it was created * * @param firstname Firstname of the user * @param lastname Lastname of the user * @param listener MegaRequestListener to track this request */ public void createEphemeralAccountPlusPlus(String firstname, String lastname, MegaRequestListenerInterface listener) { megaApi.createEphemeralAccountPlusPlus(firstname, lastname, createDelegateRequestListener(listener)); } /** * Initialize the creation of a new MEGA account, with firstname and lastname * * The associated request type with this request is MegaRequest::TYPE_CREATE_ACCOUNT. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getEmail - Returns the email for the account * - MegaRequest::getPassword - Returns the password for the account * - MegaRequest::getName - Returns the firstname of the user * - MegaRequest::getText - Returns the lastname of the user * - MegaRequest::getParamType - Returns the value MegaApi::CREATE_ACCOUNT * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getSessionKey - Returns the session id to resume the process * * If this request succeeds, a new ephemeral account will be created for the new user * and a confirmation email will be sent to the specified email address. The app may * resume the create-account process by using MegaApi::resumeCreateAccount. * * If an account with the same email already exists, you will get the error code * MegaError::API_EEXIST in onRequestFinish * * @param email Email for the account * @param password Password for the account * @param firstname Firstname of the user * @param lastname Lastname of the user * @param listener MegaRequestListener to track this request */ public void createAccount(String email, String password, String firstname, String lastname, MegaRequestListenerInterface listener){ megaApi.createAccount(email, password, firstname, lastname, createDelegateRequestListener(listener)); } /** * Initialize the creation of a new MEGA account, with firstname and lastname * * The associated request type with this request is MegaRequest::TYPE_CREATE_ACCOUNT. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getEmail - Returns the email for the account * - MegaRequest::getPassword - Returns the password for the account * - MegaRequest::getName - Returns the firstname of the user * - MegaRequest::getText - Returns the lastname of the user * - MegaRequest::getParamType - Returns the value MegaApi::CREATE_ACCOUNT * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getSessionKey - Returns the session id to resume the process * * If this request succeeds, a new ephemeral account will be created for the new user * and a confirmation email will be sent to the specified email address. The app may * resume the create-account process by using MegaApi::resumeCreateAccount. * * If an account with the same email already exists, you will get the error code * MegaError::API_EEXIST in onRequestFinish * * @param email Email for the account * @param password Password for the account * @param firstname Firstname of the user * @param lastname Lastname of the user */ public void createAccount(String email, String password, String firstname, String lastname){ megaApi.createAccount(email, password, firstname, lastname); } /** * Initialize the creation of a new MEGA account, with firstname and lastname * * The associated request type with this request is MegaRequest::TYPE_CREATE_ACCOUNT. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getEmail - Returns the email for the account * - MegaRequest::getPassword - Returns the password for the account * - MegaRequest::getName - Returns the firstname of the user * - MegaRequest::getText - Returns the lastname of the user * - MegaRequest::getNodeHandle - Returns the last public node handle accessed * - MegaRequest::getAccess - Returns the type of lastPublicHandle * - MegaRequest::getTransferredBytes - Returns the timestamp of the last access * - MegaRequest::getParamType - Returns the value MegaApi::CREATE_ACCOUNT * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getSessionKey - Returns the session id to resume the process * * If this request succeeds, a new ephemeral session will be created for the new user * and a confirmation email will be sent to the specified email address. The app may * resume the create-account process by using MegaApi::resumeCreateAccount. * * If an account with the same email already exists, you will get the error code * MegaError::API_EEXIST in onRequestFinish * * @param email Email for the account * @param password Password for the account * @param firstname Firstname of the user * @param lastname Lastname of the user * @param lastPublicHandle Last public node handle accessed by the user in the last 24h * @param lastPublicHandleType Indicates the type of lastPublicHandle, valid values are: * - MegaApi::AFFILIATE_TYPE_ID = 1 * - MegaApi::AFFILIATE_TYPE_FILE_FOLDER = 2 * - MegaApi::AFFILIATE_TYPE_CHAT = 3 * - MegaApi::AFFILIATE_TYPE_CONTACT = 4 * * @param lastAccessTimestamp Timestamp of the last access * @param listener MegaRequestListener to track this request */ public void createAccount(String email, String password, String firstname, String lastname, long lastPublicHandle, int lastPublicHandleType, long lastAccessTimestamp, MegaRequestListenerInterface listener) { megaApi.createAccount(email, password, firstname, lastname, lastPublicHandle, lastPublicHandleType, lastAccessTimestamp, createDelegateRequestListener(listener)); } /** * Initialize the creation of a new MEGA account, with firstname and lastname * * The associated request type with this request is MegaRequest::TYPE_CREATE_ACCOUNT. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getEmail - Returns the email for the account * - MegaRequest::getPassword - Returns the password for the account * - MegaRequest::getName - Returns the firstname of the user * - MegaRequest::getText - Returns the lastname of the user * - MegaRequest::getNodeHandle - Returns the last public node handle accessed * - MegaRequest::getAccess - Returns the type of lastPublicHandle * - MegaRequest::getTransferredBytes - Returns the timestamp of the last access * - MegaRequest::getParamType - Returns the value MegaApi::CREATE_ACCOUNT * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getSessionKey - Returns the session id to resume the process * * If this request succeeds, a new ephemeral session will be created for the new user * and a confirmation email will be sent to the specified email address. The app may * resume the create-account process by using MegaApi::resumeCreateAccount. * * If an account with the same email already exists, you will get the error code * MegaError::API_EEXIST in onRequestFinish * * @param email Email for the account * @param password Password for the account * @param firstname Firstname of the user * @param lastname Lastname of the user * @param lastPublicHandle Last public node handle accessed by the user in the last 24h * @param lastPublicHandleType Indicates the type of lastPublicHandle, valid values are: * - MegaApi::AFFILIATE_TYPE_ID = 1 * - MegaApi::AFFILIATE_TYPE_FILE_FOLDER = 2 * - MegaApi::AFFILIATE_TYPE_CHAT = 3 * - MegaApi::AFFILIATE_TYPE_CONTACT = 4 * * @param lastAccessTimestamp Timestamp of the last access */ public void createAccount(String email, String password, String firstname, String lastname, long lastPublicHandle, int lastPublicHandleType, long lastAccessTimestamp) { megaApi.createAccount(email, password, firstname, lastname, lastPublicHandle, lastPublicHandleType, lastAccessTimestamp); } /** * Resume a registration process * * When a user begins the account registration process by calling MegaApi::createAccount, * an ephemeral account is created. * * Until the user successfully confirms the signup link sent to the provided email address, * you can resume the ephemeral session in order to change the email address, resend the * signup link (@see MegaApi::sendSignupLink) and also to receive notifications in case the * user confirms the account using another client (MegaGlobalListener::onAccountUpdate or * MegaListener::onAccountUpdate). It is also possible to cancel the registration process by * MegaApi::cancelCreateAccount, which invalidates the signup link associated to the ephemeral * session (the session will be still valid). * * The associated request type with this request is MegaRequest::TYPE_CREATE_ACCOUNT. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getSessionKey - Returns the session id to resume the process * - MegaRequest::getParamType - Returns the value MegaApi::RESUME_ACCOUNT * * In case the account is already confirmed, the associated request will fail with * error MegaError::API_EARGS. * * @param sid Session id valid for the ephemeral account (@see MegaApi::createAccount) * @param listener MegaRequestListener to track this request */ public void resumeCreateAccount(String sid, MegaRequestListenerInterface listener) { megaApi.resumeCreateAccount(sid, createDelegateRequestListener(listener)); } /** * Resume a registration process * * When a user begins the account registration process by calling MegaApi::createAccount, * an ephemeral account is created. * * Until the user successfully confirms the signup link sent to the provided email address, * you can resume the ephemeral session in order to change the email address, resend the * signup link (@see MegaApi::sendSignupLink) and also to receive notifications in case the * user confirms the account using another client (MegaGlobalListener::onAccountUpdate or * MegaListener::onAccountUpdate). It is also possible to cancel the registration process by * MegaApi::cancelCreateAccount, which invalidates the signup link associated to the ephemeral * session (the session will be still valid). * * The associated request type with this request is MegaRequest::TYPE_CREATE_ACCOUNT. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getSessionKey - Returns the session id to resume the process * - MegaRequest::getParamType - Returns the value MegaApi::RESUME_ACCOUNT * * In case the account is already confirmed, the associated request will fail with * error MegaError::API_EARGS. * * @param sid Session id valid for the ephemeral account (@see MegaApi::createAccount) */ public void resumeCreateAccount(String sid) { megaApi.resumeCreateAccount(sid); } /** * Sends the confirmation email for a new account * * This function is useful to send the confirmation link again or to send it to a different * email address, in case the user mistyped the email at the registration form. * * @param email Email for the account * @param name Firstname of the user * @param password Password for the account * @param listener MegaRequestListener to track this request */ public void sendSignupLink(String email, String name, String password, MegaRequestListenerInterface listener) { megaApi.sendSignupLink(email, name, password, createDelegateRequestListener(listener)); } /** * Sends the confirmation email for a new account * * This function is useful to send the confirmation link again or to send it to a different * email address, in case the user mistyped the email at the registration form. * * @param email Email for the account * @param name Firstname of the user * @param password Password for the account */ public void sendSignupLink(String email, String name, String password) { megaApi.sendSignupLink(email, name, password); } /** * Get information about a confirmation link. * <p> * The associated request type with this request is MegaRequest.TYPE_QUERY_SIGNUP_LINK. * Valid data in the MegaRequest object received on all callbacks: <br> * - MegaRequest.getLink() - Returns the confirmation link. * <p> * Valid data in the MegaRequest object received in onRequestFinish() when the error code * is MegaError.API_OK: <br> * - MegaRequest.getEmail() - Return the email associated with the confirmation link. <br> * - MegaRequest.getName() - Returns the name associated with the confirmation link. * * @param link * Confirmation link. * @param listener * MegaRequestListener to track this request. */ public void querySignupLink(String link, MegaRequestListenerInterface listener) { megaApi.querySignupLink(link, createDelegateRequestListener(listener)); } /** * Get information about a confirmation link. * * @param link * Confirmation link. */ public void querySignupLink(String link) { megaApi.querySignupLink(link); } /** * Confirm a MEGA account using a confirmation link and the user password. * <p> * The associated request type with this request is MegaRequest.TYPE_CONFIRM_ACCOUNT * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getLink() - Returns the confirmation link. <br> * - MegaRequest.getPassword() - Returns the password. * <p> * Valid data in the MegaRequest object received in onRequestFinish() when the error code * is MegaError.API_OK: <br> * - MegaRequest.getEmail() - Email of the account. <br> * - MegaRequest.getName() - Name of the user. * * @param link * Confirmation link. * @param password * Password for the account. * @param listener * MegaRequestListener to track this request. */ public void confirmAccount(String link, String password, MegaRequestListenerInterface listener) { megaApi.confirmAccount(link, password, createDelegateRequestListener(listener)); } /** * Confirm a MEGA account using a confirmation link and the user password. * * @param link * Confirmation link. * @param password * Password for the account. */ public void confirmAccount(String link, String password) { megaApi.confirmAccount(link, password); } /** * Confirm a MEGA account using a confirmation link and a precomputed key. * <p> * The associated request type with this request is MegaRequest.TYPE_CONFIRM_ACCOUNT * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getLink() - Returns the confirmation link. <br> * - MegaRequest.getPrivateKey() - Returns the base64pwkey parameter. * <p> * Valid data in the MegaRequest object received in onRequestFinish() when the error code * is MegaError.API_OK: <br> * - MegaRequest.getEmail() - Email of the account. <br> * - MegaRequest.getName() - Name of the user. * * @param link * Confirmation link. * @param base64pwkey * Private key precomputed with MegaApiJava.getBase64PwKey(). * @param listener * MegaRequestListener to track this request. */ public void fastConfirmAccount(String link, String base64pwkey, MegaRequestListenerInterface listener) { megaApi.fastConfirmAccount(link, base64pwkey, createDelegateRequestListener(listener)); } /** * Confirm a MEGA account using a confirmation link and a precomputed key. * * @param link * Confirmation link. * @param base64pwkey * Private key precomputed with MegaApiJava.getBase64PwKey(). */ public void fastConfirmAccount(String link, String base64pwkey) { megaApi.fastConfirmAccount(link, base64pwkey); } /** * Initialize the reset of the existing password, with and without the Master Key. * * The associated request type with this request is MegaRequest::TYPE_GET_RECOVERY_LINK. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getEmail - Returns the email for the account * - MegaRequest::getFlag - Returns whether the user has a backup of the master key or not. * * If this request succeed, a recovery link will be sent to the user. * If no account is registered under the provided email, you will get the error code * MegaError::API_EEXIST in onRequestFinish * * @param email Email used to register the account whose password wants to be reset. * @param hasMasterKey True if the user has a backup of the master key. Otherwise, false. * @param listener MegaRequestListener to track this request */ public void resetPassword(String email, boolean hasMasterKey, MegaRequestListenerInterface listener){ megaApi.resetPassword(email, hasMasterKey, createDelegateRequestListener(listener)); } /** * Get information about a recovery link created by MegaApi::resetPassword. * * The associated request type with this request is MegaRequest::TYPE_QUERY_RECOVERY_LINK * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getLink - Returns the recovery link * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getEmail - Return the email associated with the link * - MegaRequest::getFlag - Return whether the link requires masterkey to reset password. * * @param link Recovery link (#recover) * @param listener MegaRequestListener to track this request */ public void queryResetPasswordLink(String link, MegaRequestListenerInterface listener){ megaApi.queryResetPasswordLink(link, createDelegateRequestListener(listener)); } /** * Set a new password for the account pointed by the recovery link. * * Recovery links are created by calling MegaApi::resetPassword and may or may not * require to provide the Master Key. * * @see The flag of the MegaRequest::TYPE_QUERY_RECOVERY_LINK in MegaApi::queryResetPasswordLink. * * The associated request type with this request is MegaRequest::TYPE_CONFIRM_ACCOUNT * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getLink - Returns the recovery link * - MegaRequest::getPassword - Returns the new password * - MegaRequest::getPrivateKey - Returns the Master Key, when provided * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getEmail - Return the email associated with the link * - MegaRequest::getFlag - Return whether the link requires masterkey to reset password. * * @param link The recovery link sent to the user's email address. * @param newPwd The new password to be set. * @param masterKey Base64-encoded string containing the master key (optional). * @param listener MegaRequestListener to track this request */ public void confirmResetPassword(String link, String newPwd, String masterKey, MegaRequestListenerInterface listener){ megaApi.confirmResetPassword(link, newPwd, masterKey, createDelegateRequestListener(listener)); } /** * Initialize the cancellation of an account. * * The associated request type with this request is MegaRequest::TYPE_GET_CANCEL_LINK. * * If this request succeed, a cancellation link will be sent to the email address of the user. * If no user is logged in, you will get the error code MegaError::API_EACCESS in onRequestFinish(). * * If the MEGA account is a sub-user business account, onRequestFinish will * be called with the error code MegaError::API_EMASTERONLY. * * @see MegaApi::confirmCancelAccount * * @param listener MegaRequestListener to track this request */ public void cancelAccount(MegaRequestListenerInterface listener){ megaApi.cancelAccount(createDelegateRequestListener(listener)); } /** * Get information about a cancel link created by MegaApi::cancelAccount. * * The associated request type with this request is MegaRequest::TYPE_QUERY_RECOVERY_LINK * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getLink - Returns the cancel link * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getEmail - Return the email associated with the link * * @param link Cancel link (#cancel) * @param listener MegaRequestListener to track this request */ public void queryCancelLink(String link, MegaRequestListenerInterface listener){ megaApi.queryCancelLink(link, createDelegateRequestListener(listener)); } /** * Effectively parks the user's account without creating a new fresh account. * * The contents of the account will then be purged after 60 days. Once the account is * parked, the user needs to contact MEGA support to restore the account. * * The associated request type with this request is MegaRequest::TYPE_CONFIRM_CANCEL_LINK. * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getLink - Returns the recovery link * - MegaRequest::getPassword - Returns the new password * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getEmail - Return the email associated with the link * * @param link Cancellation link sent to the user's email address; * @param pwd Password for the account. * @param listener MegaRequestListener to track this request */ public void confirmCancelAccount(String link, String pwd, MegaRequestListenerInterface listener){ megaApi.confirmCancelAccount(link, pwd, createDelegateRequestListener(listener)); } /** * Allow to resend the verification email for Weak Account Protection * * The verification email will be resent to the same address as it was previously sent to. * * This function can be called if the the reason for being blocked is: * 700: the account is supended for Weak Account Protection. * * If the logged in account is not suspended or is suspended for some other reason, * onRequestFinish will be called with the error code MegaError::API_EACCESS. * * If the logged in account has not been sent the unlock email before, * onRequestFinish will be called with the error code MegaError::API_EARGS. * * @param listener MegaRequestListener to track this request */ public void resendVerificationEmail(MegaRequestListenerInterface listener) { megaApi.resendVerificationEmail(createDelegateRequestListener(listener)); } /** * Allow to resend the verification email for Weak Account Protection * * The verification email will be resent to the same address as it was previously sent to. * * This function can be called if the the reason for being blocked is: * 700: the account is supended for Weak Account Protection. * * If the logged in account is not suspended or is suspended for some other reason, * onRequestFinish will be called with the error code MegaError::API_EACCESS. * * If the logged in account has not been sent the unlock email before, * onRequestFinish will be called with the error code MegaError::API_EARGS. */ public void resendVerificationEmail() { megaApi.resendVerificationEmail(); } /** * Initialize the change of the email address associated to the account. * * The associated request type with this request is MegaRequest::TYPE_GET_CHANGE_EMAIL_LINK. * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getEmail - Returns the email for the account * * If this request succeed, a change-email link will be sent to the specified email address. * If no user is logged in, you will get the error code MegaError::API_EACCESS in onRequestFinish(). * * If the MEGA account is a sub-user business account, onRequestFinish will * be called with the error code MegaError::API_EMASTERONLY. * * @param email The new email to be associated to the account. * @param listener MegaRequestListener to track this request */ public void changeEmail(String email, MegaRequestListenerInterface listener){ megaApi.changeEmail(email, createDelegateRequestListener(listener)); } /** * Get information about a change-email link created by MegaApi::changeEmail. * * If no user is logged in, you will get the error code MegaError::API_EACCESS in onRequestFinish(). * * The associated request type with this request is MegaRequest::TYPE_QUERY_RECOVERY_LINK * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getLink - Returns the change-email link * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getEmail - Return the email associated with the link * * @param link Change-email link (#verify) * @param listener MegaRequestListener to track this request */ public void queryChangeEmailLink(String link, MegaRequestListenerInterface listener){ megaApi.queryChangeEmailLink(link, createDelegateRequestListener(listener)); } /** * Effectively changes the email address associated to the account. * * The associated request type with this request is MegaRequest::TYPE_CONFIRM_CHANGE_EMAIL_LINK. * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getLink - Returns the change-email link * - MegaRequest::getPassword - Returns the password * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getEmail - Return the email associated with the link * * @param link Change-email link sent to the user's email address. * @param pwd Password for the account. * @param listener MegaRequestListener to track this request */ public void confirmChangeEmail(String link, String pwd, MegaRequestListenerInterface listener){ megaApi.confirmChangeEmail(link, pwd, createDelegateRequestListener(listener)); } /** * Set proxy settings. * <p> * The SDK will start using the provided proxy settings as soon as this function returns. * * @param proxySettings * settings. * @see MegaProxy */ public void setProxySettings(MegaProxy proxySettings) { megaApi.setProxySettings(proxySettings); } /** * Try to detect the system's proxy settings. * * Automatic proxy detection is currently supported on Windows only. * On other platforms, this function will return a MegaProxy object * of type MegaProxy.PROXY_NONE. * * @return MegaProxy object with the detected proxy settings. */ public MegaProxy getAutoProxySettings() { return megaApi.getAutoProxySettings(); } /** * Check if the MegaApi object is logged in. * * @return 0 if not logged in. Otherwise, a number >= 0. */ public int isLoggedIn() { return megaApi.isLoggedIn(); } /** * Check if we are logged in into an Ephemeral account ++ * @return true if logged into an Ephemeral account ++, Otherwise return false */ public boolean isEphemeralPlusPlus() { return megaApi.isEphemeralPlusPlus(); } /** * Check the reason of being blocked. * * The associated request type with this request is MegaRequest::TYPE_WHY_AM_I_BLOCKED. * * This request can be sent internally at anytime (whenever an account gets blocked), so * a MegaGlobalListener should process the result, show the reason and logout. * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Returns the reason string (in English) * - MegaRequest::getNumber - Returns the reason code. Possible values: * 0: The account is not blocked * 200: suspension message for any type of suspension, but copyright suspension. * 300: suspension only for multiple copyright violations. * 400: the subuser account has been disabled. * 401: the subuser account has been removed. * 500: The account needs to be verified by an SMS code. * 700: the account is supended for Weak Account Protection. * * If the error code in the MegaRequest object received in onRequestFinish * is MegaError::API_OK, the user is not blocked. * * @param listener MegaRequestListener to track this request */ public void whyAmIBlocked(MegaRequestListenerInterface listener) { megaApi.whyAmIBlocked(createDelegateRequestListener(listener)); } /** * Check the reason of being blocked. * * The associated request type with this request is MegaRequest::TYPE_WHY_AM_I_BLOCKED. * * This request can be sent internally at anytime (whenever an account gets blocked), so * a MegaGlobalListener should process the result, show the reason and logout. * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Returns the reason string (in English) * - MegaRequest::getNumber - Returns the reason code. Possible values: * 0: The account is not blocked * 200: suspension message for any type of suspension, but copyright suspension. * 300: suspension only for multiple copyright violations. * 400: the subuser account has been disabled. * 401: the subuser account has been removed. * 500: The account needs to be verified by an SMS code. * 700: the account is supended for Weak Account Protection. * * If the error code in the MegaRequest object received in onRequestFinish * is MegaError::API_OK, the user is not blocked. */ public void whyAmIBlocked() { megaApi.whyAmIBlocked(); } /** * Create a contact link * * The associated request type with this request is MegaRequest::TYPE_CONTACT_LINK_CREATE. * * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getFlag - Returns the value of \c renew parameter * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodeHandle - Return the handle of the new contact link * * @param renew True to invalidate the previous contact link (if any). * @param listener MegaRequestListener to track this request */ public void contactLinkCreate(boolean renew, MegaRequestListenerInterface listener){ megaApi.contactLinkCreate(renew, createDelegateRequestListener(listener)); } /** * Create a contact link * * The associated request type with this request is MegaRequest::TYPE_CONTACT_LINK_CREATE. * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodeHandle - Return the handle of the new contact link * */ public void contactLinkCreate(){ megaApi.contactLinkCreate(); } /** * Get information about a contact link * * The associated request type with this request is MegaRequest::TYPE_CONTACT_LINK_QUERY. * * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the contact link * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getEmail - Returns the email of the contact * - MegaRequest::getName - Returns the first name of the contact * - MegaRequest::getText - Returns the last name of the contact * * @param handle Handle of the contact link to check * @param listener MegaRequestListener to track this request */ public void contactLinkQuery(long handle, MegaRequestListenerInterface listener){ megaApi.contactLinkQuery(handle, createDelegateRequestListener(listener)); } /** * Get information about a contact link * * The associated request type with this request is MegaRequest::TYPE_CONTACT_LINK_QUERY. * * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the contact link * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getEmail - Returns the email of the contact * - MegaRequest::getName - Returns the first name of the contact * - MegaRequest::getText - Returns the last name of the contact * * @param handle Handle of the contact link to check */ public void contactLinkQuery(long handle){ megaApi.contactLinkQuery(handle); } /** * Delete a contact link * * The associated request type with this request is MegaRequest::TYPE_CONTACT_LINK_DELETE. * * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the contact link * * @param handle Handle of the contact link to delete * If the parameter is INVALID_HANDLE, the active contact link is deleted * * @param listener MegaRequestListener to track this request */ public void contactLinkDelete(long handle, MegaRequestListenerInterface listener){ megaApi.contactLinkDelete(handle, createDelegateRequestListener(listener)); } /** * Delete a contact link * * The associated request type with this request is MegaRequest::TYPE_CONTACT_LINK_DELETE. * * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the contact link * * @param handle Handle of the contact link to delete */ public void contactLinkDelete(long handle){ megaApi.contactLinkDelete(handle); } /** * Get the next PSA (Public Service Announcement) that should be shown to the user * * After the PSA has been accepted or dismissed by the user, app should * use MegaApi::setPSA to notify API servers about this event and * do not get the same PSA again in the next call to this function. * * The associated request type with this request is MegaRequest::TYPE_GET_PSA. * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNumber - Returns the id of the PSA (useful to call MegaApi::setPSA later) * Depending on the format of the PSA, the request may additionally return, for the new format: * - MegaRequest::getEmail - Returns the URL (or an empty string) * ...or for the old format: * - MegaRequest::getName - Returns the title of the PSA * - MegaRequest::getText - Returns the text of the PSA * - MegaRequest::getFile - Returns the URL of the image of the PSA * - MegaRequest::getPassword - Returns the text for the positive button (or an empty string) * - MegaRequest::getLink - Returns the link for the positive button (or an empty string) * * If there isn't any new PSA to show, onRequestFinish will be called with the error * code MegaError::API_ENOENT * * @param listener MegaRequestListener to track this request * @see MegaApi::setPSA */ public void getPSAWithUrl(MegaRequestListenerInterface listener){ megaApi.getPSAWithUrl(createDelegateRequestListener(listener)); } /** * Notify API servers that a PSA (Public Service Announcement) has been already seen * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER. * * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the value MegaApi::USER_ATTR_LAST_PSA * - MegaRequest::getText - Returns the id passed in the first parameter (as a string) * * @param id Identifier of the PSA * @param listener MegaRequestListener to track this request * * @see MegaApi::getPSA */ public void setPSA(int id, MegaRequestListenerInterface listener){ megaApi.setPSA(id, createDelegateRequestListener(listener)); } /** * Notify API servers that a PSA (Public Service Announcement) has been already seen * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER. * * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the value MegaApi::USER_ATTR_LAST_PSA * - MegaRequest::getText - Returns the id passed in the first parameter (as a string) * * @param id Identifier of the PSA * * @see MegaApi::getPSA */ public void setPSA(int id){ megaApi.setPSA(id); } /** * Command to acknowledge user alerts. * * Other clients will be notified that alerts to this point have been seen. * * @param listener MegaRequestListener to track this request */ public void acknowledgeUserAlerts(MegaRequestListenerInterface listener){ megaApi.acknowledgeUserAlerts(createDelegateRequestListener(listener)); } /** * Command to acknowledge user alerts. * * Other clients will be notified that alerts to this point have been seen. * * @see MegaApi::getUserAlerts */ public void acknowledgeUserAlerts(){ megaApi.acknowledgeUserAlerts(); } /** * Returns the email of the currently open account. * * If the MegaApi object is not logged in or the email is not available, * this function returns null. * * @return Email of the account. */ public String getMyEmail() { return megaApi.getMyEmail(); } /** * Returns the user handle of the currently open account * * If the MegaApi object isn't logged in, * this function returns null * * @return User handle of the account */ public String getMyUserHandle() { return megaApi.getMyUserHandle(); } /** * Returns the user handle of the currently open account * * If the MegaApi object isn't logged in, * this function returns INVALID_HANDLE * * @return User handle of the account */ public long getMyUserHandleBinary(){ return megaApi.getMyUserHandleBinary(); } /** * Get the MegaUser of the currently open account * * If the MegaApi object isn't logged in, this function returns NULL. * * You take the ownership of the returned value * * @note The visibility of your own user is unhdefined and shouldn't be used. * @return MegaUser of the currently open account, otherwise NULL */ public MegaUser getMyUser(){ return megaApi.getMyUser(); } /** * Returns whether MEGA Achievements are enabled for the open account * @return True if enabled, false otherwise. */ public boolean isAchievementsEnabled() { return megaApi.isAchievementsEnabled(); } /** * Check if the account is a business account. * @return returns true if it's a business account, otherwise false */ public boolean isBusinessAccount() { return megaApi.isBusinessAccount(); } /** * Check if the account is a master account. * * When a business account is a sub-user, not the master, some user actions will be blocked. * In result, the API will return the error code MegaError::API_EMASTERONLY. Some examples of * requests that may fail with this error are: * - MegaApi::cancelAccount * - MegaApi::changeEmail * - MegaApi::remove * - MegaApi::removeVersion * * @return returns true if it's a master account, false if it's a sub-user account */ public boolean isMasterBusinessAccount() { return megaApi.isMasterBusinessAccount(); } /** * Check if the business account is active or not. * * When a business account is not active, some user actions will be blocked. In result, the API * will return the error code MegaError::API_EBUSINESSPASTDUE. Some examples of requests * that may fail with this error are: * - MegaApi::startDownload * - MegaApi::startUpload * - MegaApi::copyNode * - MegaApi::share * - MegaApi::cleanRubbishBin * * @return returns true if the account is active, otherwise false */ public boolean isBusinessAccountActive() { return megaApi.isBusinessAccountActive(); } /** * Get the status of a business account. * @return Returns the business account status, possible values: * MegaApi::BUSINESS_STATUS_EXPIRED = -1 * MegaApi::BUSINESS_STATUS_INACTIVE = 0 * MegaApi::BUSINESS_STATUS_ACTIVE = 1 * MegaApi::BUSINESS_STATUS_GRACE_PERIOD = 2 */ public int getBusinessStatus() { return megaApi.getBusinessStatus(); } /** * Returns the deadline to remedy the storage overquota situation * * This value is valid only when MegaApi::getUserData has been called after * receiving a callback MegaListener/MegaGlobalListener::onEvent of type * MegaEvent::EVENT_STORAGE, reporting STORAGE_STATE_PAYWALL. * The value will become invalid once the state of storage changes. * * @return Timestamp representing the deadline to remedy the overquota */ public long getOverquotaDeadlineTs() { return megaApi.getOverquotaDeadlineTs(); } /** * Returns when the user was warned about overquota state * * This value is valid only when MegaApi::getUserData has been called after * receiving a callback MegaListener/MegaGlobalListener::onEvent of type * MegaEvent::EVENT_STORAGE, reporting STORAGE_STATE_PAYWALL. * The value will become invalid once the state of storage changes. * * You take the ownership of the returned value. * * @return MegaIntegerList with the timestamp corresponding to each warning */ public MegaIntegerList getOverquotaWarningsTs() { return megaApi.getOverquotaWarningsTs(); } /** * Check if the password is correct for the current account * @param password Password to check * @return True if the password is correct for the current account, otherwise false. */ public boolean checkPassword(String password){ return megaApi.checkPassword(password); } /** * Returns the credentials of the currently open account * * If the MegaApi object isn't logged in or there's no signing key available, * this function returns NULL * * You take the ownership of the returned value. * Use delete [] to free it. * * @return Fingerprint of the signing key of the current account */ public String getMyCredentials() { return megaApi.getMyCredentials(); } /** * Returns the credentials of a given user * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns MegaApi::USER_ATTR_ED25519_PUBLIC_KEY * - MegaRequest::getFlag - Returns true * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getPassword - Returns the credentials in hexadecimal format * * @param user MegaUser of the contact (see MegaApi::getContact) to get the fingerprint * @param listener MegaRequestListener to track this request */ public void getUserCredentials(MegaUser user, MegaRequestListenerInterface listener) { megaApi.getUserCredentials(user, createDelegateRequestListener(listener)); } /** * Checks if credentials are verified for the given user * * @param user MegaUser of the contact whose credentiasl want to be checked * @return true if verified, false otherwise */ public boolean areCredentialsVerified(MegaUser user){ return megaApi.areCredentialsVerified(user); } /** * Verify credentials of a given user * * This function allow to tag credentials of a user as verified. It should be called when the * logged in user compares the fingerprint of the user (provided by an independent and secure * method) with the fingerprint shown by the app (@see MegaApi::getUserCredentials). * * The associated request type with this request is MegaRequest::TYPE_VERIFY_CREDENTIALS * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns userhandle * * @param user MegaUser of the contact whose credentials want to be verified * @param listener MegaRequestListener to track this request */ public void verifyCredentials(MegaUser user, MegaRequestListenerInterface listener){ megaApi.verifyCredentials(user, createDelegateRequestListener(listener)); } /** * Reset credentials of a given user * * Call this function to forget the existing authentication of keys and signatures for a given * user. A full reload of the account will start the authentication process again. * * The associated request type with this request is MegaRequest::TYPE_VERIFY_CREDENTIALS * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns userhandle * - MegaRequest::getFlag - Returns true * * @param user MegaUser of the contact whose credentials want to be reset * @param listener MegaRequestListener to track this request */ public void resetCredentials(MegaUser user, MegaRequestListenerInterface listener) { megaApi.resetCredentials(user, createDelegateRequestListener(listener)); } /** * Set the active log level. * <p> * This function sets the log level of the logging system. If you set a log listener using * MegaApiJava.setLoggerObject(), you will receive logs with the same or a lower level than * the one passed to this function. * * @param logLevel * Active log level. These are the valid values for this parameter: <br> * - MegaApiJava.LOG_LEVEL_FATAL = 0. <br> * - MegaApiJava.LOG_LEVEL_ERROR = 1. <br> * - MegaApiJava.LOG_LEVEL_WARNING = 2. <br> * - MegaApiJava.LOG_LEVEL_INFO = 3. <br> * - MegaApiJava.LOG_LEVEL_DEBUG = 4. <br> * - MegaApiJava.LOG_LEVEL_MAX = 5. */ public static void setLogLevel(int logLevel) { MegaApi.setLogLevel(logLevel); } /** * Add a MegaLogger implementation to receive SDK logs * * Logs received by this objects depends on the active log level. * By default, it is MegaApi::LOG_LEVEL_INFO. You can change it * using MegaApi::setLogLevel. * * You can remove the existing logger by using MegaApi::removeLoggerObject. * * @param megaLogger MegaLogger implementation */ public static void addLoggerObject(MegaLoggerInterface megaLogger){ MegaApi.addLoggerObject(createDelegateMegaLogger(megaLogger)); } /** * Remove a MegaLogger implementation to stop receiving SDK logs * * If the logger was registered in the past, it will stop receiving log * messages after the call to this function. * * @param megaLogger Previously registered MegaLogger implementation */ public static void removeLoggerObject(MegaLoggerInterface megaLogger){ ArrayList<DelegateMegaLogger> listenersToRemove = new ArrayList<DelegateMegaLogger>(); synchronized (activeMegaLoggers) { Iterator<DelegateMegaLogger> it = activeMegaLoggers.iterator(); while (it.hasNext()) { DelegateMegaLogger delegate = it.next(); if (delegate.getUserListener() == megaLogger) { listenersToRemove.add(delegate); it.remove(); } } } for (int i=0;i<listenersToRemove.size();i++){ MegaApi.removeLoggerObject(listenersToRemove.get(i)); } } /** * Send a log to the logging system. * <p> * This log will be received by the active logger object (MegaApiJava.setLoggerObject()) if * the log level is the same or lower than the active log level (MegaApiJava.setLogLevel()). * * @param logLevel * Log level for this message. * @param message * Message for the logging system. * @param filename * Origin of the log message. * @param line * Line of code where this message was generated. */ public static void log(int logLevel, String message, String filename, int line) { MegaApi.log(logLevel, message, filename, line); } /** * Send a log to the logging system. * <p> * This log will be received by the active logger object (MegaApiJava.setLoggerObject()) if * the log level is the same or lower than the active log level (MegaApiJava.setLogLevel()). * * @param logLevel * Log level for this message. * @param message * Message for the logging system. * @param filename * Origin of the log message. */ public static void log(int logLevel, String message, String filename) { MegaApi.log(logLevel, message, filename); } /** * Send a log to the logging system. * <p> * This log will be received by the active logger object (MegaApiJava.setLoggerObject()) if * the log level is the same or lower than the active log level (MegaApiJava.setLogLevel()). * * @param logLevel * Log level for this message. * @param message * Message for the logging system. */ public static void log(int logLevel, String message) { MegaApi.log(logLevel, message); } /** * Create a folder in the MEGA account * * The associated request type with this request is MegaRequest::TYPE_CREATE_FOLDER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParentHandle - Returns the handle of the parent folder * - MegaRequest::getName - Returns the name of the new folder * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodeHandle - Handle of the new folder * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param name Name of the new folder * @param parent Parent folder * @param listener MegaRequestListener to track this request */ public void createFolder(String name, MegaNode parent, MegaRequestListenerInterface listener) { megaApi.createFolder(name, parent, createDelegateRequestListener(listener)); } /** * Create a folder in the MEGA account * * The associated request type with this request is MegaRequest::TYPE_CREATE_FOLDER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParentHandle - Returns the handle of the parent folder * - MegaRequest::getName - Returns the name of the new folder * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodeHandle - Handle of the new folder * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param name Name of the new folder * @param parent Parent folder */ public void createFolder(String name, MegaNode parent) { megaApi.createFolder(name, parent); } /** * Move a node in the MEGA account * * The associated request type with this request is MegaRequest::TYPE_MOVE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to move * - MegaRequest::getParentHandle - Returns the handle of the new parent for the node * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node Node to move * @param newParent New parent for the node * @param listener MegaRequestListener to track this request */ public void moveNode(MegaNode node, MegaNode newParent, MegaRequestListenerInterface listener) { megaApi.moveNode(node, newParent, createDelegateRequestListener(listener)); } /** * Move a node in the MEGA account * * The associated request type with this request is MegaRequest::TYPE_MOVE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to move * - MegaRequest::getParentHandle - Returns the handle of the new parent for the node * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node Node to move * @param newParent New parent for the node */ public void moveNode(MegaNode node, MegaNode newParent) { megaApi.moveNode(node, newParent); } /** * Move a node in the MEGA account changing the file name * * The associated request type with this request is MegaRequest::TYPE_MOVE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to move * - MegaRequest::getParentHandle - Returns the handle of the new parent for the node * - MegaRequest::getName - Returns the name for the new node * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node Node to move * @param newParent New parent for the node * @param newName Name for the new node * @param listener MegaRequestListener to track this request */ void moveNode(MegaNode node, MegaNode newParent, String newName, MegaRequestListenerInterface listener) { megaApi.moveNode(node, newParent, newName, createDelegateRequestListener(listener)); } /** * Move a node in the MEGA account changing the file name * * The associated request type with this request is MegaRequest::TYPE_MOVE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to move * - MegaRequest::getParentHandle - Returns the handle of the new parent for the node * - MegaRequest::getName - Returns the name for the new node * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node Node to move * @param newParent New parent for the node * @param newName Name for the new node */ void moveNode(MegaNode node, MegaNode newParent, String newName) { megaApi.moveNode(node, newParent, newName); } /** * Copy a node in the MEGA account * * The associated request type with this request is MegaRequest::TYPE_COPY * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to copy * - MegaRequest::getParentHandle - Returns the handle of the new parent for the new node * - MegaRequest::getPublicMegaNode - Returns the node to copy (if it is a public node) * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodeHandle - Handle of the new node * * If the status of the business account is expired, onRequestFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. * * @param node Node to copy * @param newParent Parent for the new node * @param listener MegaRequestListener to track this request */ public void copyNode(MegaNode node, MegaNode newParent, MegaRequestListenerInterface listener) { megaApi.copyNode(node, newParent, createDelegateRequestListener(listener)); } /** * Copy a node in the MEGA account * * The associated request type with this request is MegaRequest::TYPE_COPY * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to copy * - MegaRequest::getParentHandle - Returns the handle of the new parent for the new node * - MegaRequest::getPublicMegaNode - Returns the node to copy (if it is a public node) * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodeHandle - Handle of the new node * * If the status of the business account is expired, onRequestFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. * * @param node Node to copy * @param newParent Parent for the new node */ public void copyNode(MegaNode node, MegaNode newParent) { megaApi.copyNode(node, newParent); } /** * Copy a node in the MEGA account changing the file name * * The associated request type with this request is MegaRequest::TYPE_COPY * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to copy * - MegaRequest::getParentHandle - Returns the handle of the new parent for the new node * - MegaRequest::getPublicMegaNode - Returns the node to copy * - MegaRequest::getName - Returns the name for the new node * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodeHandle - Handle of the new node * * If the status of the business account is expired, onRequestFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. * * @param node Node to copy * @param newParent Parent for the new node * @param newName Name for the new node * @param listener MegaRequestListener to track this request */ public void copyNode(MegaNode node, MegaNode newParent, String newName, MegaRequestListenerInterface listener) { megaApi.copyNode(node, newParent, newName, createDelegateRequestListener(listener)); } /** * Copy a node in the MEGA account changing the file name * * The associated request type with this request is MegaRequest::TYPE_COPY * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to copy * - MegaRequest::getParentHandle - Returns the handle of the new parent for the new node * - MegaRequest::getPublicMegaNode - Returns the node to copy * - MegaRequest::getName - Returns the name for the new node * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodeHandle - Handle of the new node * * If the status of the business account is expired, onRequestFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. * * @param node Node to copy * @param newParent Parent for the new node * @param newName Name for the new node */ public void copyNode(MegaNode node, MegaNode newParent, String newName) { megaApi.copyNode(node, newParent, newName); } /** * Rename a node in the MEGA account * * The associated request type with this request is MegaRequest::TYPE_RENAME * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to rename * - MegaRequest::getName - Returns the new name for the node * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node Node to modify * @param newName New name for the node * @param listener MegaRequestListener to track this request */ public void renameNode(MegaNode node, String newName, MegaRequestListenerInterface listener) { megaApi.renameNode(node, newName, createDelegateRequestListener(listener)); } /** * Rename a node in the MEGA account * * The associated request type with this request is MegaRequest::TYPE_RENAME * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to rename * - MegaRequest::getName - Returns the new name for the node * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node Node to modify * @param newName New name for the node */ public void renameNode(MegaNode node, String newName) { megaApi.renameNode(node, newName); } /** * Remove a node from the MEGA account * * This function doesn't move the node to the Rubbish Bin, it fully removes the node. To move * the node to the Rubbish Bin use MegaApi::moveNode * * If the node has previous versions, they will be deleted too * * The associated request type with this request is MegaRequest::TYPE_REMOVE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to remove * - MegaRequest::getFlag - Returns false because previous versions won't be preserved * * If the MEGA account is a sub-user business account, onRequestFinish will * be called with the error code MegaError::API_EMASTERONLY. * * @param node Node to remove * @param listener MegaRequestListener to track this request */ public void remove(MegaNode node, MegaRequestListenerInterface listener) { megaApi.remove(node, createDelegateRequestListener(listener)); } /** * Remove a node from the MEGA account * * This function doesn't move the node to the Rubbish Bin, it fully removes the node. To move * the node to the Rubbish Bin use MegaApi::moveNode * * If the node has previous versions, they will be deleted too * * The associated request type with this request is MegaRequest::TYPE_REMOVE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to remove * - MegaRequest::getFlag - Returns false because previous versions won't be preserved * * If the MEGA account is a sub-user business account, onRequestFinish will * be called with the error code MegaError::API_EMASTERONLY. * * @param node Node to remove */ public void remove(MegaNode node) { megaApi.remove(node); } /** * Remove all versions from the MEGA account * * The associated request type with this request is MegaRequest::TYPE_REMOVE_VERSIONS * * When the request finishes, file versions might not be deleted yet. * Deletions are notified using onNodesUpdate callbacks. * * @param listener MegaRequestListener to track this request */ public void removeVersions(MegaRequestListenerInterface listener){ megaApi.removeVersions(createDelegateRequestListener(listener)); } /** * Remove a version of a file from the MEGA account * * This function doesn't move the node to the Rubbish Bin, it fully removes the node. To move * the node to the Rubbish Bin use MegaApi::moveNode. * * If the node has previous versions, they won't be deleted. * * The associated request type with this request is MegaRequest::TYPE_REMOVE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to remove * - MegaRequest::getFlag - Returns true because previous versions will be preserved * * If the MEGA account is a sub-user business account, onRequestFinish will * be called with the error code MegaError::API_EMASTERONLY. * * @param node Node to remove * @param listener MegaRequestListener to track this request */ public void removeVersion(MegaNode node, MegaRequestListenerInterface listener){ megaApi.removeVersion(node, createDelegateRequestListener(listener)); } /** * Restore a previous version of a file * * Only versions of a file can be restored, not the current version (because it's already current). * The node will be copied and set as current. All the version history will be preserved without changes, * being the old current node the previous version of the new current node, and keeping the restored * node also in its previous place in the version history. * * The associated request type with this request is MegaRequest::TYPE_RESTORE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to restore * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param version Node with the version to restore * @param listener MegaRequestListener to track this request */ public void restoreVersion(MegaNode version, MegaRequestListenerInterface listener){ megaApi.restoreVersion(version, createDelegateRequestListener(listener)); } /** * Clean the Rubbish Bin in the MEGA account * * This function effectively removes every node contained in the Rubbish Bin. In order to * avoid accidental deletions, you might want to warn the user about the action. * * The associated request type with this request is MegaRequest::TYPE_CLEAN_RUBBISH_BIN. This * request returns MegaError::API_ENOENT if the Rubbish bin is already empty. * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param listener MegaRequestListener to track this request */ public void cleanRubbishBin(MegaRequestListenerInterface listener) { megaApi.cleanRubbishBin(createDelegateRequestListener(listener)); } /** * Clean the Rubbish Bin in the MEGA account * * This function effectively removes every node contained in the Rubbish Bin. In order to * avoid accidental deletions, you might want to warn the user about the action. * * The associated request type with this request is MegaRequest::TYPE_CLEAN_RUBBISH_BIN. This * request returns MegaError::API_ENOENT if the Rubbish bin is already empty. * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. */ public void cleanRubbishBin() { megaApi.cleanRubbishBin(); } /** * Send a node to the Inbox of another MEGA user using a MegaUser * * The associated request type with this request is MegaRequest::TYPE_COPY * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to send * - MegaRequest::getEmail - Returns the email of the user that receives the node * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node Node to send * @param user User that receives the node * @param listener MegaRequestListener to track this request */ public void sendFileToUser(MegaNode node, MegaUser user, MegaRequestListenerInterface listener) { megaApi.sendFileToUser(node, user, createDelegateRequestListener(listener)); } /** * Send a node to the Inbox of another MEGA user using a MegaUser * * The associated request type with this request is MegaRequest::TYPE_COPY * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to send * - MegaRequest::getEmail - Returns the email of the user that receives the node * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node Node to send * @param user User that receives the node */ public void sendFileToUser(MegaNode node, MegaUser user) { megaApi.sendFileToUser(node, user); } /** * Send a node to the Inbox of another MEGA user using his email * * The associated request type with this request is MegaRequest::TYPE_COPY * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node to send * - MegaRequest::getEmail - Returns the email of the user that receives the node * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node Node to send * @param email Email of the user that receives the node * @param listener MegaRequestListener to track this request */ public void sendFileToUser(MegaNode node, String email, MegaRequestListenerInterface listener){ megaApi.sendFileToUser(node, email, createDelegateRequestListener(listener)); } /** * Share or stop sharing a folder in MEGA with another user using a MegaUser * * To share a folder with an user, set the desired access level in the level parameter. If you * want to stop sharing a folder use the access level MegaShare::ACCESS_UNKNOWN * * The associated request type with this request is MegaRequest::TYPE_SHARE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the folder to share * - MegaRequest::getEmail - Returns the email of the user that receives the shared folder * - MegaRequest::getAccess - Returns the access that is granted to the user * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node The folder to share. It must be a non-root folder * @param user User that receives the shared folder * @param level Permissions that are granted to the user * Valid values for this parameter: * - MegaShare::ACCESS_UNKNOWN = -1 * Stop sharing a folder with this user * * - MegaShare::ACCESS_READ = 0 * - MegaShare::ACCESS_READWRITE = 1 * - MegaShare::ACCESS_FULL = 2 * - MegaShare::ACCESS_OWNER = 3 * * @param listener MegaRequestListener to track this request */ public void share(MegaNode node, MegaUser user, int level, MegaRequestListenerInterface listener) { megaApi.share(node, user, level, createDelegateRequestListener(listener)); } /** * Share or stop sharing a folder in MEGA with another user using a MegaUser * * To share a folder with an user, set the desired access level in the level parameter. If you * want to stop sharing a folder use the access level MegaShare::ACCESS_UNKNOWN * * The associated request type with this request is MegaRequest::TYPE_SHARE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the folder to share * - MegaRequest::getEmail - Returns the email of the user that receives the shared folder * - MegaRequest::getAccess - Returns the access that is granted to the user * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node The folder to share. It must be a non-root folder * @param user User that receives the shared folder * @param level Permissions that are granted to the user * Valid values for this parameter: * - MegaShare::ACCESS_UNKNOWN = -1 * Stop sharing a folder with this user * * - MegaShare::ACCESS_READ = 0 * - MegaShare::ACCESS_READWRITE = 1 * - MegaShare::ACCESS_FULL = 2 * - MegaShare::ACCESS_OWNER = 3 */ public void share(MegaNode node, MegaUser user, int level) { megaApi.share(node, user, level); } /** * Share or stop sharing a folder in MEGA with another user using his email * * To share a folder with an user, set the desired access level in the level parameter. If you * want to stop sharing a folder use the access level MegaShare::ACCESS_UNKNOWN * * The associated request type with this request is MegaRequest::TYPE_SHARE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the folder to share * - MegaRequest::getEmail - Returns the email of the user that receives the shared folder * - MegaRequest::getAccess - Returns the access that is granted to the user * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node The folder to share. It must be a non-root folder * @param email Email of the user that receives the shared folder. If it doesn't have a MEGA account, the folder will be shared anyway * and the user will be invited to register an account. * * @param level Permissions that are granted to the user * Valid values for this parameter: * - MegaShare::ACCESS_UNKNOWN = -1 * Stop sharing a folder with this user * * - MegaShare::ACCESS_READ = 0 * - MegaShare::ACCESS_READWRITE = 1 * - MegaShare::ACCESS_FULL = 2 * - MegaShare::ACCESS_OWNER = 3 * * @param listener MegaRequestListener to track this request */ public void share(MegaNode node, String email, int level, MegaRequestListenerInterface listener) { megaApi.share(node, email, level, createDelegateRequestListener(listener)); } /** * Share or stop sharing a folder in MEGA with another user using his email * * To share a folder with an user, set the desired access level in the level parameter. If you * want to stop sharing a folder use the access level MegaShare::ACCESS_UNKNOWN * * The associated request type with this request is MegaRequest::TYPE_SHARE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the folder to share * - MegaRequest::getEmail - Returns the email of the user that receives the shared folder * - MegaRequest::getAccess - Returns the access that is granted to the user * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node The folder to share. It must be a non-root folder * @param email Email of the user that receives the shared folder. If it doesn't have a MEGA account, the folder will be shared anyway * and the user will be invited to register an account. * * @param level Permissions that are granted to the user * Valid values for this parameter: * - MegaShare::ACCESS_UNKNOWN = -1 * Stop sharing a folder with this user * * - MegaShare::ACCESS_READ = 0 * - MegaShare::ACCESS_READWRITE = 1 * - MegaShare::ACCESS_FULL = 2 * - MegaShare::ACCESS_OWNER = 3 */ public void share(MegaNode node, String email, int level) { megaApi.share(node, email, level); } /** * Import a public link to the account * * The associated request type with this request is MegaRequest::TYPE_IMPORT_LINK * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getLink - Returns the public link to the file * - MegaRequest::getParentHandle - Returns the folder that receives the imported file * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodeHandle - Handle of the new node in the account * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param megaFileLink Public link to a file in MEGA * @param parent Parent folder for the imported file * @param listener MegaRequestListener to track this request */ public void importFileLink(String megaFileLink, MegaNode parent, MegaRequestListenerInterface listener) { megaApi.importFileLink(megaFileLink, parent, createDelegateRequestListener(listener)); } /** * Import a public link to the account * * The associated request type with this request is MegaRequest::TYPE_IMPORT_LINK * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getLink - Returns the public link to the file * - MegaRequest::getParentHandle - Returns the folder that receives the imported file * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodeHandle - Handle of the new node in the account * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param megaFileLink Public link to a file in MEGA * @param parent Parent folder for the imported file */ public void importFileLink(String megaFileLink, MegaNode parent) { megaApi.importFileLink(megaFileLink, parent); } /** * Decrypt password-protected public link * * The associated request type with this request is MegaRequest::TYPE_PASSWORD_LINK * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getLink - Returns the encrypted public link to the file/folder * - MegaRequest::getPassword - Returns the password to decrypt the link * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Decrypted public link * * @param link Password/protected public link to a file/folder in MEGA * @param password Password to decrypt the link * @param listener MegaRequestListenerInterface to track this request */ public void decryptPasswordProtectedLink(String link, String password, MegaRequestListenerInterface listener) { megaApi.decryptPasswordProtectedLink(link, password, createDelegateRequestListener(listener)); } /** * Decrypt password-protected public link * * The associated request type with this request is MegaRequest::TYPE_PASSWORD_LINK * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getLink - Returns the encrypted public link to the file/folder * - MegaRequest::getPassword - Returns the password to decrypt the link * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Decrypted public link * * @param link Password/protected public link to a file/folder in MEGA * @param password Password to decrypt the link */ public void decryptPasswordProtectedLink(String link, String password){ megaApi.decryptPasswordProtectedLink(link, password); } /** * Encrypt public link with password * * The associated request type with this request is MegaRequest::TYPE_PASSWORD_LINK * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getLink - Returns the public link to be encrypted * - MegaRequest::getPassword - Returns the password to encrypt the link * - MegaRequest::getFlag - Returns true * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Encrypted public link * * @param link Public link to be encrypted, including encryption key for the link * @param password Password to encrypt the link * @param listener MegaRequestListenerInterface to track this request */ public void encryptLinkWithPassword(String link, String password, MegaRequestListenerInterface listener) { megaApi.encryptLinkWithPassword(link, password, createDelegateRequestListener(listener)); } /** * Encrypt public link with password * * The associated request type with this request is MegaRequest::TYPE_PASSWORD_LINK * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getLink - Returns the public link to be encrypted * - MegaRequest::getPassword - Returns the password to encrypt the link * - MegaRequest::getFlag - Returns true * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Encrypted public link * * @param link Public link to be encrypted, including encryption key for the link * @param password Password to encrypt the link */ public void encryptLinkWithPassword(String link, String password) { megaApi.encryptLinkWithPassword(link, password); } /** * Get a MegaNode from a public link to a file * * A public node can be imported using MegaApi::copyNode or downloaded using MegaApi::startDownload * * The associated request type with this request is MegaRequest::TYPE_GET_PUBLIC_NODE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getLink - Returns the public link to the file * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getPublicMegaNode - Public MegaNode corresponding to the public link * - MegaRequest::getFlag - Return true if the provided key along the link is invalid. * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param megaFileLink Public link to a file in MEGA * @param listener MegaRequestListener to track this request */ public void getPublicNode(String megaFileLink, MegaRequestListenerInterface listener) { megaApi.getPublicNode(megaFileLink, createDelegateRequestListener(listener)); } /** * Get a MegaNode from a public link to a file * * A public node can be imported using MegaApi::copyNode or downloaded using MegaApi::startDownload * * The associated request type with this request is MegaRequest::TYPE_GET_PUBLIC_NODE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getLink - Returns the public link to the file * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getPublicMegaNode - Public MegaNode corresponding to the public link * - MegaRequest::getFlag - Return true if the provided key along the link is invalid. * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param megaFileLink Public link to a file in MEGA */ public void getPublicNode(String megaFileLink) { megaApi.getPublicNode(megaFileLink); } /** * Get the thumbnail of a node. * <p> * If the node does not have a thumbnail, the request fails with the MegaError.API_ENOENT * error code. * <p> * The associated request type with this request is MegaRequest.TYPE_GET_ATTR_FILE * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getNodeHandle() - Returns the handle of the node. <br> * - MegaRequest.getFile() - Returns the destination path. <br> * - MegaRequest.getParamType() - Returns MegaApiJava.ATTR_TYPE_THUMBNAIL. * * @param node * Node to get the thumbnail. * @param dstFilePath * Destination path for the thumbnail. * If this path is a local folder, it must end with a '\' or '/' character and (Base64-encoded handle + "0.jpg") * will be used as the file name inside that folder. If the path does not finish with * one of these characters, the file will be downloaded to a file in that path. * * @param listener * MegaRequestListener to track this request. */ public void getThumbnail(MegaNode node, String dstFilePath, MegaRequestListenerInterface listener) { megaApi.getThumbnail(node, dstFilePath, createDelegateRequestListener(listener)); } /** * Get the thumbnail of a node. * <p> * If the node does not have a thumbnail the request fails with the MegaError.API_ENOENT * error code. * * @param node * Node to get the thumbnail. * @param dstFilePath * Destination path for the thumbnail. * If this path is a local folder, it must end with a '\' or '/' character and (Base64-encoded handle + "0.jpg") * will be used as the file name inside that folder. If the path does not finish with * one of these characters, the file will be downloaded to a file in that path. */ public void getThumbnail(MegaNode node, String dstFilePath) { megaApi.getThumbnail(node, dstFilePath); } /** * Get the preview of a node. * <p> * If the node does not have a preview the request fails with the MegaError.API_ENOENT * error code. * <p> * The associated request type with this request is MegaRequest.TYPE_GET_ATTR_FILE * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getNodeHandle() - Returns the handle of the node. <br> * - MegaRequest.getFile() - Returns the destination path. <br> * - MegaRequest.getParamType() - Returns MegaApiJava.ATTR_TYPE_PREVIEW. * * @param node * Node to get the preview. * @param dstFilePath * Destination path for the preview. * If this path is a local folder, it must end with a '\' or '/' character and (Base64-encoded handle + "1.jpg") * will be used as the file name inside that folder. If the path does not finish with * one of these characters, the file will be downloaded to a file in that path. * * @param listener * MegaRequestListener to track this request. */ public void getPreview(MegaNode node, String dstFilePath, MegaRequestListenerInterface listener) { megaApi.getPreview(node, dstFilePath, createDelegateRequestListener(listener)); } /** * Get the preview of a node. * <p> * If the node does not have a preview the request fails with the MegaError.API_ENOENT * error code. * * @param node * Node to get the preview. * @param dstFilePath * Destination path for the preview. * If this path is a local folder, it must end with a '\' or '/' character and (Base64-encoded handle + "1.jpg") * will be used as the file name inside that folder. If the path does not finish with * one of these characters, the file will be downloaded to a file in that path. */ public void getPreview(MegaNode node, String dstFilePath) { megaApi.getPreview(node, dstFilePath); } /** * Get the avatar of a MegaUser. * <p> * The associated request type with this request is MegaRequest.TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getFile() - Returns the destination path. <br> * - MegaRequest.getEmail() - Returns the email of the user. * * @param user * MegaUser to get the avatar. * @param dstFilePath * Destination path for the avatar. It has to be a path to a file, not to a folder. * If this path is a local folder, it must end with a '\' or '/' character and (email + "0.jpg") * will be used as the file name inside that folder. If the path does not finish with * one of these characters, the file will be downloaded to a file in that path. * * @param listener * MegaRequestListener to track this request. */ public void getUserAvatar(MegaUser user, String dstFilePath, MegaRequestListenerInterface listener) { megaApi.getUserAvatar(user, dstFilePath, createDelegateRequestListener(listener)); } /** * Get the avatar of a MegaUser. * * @param user * MegaUser to get the avatar. * @param dstFilePath * Destination path for the avatar. It has to be a path to a file, not to a folder. * If this path is a local folder, it must end with a '\' or '/' character and (email + "0.jpg") * will be used as the file name inside that folder. If the path does not finish with * one of these characters, the file will be downloaded to a file in that path. */ public void getUserAvatar(MegaUser user, String dstFilePath) { megaApi.getUserAvatar(user, dstFilePath); } /** * Get the avatar of any user in MEGA * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getFile - Returns the destination path * - MegaRequest::getEmail - Returns the email or the handle of the user (the provided one as parameter) * * @param user email_or_user Email or user handle (Base64 encoded) to get the avatar. If this parameter is * set to null, the avatar is obtained for the active account * @param dstFilePath Destination path for the avatar. It has to be a path to a file, not to a folder. * If this path is a local folder, it must end with a '\' or '/' character and (email + "0.jpg") * will be used as the file name inside that folder. If the path doesn't finish with * one of these characters, the file will be downloaded to a file in that path. * * @param listener MegaRequestListenerInterface to track this request */ public void getUserAvatar(String email_or_handle, String dstFilePath, MegaRequestListenerInterface listener) { megaApi.getUserAvatar(email_or_handle, dstFilePath, createDelegateRequestListener(listener)); } /** * Get the avatar of any user in MEGA * * @param user email_or_user Email or user handle (Base64 encoded) to get the avatar. If this parameter is * set to null, the avatar is obtained for the active account * @param dstFilePath Destination path for the avatar. It has to be a path to a file, not to a folder. * If this path is a local folder, it must end with a '\' or '/' character and (email + "0.jpg") * will be used as the file name inside that folder. If the path doesn't finish with * one of these characters, the file will be downloaded to a file in that path. */ public void getUserAvatar(String email_or_handle, String dstFilePath) { megaApi.getUserAvatar(email_or_handle, dstFilePath); } /** * Get the avatar of the active account * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getFile - Returns the destination path * - MegaRequest::getEmail - Returns the email of the user * * @param dstFilePath Destination path for the avatar. It has to be a path to a file, not to a folder. * If this path is a local folder, it must end with a '\' or '/' character and (email + "0.jpg") * will be used as the file name inside that folder. If the path doesn't finish with * one of these characters, the file will be downloaded to a file in that path. * * @param listener MegaRequestListenerInterface to track this request */ public void getUserAvatar(String dstFilePath, MegaRequestListenerInterface listener) { megaApi.getUserAvatar(dstFilePath, createDelegateRequestListener(listener)); } /** * Get the avatar of the active account * * @param dstFilePath Destination path for the avatar. It has to be a path to a file, not to a folder. * If this path is a local folder, it must end with a '\' or '/' character and (email + "0.jpg") * will be used as the file name inside that folder. If the path doesn't finish with * one of these characters, the file will be downloaded to a file in that path. */ public void getUserAvatar(String dstFilePath) { megaApi.getUserAvatar(dstFilePath); } /** * Get the default color for the avatar. * * This color should be used only when the user doesn't have an avatar. * * You take the ownership of the returned value. * * @param user MegaUser to get the color of the avatar. If this parameter is set to NULL, the color * is obtained for the active account. * @return The RGB color as a string with 3 components in hex: #RGB. Ie. "#FF6A19" * If the user is not found, this function returns NULL. */ public String getUserAvatarColor(MegaUser user){ return megaApi.getUserAvatarColor(user); } /** * Get the default color for the avatar. * * This color should be used only when the user doesn't have an avatar. * * You take the ownership of the returned value. * * @param userhandle User handle (Base64 encoded) to get the avatar. If this parameter is * set to NULL, the avatar is obtained for the active account * @return The RGB color as a string with 3 components in hex: #RGB. Ie. "#FF6A19" * If the user is not found (invalid userhandle), this function returns NULL. */ public String getUserAvatarColor(String userhandle){ return megaApi.getUserAvatarColor(userhandle); } /** * Get an attribute of a MegaUser. * * User attributes can be private or public. Private attributes are accessible only by * your own user, while public ones are retrievable by any of your contacts. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Returns the value for public attributes * - MegaRequest::getMegaStringMap - Returns the value for private attributes * * @param user MegaUser to get the attribute. If this parameter is set to NULL, the attribute * is obtained for the active account * @param type Attribute type * * Valid values are: * * MegaApi::USER_ATTR_FIRSTNAME = 1 * Get the firstname of the user (public) * MegaApi::USER_ATTR_LASTNAME = 2 * Get the lastname of the user (public) * MegaApi::USER_ATTR_AUTHRING = 3 * Get the authentication ring of the user (private) * MegaApi::USER_ATTR_LAST_INTERACTION = 4 * Get the last interaction of the contacts of the user (private) * MegaApi::USER_ATTR_ED25519_PUBLIC_KEY = 5 * Get the public key Ed25519 of the user (public) * MegaApi::USER_ATTR_CU25519_PUBLIC_KEY = 6 * Get the public key Cu25519 of the user (public) * MegaApi::USER_ATTR_KEYRING = 7 * Get the key ring of the user: private keys for Cu25519 and Ed25519 (private) * MegaApi::USER_ATTR_SIG_RSA_PUBLIC_KEY = 8 * Get the signature of RSA public key of the user (public) * MegaApi::USER_ATTR_SIG_CU255_PUBLIC_KEY = 9 * Get the signature of Cu25519 public key of the user (public) * MegaApi::USER_ATTR_LANGUAGE = 14 * Get the preferred language of the user (private, non-encrypted) * MegaApi::USER_ATTR_PWD_REMINDER = 15 * Get the password-reminder-dialog information (private, non-encrypted) * MegaApi::USER_ATTR_DISABLE_VERSIONS = 16 * Get whether user has versions disabled or enabled (private, non-encrypted) * MegaApi::USER_ATTR_RICH_PREVIEWS = 18 * Get whether user generates rich-link messages or not (private) * MegaApi::USER_ATTR_RUBBISH_TIME = 19 * Get number of days for rubbish-bin cleaning scheduler (private non-encrypted) * MegaApi::USER_ATTR_STORAGE_STATE = 21 * Get the state of the storage (private non-encrypted) * MegaApi::USER_ATTR_GEOLOCATION = 22 * Get whether the user has enabled send geolocation messages (private) * MegaApi::USER_ATTR_PUSH_SETTINGS = 23 * Get the settings for push notifications (private non-encrypted) * * @param listener MegaRequestListener to track this request */ public void getUserAttribute(MegaUser user, int type, MegaRequestListenerInterface listener) { megaApi.getUserAttribute(user, type, createDelegateRequestListener(listener)); } /** * Get an attribute of a MegaUser. * * User attributes can be private or public. Private attributes are accessible only by * your own user, while public ones are retrievable by any of your contacts. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Returns the value for public attributes * - MegaRequest::getMegaStringMap - Returns the value for private attributes * * @param user MegaUser to get the attribute. If this parameter is set to NULL, the attribute * is obtained for the active account * @param type Attribute type * * Valid values are: * * MegaApi::USER_ATTR_FIRSTNAME = 1 * Get the firstname of the user (public) * MegaApi::USER_ATTR_LASTNAME = 2 * Get the lastname of the user (public) * MegaApi::USER_ATTR_AUTHRING = 3 * Get the authentication ring of the user (private) * MegaApi::USER_ATTR_LAST_INTERACTION = 4 * Get the last interaction of the contacts of the user (private) * MegaApi::USER_ATTR_ED25519_PUBLIC_KEY = 5 * Get the public key Ed25519 of the user (public) * MegaApi::USER_ATTR_CU25519_PUBLIC_KEY = 6 * Get the public key Cu25519 of the user (public) * MegaApi::USER_ATTR_KEYRING = 7 * Get the key ring of the user: private keys for Cu25519 and Ed25519 (private) * MegaApi::USER_ATTR_SIG_RSA_PUBLIC_KEY = 8 * Get the signature of RSA public key of the user (public) * MegaApi::USER_ATTR_SIG_CU255_PUBLIC_KEY = 9 * Get the signature of Cu25519 public key of the user (public) * MegaApi::USER_ATTR_LANGUAGE = 14 * Get the preferred language of the user (private, non-encrypted) * MegaApi::USER_ATTR_PWD_REMINDER = 15 * Get the password-reminder-dialog information (private, non-encrypted) * MegaApi::USER_ATTR_DISABLE_VERSIONS = 16 * Get whether user has versions disabled or enabled (private, non-encrypted) * MegaApi::USER_ATTR_RICH_PREVIEWS = 18 * Get whether user generates rich-link messages or not (private) * MegaApi::USER_ATTR_RUBBISH_TIME = 19 * Get number of days for rubbish-bin cleaning scheduler (private non-encrypted) * MegaApi::USER_ATTR_STORAGE_STATE = 21 * Get the state of the storage (private non-encrypted) * MegaApi::USER_ATTR_GEOLOCATION = 22 * Get whether the user has enabled send geolocation messages (private) * MegaApi::USER_ATTR_PUSH_SETTINGS = 23 * Get the settings for push notifications (private non-encrypted) */ public void getUserAttribute(MegaUser user, int type) { megaApi.getUserAttribute(user, type); } /** * Get an attribute of any user in MEGA. * * User attributes can be private or public. Private attributes are accessible only by * your own user, while public ones are retrievable by any of your contacts. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type * - MegaRequest::getEmail - Returns the email or the handle of the user (the provided one as parameter) * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Returns the value for public attributes * - MegaRequest::getMegaStringMap - Returns the value for private attributes * * @param email_or_handle Email or user handle (Base64 encoded) to get the attribute. * If this parameter is set to NULL, the attribute is obtained for the active account. * @param type Attribute type * * Valid values are: * * MegaApi::USER_ATTR_FIRSTNAME = 1 * Get the firstname of the user (public) * MegaApi::USER_ATTR_LASTNAME = 2 * Get the lastname of the user (public) * MegaApi::USER_ATTR_AUTHRING = 3 * Get the authentication ring of the user (private) * MegaApi::USER_ATTR_LAST_INTERACTION = 4 * Get the last interaction of the contacts of the user (private) * MegaApi::USER_ATTR_ED25519_PUBLIC_KEY = 5 * Get the public key Ed25519 of the user (public) * MegaApi::USER_ATTR_CU25519_PUBLIC_KEY = 6 * Get the public key Cu25519 of the user (public) * MegaApi::USER_ATTR_KEYRING = 7 * Get the key ring of the user: private keys for Cu25519 and Ed25519 (private) * MegaApi::USER_ATTR_SIG_RSA_PUBLIC_KEY = 8 * Get the signature of RSA public key of the user (public) * MegaApi::USER_ATTR_SIG_CU255_PUBLIC_KEY = 9 * Get the signature of Cu25519 public key of the user (public) * MegaApi::USER_ATTR_LANGUAGE = 14 * Get the preferred language of the user (private, non-encrypted) * MegaApi::USER_ATTR_PWD_REMINDER = 15 * Get the password-reminder-dialog information (private, non-encrypted) * MegaApi::USER_ATTR_DISABLE_VERSIONS = 16 * Get whether user has versions disabled or enabled (private, non-encrypted) * MegaApi::USER_ATTR_RUBBISH_TIME = 19 * Get number of days for rubbish-bin cleaning scheduler (private non-encrypted) * MegaApi::USER_ATTR_STORAGE_STATE = 21 * Get the state of the storage (private non-encrypted) * MegaApi::USER_ATTR_GEOLOCATION = 22 * Get whether the user has enabled send geolocation messages (private) * MegaApi::USER_ATTR_PUSH_SETTINGS = 23 * Get the settings for push notifications (private non-encrypted) * * @param listener MegaRequestListener to track this request */ public void getUserAttribute(String email_or_handle, int type, MegaRequestListenerInterface listener) { megaApi.getUserAttribute(email_or_handle, type, createDelegateRequestListener(listener)); } /** * Get an attribute of any user in MEGA. * * User attributes can be private or public. Private attributes are accessible only by * your own user, while public ones are retrievable by any of your contacts. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type * - MegaRequest::getEmail - Returns the email or the handle of the user (the provided one as parameter) * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Returns the value for public attributes * - MegaRequest::getMegaStringMap - Returns the value for private attributes * * @param email_or_handle Email or user handle (Base64 encoded) to get the attribute. * If this parameter is set to NULL, the attribute is obtained for the active account. * @param type Attribute type * * Valid values are: * * MegaApi::USER_ATTR_FIRSTNAME = 1 * Get the firstname of the user (public) * MegaApi::USER_ATTR_LASTNAME = 2 * Get the lastname of the user (public) * MegaApi::USER_ATTR_AUTHRING = 3 * Get the authentication ring of the user (private) * MegaApi::USER_ATTR_LAST_INTERACTION = 4 * Get the last interaction of the contacts of the user (private) * MegaApi::USER_ATTR_ED25519_PUBLIC_KEY = 5 * Get the public key Ed25519 of the user (public) * MegaApi::USER_ATTR_CU25519_PUBLIC_KEY = 6 * Get the public key Cu25519 of the user (public) * MegaApi::USER_ATTR_KEYRING = 7 * Get the key ring of the user: private keys for Cu25519 and Ed25519 (private) * MegaApi::USER_ATTR_SIG_RSA_PUBLIC_KEY = 8 * Get the signature of RSA public key of the user (public) * MegaApi::USER_ATTR_SIG_CU255_PUBLIC_KEY = 9 * Get the signature of Cu25519 public key of the user (public) * MegaApi::USER_ATTR_LANGUAGE = 14 * Get the preferred language of the user (private, non-encrypted) * MegaApi::USER_ATTR_PWD_REMINDER = 15 * Get the password-reminder-dialog information (private, non-encrypted) * MegaApi::USER_ATTR_DISABLE_VERSIONS = 16 * Get whether user has versions disabled or enabled (private, non-encrypted) * MegaApi::USER_ATTR_RUBBISH_TIME = 19 * Get number of days for rubbish-bin cleaning scheduler (private non-encrypted) * MegaApi::USER_ATTR_STORAGE_STATE = 21 * Get the state of the storage (private non-encrypted) * MegaApi::USER_ATTR_GEOLOCATION = 22 * Get whether the user has enabled send geolocation messages (private) * MegaApi::USER_ATTR_PUSH_SETTINGS = 23 * Get the settings for push notifications (private non-encrypted) * */ public void getUserAttribute(String email_or_handle, int type) { megaApi.getUserAttribute(email_or_handle, type); } /** * Get an attribute of the current account. * * User attributes can be private or public. Private attributes are accessible only by * your own user, while public ones are retrievable by any of your contacts. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Returns the value for public attributes * - MegaRequest::getMegaStringMap - Returns the value for private attributes * * @param type Attribute type * * Valid values are: * * MegaApi::USER_ATTR_FIRSTNAME = 1 * Get the firstname of the user (public) * MegaApi::USER_ATTR_LASTNAME = 2 * Get the lastname of the user (public) * MegaApi::USER_ATTR_AUTHRING = 3 * Get the authentication ring of the user (private) * MegaApi::USER_ATTR_LAST_INTERACTION = 4 * Get the last interaction of the contacts of the user (private) * MegaApi::USER_ATTR_ED25519_PUBLIC_KEY = 5 * Get the public key Ed25519 of the user (public) * MegaApi::USER_ATTR_CU25519_PUBLIC_KEY = 6 * Get the public key Cu25519 of the user (public) * MegaApi::USER_ATTR_KEYRING = 7 * Get the key ring of the user: private keys for Cu25519 and Ed25519 (private) * MegaApi::USER_ATTR_SIG_RSA_PUBLIC_KEY = 8 * Get the signature of RSA public key of the user (public) * MegaApi::USER_ATTR_SIG_CU255_PUBLIC_KEY = 9 * Get the signature of Cu25519 public key of the user (public) * MegaApi::USER_ATTR_LANGUAGE = 14 * Get the preferred language of the user (private, non-encrypted) * MegaApi::USER_ATTR_PWD_REMINDER = 15 * Get the password-reminder-dialog information (private, non-encrypted) * MegaApi::USER_ATTR_DISABLE_VERSIONS = 16 * Get whether user has versions disabled or enabled (private, non-encrypted) * MegaApi::USER_ATTR_RICH_PREVIEWS = 18 * Get whether user generates rich-link messages or not (private) * MegaApi::USER_ATTR_RUBBISH_TIME = 19 * Get number of days for rubbish-bin cleaning scheduler (private non-encrypted) * MegaApi::USER_ATTR_STORAGE_STATE = 21 * Get the state of the storage (private non-encrypted) * MegaApi::USER_ATTR_GEOLOCATION = 22 * Get whether the user has enabled send geolocation messages (private) * MegaApi::USER_ATTR_PUSH_SETTINGS = 23 * Get the settings for push notifications (private non-encrypted) * * @param listener MegaRequestListener to track this request */ public void getUserAttribute(int type, MegaRequestListenerInterface listener) { megaApi.getUserAttribute(type, createDelegateRequestListener(listener)); } /** * Get an attribute of the current account. * * User attributes can be private or public. Private attributes are accessible only by * your own user, while public ones are retrievable by any of your contacts. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Returns the value for public attributes * - MegaRequest::getMegaStringMap - Returns the value for private attributes * * @param type Attribute type * * Valid values are: * * MegaApi::USER_ATTR_FIRSTNAME = 1 * Get the firstname of the user (public) * MegaApi::USER_ATTR_LASTNAME = 2 * Get the lastname of the user (public) * MegaApi::USER_ATTR_AUTHRING = 3 * Get the authentication ring of the user (private) * MegaApi::USER_ATTR_LAST_INTERACTION = 4 * Get the last interaction of the contacts of the user (private) * MegaApi::USER_ATTR_ED25519_PUBLIC_KEY = 5 * Get the public key Ed25519 of the user (public) * MegaApi::USER_ATTR_CU25519_PUBLIC_KEY = 6 * Get the public key Cu25519 of the user (public) * MegaApi::USER_ATTR_KEYRING = 7 * Get the key ring of the user: private keys for Cu25519 and Ed25519 (private) * MegaApi::USER_ATTR_SIG_RSA_PUBLIC_KEY = 8 * Get the signature of RSA public key of the user (public) * MegaApi::USER_ATTR_SIG_CU255_PUBLIC_KEY = 9 * Get the signature of Cu25519 public key of the user (public) * MegaApi::USER_ATTR_LANGUAGE = 14 * Get the preferred language of the user (private, non-encrypted) * MegaApi::USER_ATTR_PWD_REMINDER = 15 * Get the password-reminder-dialog information (private, non-encrypted) * MegaApi::USER_ATTR_DISABLE_VERSIONS = 16 * Get whether user has versions disabled or enabled (private, non-encrypted) * MegaApi::USER_ATTR_RICH_PREVIEWS = 18 * Get whether user generates rich-link messages or not (private) * MegaApi::USER_ATTR_RUBBISH_TIME = 19 * Get number of days for rubbish-bin cleaning scheduler (private non-encrypted) * MegaApi::USER_ATTR_STORAGE_STATE = 21 * Get the state of the storage (private non-encrypted) * MegaApi::USER_ATTR_GEOLOCATION = 22 * Get whether the user has enabled send geolocation messages (private) * MegaApi::USER_ATTR_PUSH_SETTINGS = 23 * Get the settings for push notifications (private non-encrypted) * */ public void getUserAttribute(int type) { megaApi.getUserAttribute(type); } /** * Cancel the retrieval of a thumbnail. * <p> * The associated request type with this request is MegaRequest.TYPE_CANCEL_ATTR_FILE. * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getNodeHandle() - Returns the handle of the node. <br> * - MegaRequest.getParamType() - Returns MegaApiJava.ATTR_TYPE_THUMBNAIL. * * @param node * Node to cancel the retrieval of the thumbnail. * @param listener * MegaRequestListener to track this request. * @see #getThumbnail(MegaNode node, String dstFilePath) */ public void cancelGetThumbnail(MegaNode node, MegaRequestListenerInterface listener) { megaApi.cancelGetThumbnail(node, createDelegateRequestListener(listener)); } /** * Cancel the retrieval of a thumbnail. * * @param node * Node to cancel the retrieval of the thumbnail. * @see #getThumbnail(MegaNode node, String dstFilePath) */ public void cancelGetThumbnail(MegaNode node) { megaApi.cancelGetThumbnail(node); } /** * Cancel the retrieval of a preview. * <p> * The associated request type with this request is MegaRequest.TYPE_CANCEL_ATTR_FILE * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getNodeHandle - Returns the handle of the node. <br> * - MegaRequest.getParamType - Returns MegaApiJava.ATTR_TYPE_PREVIEW. * * @param node * Node to cancel the retrieval of the preview. * @param listener * MegaRequestListener to track this request. * @see MegaApi#getPreview(MegaNode node, String dstFilePath) */ public void cancelGetPreview(MegaNode node, MegaRequestListenerInterface listener) { megaApi.cancelGetPreview(node, createDelegateRequestListener(listener)); } /** * Cancel the retrieval of a preview. * * @param node * Node to cancel the retrieval of the preview. * @see MegaApi#getPreview(MegaNode node, String dstFilePath) */ public void cancelGetPreview(MegaNode node) { megaApi.cancelGetPreview(node); } /** * Set the thumbnail of a MegaNode. * * The associated request type with this request is MegaRequest.TYPE_SET_ATTR_FILE * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getNodeHandle() - Returns the handle of the node. <br> * - MegaRequest.getFile() - Returns the source path. <br> * - MegaRequest.getParamType() - Returns MegaApiJava.ATTR_TYPE_THUMBNAIL. * * @param node * MegaNode to set the thumbnail. * @param srcFilePath * Source path of the file that will be set as thumbnail. * @param listener * MegaRequestListener to track this request. */ public void setThumbnail(MegaNode node, String srcFilePath, MegaRequestListenerInterface listener) { megaApi.setThumbnail(node, srcFilePath, createDelegateRequestListener(listener)); } /** * Set the thumbnail of a MegaNode. * * @param node * MegaNode to set the thumbnail. * @param srcFilePath * Source path of the file that will be set as thumbnail. */ public void setThumbnail(MegaNode node, String srcFilePath) { megaApi.setThumbnail(node, srcFilePath); } /** * Set the preview of a MegaNode. * <p> * The associated request type with this request is MegaRequest.TYPE_SET_ATTR_FILE. * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getNodeHandle() - Returns the handle of the node. <br> * - MegaRequest.getFile() - Returns the source path. <br> * - MegaRequest.getParamType() - Returns MegaApiJava.ATTR_TYPE_PREVIEW. * * @param node * MegaNode to set the preview. * @param srcFilePath * Source path of the file that will be set as preview. * @param listener * MegaRequestListener to track this request. */ public void setPreview(MegaNode node, String srcFilePath, MegaRequestListenerInterface listener) { megaApi.setPreview(node, srcFilePath, createDelegateRequestListener(listener)); } /** * Set the preview of a MegaNode. * * @param node * MegaNode to set the preview. * @param srcFilePath * Source path of the file that will be set as preview. */ public void setPreview(MegaNode node, String srcFilePath) { megaApi.setPreview(node, srcFilePath); } /** * Set the avatar of the MEGA account. * <p> * The associated request type with this request is MegaRequest.TYPE_SET_ATTR_USER. * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getFile() - Returns the source path. * * @param srcFilePath * Source path of the file that will be set as avatar. * @param listener * MegaRequestListener to track this request. */ public void setAvatar(String srcFilePath, MegaRequestListenerInterface listener) { megaApi.setAvatar(srcFilePath, createDelegateRequestListener(listener)); } /** * Set the avatar of the MEGA account. * * @param srcFilePath * Source path of the file that will be set as avatar. */ public void setAvatar(String srcFilePath) { megaApi.setAvatar(srcFilePath); } /** * Set a public attribute of the current user * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type * - MegaRequest::getText - Returns the new value for the attribute * * @param type Attribute type * * Valid values are: * * MegaApi::USER_ATTR_FIRSTNAME = 1 * Set the firstname of the user (public) * MegaApi::USER_ATTR_LASTNAME = 2 * Set the lastname of the user (public) * MegaApi::USER_ATTR_ED25519_PUBLIC_KEY = 5 * Set the public key Ed25519 of the user (public) * MegaApi::USER_ATTR_CU25519_PUBLIC_KEY = 6 * Set the public key Cu25519 of the user (public) * MegaApi::USER_ATTR_RUBBISH_TIME = 19 * Set number of days for rubbish-bin cleaning scheduler (private non-encrypted) * * If the MEGA account is a sub-user business account, and the value of the parameter * type is equal to MegaApi::USER_ATTR_FIRSTNAME or MegaApi::USER_ATTR_LASTNAME * onRequestFinish will be called with the error code MegaError::API_EMASTERONLY. * * @param value New attribute value * @param listener MegaRequestListener to track this request */ public void setUserAttribute(int type, String value, MegaRequestListenerInterface listener) { megaApi.setUserAttribute(type, value, createDelegateRequestListener(listener)); } /** * Set a public attribute of the current user * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type * - MegaRequest::getText - Returns the new value for the attribute * * @param type Attribute type * * Valid values are: * * MegaApi::USER_ATTR_FIRSTNAME = 1 * Set the firstname of the user (public) * MegaApi::USER_ATTR_LASTNAME = 2 * Set the lastname of the user (public) * MegaApi::USER_ATTR_ED25519_PUBLIC_KEY = 5 * Set the public key Ed25519 of the user (public) * MegaApi::USER_ATTR_CU25519_PUBLIC_KEY = 6 * Set the public key Cu25519 of the user (public) * MegaApi::USER_ATTR_RUBBISH_TIME = 19 * Set number of days for rubbish-bin cleaning scheduler (private non-encrypted) * * If the MEGA account is a sub-user business account, and the value of the parameter * type is equal to MegaApi::USER_ATTR_FIRSTNAME or MegaApi::USER_ATTR_LASTNAME * onRequestFinish will be called with the error code MegaError::API_EMASTERONLY. * * @param value New attribute value */ public void setUserAttribute(int type, String value) { megaApi.setUserAttribute(type, value); } /** * Set a custom attribute for the node * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_NODE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node that receive the attribute * - MegaRequest::getName - Returns the name of the custom attribute * - MegaRequest::getText - Returns the text for the attribute * - MegaRequest::getFlag - Returns false (not official attribute) * * The attribute name must be an UTF8 string with between 1 and 7 bytes * If the attribute already has a value, it will be replaced * If value is NULL, the attribute will be removed from the node * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node Node that will receive the attribute * @param attrName Name of the custom attribute. * The length of this parameter must be between 1 and 7 UTF8 bytes * @param value Value for the attribute * @param listener MegaRequestListener to track this request */ public void setCustomNodeAttribute(MegaNode node, String attrName, String value, MegaRequestListenerInterface listener) { megaApi.setCustomNodeAttribute(node, attrName, value, createDelegateRequestListener(listener)); } /** * Set a custom attribute for the node * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_NODE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node that receive the attribute * - MegaRequest::getName - Returns the name of the custom attribute * - MegaRequest::getText - Returns the text for the attribute * - MegaRequest::getFlag - Returns false (not official attribute) * * The attribute name must be an UTF8 string with between 1 and 7 bytes * If the attribute already has a value, it will be replaced * If value is NULL, the attribute will be removed from the node * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node Node that will receive the attribute * @param attrName Name of the custom attribute. * The length of this parameter must be between 1 and 7 UTF8 bytes * @param value Value for the attribute */ public void setCustomNodeAttribute(MegaNode node, String attrName, String value) { megaApi.setCustomNodeAttribute(node, attrName, value); } /** * Set the GPS coordinates of image files as a node attribute. * * To remove the existing coordinates, set both the latitude and longitude to * the value MegaNode::INVALID_COORDINATE. * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_NODE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node that receive the attribute * - MegaRequest::getFlag - Returns true (official attribute) * - MegaRequest::getParamType - Returns MegaApi::NODE_ATTR_COORDINATES * - MegaRequest::getNumDetails - Returns the longitude, scaled to integer in the range of [0, 2^24] * - MegaRequest::getTransferTag() - Returns the latitude, scaled to integer in the range of [0, 2^24) * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node Node that will receive the information. * @param latitude Latitude in signed decimal degrees notation * @param longitude Longitude in signed decimal degrees notation * @param listener MegaRequestListener to track this request */ public void setNodeCoordinates(MegaNode node, double latitude, double longitude, MegaRequestListenerInterface listener){ megaApi.setNodeCoordinates(node, latitude, longitude, createDelegateRequestListener(listener)); } /** * Set node label as a node attribute. * Valid values for label attribute are: * - MegaNode::NODE_LBL_UNKNOWN = 0 * - MegaNode::NODE_LBL_RED = 1 * - MegaNode::NODE_LBL_ORANGE = 2 * - MegaNode::NODE_LBL_YELLOW = 3 * - MegaNode::NODE_LBL_GREEN = 4 * - MegaNode::NODE_LBL_BLUE = 5 * - MegaNode::NODE_LBL_PURPLE = 6 * - MegaNode::NODE_LBL_GREY = 7 * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_NODE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node that receive the attribute * - MegaRequest::getNumDetails - Returns the label for the node * - MegaRequest::getFlag - Returns true (official attribute) * - MegaRequest::getParamType - Returns MegaApi::NODE_ATTR_LABEL * * @param node Node that will receive the information. * @param label Label of the node * @param listener MegaRequestListener to track this request */ public void setNodeLabel(MegaNode node, int label, MegaRequestListenerInterface listener){ megaApi.setNodeLabel(node, label, createDelegateRequestListener(listener)); } /** * Set node label as a node attribute. * Valid values for label attribute are: * - MegaNode::NODE_LBL_UNKNOWN = 0 * - MegaNode::NODE_LBL_RED = 1 * - MegaNode::NODE_LBL_ORANGE = 2 * - MegaNode::NODE_LBL_YELLOW = 3 * - MegaNode::NODE_LBL_GREEN = 4 * - MegaNode::NODE_LBL_BLUE = 5 * - MegaNode::NODE_LBL_PURPLE = 6 * - MegaNode::NODE_LBL_GREY = 7 * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_NODE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node that receive the attribute * - MegaRequest::getNumDetails - Returns the label for the node * - MegaRequest::getFlag - Returns true (official attribute) * - MegaRequest::getParamType - Returns MegaApi::NODE_ATTR_LABEL * * @param node Node that will receive the information. * @param label Label of the node */ public void setNodeLabel(MegaNode node, int label){ megaApi.setNodeLabel(node, label); } /** * Remove node label * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_NODE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node that receive the attribute * - MegaRequest::getFlag - Returns true (official attribute) * - MegaRequest::getParamType - Returns MegaApi::NODE_ATTR_LABEL * * @param node Node that will receive the information. * @param listener MegaRequestListener to track this request */ public void resetNodeLabel(MegaNode node, MegaRequestListenerInterface listener){ megaApi.resetNodeLabel(node, createDelegateRequestListener(listener)); } /** * Remove node label * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_NODE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node that receive the attribute * - MegaRequest::getFlag - Returns true (official attribute) * - MegaRequest::getParamType - Returns MegaApi::NODE_ATTR_LABEL * * @param node Node that will receive the information. */ public void resetNodeLabel(MegaNode node){ megaApi.resetNodeLabel(node); } /** * Set node favourite as a node attribute. * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_NODE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node that receive the attribute * - MegaRequest::getNumDetails - Returns 1 if node is set as favourite, otherwise return 0 * - MegaRequest::getFlag - Returns true (official attribute) * - MegaRequest::getParamType - Returns MegaApi::NODE_ATTR_FAV * * @param node Node that will receive the information. * @param favourite if true set node as favourite, otherwise remove the attribute * @param listener MegaRequestListener to track this request */ public void setNodeFavourite(MegaNode node, boolean favourite, MegaRequestListenerInterface listener){ megaApi.setNodeFavourite(node, favourite, createDelegateRequestListener(listener)); } /** * Set node favourite as a node attribute. * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_NODE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node that receive the attribute * - MegaRequest::getNumDetails - Returns 1 if node is set as favourite, otherwise return 0 * - MegaRequest::getFlag - Returns true (official attribute) * - MegaRequest::getParamType - Returns MegaApi::NODE_ATTR_FAV * * @param node Node that will receive the information. * @param favourite if true set node as favourite, otherwise remove the attribute */ public void setNodeFavourite(MegaNode node, boolean favourite){ megaApi.setNodeFavourite(node, favourite); } /** * Generate a public link of a file/folder in MEGA * * The associated request type with this request is MegaRequest::TYPE_EXPORT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node * - MegaRequest::getAccess - Returns true * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getLink - Public link * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node MegaNode to get the public link * @param listener MegaRequestListener to track this request */ public void exportNode(MegaNode node, MegaRequestListenerInterface listener) { megaApi.exportNode(node, createDelegateRequestListener(listener)); } /** * Generate a public link of a file/folder in MEGA * * The associated request type with this request is MegaRequest::TYPE_EXPORT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node * - MegaRequest::getAccess - Returns true * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getLink - Public link * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node MegaNode to get the public link */ public void exportNode(MegaNode node) { megaApi.exportNode(node); } /** * Generate a temporary public link of a file/folder in MEGA * * The associated request type with this request is MegaRequest::TYPE_EXPORT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node * - MegaRequest::getAccess - Returns true * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getLink - Public link * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node MegaNode to get the public link * @param expireTime Unix timestamp until the public link will be valid * @param listener MegaRequestListener to track this request * * A Unix timestamp represents the number of seconds since 00:00 hours, Jan 1, 1970 UTC */ public void exportNode(MegaNode node, int expireTime, MegaRequestListenerInterface listener) { megaApi.exportNode(node, expireTime, createDelegateRequestListener(listener)); } /** * Generate a temporary public link of a file/folder in MEGA * * The associated request type with this request is MegaRequest::TYPE_EXPORT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node * - MegaRequest::getAccess - Returns true * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getLink - Public link * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node MegaNode to get the public link * @param expireTime Unix timestamp until the public link will be valid * * A Unix timestamp represents the number of seconds since 00:00 hours, Jan 1, 1970 UTC */ public void exportNode(MegaNode node, int expireTime) { megaApi.exportNode(node, expireTime); } /** * Stop sharing a file/folder * * The associated request type with this request is MegaRequest::TYPE_EXPORT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node * - MegaRequest::getAccess - Returns false * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node MegaNode to stop sharing * @param listener MegaRequestListener to track this request */ public void disableExport(MegaNode node, MegaRequestListenerInterface listener) { megaApi.disableExport(node, createDelegateRequestListener(listener)); } /** * Stop sharing a file/folder * * The associated request type with this request is MegaRequest::TYPE_EXPORT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node * - MegaRequest::getAccess - Returns false * * If the MEGA account is a business account and it's status is expired, onRequestFinish will * be called with the error code MegaError::API_EBUSINESSPASTDUE. * * @param node MegaNode to stop sharing */ public void disableExport(MegaNode node) { megaApi.disableExport(node); } /** * Fetch the filesystem in MEGA. * <p> * The MegaApi object must be logged in in an account or a public folder * to successfully complete this request. * <p> * The associated request type with this request is MegaRequest.TYPE_FETCH_NODES. * * @param listener * MegaRequestListener to track this request. */ public void fetchNodes(MegaRequestListenerInterface listener) { megaApi.fetchNodes(createDelegateRequestListener(listener)); } /** * Fetch the filesystem in MEGA. * <p> * The MegaApi object must be logged in in an account or a public folder * to successfully complete this request. */ public void fetchNodes() { megaApi.fetchNodes(); } /** * Get details about the MEGA account * * Only basic data will be available. If you can get more data (sessions, transactions, purchases), * use MegaApi::getExtendedAccountDetails. * * The associated request type with this request is MegaRequest::TYPE_ACCOUNT_DETAILS * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaAccountDetails - Details of the MEGA account * - MegaRequest::getNumDetails - Requested flags * * The available flags are: * - storage quota: (numDetails & 0x01) * - transfer quota: (numDetails & 0x02) * - pro level: (numDetails & 0x04) * * @param listener MegaRequestListener to track this request */ public void getAccountDetails(MegaRequestListenerInterface listener) { megaApi.getAccountDetails(createDelegateRequestListener(listener)); } /** * Get details about the MEGA account * * Only basic data will be available. If you can get more data (sessions, transactions, purchases), * use MegaApi::getExtendedAccountDetails. * * The associated request type with this request is MegaRequest::TYPE_ACCOUNT_DETAILS * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaAccountDetails - Details of the MEGA account * - MegaRequest::getNumDetails - Requested flags * * The available flags are: * - storage quota: (numDetails & 0x01) * - transfer quota: (numDetails & 0x02) * - pro level: (numDetails & 0x04) */ public void getAccountDetails() { megaApi.getAccountDetails(); } /** * Get details about the MEGA account * * Only basic data will be available. If you need more data (sessions, transactions, purchases), * use MegaApi::getExtendedAccountDetails. * * The associated request type with this request is MegaRequest::TYPE_ACCOUNT_DETAILS * * Use this version of the function to get just the details you need, to minimise server load * and keep the system highly available for all. At least one flag must be set. * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaAccountDetails - Details of the MEGA account * - MegaRequest::getNumDetails - Requested flags * * The available flags are: * - storage quota: (numDetails & 0x01) * - transfer quota: (numDetails & 0x02) * - pro level: (numDetails & 0x04) * * In case none of the flags are set, the associated request will fail with error MegaError::API_EARGS. * * @param storage If true, account storage details are requested * @param transfer If true, account transfer details are requested * @param pro If true, pro level of account is requested * @param listener MegaRequestListener to track this request */ public void getSpecificAccountDetails(boolean storage, boolean transfer, boolean pro, MegaRequestListenerInterface listener) { megaApi.getSpecificAccountDetails(storage, transfer, pro, -1, createDelegateRequestListener(listener)); } /** * Get details about the MEGA account * * Only basic data will be available. If you need more data (sessions, transactions, purchases), * use MegaApi::getExtendedAccountDetails. * * The associated request type with this request is MegaRequest::TYPE_ACCOUNT_DETAILS * * Use this version of the function to get just the details you need, to minimise server load * and keep the system highly available for all. At least one flag must be set. * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaAccountDetails - Details of the MEGA account * - MegaRequest::getNumDetails - Requested flags * * The available flags are: * - storage quota: (numDetails & 0x01) * - transfer quota: (numDetails & 0x02) * - pro level: (numDetails & 0x04) * * In case none of the flags are set, the associated request will fail with error MegaError::API_EARGS. * * @param storage If true, account storage details are requested * @param transfer If true, account transfer details are requested * @param pro If true, pro level of account is requested */ public void getSpecificAccountDetails(boolean storage, boolean transfer, boolean pro) { megaApi.getSpecificAccountDetails(storage, transfer, pro, -1); } /** * Get details about the MEGA account * * This function allows to optionally get data about sessions, transactions and purchases related to the account. * * The associated request type with this request is MegaRequest::TYPE_ACCOUNT_DETAILS * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaAccountDetails - Details of the MEGA account * - MegaRequest::getNumDetails - Requested flags * * The available flags are: * - transactions: (numDetails & 0x08) * - purchases: (numDetails & 0x10) * - sessions: (numDetails & 0x020) * * In case none of the flags are set, the associated request will fail with error MegaError::API_EARGS. * * @param sessions If true, sessions are requested * @param purchases If true, purchases are requested * @param transactions If true, transactions are requested * @param listener MegaRequestListener to track this request */ public void getExtendedAccountDetails(boolean sessions, boolean purchases, boolean transactions, MegaRequestListenerInterface listener) { megaApi.getExtendedAccountDetails(sessions, purchases, transactions, createDelegateRequestListener(listener)); } /** * Get details about the MEGA account * * This function allows to optionally get data about sessions, transactions and purchases related to the account. * * The associated request type with this request is MegaRequest::TYPE_ACCOUNT_DETAILS * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaAccountDetails - Details of the MEGA account * - MegaRequest::getNumDetails - Requested flags * * The available flags are: * - transactions: (numDetails & 0x08) * - purchases: (numDetails & 0x10) * - sessions: (numDetails & 0x020) * * In case none of the flags are set, the associated request will fail with error MegaError::API_EARGS. * * @param sessions If true, sessions are requested * @param purchases If true, purchases are requested * @param transactions If true, transactions are requested */ public void getExtendedAccountDetails(boolean sessions, boolean purchases, boolean transactions) { megaApi.getExtendedAccountDetails(sessions, purchases, transactions); } /** * Get the available pricing plans to upgrade a MEGA account. * <p> * The associated request type with this request is MegaRequest.TYPE_GET_PRICING. * <p> * Valid data in the MegaRequest object received in onRequestFinish() when the error code * is MegaError.API_OK: <br> * - MegaRequest.getPricing() - MegaPricing object with all pricing plans. * * @param listener * MegaRequestListener to track this request. */ public void getPricing(MegaRequestListenerInterface listener) { megaApi.getPricing(createDelegateRequestListener(listener)); } /** * Get the available pricing plans to upgrade a MEGA account. */ public void getPricing() { megaApi.getPricing(); } /** * Get the payment URL for an upgrade * * The associated request type with this request is MegaRequest::TYPE_GET_PAYMENT_ID * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the product * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getLink - Payment ID * * @param productHandle Handle of the product (see MegaApi::getPricing) * @param listener MegaRequestListener to track this request * * @see MegaApi::getPricing */ public void getPaymentId(long productHandle, MegaRequestListenerInterface listener) { megaApi.getPaymentId(productHandle, createDelegateRequestListener(listener)); } /** * Get the payment URL for an upgrade * * The associated request type with this request is MegaRequest::TYPE_GET_PAYMENT_ID * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the product * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getLink - Payment ID * * @param productHandle Handle of the product (see MegaApi::getPricing) * * @see MegaApi::getPricing */ public void getPaymentId(long productHandle) { megaApi.getPaymentId(productHandle); } /** * Get the payment URL for an upgrade * * The associated request type with this request is MegaRequest::TYPE_GET_PAYMENT_ID * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the product * - MegaRequest::getParentHandle - Returns the last public node handle accessed * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getLink - Payment ID * * @param productHandle Handle of the product (see MegaApi::getPricing) * @param lastPublicHandle Last public node handle accessed by the user in the last 24h * @param listener MegaRequestListener to track this request * * @see MegaApi::getPricing */ public void getPaymentId(long productHandle, long lastPublicHandle, MegaRequestListenerInterface listener) { megaApi.getPaymentId(productHandle, lastPublicHandle, createDelegateRequestListener(listener)); } /** * Get the payment URL for an upgrade * * The associated request type with this request is MegaRequest::TYPE_GET_PAYMENT_ID * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the product * - MegaRequest::getParentHandle - Returns the last public node handle accessed * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getLink - Payment ID * * @param productHandle Handle of the product (see MegaApi::getPricing) * @param lastPublicHandle Last public node handle accessed by the user in the last 24h * * @see MegaApi::getPricing */ public void getPaymentId(long productHandle, long lastPublicHandle) { megaApi.getPaymentId(productHandle, lastPublicHandle); } /** * Get the payment URL for an upgrade * * The associated request type with this request is MegaRequest::TYPE_GET_PAYMENT_ID * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the product * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getLink - Payment ID * - MegaRequest::getParentHandle - Returns the last public node handle accessed * - MegaRequest::getParamType - Returns the type of lastPublicHandle * - MegaRequest::getTransferredBytes - Returns the timestamp of the last access * * @param productHandle Handle of the product (see MegaApi::getPricing) * @param lastPublicHandle Last public node handle accessed by the user in the last 24h * @param lastPublicHandleType Indicates the type of lastPublicHandle, valid values are: * - MegaApi::AFFILIATE_TYPE_ID = 1 * - MegaApi::AFFILIATE_TYPE_FILE_FOLDER = 2 * - MegaApi::AFFILIATE_TYPE_CHAT = 3 * - MegaApi::AFFILIATE_TYPE_CONTACT = 4 * * @param lastAccessTimestamp Timestamp of the last access * @param listener MegaRequestListener to track this request * @see MegaApi::getPricing */ public void getPaymentId(long productHandle, long lastPublicHandle, int lastPublicHandleType, long lastAccessTimestamp, MegaRequestListenerInterface listener) { megaApi.getPaymentId(productHandle, lastPublicHandle, lastPublicHandleType, lastAccessTimestamp, createDelegateRequestListener(listener)); } /** * Get the payment URL for an upgrade * * The associated request type with this request is MegaRequest::TYPE_GET_PAYMENT_ID * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the product * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getLink - Payment ID * - MegaRequest::getParentHandle - Returns the last public node handle accessed * - MegaRequest::getParamType - Returns the type of lastPublicHandle * - MegaRequest::getTransferredBytes - Returns the timestamp of the last access * * @param productHandle Handle of the product (see MegaApi::getPricing) * @param lastPublicHandle Last public node handle accessed by the user in the last 24h * @param lastPublicHandleType Indicates the type of lastPublicHandle, valid values are: * - MegaApi::AFFILIATE_TYPE_ID = 1 * - MegaApi::AFFILIATE_TYPE_FILE_FOLDER = 2 * - MegaApi::AFFILIATE_TYPE_CHAT = 3 * - MegaApi::AFFILIATE_TYPE_CONTACT = 4 * * @param lastAccessTimestamp Timestamp of the last access * @see MegaApi::getPricing */ public void getPaymentId(long productHandle, long lastPublicHandle, int lastPublicHandleType, long lastAccessTimestamp) { megaApi.getPaymentId(productHandle, lastPublicHandle, lastPublicHandleType, lastAccessTimestamp); } /** * Upgrade an account. * * @param productHandle Product handle to purchase. * It is possible to get all pricing plans with their product handles using * MegaApi.getPricing(). * * The associated request type with this request is MegaRequest.TYPE_UPGRADE_ACCOUNT. * * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getNodeHandle() - Returns the handle of the product. <br> * - MegaRequest.getNumber() - Returns the payment method. * * @param paymentMethod Payment method. * Valid values are: <br> * - MegaApi.PAYMENT_METHOD_BALANCE = 0. * Use the account balance for the payment. <br> * * - MegaApi.PAYMENT_METHOD_CREDIT_CARD = 8. * Complete the payment with your credit card. Use MegaApi.creditCardStore to add * a credit card to your account. * * @param listener MegaRequestListener to track this request. */ public void upgradeAccount(long productHandle, int paymentMethod, MegaRequestListenerInterface listener) { megaApi.upgradeAccount(productHandle, paymentMethod, createDelegateRequestListener(listener)); } /** * Upgrade an account. * * @param productHandle Product handle to purchase. * It is possible to get all pricing plans with their product handles using * MegaApi.getPricing(). * * @param paymentMethod Payment method. * Valid values are: <br> * - MegaApi.PAYMENT_METHOD_BALANCE = 0. * Use the account balance for the payment. <br> * * - MegaApi.PAYMENT_METHOD_CREDIT_CARD = 8. * Complete the payment with your credit card. Use MegaApi.creditCardStore() to add * a credit card to your account. */ public void upgradeAccount(long productHandle, int paymentMethod) { megaApi.upgradeAccount(productHandle, paymentMethod); } /** * Submit a purchase receipt for verification * * The associated request type with this request is MegaRequest::TYPE_SUBMIT_PURCHASE_RECEIPT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNumber - Returns the payment gateway * - MegaRequest::getText - Returns the purchase receipt * * @param gateway Payment gateway * Currently supported payment gateways are: * - MegaApi::PAYMENT_METHOD_ITUNES = 2 * - MegaApi::PAYMENT_METHOD_GOOGLE_WALLET = 3 * - MegaApi::PAYMENT_METHOD_WINDOWS_STORE = 13 * * @param receipt Purchase receipt * @param listener MegaRequestListener to track this request */ public void submitPurchaseReceipt(int gateway, String receipt, MegaRequestListenerInterface listener) { megaApi.submitPurchaseReceipt(gateway, receipt, createDelegateRequestListener(listener)); } /** * Submit a purchase receipt for verification * * The associated request type with this request is MegaRequest::TYPE_SUBMIT_PURCHASE_RECEIPT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNumber - Returns the payment gateway * - MegaRequest::getText - Returns the purchase receipt * * @param gateway Payment gateway * Currently supported payment gateways are: * - MegaApi::PAYMENT_METHOD_ITUNES = 2 * - MegaApi::PAYMENT_METHOD_GOOGLE_WALLET = 3 * - MegaApi::PAYMENT_METHOD_WINDOWS_STORE = 13 * * @param receipt Purchase receipt */ public void submitPurchaseReceipt(int gateway, String receipt) { megaApi.submitPurchaseReceipt(gateway, receipt); } /** * Submit a purchase receipt for verification * * The associated request type with this request is MegaRequest::TYPE_SUBMIT_PURCHASE_RECEIPT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNumber - Returns the payment gateway * - MegaRequest::getText - Returns the purchase receipt * - MegaRequest::getParentHandle - Returns the last public node handle accessed * * @param gateway Payment gateway * Currently supported payment gateways are: * - MegaApi::PAYMENT_METHOD_ITUNES = 2 * - MegaApi::PAYMENT_METHOD_GOOGLE_WALLET = 3 * - MegaApi::PAYMENT_METHOD_WINDOWS_STORE = 13 * * @param receipt Purchase receipt * @param lastPublicHandle Last public node handle accessed by the user in the last 24h * @param listener MegaRequestListener to track this request */ public void submitPurchaseReceipt(int gateway, String receipt, long lastPublicHandle, MegaRequestListenerInterface listener) { megaApi.submitPurchaseReceipt(gateway, receipt, lastPublicHandle, createDelegateRequestListener(listener)); } /** * Submit a purchase receipt for verification * * The associated request type with this request is MegaRequest::TYPE_SUBMIT_PURCHASE_RECEIPT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNumber - Returns the payment gateway * - MegaRequest::getText - Returns the purchase receipt * - MegaRequest::getParentHandle - Returns the last public node handle accessed * * @param gateway Payment gateway * Currently supported payment gateways are: * - MegaApi::PAYMENT_METHOD_ITUNES = 2 * - MegaApi::PAYMENT_METHOD_GOOGLE_WALLET = 3 * - MegaApi::PAYMENT_METHOD_WINDOWS_STORE = 13 * * @param receipt Purchase receipt * @param lastPublicHandle Last public node handle accessed by the user in the last 24h */ public void submitPurchaseReceipt(int gateway, String receipt, long lastPublicHandle) { megaApi.submitPurchaseReceipt(gateway, receipt, lastPublicHandle); } /** * Submit a purchase receipt for verification * * The associated request type with this request is MegaRequest::TYPE_SUBMIT_PURCHASE_RECEIPT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNumber - Returns the payment gateway * - MegaRequest::getText - Returns the purchase receipt * - MegaRequest::getParentHandle - Returns the last public node handle accessed * - MegaRequest::getParamType - Returns the type of lastPublicHandle * - MegaRequest::getTransferredBytes - Returns the timestamp of the last access * * @param gateway Payment gateway * Currently supported payment gateways are: * - MegaApi::PAYMENT_METHOD_ITUNES = 2 * - MegaApi::PAYMENT_METHOD_GOOGLE_WALLET = 3 * - MegaApi::PAYMENT_METHOD_WINDOWS_STORE = 13 * * @param receipt Purchase receipt * @param lastPublicHandle Last public node handle accessed by the user in the last 24h * @param lastPublicHandleType Indicates the type of lastPublicHandle, valid values are: * - MegaApi::AFFILIATE_TYPE_ID = 1 * - MegaApi::AFFILIATE_TYPE_FILE_FOLDER = 2 * - MegaApi::AFFILIATE_TYPE_CHAT = 3 * - MegaApi::AFFILIATE_TYPE_CONTACT = 4 * * @param lastAccessTimestamp Timestamp of the last access * @param listener MegaRequestListener to track this request */ public void submitPurchaseReceipt(int gateway, String receipt, long lastPublicHandle, int lastPublicHandleType, long lastAccessTimestamp, MegaRequestListenerInterface listener) { megaApi.submitPurchaseReceipt(gateway, receipt, lastPublicHandle, lastPublicHandleType, lastAccessTimestamp, createDelegateRequestListener(listener)); } /** * Submit a purchase receipt for verification * * The associated request type with this request is MegaRequest::TYPE_SUBMIT_PURCHASE_RECEIPT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNumber - Returns the payment gateway * - MegaRequest::getText - Returns the purchase receipt * - MegaRequest::getParentHandle - Returns the last public node handle accessed * - MegaRequest::getParamType - Returns the type of lastPublicHandle * - MegaRequest::getTransferredBytes - Returns the timestamp of the last access * * @param gateway Payment gateway * Currently supported payment gateways are: * - MegaApi::PAYMENT_METHOD_ITUNES = 2 * - MegaApi::PAYMENT_METHOD_GOOGLE_WALLET = 3 * - MegaApi::PAYMENT_METHOD_WINDOWS_STORE = 13 * * @param receipt Purchase receipt * @param lastPublicHandle Last public node handle accessed by the user in the last 24h * @param lastPublicHandleType Indicates the type of lastPublicHandle, valid values are: * - MegaApi::AFFILIATE_TYPE_ID = 1 * - MegaApi::AFFILIATE_TYPE_FILE_FOLDER = 2 * - MegaApi::AFFILIATE_TYPE_CHAT = 3 * - MegaApi::AFFILIATE_TYPE_CONTACT = 4 * * @param lastAccessTimestamp Timestamp of the last access */ public void submitPurchaseReceipt(int gateway, String receipt, long lastPublicHandle, int lastPublicHandleType, long lastAccessTimestamp) { megaApi.submitPurchaseReceipt(gateway, receipt, lastPublicHandle, lastPublicHandleType, lastAccessTimestamp); } /** * Store a credit card. * <p> * The associated request type with this request is MegaRequest.TYPE_CREDIT_CARD_STORE. * * @param address1 Billing address. * @param address2 Second line of the billing address (optional). * @param city City of the billing address. * @param province Province of the billing address. * @param country Country of the billing address. * @param postalcode Postal code of the billing address. * @param firstname Firstname of the owner of the credit card. * @param lastname Lastname of the owner of the credit card. * @param creditcard Credit card number. Only digits, no spaces nor dashes. * @param expire_month Expire month of the credit card. Must have two digits ("03" for example). * @param expire_year Expire year of the credit card. Must have four digits ("2010" for example). * @param cv2 Security code of the credit card (3 digits). * @param listener MegaRequestListener to track this request. */ public void creditCardStore(String address1, String address2, String city, String province, String country, String postalcode, String firstname, String lastname, String creditcard, String expire_month, String expire_year, String cv2, MegaRequestListenerInterface listener) { megaApi.creditCardStore(address1, address2, city, province, country, postalcode, firstname, lastname, creditcard, expire_month, expire_year, cv2, createDelegateRequestListener(listener)); } /** * Store a credit card. * * @param address1 Billing address. * @param address2 Second line of the billing address (optional). * @param city City of the billing address. * @param province Province of the billing address. * @param country Country of the billing address. * @param postalcode Postal code of the billing address. * @param firstname Firstname of the owner of the credit card. * @param lastname Lastname of the owner of the credit card. * @param creditcard Credit card number. Only digits, no spaces nor dashes. * @param expire_month Expire month of the credit card. Must have two digits ("03" for example). * @param expire_year Expire year of the credit card. Must have four digits ("2010" for example). * @param cv2 Security code of the credit card (3 digits). */ public void creditCardStore(String address1, String address2, String city, String province, String country, String postalcode, String firstname, String lastname, String creditcard, String expire_month, String expire_year, String cv2) { megaApi.creditCardStore(address1, address2, city, province, country, postalcode, firstname, lastname, creditcard, expire_month, expire_year, cv2); } /** * Get the credit card subscriptions of the account. * <p> * The associated request type with this request is MegaRequest.TYPE_CREDIT_CARD_QUERY_SUBSCRIPTIONS. * <p> * Valid data in the MegaRequest object received in onRequestFinish() when the error code * is MegaError.API_OK: <br> * - MegaRequest.getNumber() - Number of credit card subscriptions. * * @param listener MegaRequestListener to track this request. */ public void creditCardQuerySubscriptions(MegaRequestListenerInterface listener) { megaApi.creditCardQuerySubscriptions(createDelegateRequestListener(listener)); } /** * Get the credit card subscriptions of the account. * */ public void creditCardQuerySubscriptions() { megaApi.creditCardQuerySubscriptions(); } /** * Cancel credit card subscriptions of the account. * <p> * The associated request type with this request is MegaRequest.TYPE_CREDIT_CARD_CANCEL_SUBSCRIPTIONS. * * @param reason Reason for the cancellation. It can be null. * @param listener MegaRequestListener to track this request. */ public void creditCardCancelSubscriptions(String reason, MegaRequestListenerInterface listener) { megaApi.creditCardCancelSubscriptions(reason, createDelegateRequestListener(listener)); } /** * Cancel credit card subscriptions of the account. * * @param reason Reason for the cancellation. It can be null. * */ public void creditCardCancelSubscriptions(String reason) { megaApi.creditCardCancelSubscriptions(reason); } /** * Get the available payment methods. * <p> * The associated request type with this request is MegaRequest.TYPE_GET_PAYMENT_METHODS. * <p> * Valid data in the MegaRequest object received in onRequestFinish() when the error code * is MegaError.API_OK: <br> * - MegaRequest.getNumber() - Bitfield with available payment methods. * * To identify if a payment method is available, the following check can be performed: <br> * (request.getNumber() & (1 << MegaApiJava.PAYMENT_METHOD_CREDIT_CARD) != 0). * * @param listener MegaRequestListener to track this request. */ public void getPaymentMethods(MegaRequestListenerInterface listener) { megaApi.getPaymentMethods(createDelegateRequestListener(listener)); } /** * Get the available payment methods. */ public void getPaymentMethods() { megaApi.getPaymentMethods(); } /** * Export the master key of the account. * <p> * The returned value is a Base64-encoded string. * <p> * With the master key, it's possible to start the recovery of an account when the * password is lost: <br> * - https://mega.co.nz/#recovery. * * @return Base64-encoded master key. */ public String exportMasterKey() { return megaApi.exportMasterKey(); } /** * Notify the user has exported the master key * * This function should be called when the user exports the master key by * clicking on "Copy" or "Save file" options. * * As result, the user attribute MegaApi::USER_ATTR_PWD_REMINDER will be updated * to remember the user has a backup of his/her master key. In consequence, * MEGA will not ask the user to remind the password for the account. * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_PWD_REMINDER * - MegaRequest::getText - Returns the new value for the attribute * * @param listener MegaRequestListener to track this request */ public void masterKeyExported(MegaRequestListenerInterface listener){ megaApi.masterKeyExported(createDelegateRequestListener(listener)); } /** * Check if the master key has been exported * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_PWD_REMINDER * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getAccess - Returns true if the master key has been exported * * If the corresponding user attribute is not set yet, the request will fail with the * error code MegaError::API_ENOENT. * * @param listener MegaRequestListener to track this request */ public void isMasterKeyExported (MegaRequestListenerInterface listener) { megaApi.isMasterKeyExported(createDelegateRequestListener(listener)); } /** * Notify the user has successfully checked his password * * This function should be called when the user demonstrates that he remembers * the password to access the account * * As result, the user attribute MegaApi::USER_ATTR_PWD_REMINDER will be updated * to remember this event. In consequence, MEGA will not continue asking the user * to remind the password for the account in a short time. * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_PWD_REMINDER * - MegaRequest::getText - Returns the new value for the attribute * * @param listener MegaRequestListener to track this request */ public void passwordReminderDialogSucceeded(MegaRequestListenerInterface listener){ megaApi.passwordReminderDialogSucceeded(createDelegateRequestListener(listener)); } /** * Notify the user has successfully skipped the password check * * This function should be called when the user skips the verification of * the password to access the account * * As result, the user attribute MegaApi::USER_ATTR_PWD_REMINDER will be updated * to remember this event. In consequence, MEGA will not continue asking the user * to remind the password for the account in a short time. * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_PWD_REMINDER * - MegaRequest::getText - Returns the new value for the attribute * * @param listener MegaRequestListener to track this request */ public void passwordReminderDialogSkipped(MegaRequestListenerInterface listener){ megaApi.passwordReminderDialogSkipped(createDelegateRequestListener(listener)); } /** * Notify the user wants to totally disable the password check * * This function should be called when the user rejects to verify that he remembers * the password to access the account and doesn't want to see the reminder again. * * As result, the user attribute MegaApi::USER_ATTR_PWD_REMINDER will be updated * to remember this event. In consequence, MEGA will not ask the user * to remind the password for the account again. * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_PWD_REMINDER * - MegaRequest::getText - Returns the new value for the attribute * * @param listener MegaRequestListener to track this request */ public void passwordReminderDialogBlocked(MegaRequestListenerInterface listener){ megaApi.passwordReminderDialogBlocked(createDelegateRequestListener(listener)); } /** * Check if the app should show the password reminder dialog to the user * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_PWD_REMINDER * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getFlag - Returns true if the password reminder dialog should be shown * * @param atLogout True if the check is being done just before a logout * @param listener MegaRequestListener to track this request */ public void shouldShowPasswordReminderDialog(boolean atLogout, MegaRequestListenerInterface listener){ megaApi.shouldShowPasswordReminderDialog(atLogout, createDelegateRequestListener(listener)); } /** * Enable or disable the generation of rich previews * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_RICH_PREVIEWS * * @param enable True to enable the generation of rich previews * @param listener MegaRequestListener to track this request */ public void enableRichPreviews(boolean enable, MegaRequestListenerInterface listener){ megaApi.enableRichPreviews(enable, createDelegateRequestListener(listener)); } /** * Enable or disable the generation of rich previews * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_RICH_PREVIEWS * * @param enable True to enable the generation of rich previews */ public void enableRichPreviews(boolean enable){ megaApi.enableRichPreviews(enable); } /** * Check if rich previews are automatically generated * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_RICH_PREVIEWS * - MegaRequest::getNumDetails - Returns zero * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getFlag - Returns true if generation of rich previews is enabled * - MegaRequest::getMegaStringMap - Returns the raw content of the atribute: [<key><value>]* * * If the corresponding user attribute is not set yet, the request will fail with the * error code MegaError::API_ENOENT, but the value of MegaRequest::getFlag will still be valid (false). * * @param listener MegaRequestListener to track this request */ public void isRichPreviewsEnabled(MegaRequestListenerInterface listener){ megaApi.isRichPreviewsEnabled(createDelegateRequestListener(listener)); } /** * Check if rich previews are automatically generated * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_RICH_PREVIEWS * - MegaRequest::getNumDetails - Returns zero * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getFlag - Returns true if generation of rich previews is enabled * - MegaRequest::getMegaStringMap - Returns the raw content of the atribute: [<key><value>]* * * If the corresponding user attribute is not set yet, the request will fail with the * error code MegaError::API_ENOENT, but the value of MegaRequest::getFlag will still be valid (false). * */ public void isRichPreviewsEnabled(){ megaApi.isRichPreviewsEnabled(); } /** * Check if the app should show the rich link warning dialog to the user * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_RICH_PREVIEWS * - MegaRequest::getNumDetails - Returns one * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getFlag - Returns true if it is necessary to show the rich link warning * - MegaRequest::getNumber - Returns the number of times that user has indicated that doesn't want * modify the message with a rich link. If number is bigger than three, the extra option "Never" * must be added to the warning dialog. * - MegaRequest::getMegaStringMap - Returns the raw content of the atribute: [<key><value>]* * * If the corresponding user attribute is not set yet, the request will fail with the * error code MegaError::API_ENOENT, but the value of MegaRequest::getFlag will still be valid (true). * * @param listener MegaRequestListener to track this request */ public void shouldShowRichLinkWarning(MegaRequestListenerInterface listener){ megaApi.shouldShowRichLinkWarning(createDelegateRequestListener(listener)); } /** * Check if the app should show the rich link warning dialog to the user * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_RICH_PREVIEWS * - MegaRequest::getNumDetails - Returns one * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getFlag - Returns true if it is necessary to show the rich link warning * - MegaRequest::getNumber - Returns the number of times that user has indicated that doesn't want * modify the message with a rich link. If number is bigger than three, the extra option "Never" * must be added to the warning dialog. * - MegaRequest::getMegaStringMap - Returns the raw content of the atribute: [<key><value>]* * * If the corresponding user attribute is not set yet, the request will fail with the * error code MegaError::API_ENOENT, but the value of MegaRequest::getFlag will still be valid (true). * */ public void shouldShowRichLinkWarning(){ megaApi.shouldShowRichLinkWarning(); } /** * Set the number of times "Not now" option has been selected in the rich link warning dialog * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_RICH_PREVIEWS * * @param value Number of times "Not now" option has been selected * @param listener MegaRequestListener to track this request */ public void setRichLinkWarningCounterValue(int value, MegaRequestListenerInterface listener){ megaApi.setRichLinkWarningCounterValue(value, createDelegateRequestListener(listener)); } /** * Set the number of times "Not now" option has been selected in the rich link warning dialog * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_RICH_PREVIEWS * * @param value Number of times "Not now" option has been selected */ public void setRichLinkWarningCounterValue(int value){ megaApi.setRichLinkWarningCounterValue(value); } /** * Enable the sending of geolocation messages * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_GEOLOCATION * * @param listener MegaRequestListener to track this request */ public void enableGeolocation(MegaRequestListenerInterface listener){ megaApi.enableGeolocation(createDelegateRequestListener(listener)); } /** * Check if the sending of geolocation messages is enabled * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_GEOLOCATION * * Sending a Geolocation message is enabled if the MegaRequest object, received in onRequestFinish, * has error code MegaError::API_OK. In other cases, send geolocation messages is not enabled and * the application has to answer before send a message of this type. * * @param listener MegaRequestListener to track this request */ public void isGeolocationEnabled(MegaRequestListenerInterface listener){ megaApi.isGeolocationEnabled(createDelegateRequestListener(listener)); } /** * Set My Chat Files target folder. * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_MY_CHAT_FILES_FOLDER * - MegaRequest::getMegaStringMap - Returns a MegaStringMap. * The key "h" in the map contains the nodehandle specified as parameter encoded in B64 * * @param nodehandle MegaHandle of the node to be used as target folder * @param listener MegaRequestListener to track this request */ public void setMyChatFilesFolder(long nodehandle, MegaRequestListenerInterface listener) { megaApi.setMyChatFilesFolder(nodehandle, createDelegateRequestListener(listener)); } /** * Gets My chat files target folder. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_MY_CHAT_FILES_FOLDER * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodehandle - Returns the handle of the node where My Chat Files are stored * * If the folder is not set, the request will fail with the error code MegaError::API_ENOENT. * * @param listener MegaRequestListener to track this request */ public void getMyChatFilesFolder(MegaRequestListenerInterface listener){ megaApi.getMyChatFilesFolder(createDelegateRequestListener(listener)); } /** * Set Camera Uploads primary target folder. * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_CAMERA_UPLOADS_FOLDER * - MegaRequest::getFlag - Returns false * - MegaRequest::getNodehandle - Returns the provided node handle * - MegaRequest::getMegaStringMap - Returns a MegaStringMap. * The key "h" in the map contains the nodehandle specified as parameter encoded in B64 * * @param nodehandle MegaHandle of the node to be used as primary target folder * @param listener MegaRequestListener to track this request */ public void setCameraUploadsFolder(long nodehandle, MegaRequestListenerInterface listener){ megaApi.setCameraUploadsFolder(nodehandle, createDelegateRequestListener(listener)); } /** * Set Camera Uploads secondary target folder. * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_CAMERA_UPLOADS_FOLDER * - MegaRequest::getFlag - Returns true * - MegaRequest::getNodehandle - Returns the provided node handle * - MegaRequest::getMegaStringMap - Returns a MegaStringMap. * The key "sh" in the map contains the nodehandle specified as parameter encoded in B64 * * @param nodehandle MegaHandle of the node to be used as secondary target folder * @param listener MegaRequestListener to track this request */ public void setCameraUploadsFolderSecondary(long nodehandle, MegaRequestListenerInterface listener){ megaApi.setCameraUploadsFolderSecondary(nodehandle, createDelegateRequestListener(listener)); } /** * Set Camera Uploads for both primary and secondary target folder. * * If only one of the target folders wants to be set, simply pass a INVALID_HANDLE to * as the other target folder and it will remain untouched. * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_CAMERA_UPLOADS_FOLDER * - MegaRequest::getNodehandle - Returns the provided node handle for primary folder * - MegaRequest::getParentHandle - Returns the provided node handle for secondary folder * * @param primaryFolder MegaHandle of the node to be used as primary target folder * @param secondaryFolder MegaHandle of the node to be used as secondary target folder * @param listener MegaRequestListener to track this request */ public void setCameraUploadsFolders(long primaryFolder, long secondaryFolder, MegaRequestListenerInterface listener) { megaApi.setCameraUploadsFolders(primaryFolder, secondaryFolder, createDelegateRequestListener(listener)); } /** * Gets Camera Uploads primary target folder. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_CAMERA_UPLOADS_FOLDER * - MegaRequest::getFlag - Returns false * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodehandle - Returns the handle of the primary node where Camera Uploads files are stored * * If the folder is not set, the request will fail with the error code MegaError::API_ENOENT. * * @param listener MegaRequestListener to track this request */ public void getCameraUploadsFolder(MegaRequestListenerInterface listener){ megaApi.getCameraUploadsFolder(createDelegateRequestListener(listener)); } /** * Gets Camera Uploads secondary target folder. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_CAMERA_UPLOADS_FOLDER * - MegaRequest::getFlag - Returns true * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodehandle - Returns the handle of the secondary node where Camera Uploads files are stored * * If the secondary folder is not set, the request will fail with the error code MegaError::API_ENOENT. * * @param listener MegaRequestListener to track this request */ public void getCameraUploadsFolderSecondary(MegaRequestListenerInterface listener){ megaApi.getCameraUploadsFolderSecondary(createDelegateRequestListener(listener)); } /** * Gets the alias for an user * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_ALIAS * - MegaRequest::getNodeHandle - user handle in binary * - MegaRequest::getText - user handle encoded in B64 * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getName - Returns the user alias * * If the user alias doesn't exists the request will fail with the error code MegaError::API_ENOENT. * * @param uh handle of the user in binary * @param listener MegaRequestListener to track this request */ public void getUserAlias(long uh, MegaRequestListenerInterface listener) { megaApi.getUserAlias(uh, createDelegateRequestListener(listener)); } /** * Set or reset an alias for a user * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_ALIAS * - MegaRequest::getNodeHandle - Returns the user handle in binary * - MegaRequest::getText - Returns the user alias * * @param uh handle of the user in binary * @param alias the user alias, or null to reset the existing * @param listener MegaRequestListener to track this request */ public void setUserAlias(long uh, String alias, MegaRequestListenerInterface listener) { megaApi.setUserAlias(uh, alias, createDelegateRequestListener(listener)); } /** * Get push notification settings * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_PUSH_SETTINGS * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaPushNotificationSettings - Returns settings for push notifications * * @see MegaPushNotificationSettings class for more details. * * @param listener MegaRequestListener to track this request */ public void getPushNotificationSettings(MegaRequestListenerInterface listener) { megaApi.getPushNotificationSettings(createDelegateRequestListener(listener)); } /** * Set push notification settings * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_PUSH_SETTINGS * - MegaRequest::getMegaPushNotificationSettings - Returns settings for push notifications * * @see MegaPushNotificationSettings class for more details. You can prepare a new object by * calling MegaPushNotificationSettings::createInstance. * * @param settings MegaPushNotificationSettings with the new settings * @param listener MegaRequestListener to track this request */ public void setPushNotificationSettings(MegaPushNotificationSettings settings, MegaRequestListenerInterface listener) { megaApi.setPushNotificationSettings(settings, createDelegateRequestListener(listener)); } /** * Get the number of days for rubbish-bin cleaning scheduler * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_RUBBISH_TIME * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNumber - Returns the days for rubbish-bin cleaning scheduler. * Zero means that the rubbish-bin cleaning scheduler is disabled (only if the account is PRO) * Any negative value means that the configured value is invalid. * * @param listener MegaRequestListener to track this request */ public void getRubbishBinAutopurgePeriod(MegaRequestListenerInterface listener){ megaApi.getRubbishBinAutopurgePeriod(createDelegateRequestListener(listener)); } /** * Set the number of days for rubbish-bin cleaning scheduler * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_RUBBISH_TIME * - MegaRequest::getNumber - Returns the days for rubbish-bin cleaning scheduler passed as parameter * * @param days Number of days for rubbish-bin cleaning scheduler. It must be >= 0. * The value zero disables the rubbish-bin cleaning scheduler (only for PRO accounts). * * @param listener MegaRequestListener to track this request */ public void setRubbishBinAutopurgePeriod(int days, MegaRequestListenerInterface listener){ megaApi.setRubbishBinAutopurgePeriod(days, createDelegateRequestListener(listener)); } /** * Returns the id of this device * * You take the ownership of the returned value. * * @return The id of this device */ public String getDeviceId() { return megaApi.getDeviceId(); } /** * Returns the name set for this device * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_DEVICE_NAMES * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getName - Returns device name. * * @param listener MegaRequestListener to track this request */ public void getDeviceName(MegaRequestListenerInterface listener) { megaApi.getDeviceName(createDelegateRequestListener(listener)); } /** * Returns the name set for this device * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_DEVICE_NAMES * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getName - Returns device name. */ public void getDeviceName() { megaApi.getDeviceName(); } /** * Sets device name * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_DEVICE_NAMES * - MegaRequest::getName - Returns device name. * * @param deviceName String with device name * @param listener MegaRequestListener to track this request */ public void setDeviceName(String deviceName, MegaRequestListenerInterface listener) { megaApi.setDeviceName(deviceName, createDelegateRequestListener(listener)); } /** * Sets device name * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_DEVICE_NAMES * - MegaRequest::getName - Returns device name. * * @param deviceName String with device name */ public void setDeviceName(String deviceName) { megaApi.setDeviceName(deviceName); } /** * Returns the name set for this drive * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_DRIVE_NAMES * - MegaRequest::getFile - Returns the path to the drive * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getName - Returns drive name. * * @param pathToDrive Path to the root of the external drive * @param listener MegaRequestListener to track this request */ public void getDriveName(String pathToDrive, MegaRequestListenerInterface listener) { megaApi.getDriveName(pathToDrive, createDelegateRequestListener(listener)); } /** * Returns the name set for this drive * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_DRIVE_NAMES * - MegaRequest::getFile - Returns the path to the drive * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getName - Returns drive name. * * @param pathToDrive Path to the root of the external drive */ public void getDriveName(String pathToDrive) { megaApi.getDriveName(pathToDrive); } /** * Sets drive name * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_DRIVE_NAMES * - MegaRequest::getName - Returns drive name. * - MegaRequest::getFile - Returns the path to the drive * * @param pathToDrive Path to the root of the external drive * @param driveName String with drive name * @param listener MegaRequestListener to track this request */ public void setDriveName(String pathToDrive, String driveName, MegaRequestListenerInterface listener) { megaApi.setDriveName(pathToDrive, driveName, createDelegateRequestListener(listener)); } /** * Sets drive name * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_DRIVE_NAMES * - MegaRequest::getName - Returns drive name. * - MegaRequest::getFile - Returns the path to the drive * * @param pathToDrive Path to the root of the external drive * @param driveName String with drive name */ public void setDriveName(String pathToDrive, String driveName) { megaApi.setDriveName(pathToDrive, driveName); } /** * Change the password of the MEGA account * * The associated request type with this request is MegaRequest::TYPE_CHANGE_PW * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getPassword - Returns the old password (if it was passed as parameter) * - MegaRequest::getNewPassword - Returns the new password * * @param oldPassword Old password (optional, it can be NULL to not check the old password) * @param newPassword New password * @param listener MegaRequestListener to track this request */ public void changePassword(String oldPassword, String newPassword, MegaRequestListenerInterface listener) { megaApi.changePassword(oldPassword, newPassword, createDelegateRequestListener(listener)); } /** * Change the password of the MEGA account * * The associated request type with this request is MegaRequest::TYPE_CHANGE_PW * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getPassword - Returns the old password (if it was passed as parameter) * - MegaRequest::getNewPassword - Returns the new password * * @param oldPassword Old password (optional, it can be NULL to not check the old password) * @param newPassword New password */ public void changePassword(String oldPassword, String newPassword) { megaApi.changePassword(oldPassword, newPassword); } /** * Invite another person to be your MEGA contact. * <p> * The user does not need to be registered with MEGA. If the email is not associated with * a MEGA account, an invitation email will be sent with the text in the "message" parameter. * <p> * The associated request type with this request is MegaRequest.TYPE_INVITE_CONTACT. * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getEmail() - Returns the email of the contact. <br> * - MegaRequest.getText() - Returns the text of the invitation. * * @param email Email of the new contact. * @param message Message for the user (can be null). * @param action Action for this contact request. Valid values are: <br> * - MegaContactRequest.INVITE_ACTION_ADD = 0. <br> * - MegaContactRequest.INVITE_ACTION_DELETE = 1. <br> * - MegaContactRequest.INVITE_ACTION_REMIND = 2. * * @param listener MegaRequestListenerInterface to track this request. */ public void inviteContact(String email, String message, int action, MegaRequestListenerInterface listener) { megaApi.inviteContact(email, message, action, createDelegateRequestListener(listener)); } /** * Invite another person to be your MEGA contact. * <p> * The user does not need to be registered on MEGA. If the email is not associated with * a MEGA account, an invitation email will be sent with the text in the "message" parameter. * * @param email Email of the new contact. * @param message Message for the user (can be null). * @param action Action for this contact request. Valid values are: <br> * - MegaContactRequest.INVITE_ACTION_ADD = 0. <br> * - MegaContactRequest.INVITE_ACTION_DELETE = 1. <br> * - MegaContactRequest.INVITE_ACTION_REMIND = 2. */ public void inviteContact(String email, String message, int action) { megaApi.inviteContact(email, message, action); } /** * Invite another person to be your MEGA contact using a contact link handle * * The associated request type with this request is MegaRequest::TYPE_INVITE_CONTACT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getEmail - Returns the email of the contact * - MegaRequest::getText - Returns the text of the invitation * - MegaRequest::getNumber - Returns the action * - MegaRequest::getNodeHandle - Returns the contact link handle * * Sending a reminder within a two week period since you started or your last reminder will * fail the API returning the error code MegaError::API_EACCESS. * * @param email Email of the new contact * @param message Message for the user (can be NULL) * @param action Action for this contact request. Valid values are: * - MegaContactRequest::INVITE_ACTION_ADD = 0 * - MegaContactRequest::INVITE_ACTION_DELETE = 1 * - MegaContactRequest::INVITE_ACTION_REMIND = 2 * @param contactLink Contact link handle of the other account. This parameter is considered only if the * \c action is MegaContactRequest::INVITE_ACTION_ADD. Otherwise, it's ignored and it has no effect. * * @param listener MegaRequestListener to track this request */ public void inviteContact(String email, String message, int action, long contactLink, MegaRequestListenerInterface listener){ megaApi.inviteContact(email, message, action, contactLink, createDelegateRequestListener(listener)); } /** * Reply to a contact request. * * @param request Contact request. You can get your pending contact requests using * MegaApi.getIncomingContactRequests(). * @param action Action for this contact request. Valid values are: <br> * - MegaContactRequest.REPLY_ACTION_ACCEPT = 0. <br> * - MegaContactRequest.REPLY_ACTION_DENY = 1. <br> * - MegaContactRequest.REPLY_ACTION_IGNORE = 2. <br> * * The associated request type with this request is MegaRequest.TYPE_REPLY_CONTACT_REQUEST. * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getNodeHandle() - Returns the handle of the contact request. <br> * - MegaRequest.getNumber() - Returns the action. <br> * * @param listener MegaRequestListenerInterface to track this request. */ public void replyContactRequest(MegaContactRequest request, int action, MegaRequestListenerInterface listener) { megaApi.replyContactRequest(request, action, createDelegateRequestListener(listener)); } /** * Reply to a contact request. * * @param request Contact request. You can get your pending contact requests using MegaApi.getIncomingContactRequests() * @param action Action for this contact request. Valid values are: <br> * - MegaContactRequest.REPLY_ACTION_ACCEPT = 0. <br> * - MegaContactRequest.REPLY_ACTION_DENY = 1. <br> * - MegaContactRequest.REPLY_ACTION_IGNORE = 2. */ public void replyContactRequest(MegaContactRequest request, int action) { megaApi.replyContactRequest(request, action); } /** * Remove a contact to the MEGA account. * <p> * The associated request type with this request is MegaRequest.TYPE_REMOVE_CONTACT. * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getEmail() - Returns the email of the contact. * * @param user * Email of the contact. * @param listener * MegaRequestListener to track this request. */ public void removeContact(MegaUser user, MegaRequestListenerInterface listener) { megaApi.removeContact(user, createDelegateRequestListener(listener)); } /** * Remove a contact to the MEGA account. * <p> * The associated request type with this request is MegaRequest.TYPE_REMOVE_CONTACT. * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getEmail() - Returns the email of the contact. * @param user * Email of the contact. */ public void removeContact(MegaUser user) { megaApi.removeContact(user); } /** * Logout of the MEGA account. * * The associated request type with this request is MegaRequest.TYPE_LOGOUT * * @param listener * MegaRequestListener to track this request. */ public void logout(MegaRequestListenerInterface listener) { megaApi.logout(createDelegateRequestListener(listener)); } /** * Logout of the MEGA account. */ public void logout() { megaApi.logout(); } /** * Logout of the MEGA account without invalidating the session. * <p> * The associated request type with this request is MegaRequest.TYPE_LOGOUT. * * @param listener * MegaRequestListener to track this request. */ public void localLogout(MegaRequestListenerInterface listener) { megaApi.localLogout(createDelegateRequestListener(listener)); } /** * Logout of the MEGA account without invalidating the session. * */ public void localLogout() { megaApi.localLogout(); } /** * Invalidate the existing cache and create a fresh one */ public void invalidateCache(){ megaApi.invalidateCache(); } /** * Estimate the strength of a password * * Possible return values are: * - PASSWORD_STRENGTH_VERYWEAK = 0 * - PASSWORD_STRENGTH_WEAK = 1 * - PASSWORD_STRENGTH_MEDIUM = 2 * - PASSWORD_STRENGTH_GOOD = 3 * - PASSWORD_STRENGTH_STRONG = 4 * * @param password Password to check * @return Estimated strength of the password */ public int getPasswordStrength(String password){ return megaApi.getPasswordStrength(password); } /** * Use HTTPS communications only * * The default behavior is to use HTTP for transfers and the persistent connection * to wait for external events. Those communications don't require HTTPS because * all transfer data is already end-to-end encrypted and no data is transmitted * over the connection to wait for events (it's just closed when there are new events). * * This feature should only be enabled if there are problems to contact MEGA servers * through HTTP because otherwise it doesn't have any benefit and will cause a * higher CPU usage. * * See MegaApi::usingHttpsOnly * * @param httpsOnly True to use HTTPS communications only */ public void useHttpsOnly(boolean httpsOnly) { megaApi.useHttpsOnly(httpsOnly); } /** * Check if the SDK is using HTTPS communications only * * The default behavior is to use HTTP for transfers and the persistent connection * to wait for external events. Those communications don't require HTTPS because * all transfer data is already end-to-end encrypted and no data is transmitted * over the connection to wait for events (it's just closed when there are new events). * * See MegaApi::useHttpsOnly * * @return True if the SDK is using HTTPS communications only. Otherwise false. */ public boolean usingHttpsOnly() { return megaApi.usingHttpsOnly(); } /****************************************************************************************************/ // TRANSFERS /****************************************************************************************************/ /** * Upload a file or a folder * * If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file or folder * @param parent Parent node for the file or folder in the MEGA account * @param listener MegaTransferListener to track this transfer */ public void startUpload(String localPath, MegaNode parent, MegaTransferListenerInterface listener) { megaApi.startUpload(localPath, parent, createDelegateTransferListener(listener)); } /** * Upload a file or a folder * * If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file or folder * @param parent Parent node for the file or folder in the MEGA account */ public void startUpload(String localPath, MegaNode parent) { megaApi.startUpload(localPath, parent); } /** * Upload a file or a folder with a custom modification time * *If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file * @param parent Parent node for the file in the MEGA account * @param mtime Custom modification time for the file in MEGA (in seconds since the epoch) * @param listener MegaTransferListener to track this transfer * * The custom modification time will be only applied for file transfers. If a folder * is transferred using this function, the custom modification time won't have any effect, */ public void startUpload(String localPath, MegaNode parent, long mtime, MegaTransferListenerInterface listener) { megaApi.startUpload(localPath, parent, mtime, createDelegateTransferListener(listener)); } /** * Upload a file or a folder with a custom modification time * *If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file * @param parent Parent node for the file in the MEGA account * @param mtime Custom modification time for the file in MEGA (in seconds since the epoch) * * The custom modification time will be only applied for file transfers. If a folder * is transferred using this function, the custom modification time won't have any effect, */ public void startUpload(String localPath, MegaNode parent, long mtime) { megaApi.startUpload(localPath, parent, mtime); } /** * Upload a file or folder with a custom name * *If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file or folder * @param parent Parent node for the file or folder in the MEGA account * @param fileName Custom file name for the file or folder in MEGA * @param listener MegaTransferListener to track this transfer */ public void startUpload(String localPath, MegaNode parent, String fileName, MegaTransferListenerInterface listener) { megaApi.startUpload(localPath, parent, fileName, createDelegateTransferListener(listener)); } /** * Upload a file or folder with a custom name * *If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file or folder * @param parent Parent node for the file or folder in the MEGA account * @param fileName Custom file name for the file or folder in MEGA */ public void startUpload(String localPath, MegaNode parent, String fileName) { megaApi.startUpload(localPath, parent, fileName); } /** * Upload a file or a folder with a custom name and a custom modification time * *If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file * @param parent Parent node for the file in the MEGA account * @param fileName Custom file name for the file in MEGA * @param mtime Custom modification time for the file in MEGA (in seconds since the epoch) * @param listener MegaTransferListener to track this transfer * * The custom modification time will be only applied for file transfers. If a folder * is transferred using this function, the custom modification time won't have any effect */ public void startUpload(String localPath, MegaNode parent, String fileName, long mtime, MegaTransferListenerInterface listener) { megaApi.startUpload(localPath, parent, fileName, mtime, createDelegateTransferListener(listener)); } /** * Upload a file or a folder with a custom name and a custom modification time * *If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file * @param parent Parent node for the file in the MEGA account * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. If a transfer is started with exactly the same data * (local path and target parent) as another one in the transfer queue, the new transfer * fails with the error API_EEXISTS and the appData of the new transfer is appended to * the appData of the old transfer, using a '!' separator if the old transfer had already * appData. * @param fileName Custom file name for the file in MEGA * @param mtime Custom modification time for the file in MEGA (in seconds since the epoch) * @param listener MegaTransferListener to track this transfer * * The custom modification time will be only applied for file transfers. If a folder * is transferred using this function, the custom modification time won't have any effect */ public void startUpload(String localPath, MegaNode parent, String appData, String fileName, long mtime, MegaTransferListenerInterface listener) { megaApi.startUpload(localPath, parent, appData, fileName, mtime, createDelegateTransferListener(listener)); } /** * Upload a file or a folder with a custom name and a custom modification time * *If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file * @param parent Parent node for the file in the MEGA account * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. If a transfer is started with exactly the same data * (local path and target parent) as another one in the transfer queue, the new transfer * fails with the error API_EEXISTS and the appData of the new transfer is appended to * the appData of the old transfer, using a '!' separator if the old transfer had already * appData. * @param fileName Custom file name for the file in MEGA * @param mtime Custom modification time for the file in MEGA (in seconds since the epoch) * * The custom modification time will be only applied for file transfers. If a folder * is transferred using this function, the custom modification time won't have any effect */ public void startUpload(String localPath, MegaNode parent, String appData, String fileName, long mtime) { megaApi.startUpload(localPath, parent, appData, fileName, mtime); } /** * Upload a file or a folder with a custom name and a custom modification time * *If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file * @param parent Parent node for the file in the MEGA account * @param fileName Custom file name for the file in MEGA * @param mtime Custom modification time for the file in MEGA (in seconds since the epoch) * * The custom modification time will be only applied for file transfers. If a folder * is transferred using this function, the custom modification time won't have any effect */ public void startUpload(String localPath, MegaNode parent, String fileName, long mtime) { megaApi.startUpload(localPath, parent, fileName, mtime); } /** * Upload a file or a folder, saving custom app data during the transfer * * If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file or folder * @param parent Parent node for the file or folder in the MEGA account * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. If a transfer is started with exactly the same data * (local path and target parent) as another one in the transfer queue, the new transfer * fails with the error API_EEXISTS and the appData of the new transfer is appended to * the appData of the old transfer, using a '!' separator if the old transfer had already * appData. * @param listener MegaTransferListener to track this transfer */ public void startUploadWithData(String localPath, MegaNode parent, String appData, MegaTransferListenerInterface listener){ megaApi.startUploadWithData(localPath, parent, appData, createDelegateTransferListener(listener)); } /** * Upload a file or a folder, saving custom app data during the transfer * * If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file or folder * @param parent Parent node for the file or folder in the MEGA account * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. If a transfer is started with exactly the same data * (local path and target parent) as another one in the transfer queue, the new transfer * fails with the error API_EEXISTS and the appData of the new transfer is appended to * the appData of the old transfer, using a '!' separator if the old transfer had already * appData. */ public void startUploadWithData(String localPath, MegaNode parent, String appData){ megaApi.startUploadWithData(localPath, parent, appData); } /** * Upload a file or a folder, putting the transfer on top of the upload queue * * If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file or folder * @param parent Parent node for the file or folder in the MEGA account * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. If a transfer is started with exactly the same data * (local path and target parent) as another one in the transfer queue, the new transfer * fails with the error API_EEXISTS and the appData of the new transfer is appended to * the appData of the old transfer, using a '!' separator if the old transfer had already * appData. * @param isSourceTemporary Pass the ownership of the file to the SDK, that will DELETE it when the upload finishes. * This parameter is intended to automatically delete temporary files that are only created to be uploaded. * Use this parameter with caution. Set it to true only if you are sure about what are you doing. * @param listener MegaTransferListener to track this transfer */ public void startUploadWithTopPriority(String localPath, MegaNode parent, String appData, boolean isSourceTemporary, MegaTransferListenerInterface listener){ megaApi.startUploadWithTopPriority(localPath, parent, appData, isSourceTemporary, createDelegateTransferListener(listener)); } /** * Upload a file or a folder, putting the transfer on top of the upload queue * *If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file or folder * @param parent Parent node for the file or folder in the MEGA account * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. If a transfer is started with exactly the same data * (local path and target parent) as another one in the transfer queue, the new transfer * fails with the error API_EEXISTS and the appData of the new transfer is appended to * the appData of the old transfer, using a '!' separator if the old transfer had already * appData. * @param isSourceTemporary Pass the ownership of the file to the SDK, that will DELETE it when the upload finishes. * This parameter is intended to automatically delete temporary files that are only created to be uploaded. * Use this parameter with caution. Set it to true only if you are sure about what are you doing. */ public void startUploadWithTopPriority(String localPath, MegaNode parent, String appData, boolean isSourceTemporary){ megaApi.startUploadWithTopPriority(localPath, parent, appData, isSourceTemporary); } /** * Upload a file or a folder, putting the transfer on top of the upload queue * * If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file or folder * @param parent Parent node for the file or folder in the MEGA account * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. If a transfer is started with exactly the same data * (local path and target parent) as another one in the transfer queue, the new transfer * fails with the error API_EEXISTS and the appData of the new transfer is appended to * the appData of the old transfer, using a '!' separator if the old transfer had already * appData. * @param isSourceTemporary Pass the ownership of the file to the SDK, that will DELETE it when the upload finishes. * This parameter is intended to automatically delete temporary files that are only created to be uploaded. * Use this parameter with caution. Set it to true only if you are sure about what are you doing. * @param fileName Custom file name for the file or folder in MEGA * @param listener MegaTransferListener to track this transfer */ public void startUploadWithTopPriority(String localPath, MegaNode parent, String appData, boolean isSourceTemporary, String fileName, MegaTransferListenerInterface listener){ megaApi.startUploadWithTopPriority(localPath, parent, appData, isSourceTemporary, fileName, createDelegateTransferListener(listener)); } /** * Upload a file or a folder, putting the transfer on top of the upload queue * *If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file or folder * @param parent Parent node for the file or folder in the MEGA account * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. If a transfer is started with exactly the same data * (local path and target parent) as another one in the transfer queue, the new transfer * fails with the error API_EEXISTS and the appData of the new transfer is appended to * the appData of the old transfer, using a '!' separator if the old transfer had already * appData. * @param isSourceTemporary Pass the ownership of the file to the SDK, that will DELETE it when the upload finishes. * This parameter is intended to automatically delete temporary files that are only created to be uploaded. * Use this parameter with caution. Set it to true only if you are sure about what are you doing. * @param fileName Custom file name for the file or folder in MEGA */ public void startUploadWithTopPriority(String localPath, MegaNode parent, String appData, boolean isSourceTemporary, String fileName){ megaApi.startUploadWithTopPriority(localPath, parent, appData, isSourceTemporary, fileName); } /** * Upload a file or a folder * * This method should be used ONLY to share by chat a local file. In case the file * is already uploaded, but the corresponding node is missing the thumbnail and/or preview, * this method will force a new upload from the scratch (ensuring the file attributes are set), * instead of doing a remote copy. * * If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file or folder * @param parent Parent node for the file or folder in the MEGA account * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. If a transfer is started with exactly the same data * (local path and target parent) as another one in the transfer queue, the new transfer * fails with the error API_EEXISTS and the appData of the new transfer is appended to * the appData of the old transfer, using a '!' separator if the old transfer had already * appData. * @param isSourceTemporary Pass the ownership of the file to the SDK, that will DELETE it when the upload finishes. * This parameter is intended to automatically delete temporary files that are only created to be uploaded. * Use this parameter with caution. Set it to true only if you are sure about what are you doing. */ public void startUploadForChat(String localPath, MegaNode parent, String appData, boolean isSourceTemporary) { megaApi.startUploadForChat(localPath, parent, appData, isSourceTemporary); } /** * Upload a file or a folder * * This method should be used ONLY to share by chat a local file. In case the file * is already uploaded, but the corresponding node is missing the thumbnail and/or preview, * this method will force a new upload from the scratch (ensuring the file attributes are set), * instead of doing a remote copy. * * If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param localPath Local path of the file or folder * @param parent Parent node for the file or folder in the MEGA account * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. If a transfer is started with exactly the same data * (local path and target parent) as another one in the transfer queue, the new transfer * fails with the error API_EEXISTS and the appData of the new transfer is appended to * the appData of the old transfer, using a '!' separator if the old transfer had already * appData. * @param isSourceTemporary Pass the ownership of the file to the SDK, that will DELETE it when the upload finishes. * This parameter is intended to automatically delete temporary files that are only created to be uploaded. * Use this parameter with caution. Set it to true only if you are sure about what are you doing. * @param fileName Custom file name for the file or folder in MEGA */ public void startUploadForChat(String localPath, MegaNode parent, String appData, boolean isSourceTemporary, String fileName) { megaApi.startUploadForChat(localPath, parent, appData, isSourceTemporary, fileName); } /** * Download a file or a folder from MEGA * *If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param node MegaNode that identifies the file or folder * @param localPath Destination path for the file or folder * If this path is a local folder, it must end with a '\' or '/' character and the file name * in MEGA will be used to store a file inside that folder. If the path doesn't finish with * one of these characters, the file will be downloaded to a file in that path. * * @param listener MegaTransferListener to track this transfer */ public void startDownload(MegaNode node, String localPath, MegaTransferListenerInterface listener) { megaApi.startDownload(node, localPath, createDelegateTransferListener(listener)); } /** * Download a file or a folder from MEGA * *If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param node MegaNode that identifies the file or folder * @param localPath Destination path for the file or folder * If this path is a local folder, it must end with a '\' or '/' character and the file name * in MEGA will be used to store a file inside that folder. If the path doesn't finish with * one of these characters, the file will be downloaded to a file in that path. */ public void startDownload(MegaNode node, String localPath) { megaApi.startDownload(node, localPath); } /** * Download a file or a folder from MEGA, saving custom app data during the transfer * * If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param node MegaNode that identifies the file or folder * @param localPath Destination path for the file or folder * If this path is a local folder, it must end with a '\' or '/' character and the file name * in MEGA will be used to store a file inside that folder. If the path doesn't finish with * one of these characters, the file will be downloaded to a file in that path. * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. * @param listener MegaTransferListener to track this transfer */ public void startDownloadWithData(MegaNode node, String localPath, String appData, MegaTransferListenerInterface listener){ megaApi.startDownloadWithData(node, localPath, appData, createDelegateTransferListener(listener)); } /** * Download a file or a folder from MEGA, saving custom app data during the transfer * * If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param node MegaNode that identifies the file or folder * @param localPath Destination path for the file or folder * If this path is a local folder, it must end with a '\' or '/' character and the file name * in MEGA will be used to store a file inside that folder. If the path doesn't finish with * one of these characters, the file will be downloaded to a file in that path. * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. */ public void startDownloadWithData(MegaNode node, String localPath, String appData){ megaApi.startDownloadWithData(node, localPath, appData); } /** * Download a file or a folder from MEGA, putting the transfer on top of the download queue. * * If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param node MegaNode that identifies the file or folder * @param localPath Destination path for the file or folder * If this path is a local folder, it must end with a '\' or '/' character and the file name * in MEGA will be used to store a file inside that folder. If the path doesn't finish with * one of these characters, the file will be downloaded to a file in that path. * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. * @param listener MegaTransferListener to track this transfer */ public void startDownloadWithTopPriority(MegaNode node, String localPath, String appData, MegaTransferListenerInterface listener){ megaApi.startDownloadWithTopPriority(node, localPath, appData, createDelegateTransferListener(listener)); } /** * Download a file or a folder from MEGA, putting the transfer on top of the download queue. * * If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param node MegaNode that identifies the file or folder * @param localPath Destination path for the file or folder * If this path is a local folder, it must end with a '\' or '/' character and the file name * in MEGA will be used to store a file inside that folder. If the path doesn't finish with * one of these characters, the file will be downloaded to a file in that path. * @param appData Custom app data to save in the MegaTransfer object * The data in this parameter can be accessed using MegaTransfer::getAppData in callbacks * related to the transfer. */ public void startDownloadWithTopPriority(MegaNode node, String localPath, String appData){ megaApi.startDownloadWithTopPriority(node, localPath, appData); } /** * Start an streaming download for a file in MEGA * * Streaming downloads don't save the downloaded data into a local file. It is provided * in MegaTransferListener::onTransferUpdate in a byte buffer. The pointer is returned by * MegaTransfer::getLastBytes and the size of the buffer in MegaTransfer::getDeltaSize * * The same byte array is also provided in the callback MegaTransferListener::onTransferData for * compatibility with other programming languages. Only the MegaTransferListener passed to this function * will receive MegaTransferListener::onTransferData callbacks. MegaTransferListener objects registered * with MegaApi::addTransferListener won't receive them for performance reasons * * If the status of the business account is expired, onTransferFinish will be called with the error * code MegaError::API_EBUSINESSPASTDUE. In this case, apps should show a warning message similar to * "Your business account is overdue, please contact your administrator." * * @param node MegaNode that identifies the file * @param startPos First byte to download from the file * @param size Size of the data to download * @param listener MegaTransferListener to track this transfer */ public void startStreaming(MegaNode node, long startPos, long size, MegaTransferListenerInterface listener) { megaApi.startStreaming(node, startPos, size, createDelegateTransferListener(listener)); } /** * Cancel a transfer. * <p> * When a transfer is cancelled, it will finish and will provide the error code * MegaError.API_EINCOMPLETE in MegaTransferListener.onTransferFinish() and * MegaListener.onTransferFinish(). * <p> * The associated request type with this request is MegaRequest.TYPE_CANCEL_TRANSFER * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getTransferTag() - Returns the tag of the cancelled transfer (MegaTransfer.getTag). * * @param transfer * MegaTransfer object that identifies the transfer. * You can get this object in any MegaTransferListener callback or any MegaListener callback * related to transfers. * @param listener * MegaRequestListener to track this request. */ public void cancelTransfer(MegaTransfer transfer, MegaRequestListenerInterface listener) { megaApi.cancelTransfer(transfer, createDelegateRequestListener(listener)); } /** * Cancel a transfer. * * @param transfer * MegaTransfer object that identifies the transfer. * You can get this object in any MegaTransferListener callback or any MegaListener callback * related to transfers. */ public void cancelTransfer(MegaTransfer transfer) { megaApi.cancelTransfer(transfer); } /** * Move a transfer one position up in the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_UP * * @param transfer Transfer to move * @param listener MegaRequestListener to track this request */ public void moveTransferUp(MegaTransfer transfer, MegaRequestListenerInterface listener) { megaApi.moveTransferUp(transfer, createDelegateRequestListener(listener)); } /** * Move a transfer one position up in the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_UP * * @param transfer Transfer to move */ public void moveTransferUp(MegaTransfer transfer) { megaApi.moveTransferUp(transfer); } /** * Move a transfer one position up in the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_UP * * @param transferTag Tag of the transfer to move * @param listener MegaRequestListener to track this request */ public void moveTransferUpByTag(int transferTag, MegaRequestListenerInterface listener) { megaApi.moveTransferUpByTag(transferTag, createDelegateRequestListener(listener)); } /** * Move a transfer one position up in the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_UP * * @param transferTag Tag of the transfer to move */ public void moveTransferUpByTag(int transferTag) { megaApi.moveTransferUpByTag(transferTag); } /** * Move a transfer one position down in the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_DOWN * * @param transfer Transfer to move * @param listener MegaRequestListener to track this request */ public void moveTransferDown(MegaTransfer transfer, MegaRequestListenerInterface listener) { megaApi.moveTransferDown(transfer, createDelegateRequestListener(listener)); } /** * Move a transfer one position down in the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_DOWN * * @param transfer Transfer to move */ public void moveTransferDown(MegaTransfer transfer) { megaApi.moveTransferDown(transfer); } /** * Move a transfer one position down in the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_DOWN * * @param transferTag Tag of the transfer to move * @param listener MegaRequestListener to track this request */ public void moveTransferDownByTag(int transferTag, MegaRequestListenerInterface listener) { megaApi.moveTransferDownByTag(transferTag, createDelegateRequestListener(listener)); } /** * Move a transfer one position down in the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_DOWN * * @param transferTag Tag of the transfer to move */ public void moveTransferDownByTag(int transferTag) { megaApi.moveTransferDownByTag(transferTag); } /** * Move a transfer to the top of the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_TOP * * @param transfer Transfer to move * @param listener MegaRequestListener to track this request */ public void moveTransferToFirst(MegaTransfer transfer, MegaRequestListenerInterface listener) { megaApi.moveTransferToFirst(transfer, createDelegateRequestListener(listener)); } /** * Move a transfer to the top of the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_TOP * * @param transfer Transfer to move */ public void moveTransferToFirst(MegaTransfer transfer) { megaApi.moveTransferToFirst(transfer); } /** * Move a transfer to the top of the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_TOP * * @param transferTag Tag of the transfer to move * @param listener MegaRequestListener to track this request */ public void moveTransferToFirstByTag(int transferTag, MegaRequestListenerInterface listener) { megaApi.moveTransferToFirstByTag(transferTag, createDelegateRequestListener(listener)); } /** * Move a transfer to the top of the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_TOP * * @param transferTag Tag of the transfer to move */ public void moveTransferToFirstByTag(int transferTag) { megaApi.moveTransferToFirstByTag(transferTag); } /** * Move a transfer to the bottom of the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_BOTTOM * * @param transfer Transfer to move * @param listener MegaRequestListener to track this request */ public void moveTransferToLast(MegaTransfer transfer, MegaRequestListenerInterface listener) { megaApi.moveTransferToLast(transfer, createDelegateRequestListener(listener)); } /** * Move a transfer to the bottom of the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_BOTTOM * * @param transfer Transfer to move */ public void moveTransferToLast(MegaTransfer transfer) { megaApi.moveTransferToLast(transfer); } /** * Move a transfer to the bottom of the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_BOTTOM * * @param transferTag Tag of the transfer to move * @param listener MegaRequestListener to track this request */ public void moveTransferToLastByTag(int transferTag, MegaRequestListenerInterface listener) { megaApi.moveTransferToLastByTag(transferTag, createDelegateRequestListener(listener)); } /** * Move a transfer to the bottom of the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns true (it means that it's an automatic move) * - MegaRequest::getNumber - Returns MegaTransfer::MOVE_TYPE_BOTTOM * * @param transferTag Tag of the transfer to move */ public void moveTransferToLastByTag(int transferTag) { megaApi.moveTransferToLastByTag(transferTag); } /** * Move a transfer before another one in the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns false (it means that it's a manual move) * - MegaRequest::getNumber - Returns the tag of the transfer with the target position * * @param transfer Transfer to move * @param prevTransfer Transfer with the target position * @param listener MegaRequestListener to track this request */ public void moveTransferBefore(MegaTransfer transfer, MegaTransfer prevTransfer, MegaRequestListenerInterface listener) { megaApi.moveTransferBefore(transfer, prevTransfer, createDelegateRequestListener(listener)); } /** * Move a transfer before another one in the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns false (it means that it's a manual move) * - MegaRequest::getNumber - Returns the tag of the transfer with the target position * * @param transfer Transfer to move * @param prevTransfer Transfer with the target position */ public void moveTransferBefore(MegaTransfer transfer, MegaTransfer prevTransfer) { megaApi.moveTransferBefore(transfer, prevTransfer); } /** * Move a transfer before another one in the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns false (it means that it's a manual move) * - MegaRequest::getNumber - Returns the tag of the transfer with the target position * * @param transferTag Tag of the transfer to move * @param prevTransferTag Tag of the transfer with the target position * @param listener MegaRequestListener to track this request */ public void moveTransferBeforeByTag(int transferTag, int prevTransferTag, MegaRequestListenerInterface listener) { megaApi.moveTransferBeforeByTag(transferTag, prevTransferTag, createDelegateRequestListener(listener)); } /** * Move a transfer before another one in the transfer queue * <p> * If the transfer is successfully moved, onTransferUpdate will be called * for the corresponding listeners of the moved transfer and the new priority * of the transfer will be available using MegaTransfer::getPriority * <p> * The associated request type with this request is MegaRequest::TYPE_MOVE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to move * - MegaRequest::getFlag - Returns false (it means that it's a manual move) * - MegaRequest::getNumber - Returns the tag of the transfer with the target position * * @param transferTag Tag of the transfer to move * @param prevTransferTag Tag of the transfer with the target position */ public void moveTransferBeforeByTag(int transferTag, int prevTransferTag) { megaApi.moveTransferBeforeByTag(transferTag, prevTransferTag); } /** * Cancel the transfer with a specific tag. * <p> * When a transfer is cancelled, it will finish and will provide the error code * MegaError.API_EINCOMPLETE in MegaTransferListener.onTransferFinish() and * MegaListener.onTransferFinish(). * <p> * The associated request type with this request is MegaRequest.TYPE_CANCEL_TRANSFER * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getTransferTag() - Returns the tag of the cancelled transfer (MegaTransfer.getTag). * * @param transferTag * tag that identifies the transfer. * You can get this tag using MegaTransfer.getTag(). * * @param listener * MegaRequestListener to track this request. */ public void cancelTransferByTag(int transferTag, MegaRequestListenerInterface listener) { megaApi.cancelTransferByTag(transferTag, createDelegateRequestListener(listener)); } /** * Cancel the transfer with a specific tag. * * @param transferTag * tag that identifies the transfer. * You can get this tag using MegaTransfer.getTag(). */ public void cancelTransferByTag(int transferTag) { megaApi.cancelTransferByTag(transferTag); } /** * Cancel all transfers of the same type. * <p> * The associated request type with this request is MegaRequest.TYPE_CANCEL_TRANSFERS * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getParamType() - Returns the first parameter. * * @param direction * Type of transfers to cancel. * Valid values are: <br> * - MegaTransfer.TYPE_DOWNLOAD = 0. <br> * - MegaTransfer.TYPE_UPLOAD = 1. * * @param listener * MegaRequestListener to track this request. */ public void cancelTransfers(int direction, MegaRequestListenerInterface listener) { megaApi.cancelTransfers(direction, createDelegateRequestListener(listener)); } /** * Cancel all transfers of the same type. * * @param direction * Type of transfers to cancel. * Valid values are: <br> * - MegaTransfer.TYPE_DOWNLOAD = 0. <br> * - MegaTransfer.TYPE_UPLOAD = 1. */ public void cancelTransfers(int direction) { megaApi.cancelTransfers(direction); } /** * Pause/resume all transfers. * <p> * The associated request type with this request is MegaRequest.TYPE_PAUSE_TRANSFERS * Valid data in the MegaRequest object received on callbacks: <br> * - MegaRequest.getFlag() - Returns the first parameter. * * @param pause * true to pause all transfers / false to resume all transfers. * @param listener * MegaRequestListener to track this request. */ public void pauseTransfers(boolean pause, MegaRequestListenerInterface listener) { megaApi.pauseTransfers(pause, createDelegateRequestListener(listener)); } /** * Pause/resume all transfers. * * @param pause * true to pause all transfers / false to resume all transfers. */ public void pauseTransfers(boolean pause) { megaApi.pauseTransfers(pause); } /** * Pause/resume all transfers in one direction (uploads or downloads) * * The associated request type with this request is MegaRequest::TYPE_PAUSE_TRANSFERS * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getFlag - Returns the first parameter * - MegaRequest::getNumber - Returns the direction of the transfers to pause/resume * * @param pause true to pause transfers / false to resume transfers * @param direction Direction of transfers to pause/resume * Valid values for this parameter are: * - MegaTransfer::TYPE_DOWNLOAD = 0 * - MegaTransfer::TYPE_UPLOAD = 1 * * @param listener MegaRequestListenerInterface to track this request */ public void pauseTransfers(boolean pause, int direction, MegaRequestListenerInterface listener) { megaApi.pauseTransfers(pause, direction, createDelegateRequestListener(listener)); } /** * Pause/resume all transfers in one direction (uploads or downloads) * * @param pause true to pause transfers / false to resume transfers * @param direction Direction of transfers to pause/resume * Valid values for this parameter are: * - MegaTransfer::TYPE_DOWNLOAD = 0 * - MegaTransfer::TYPE_UPLOAD = 1 */ public void pauseTransfers(boolean pause, int direction) { megaApi.pauseTransfers(pause, direction); } /** * Pause/resume a transfer * * The request finishes with MegaError::API_OK if the state of the transfer is the * desired one at that moment. That means that the request succeed when the transfer * is successfully paused or resumed, but also if the transfer was already in the * desired state and it wasn't needed to change anything. * * Resumed transfers don't necessarily continue just after the resumption. They * are tagged as queued and are processed according to its position on the request queue. * * The associated request type with this request is MegaRequest::TYPE_PAUSE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to pause or resume * - MegaRequest::getFlag - Returns true if the transfer has to be pause or false if it has to be resumed * * @param transfer Transfer to pause or resume * @param pause True to pause the transfer or false to resume it * @param listener MegaRequestListener to track this request */ public void pauseTransfer(MegaTransfer transfer, boolean pause, MegaRequestListenerInterface listener){ megaApi.pauseTransfer(transfer, pause, createDelegateRequestListener(listener)); } /** * Pause/resume a transfer * * The request finishes with MegaError::API_OK if the state of the transfer is the * desired one at that moment. That means that the request succeed when the transfer * is successfully paused or resumed, but also if the transfer was already in the * desired state and it wasn't needed to change anything. * * Resumed transfers don't necessarily continue just after the resumption. They * are tagged as queued and are processed according to its position on the request queue. * * The associated request type with this request is MegaRequest::TYPE_PAUSE_TRANSFER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getTransferTag - Returns the tag of the transfer to pause or resume * - MegaRequest::getFlag - Returns true if the transfer has to be pause or false if it has to be resumed * * @param transferTag Tag of the transfer to pause or resume * @param pause True to pause the transfer or false to resume it * @param listener MegaRequestListener to track this request */ public void pauseTransferByTag(int transferTag, boolean pause, MegaRequestListenerInterface listener){ megaApi.pauseTransferByTag(transferTag, pause, createDelegateRequestListener(listener)); } /** * Returns the state (paused/unpaused) of transfers * @param direction Direction of transfers to check * Valid values for this parameter are: * - MegaTransfer::TYPE_DOWNLOAD = 0 * - MegaTransfer::TYPE_UPLOAD = 1 * * @return true if transfers on that direction are paused, false otherwise */ public boolean areTransfersPaused(int direction) { return megaApi.areTransfersPaused(direction); } /** * Set the upload speed limit. * <p> * The limit will be applied on the server side when starting a transfer. Thus the limit won't be * applied for already started uploads and it's applied per storage server. * * @param bpslimit * -1 to automatically select the limit, 0 for no limit, otherwise the speed limit * in bytes per second. */ public void setUploadLimit(int bpslimit) { megaApi.setUploadLimit(bpslimit); } /** * Set the transfer method for downloads * * Valid methods are: * - TRANSFER_METHOD_NORMAL = 0 * HTTP transfers using port 80. Data is already encrypted. * * - TRANSFER_METHOD_ALTERNATIVE_PORT = 1 * HTTP transfers using port 8080. Data is already encrypted. * * - TRANSFER_METHOD_AUTO = 2 * The SDK selects the transfer method automatically * * - TRANSFER_METHOD_AUTO_NORMAL = 3 * The SDK selects the transfer method automatically starting with port 80. * * - TRANSFER_METHOD_AUTO_ALTERNATIVE = 4 * The SDK selects the transfer method automatically starting with alternative port 8080. * * @param method Selected transfer method for downloads */ public void setDownloadMethod(int method) { megaApi.setDownloadMethod(method); } /** * Set the transfer method for uploads * * Valid methods are: * - TRANSFER_METHOD_NORMAL = 0 * HTTP transfers using port 80. Data is already encrypted. * * - TRANSFER_METHOD_ALTERNATIVE_PORT = 1 * HTTP transfers using port 8080. Data is already encrypted. * * - TRANSFER_METHOD_AUTO = 2 * The SDK selects the transfer method automatically * * - TRANSFER_METHOD_AUTO_NORMAL = 3 * The SDK selects the transfer method automatically starting with port 80. * * - TRANSFER_METHOD_AUTO_ALTERNATIVE = 4 * The SDK selects the transfer method automatically starting with alternative port 8080. * * @param method Selected transfer method for uploads */ public void setUploadMethod(int method) { megaApi.setUploadMethod(method); } /** * Get the active transfer method for downloads * * Valid values for the return parameter are: * - TRANSFER_METHOD_NORMAL = 0 * HTTP transfers using port 80. Data is already encrypted. * * - TRANSFER_METHOD_ALTERNATIVE_PORT = 1 * HTTP transfers using port 8080. Data is already encrypted. * * - TRANSFER_METHOD_AUTO = 2 * The SDK selects the transfer method automatically * * - TRANSFER_METHOD_AUTO_NORMAL = 3 * The SDK selects the transfer method automatically starting with port 80. * * - TRANSFER_METHOD_AUTO_ALTERNATIVE = 4 * The SDK selects the transfer method automatically starting with alternative port 8080. * * @return Active transfer method for downloads */ public int getDownloadMethod() { return megaApi.getDownloadMethod(); } /** * Get the active transfer method for uploads * * Valid values for the return parameter are: * - TRANSFER_METHOD_NORMAL = 0 * HTTP transfers using port 80. Data is already encrypted. * * - TRANSFER_METHOD_ALTERNATIVE_PORT = 1 * HTTP transfers using port 8080. Data is already encrypted. * * - TRANSFER_METHOD_AUTO = 2 * The SDK selects the transfer method automatically * * - TRANSFER_METHOD_AUTO_NORMAL = 3 * The SDK selects the transfer method automatically starting with port 80. * * - TRANSFER_METHOD_AUTO_ALTERNATIVE = 4 * The SDK selects the transfer method automatically starting with alternative port 8080. * * @return Active transfer method for uploads */ public int getUploadMethod() { return megaApi.getUploadMethod(); } /** * Get all active transfers. * * @return List with all active transfers. */ public ArrayList<MegaTransfer> getTransfers() { return transferListToArray(megaApi.getTransfers()); } /** * Get all active transfers based on the type. * * @param type * MegaTransfer.TYPE_DOWNLOAD || MegaTransfer.TYPE_UPLOAD. * * @return List with all active download or upload transfers. */ public ArrayList<MegaTransfer> getTransfers(int type) { return transferListToArray(megaApi.getTransfers(type)); } /** * Get the transfer with a transfer tag. * <p> * MegaTransfer.getTag() can be used to get the transfer tag. * * @param transferTag * tag to check. * @return MegaTransfer object with that tag, or null if there is not any * active transfer with it. * */ public MegaTransfer getTransferByTag(int transferTag) { return megaApi.getTransferByTag(transferTag); } /** * Get the maximum download speed in bytes per second * * The value 0 means unlimited speed * * @return Download speed in bytes per second */ public int getMaxDownloadSpeed(){ return megaApi.getMaxDownloadSpeed(); } /** * Get the maximum upload speed in bytes per second * * The value 0 means unlimited speed * * @return Upload speed in bytes per second */ public int getMaxUploadSpeed(){ return megaApi.getMaxUploadSpeed(); } /** * Return the current download speed * @return Download speed in bytes per second */ public int getCurrentDownloadSpeed(){ return megaApi.getCurrentDownloadSpeed(); } /** * Return the current download speed * @return Download speed in bytes per second */ public int getCurrentUploadSpeed(){ return megaApi.getCurrentUploadSpeed(); } /** * Return the current transfer speed * @param type Type of transfer to get the speed. * Valid values are MegaTransfer::TYPE_DOWNLOAD or MegaTransfer::TYPE_UPLOAD * @return Transfer speed for the transfer type, or 0 if the parameter is invalid */ public int getCurrentSpeed(int type){ return megaApi.getCurrentSpeed(type); } /** * Get information about transfer queues * @param listener MegaTransferListener to start receiving information about transfers * @return Information about transfer queues */ public MegaTransferData getTransferData(MegaTransferListenerInterface listener){ return megaApi.getTransferData(createDelegateTransferListener(listener, false)); } /** * Get the first transfer in a transfer queue * * You take the ownership of the returned value. * * @param type queue to get the first transfer (MegaTransfer::TYPE_DOWNLOAD or MegaTransfer::TYPE_UPLOAD) * @return MegaTransfer object related to the first transfer in the queue or NULL if there isn't any transfer */ public MegaTransfer getFirstTransfer(int type){ return megaApi.getFirstTransfer(type); } /** * Force an onTransferUpdate callback for the specified transfer * * The callback will be received by transfer listeners registered to receive all * callbacks related to callbacks and additionally by the listener in the last * parameter of this function, if it's not NULL. * * @param transfer Transfer that will be provided in the onTransferUpdate callback * @param listener Listener that will receive the callback */ public void notifyTransfer(MegaTransfer transfer, MegaTransferListenerInterface listener){ megaApi.notifyTransfer(transfer, createDelegateTransferListener(listener)); } /** * Force an onTransferUpdate callback for the specified transfer * * The callback will be received by transfer listeners registered to receive all * callbacks related to callbacks and additionally by the listener in the last * parameter of this function, if it's not NULL. * * @param transferTag Tag of the transfer that will be provided in the onTransferUpdate callback * @param listener Listener that will receive the callback */ public void notifyTransferByTag(int transferTag, MegaTransferListenerInterface listener){ megaApi.notifyTransferByTag(transferTag, createDelegateTransferListener(listener)); } /** * Get a list of transfers that belong to a folder transfer * * This function provides the list of transfers started in the context * of a folder transfer. * * If the tag in the parameter doesn't belong to a folder transfer, * this function returns an empty list. * * The transfers provided by this function are the ones that are added to the * transfer queue when this function is called. Finished transfers, or transfers * not added to the transfer queue yet (for example, uploads that are waiting for * the creation of the parent folder in MEGA) are not returned by this function. * * @param transferTag Tag of the folder transfer to check * @return List of transfers in the context of the selected folder transfer * @see MegaTransfer::isFolderTransfer, MegaTransfer::getFolderTransferTag */ public ArrayList<MegaTransfer> getChildTransfers(int transferTag) { return transferListToArray(megaApi.getChildTransfers(transferTag)); } /** * Check if the SDK is waiting for the server. * * @return true if the SDK is waiting for the server to complete a request. */ public int isWaiting() { return megaApi.isWaiting(); } /** * Check if the SDK is waiting for the server * @return true if the SDK is waiting for the server to complete a request */ public int areServersBusy(){ return megaApi.areServersBusy(); } /** * Get the number of pending uploads * * @return Pending uploads * * Function related to statistics will be reviewed in future updates to * provide more data and avoid race conditions. They could change or be removed in the current form. */ public int getNumPendingUploads() { return megaApi.getNumPendingUploads(); } /** * Get the number of pending downloads * @return Pending downloads * * Function related to statistics will be reviewed in future updates to * provide more data and avoid race conditions. They could change or be removed in the current form. */ public int getNumPendingDownloads() { return megaApi.getNumPendingDownloads(); } /** * Get the number of queued uploads since the last call to MegaApi::resetTotalUploads * @return Number of queued uploads since the last call to MegaApi::resetTotalUploads * * Function related to statistics will be reviewed in future updates to * provide more data and avoid race conditions. They could change or be removed in the current form. */ public int getTotalUploads() { return megaApi.getTotalUploads(); } /** * Get the number of queued uploads since the last call to MegaApiJava.resetTotalDownloads(). * * @return Number of queued uploads since the last call to MegaApiJava.resetTotalDownloads(). * Function related to statistics will be reviewed in future updates. They * could change or be removed in the current form. */ public int getTotalDownloads() { return megaApi.getTotalDownloads(); } /** * Reset the number of total downloads. * <p> * This function resets the number returned by MegaApiJava.getTotalDownloads(). * * Function related to statistics will be reviewed in future updates to * provide more data and avoid race conditions. They could change or be removed in the current form. * */ public void resetTotalDownloads() { megaApi.resetTotalDownloads(); } /** * Reset the number of total uploads. * <p> * This function resets the number returned by MegaApiJava.getTotalUploads(). * * Function related to statistics will be reviewed in future updates to * provide more data and avoid race conditions. They could change or be removed in the current form. */ public void resetTotalUploads() { megaApi.resetTotalUploads(); } /** * Get the total downloaded bytes * @return Total downloaded bytes * * The count starts with the creation of MegaApi and is reset with calls to MegaApi::resetTotalDownloads * or just before a log in or a log out. * * Function related to statistics will be reviewed in future updates to * provide more data and avoid race conditions. They could change or be removed in the current form. */ public long getTotalDownloadedBytes() { return megaApi.getTotalDownloadedBytes(); } /** * Get the total uploaded bytes * @return Total uploaded bytes * * The count starts with the creation of MegaApi and is reset with calls to MegaApi::resetTotalUploads * or just before a log in or a log out. * * Function related to statistics will be reviewed in future updates to * provide more data and avoid race conditions. They could change or be removed in the current form. * */ public long getTotalUploadedBytes() { return megaApi.getTotalUploadedBytes(); } /** * @brief Get the total bytes of started downloads * @return Total bytes of started downloads * * The count starts with the creation of MegaApi and is reset with calls to MegaApi::resetTotalDownloads * or just before a log in or a log out. * * Function related to statistics will be reviewed in future updates to * provide more data and avoid race conditions. They could change or be removed in the current form. */ public long getTotalDownloadBytes(){ return megaApi.getTotalDownloadBytes(); } /** * Get the total bytes of started uploads * @return Total bytes of started uploads * * The count starts with the creation of MegaApi and is reset with calls to MegaApi::resetTotalUploads * or just before a log in or a log out. * * Function related to statistics will be reviewed in future updates to * provide more data and avoid race conditions. They could change or be removed in the current form. * */ public long getTotalUploadBytes(){ return megaApi.getTotalUploadBytes(); } /** * Get the total number of nodes in the account * @return Total number of nodes in the account */ public long getNumNodes() { return megaApi.getNumNodes(); } /** * Starts an unbuffered download of a node (file) from the user's MEGA account. * * @param node The MEGA node to download. * @param startOffset long. The byte to start from. * @param size long. Size of the download. * @param outputStream The output stream object to use for this download. * @param listener MegaRequestListener to track this request. */ public void startUnbufferedDownload(MegaNode node, long startOffset, long size, OutputStream outputStream, MegaTransferListenerInterface listener) { DelegateMegaTransferListener delegateListener = new DelegateOutputMegaTransferListener(this, outputStream, listener, true); activeTransferListeners.add(delegateListener); megaApi.startStreaming(node, startOffset, size, delegateListener); } /** * Starts an unbuffered download of a node (file) from the user's MEGA account. * * @param node The MEGA node to download. * @param outputStream The output stream object to use for this download. * @param listener MegaRequestListener to track this request. */ public void startUnbufferedDownload(MegaNode node, OutputStream outputStream, MegaTransferListenerInterface listener) { startUnbufferedDownload(node, 0, node.getSize(), outputStream, listener); } /****************************************************************************************************/ // FILESYSTEM METHODS /****************************************************************************************************/ /** * Get the number of child nodes. * <p> * If the node does not exist in MEGA or is not a folder, * this function returns 0. * <p> * This function does not search recursively, only returns the direct child nodes. * * @param parent * Parent node. * @return Number of child nodes. */ public int getNumChildren(MegaNode parent) { return megaApi.getNumChildren(parent); } /** * Get the number of child files of a node. * <p> * If the node does not exist in MEGA or is not a folder, * this function returns 0. * <p> * This function does not search recursively, only returns the direct child files. * * @param parent * Parent node. * @return Number of child files. */ public int getNumChildFiles(MegaNode parent) { return megaApi.getNumChildFiles(parent); } /** * Get the number of child folders of a node. * <p> * If the node does not exist in MEGA or is not a folder, * this function returns 0. * <p> * This function does not search recursively, only returns the direct child folders. * * @param parent * Parent node. * @return Number of child folders. */ public int getNumChildFolders(MegaNode parent) { return megaApi.getNumChildFolders(parent); } /** * Get all children of a MegaNode * * If the parent node doesn't exist or it isn't a folder, this function * returns NULL * * You take the ownership of the returned value * * @param parent Parent node * @param order Order for the returned list * Valid values for this parameter are: * - MegaApi::ORDER_NONE = 0 * Undefined order * * - MegaApi::ORDER_DEFAULT_ASC = 1 * Folders first in alphabetical order, then files in the same order * * - MegaApi::ORDER_DEFAULT_DESC = 2 * Files first in reverse alphabetical order, then folders in the same order * * - MegaApi::ORDER_SIZE_ASC = 3 * Sort by size, ascending * * - MegaApi::ORDER_SIZE_DESC = 4 * Sort by size, descending * * - MegaApi::ORDER_CREATION_ASC = 5 * Sort by creation time in MEGA, ascending * * - MegaApi::ORDER_CREATION_DESC = 6 * Sort by creation time in MEGA, descending * * - MegaApi::ORDER_MODIFICATION_ASC = 7 * Sort by modification time of the original file, ascending * * - MegaApi::ORDER_MODIFICATION_DESC = 8 * Sort by modification time of the original file, descending * * - MegaApi::ORDER_ALPHABETICAL_ASC = 9 * Same behavior than MegaApi::ORDER_DEFAULT_ASC * * - MegaApi::ORDER_ALPHABETICAL_DESC = 10 * Same behavior than MegaApi::ORDER_DEFAULT_DESC * * - MegaApi::ORDER_PHOTO_ASC = 11 * Sort with photos first, then by date ascending * * - MegaApi::ORDER_PHOTO_DESC = 12 * Sort with photos first, then by date descending * * - MegaApi::ORDER_VIDEO_ASC = 13 * Sort with videos first, then by date ascending * * - MegaApi::ORDER_VIDEO_DESC = 14 * Sort with videos first, then by date descending * * - MegaApi::ORDER_LABEL_ASC = 17 * Sort by color label, ascending. With this order, folders are returned first, then files * * - MegaApi::ORDER_LABEL_DESC = 18 * Sort by color label, descending. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_ASC = 19 * Sort nodes with favourite attr first. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_DESC = 20 * Sort nodes with favourite attr last. With this order, folders are returned first, then files * * Deprecated: MegaApi::ORDER_ALPHABETICAL_ASC and MegaApi::ORDER_ALPHABETICAL_DESC * are equivalent to MegaApi::ORDER_DEFAULT_ASC and MegaApi::ORDER_DEFAULT_DESC. * They will be eventually removed. * * @return List with all child MegaNode objects */ public ArrayList<MegaNode> getChildren(MegaNode parent, int order) { return nodeListToArray(megaApi.getChildren(parent, order)); } /** * Get all children of a list of MegaNodes * * If any parent node doesn't exist or it isn't a folder, that parent * will be skipped. * * You take the ownership of the returned value * * @param parentNodes List of parent nodes * @param order Order for the returned list * Valid values for this parameter are: * - MegaApi::ORDER_NONE = 0 * Undefined order * * - MegaApi::ORDER_DEFAULT_ASC = 1 * Folders first in alphabetical order, then files in the same order * * - MegaApi::ORDER_DEFAULT_DESC = 2 * Files first in reverse alphabetical order, then folders in the same order * * - MegaApi::ORDER_SIZE_ASC = 3 * Sort by size, ascending * * - MegaApi::ORDER_SIZE_DESC = 4 * Sort by size, descending * * - MegaApi::ORDER_CREATION_ASC = 5 * Sort by creation time in MEGA, ascending * * - MegaApi::ORDER_CREATION_DESC = 6 * Sort by creation time in MEGA, descending * * - MegaApi::ORDER_MODIFICATION_ASC = 7 * Sort by modification time of the original file, ascending * * - MegaApi::ORDER_MODIFICATION_DESC = 8 * Sort by modification time of the original file, descending * * - MegaApi::ORDER_PHOTO_ASC = 11 * Sort with photos first, then by date ascending * * - MegaApi::ORDER_PHOTO_DESC = 12 * Sort with photos first, then by date descending * * - MegaApi::ORDER_VIDEO_ASC = 13 * Sort with videos first, then by date ascending * * - MegaApi::ORDER_VIDEO_DESC = 14 * Sort with videos first, then by date descending * * - MegaApi::ORDER_LABEL_ASC = 17 * Sort by color label, ascending. With this order, folders are returned first, then files * * - MegaApi::ORDER_LABEL_DESC = 18 * Sort by color label, descending. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_ASC = 19 * Sort nodes with favourite attr first. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_DESC = 20 * Sort nodes with favourite attr last. With this order, folders are returned first, then files * @return List with all child MegaNode objects */ public ArrayList<MegaNode> getChildren(MegaNodeList parentNodes, int order) { return nodeListToArray(megaApi.getChildren(parentNodes, order)); } /** * Get all versions of a file * @param node Node to check * @return List with all versions of the node, including the current version */ public ArrayList<MegaNode> getVersions(MegaNode node){ return nodeListToArray(megaApi.getVersions(node)); } /** * Get the number of versions of a file * @param node Node to check * @return Number of versions of the node, including the current version */ public int getNumVersions(MegaNode node){ return megaApi.getNumVersions(node); } /** * Check if a file has previous versions * @param node Node to check * @return true if the node has any previous version */ public boolean hasVersions(MegaNode node){ return megaApi.hasVersions(node); } /** * Get information about the contents of a folder * * The associated request type with this request is MegaRequest::TYPE_FOLDER_INFO * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaFolderInfo - MegaFolderInfo object with the information related to the folder * * @param node Folder node to inspect * @param listener MegaRequestListener to track this request */ public void getFolderInfo(MegaNode node, MegaRequestListenerInterface listener){ megaApi.getFolderInfo(node, createDelegateRequestListener(listener)); } /** * Get file and folder children of a MegaNode separatedly * * If the parent node doesn't exist or it isn't a folder, this function * returns NULL * * You take the ownership of the returned value * * @param parent Parent node * @param order Order for the returned lists * Valid values for this parameter are: * - MegaApi::ORDER_NONE = 0 * Undefined order * * - MegaApi::ORDER_DEFAULT_ASC = 1 * Folders first in alphabetical order, then files in the same order * * - MegaApi::ORDER_DEFAULT_DESC = 2 * Files first in reverse alphabetical order, then folders in the same order * * - MegaApi::ORDER_SIZE_ASC = 3 * Sort by size, ascending * * - MegaApi::ORDER_SIZE_DESC = 4 * Sort by size, descending * * - MegaApi::ORDER_CREATION_ASC = 5 * Sort by creation time in MEGA, ascending * * - MegaApi::ORDER_CREATION_DESC = 6 * Sort by creation time in MEGA, descending * * - MegaApi::ORDER_MODIFICATION_ASC = 7 * Sort by modification time of the original file, ascending * * - MegaApi::ORDER_MODIFICATION_DESC = 8 * Sort by modification time of the original file, descending * * - MegaApi::ORDER_ALPHABETICAL_ASC = 9 * Same behavior than MegaApi::ORDER_DEFAULT_ASC * * - MegaApi::ORDER_ALPHABETICAL_DESC = 10 * Same behavior than MegaApi::ORDER_DEFAULT_DESC * * Deprecated: MegaApi::ORDER_ALPHABETICAL_ASC and MegaApi::ORDER_ALPHABETICAL_DESC * are equivalent to MegaApi::ORDER_DEFAULT_ASC and MegaApi::ORDER_DEFAULT_DESC. * They will be eventually removed. * * - MegaApi::ORDER_PHOTO_ASC = 11 * Sort with photos first, then by date ascending * * - MegaApi::ORDER_PHOTO_DESC = 12 * Sort with photos first, then by date descending * * - MegaApi::ORDER_VIDEO_ASC = 13 * Sort with videos first, then by date ascending * * - MegaApi::ORDER_VIDEO_DESC = 14 * Sort with videos first, then by date descending * * - MegaApi::ORDER_LABEL_ASC = 17 * Sort by color label, ascending. With this order, folders are returned first, then files * * - MegaApi::ORDER_LABEL_DESC = 18 * Sort by color label, descending. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_ASC = 19 * Sort nodes with favourite attr first. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_DESC = 20 * Sort nodes with favourite attr last. With this order, folders are returned first, then files * * @return Lists with files and folders child MegaNode objects */ public MegaChildren getFileFolderChildren(MegaNode parent, int order){ MegaChildren children = new MegaChildren(); MegaChildrenLists childrenList = megaApi.getFileFolderChildren(parent, order); children.setFileList(nodeListToArray(childrenList.getFileList())); children.setFolderList(nodeListToArray(childrenList.getFolderList())); return children; } /** * Get all children of a MegaNode. * <p> * If the parent node does not exist or if it is not a folder, this function. * returns null. * * @param parent * Parent node. * * @return List with all child MegaNode objects. */ public ArrayList<MegaNode> getChildren(MegaNode parent) { return nodeListToArray(megaApi.getChildren(parent)); } /** * Returns true if the node has children * @return true if the node has children */ public boolean hasChildren(MegaNode parent){ return megaApi.hasChildren(parent); } /** * Get the child node with the provided name. * <p> * If the node does not exist, this function returns null. * * @param parent * node. * @param name * of the node. * @return The MegaNode that has the selected parent and name. */ public MegaNode getChildNode(MegaNode parent, String name) { return megaApi.getChildNode(parent, name); } /** * Get the parent node of a MegaNode. * <p> * If the node does not exist in the account or * it is a root node, this function returns null. * * @param node * MegaNode to get the parent. * @return The parent of the provided node. */ public MegaNode getParentNode(MegaNode node) { return megaApi.getParentNode(node); } /** * Get the path of a MegaNode. * <p> * If the node does not exist, this function returns null. * You can recover the node later using MegaApi.getNodeByPath() * unless the path contains names with '/', '\' or ':' characters. * * @param node * MegaNode for which the path will be returned. * @return The path of the node. */ public String getNodePath(MegaNode node) { return megaApi.getNodePath(node); } /** * Get the MegaNode in a specific path in the MEGA account. * <p> * The path separator character is '/'. <br> * The Inbox root node is //in/. <br> * The Rubbish root node is //bin/. * <p> * Paths with names containing '/', '\' or ':' are not compatible * with this function. * * @param path * Path to check. * @param baseFolder * Base node if the path is relative. * @return The MegaNode object in the path, otherwise null. */ public MegaNode getNodeByPath(String path, MegaNode baseFolder) { return megaApi.getNodeByPath(path, baseFolder); } /** * Get the MegaNode in a specific path in the MEGA account. * <p> * The path separator character is '/'. <br> * The Inbox root node is //in/. <br> * The Rubbish root node is //bin/. * <p> * Paths with names containing '/', '\' or ':' are not compatible * with this function. * * @param path * Path to check. * * @return The MegaNode object in the path, otherwise null. */ public MegaNode getNodeByPath(String path) { return megaApi.getNodeByPath(path); } /** * Get the MegaNode that has a specific handle. * <p> * You can get the handle of a MegaNode using MegaNode.getHandle(). The same handle * can be got in a Base64-encoded string using MegaNode.getBase64Handle(). Conversions * between these formats can be done using MegaApiJava.base64ToHandle() and MegaApiJava.handleToBase64(). * * @param handle * Node handle to check. * @return MegaNode object with the handle, otherwise null. */ public MegaNode getNodeByHandle(long handle) { return megaApi.getNodeByHandle(handle); } /** * Get the MegaContactRequest that has a specific handle. * <p> * You can get the handle of a MegaContactRequest using MegaContactRequestgetHandle(). * You take the ownership of the returned value. * * @param handle Contact request handle to check. * @return MegaContactRequest object with the handle, otherwise null. */ public MegaContactRequest getContactRequestByHandle(long handle) { return megaApi.getContactRequestByHandle(handle); } /** * Get all contacts of this MEGA account. * * @return List of MegaUser object with all contacts of this account. */ public ArrayList<MegaUser> getContacts() { return userListToArray(megaApi.getContacts()); } /** * Get the MegaUser that has a specific email address. * <p> * You can get the email of a MegaUser using MegaUser.getEmail(). * * @param email * Email address to check. * @return MegaUser that has the email address, otherwise null. */ public MegaUser getContact(String email) { return megaApi.getContact(email); } /** * Get all MegaUserAlerts for the logged in user * * You take the ownership of the returned value * * @return List of MegaUserAlert objects */ public ArrayList<MegaUserAlert> getUserAlerts(){ return userAlertListToArray(megaApi.getUserAlerts()); } /** * Get the number of unread user alerts for the logged in user * * @return Number of unread user alerts */ public int getNumUnreadUserAlerts(){ return megaApi.getNumUnreadUserAlerts(); } /** * Get a list with all inbound shares from one MegaUser. * * @param user MegaUser sharing folders with this account. * @return List of MegaNode objects that this user is sharing with this account. */ public ArrayList<MegaNode> getInShares(MegaUser user) { return nodeListToArray(megaApi.getInShares(user)); } /** * Get a list with all inbound shares from one MegaUser. * * Valid value for order are: MegaApi::ORDER_NONE, MegaApi::ORDER_DEFAULT_ASC, * MegaApi::ORDER_DEFAULT_DESC * * You take the ownership of the returned value * * @param user MegaUser sharing folders with this account. * @param order Sorting order to use * @return List of MegaNode objects that this user is sharing with this account. */ public ArrayList<MegaNode> getInShares(MegaUser user, int order) { return nodeListToArray(megaApi.getInShares(user, order)); } /** * Get a list with all inbound shares. * * @return List of MegaNode objects that other users are sharing with this account. */ public ArrayList<MegaNode> getInShares() { return nodeListToArray(megaApi.getInShares()); } /** * Get a list with all inbound shares. * * Valid value for order are: MegaApi::ORDER_NONE, MegaApi::ORDER_DEFAULT_ASC, * MegaApi::ORDER_DEFAULT_DESC * * You take the ownership of the returned value * * @param order Sorting order to use * @return List of MegaNode objects that other users are sharing with this account. */ public ArrayList<MegaNode> getInShares(int order) { return nodeListToArray(megaApi.getInShares(order)); } /** * Get a list with all active inboud sharings * * You take the ownership of the returned value * * @return List of MegaShare objects that other users are sharing with this account */ public ArrayList<MegaShare> getInSharesList() { return shareListToArray(megaApi.getInSharesList()); } /** * Get a list with all active inboud sharings * * Valid value for order are: MegaApi::ORDER_NONE, MegaApi::ORDER_DEFAULT_ASC, * MegaApi::ORDER_DEFAULT_DESC * * You take the ownership of the returned value * * @param order Sorting order to use * @return List of MegaShare objects that other users are sharing with this account */ public ArrayList<MegaShare> getInSharesList(int order) { return shareListToArray(megaApi.getInSharesList(order)); } /** * Get the user relative to an incoming share * * This function will return NULL if the node is not found. * * If recurse is true, it will return NULL if the root corresponding to * the node received as argument doesn't represent the root of an incoming share. * Otherwise, it will return NULL if the node doesn't represent * the root of an incoming share. * * You take the ownership of the returned value * * @param node Node to look for inshare user. * @return MegaUser relative to the incoming share */ public MegaUser getUserFromInShare(MegaNode node) { return megaApi.getUserFromInShare(node); } /** * Get the user relative to an incoming share * * This function will return NULL if the node is not found. * * When recurse is true and the root of the specified node is not an incoming share, * this function will return NULL. * When recurse is false and the specified node doesn't represent the root of an * incoming share, this function will return NULL. * * You take the ownership of the returned value * * @param node Node to look for inshare user. * @param recurse use root node corresponding to the node passed * @return MegaUser relative to the incoming share */ public MegaUser getUserFromInShare(MegaNode node, boolean recurse) { return megaApi.getUserFromInShare(node, recurse); } /** * Check if a MegaNode is pending to be shared with another User. This situation * happens when a node is to be shared with a User which is not a contact yet. * * For nodes that are pending to be shared, you can get a list of MegaNode * objects using MegaApi::getPendingShares * * @param node Node to check * @return true is the MegaNode is pending to be shared, otherwise false */ public boolean isPendingShare(MegaNode node) { return megaApi.isPendingShare(node); } /** * Get a list with all active and pending outbound sharings * * @return List of MegaShare objects. */ public ArrayList<MegaShare> getOutShares() { return shareListToArray(megaApi.getOutShares()); } /** * Get a list with the active and pending outbound sharings for a MegaNode * * Valid value for order are: MegaApi::ORDER_NONE, MegaApi::ORDER_DEFAULT_ASC, * MegaApi::ORDER_DEFAULT_DESC * * You take the ownership of the returned value * * @param order Sorting order to use * @return List of MegaShare objects. */ public ArrayList<MegaShare> getOutShares(int order) { return shareListToArray(megaApi.getOutShares(order)); } /** * Get a list with the active and pending outbound sharings for a MegaNode * * If the node doesn't exist in the account, this function returns an empty list. * * You take the ownership of the returned value * * @param node MegaNode to check. * @return List of MegaShare objects. */ public ArrayList<MegaShare> getOutShares(MegaNode node) { return shareListToArray(megaApi.getOutShares(node)); } /** * Check if a node belongs to your own cloud * * @param handle Node to check * @return True if it belongs to your own cloud */ public boolean isPrivateNode(long handle) { return megaApi.isPrivateNode(handle); } /** * Check if a node does NOT belong to your own cloud * * In example, nodes from incoming shared folders do not belong to your cloud. * * @param handle Node to check * @return True if it does NOT belong to your own cloud */ public boolean isForeignNode(long handle) { return megaApi.isForeignNode(handle); } /** * Get a list with all public links * * You take the ownership of the returned value * * @return List of MegaNode objects that are shared with everyone via public link */ public ArrayList<MegaNode> getPublicLinks() { return nodeListToArray(megaApi.getPublicLinks()); } /** * Get a list with all public links * * Valid value for order are: MegaApi::ORDER_NONE, MegaApi::ORDER_DEFAULT_ASC, * MegaApi::ORDER_DEFAULT_DESC, MegaApi::ORDER_LINK_CREATION_ASC, * MegaApi::ORDER_LINK_CREATION_DESC * * You take the ownership of the returned value * * @param order Sorting order to use * @return List of MegaNode objects that are shared with everyone via public link */ public ArrayList<MegaNode> getPublicLinks(int order) { return nodeListToArray(megaApi.getPublicLinks(order)); } /** * Get a list with all incoming contact requests. * * You take the ownership of the returned value * * @return List of MegaContactRequest objects. */ public ArrayList<MegaContactRequest> getIncomingContactRequests() { return contactRequestListToArray(megaApi.getIncomingContactRequests()); } /** * Get a list with all outgoing contact requests. * * You take the ownership of the returned value * * @return List of MegaContactRequest objects. */ public ArrayList<MegaContactRequest> getOutgoingContactRequests() { return contactRequestListToArray(megaApi.getOutgoingContactRequests()); } /** * Get the access level of a MegaNode. * * @param node * MegaNode to check. * @return Access level of the node. * Valid values are: <br> * - MegaShare.ACCESS_OWNER. <br> * - MegaShare.ACCESS_FULL. <br> * - MegaShare.ACCESS_READWRITE. <br> * - MegaShare.ACCESS_READ. <br> * - MegaShare.ACCESS_UNKNOWN. */ public int getAccess(MegaNode node) { return megaApi.getAccess(node); } /** * Get the size of a node tree. * <p> * If the MegaNode is a file, this function returns the size of the file. * If it's a folder, this function returns the sum of the sizes of all nodes * in the node tree. * * @param node * Parent node. * @return Size of the node tree. */ public long getSize(MegaNode node) { return megaApi.getSize(node); } /** * Get a Base64-encoded fingerprint for a local file. * <p> * The fingerprint is created taking into account the modification time of the file * and file contents. This fingerprint can be used to get a corresponding node in MEGA * using MegaApiJava.getNodeByFingerprint(). * <p> * If the file can't be found or can't be opened, this function returns null. * * @param filePath * Local file path. * @return Base64-encoded fingerprint for the file. */ public String getFingerprint(String filePath) { return megaApi.getFingerprint(filePath); } /** * Get a Base64-encoded fingerprint for a node. * <p> * If the node does not exist or does not have a fingerprint, this function returns null. * * @param node * Node for which we want to get the fingerprint. * @return Base64-encoded fingerprint for the file. */ public String getFingerprint(MegaNode node) { return megaApi.getFingerprint(node); } /** * Returns a node with the provided fingerprint. * <p> * If there is not any node in the account with that fingerprint, this function returns null. * * @param fingerprint * Fingerprint to check. * @return MegaNode object with the provided fingerprint. */ public MegaNode getNodeByFingerprint(String fingerprint) { return megaApi.getNodeByFingerprint(fingerprint); } /** * Returns a node with the provided fingerprint in a preferred parent folder. * <p> * If there is not any node in the account with that fingerprint, this function returns null. * * @param fingerprint * Fingerprint to check. * @param preferredParent * Preferred parent if several matches are found. * @return MegaNode object with the provided fingerprint. */ public MegaNode getNodeByFingerprint(String fingerprint, MegaNode preferredParent) { return megaApi.getNodeByFingerprint(fingerprint, preferredParent); } /** * Returns all nodes that have a fingerprint * * If there isn't any node in the account with that fingerprint, this function returns an empty MegaNodeList. * * @param fingerprint Fingerprint to check * @return List of nodes with the same fingerprint */ public ArrayList<MegaNode> getNodesByFingerprint(String fingerprint) { return nodeListToArray(megaApi.getNodesByFingerprint(fingerprint)); } /** * Returns a node with the provided fingerprint that can be exported * * If there isn't any node in the account with that fingerprint, this function returns null. * If a file name is passed in the second parameter, it's also checked if nodes with a matching * fingerprint has that name. If there isn't any matching node, this function returns null. * This function ignores nodes that are inside the Rubbish Bin because public links to those nodes * can't be downloaded. * * @param fingerprint Fingerprint to check * @param name Name that the node should have * @return Exportable node that meet the requirements */ public MegaNode getExportableNodeByFingerprint(String fingerprint, String name) { return megaApi.getExportableNodeByFingerprint(fingerprint, name); } /** * Returns a node with the provided fingerprint that can be exported * * If there isn't any node in the account with that fingerprint, this function returns null. * This function ignores nodes that are inside the Rubbish Bin because public links to those nodes * can't be downloaded. * * @param fingerprint Fingerprint to check * @return Exportable node that meet the requirements */ public MegaNode getExportableNodeByFingerprint(String fingerprint) { return megaApi.getExportableNodeByFingerprint(fingerprint); } /** * Check if the account already has a node with the provided fingerprint. * <p> * A fingerprint for a local file can be generated using MegaApiJava.getFingerprint(). * * @param fingerprint * Fingerprint to check. * @return true if the account contains a node with the same fingerprint. */ public boolean hasFingerprint(String fingerprint) { return megaApi.hasFingerprint(fingerprint); } /** * getCRC Get the CRC of a file * * The CRC of a file is a hash of its contents. * If you need a more realiable method to check files, use fingerprint functions * (MegaApi::getFingerprint, MegaApi::getNodeByFingerprint) that also takes into * account the size and the modification time of the file to create the fingerprint. * * @param filePath Local file path * @return Base64-encoded CRC of the file */ public String getCRC(String filePath) { return megaApi.getCRC(filePath); } /** * Get the CRC from a fingerprint * * @param fingerprint fingerprint from which we want to get the CRC * @return Base64-encoded CRC from the fingerprint */ public String getCRCFromFingerprint(String fingerprint) { return megaApi.getCRCFromFingerprint(fingerprint); } /** * getCRC Get the CRC of a node * * The CRC of a node is a hash of its contents. * If you need a more realiable method to check files, use fingerprint functions * (MegaApi::getFingerprint, MegaApi::getNodeByFingerprint) that also takes into * account the size and the modification time of the node to create the fingerprint. * * @param node Node for which we want to get the CRC * @return Base64-encoded CRC of the node */ public String getCRC(MegaNode node) { return megaApi.getCRC(node); } /** * getNodeByCRC Returns a node with the provided CRC * * If there isn't any node in the selected folder with that CRC, this function returns NULL. * If there are several nodes with the same CRC, anyone can be returned. * * @param crc CRC to check * @param parent Parent node to scan. It must be a folder. * @return Node with the selected CRC in the selected folder, or NULL * if it's not found. */ public MegaNode getNodeByCRC(String crc, MegaNode parent) { return megaApi.getNodeByCRC(crc, parent); } /** * Check if a node has an access level. * * @param node * Node to check. * @param level * Access level to check. * Valid values for this parameter are: <br> * - MegaShare.ACCESS_OWNER. <br> * - MegaShare.ACCESS_FULL. <br> * - MegaShare.ACCESS_READWRITE. <br> * - MegaShare.ACCESS_READ. * @return MegaError object with the result. * Valid values for the error code are: <br> * - MegaError.API_OK - The node has the required access level. <br> * - MegaError.API_EACCESS - The node does not have the required access level. <br> * - MegaError.API_ENOENT - The node does not exist in the account. <br> * - MegaError.API_EARGS - Invalid parameters. */ public MegaError checkAccess(MegaNode node, int level) { return megaApi.checkAccess(node, level); } /** * Check if a node can be moved to a target node. * * @param node * Node to check. * @param target * Target for the move operation. * @return MegaError object with the result. * Valid values for the error code are: <br> * - MegaError.API_OK - The node can be moved to the target. <br> * - MegaError.API_EACCESS - The node can't be moved because of permissions problems. <br> * - MegaError.API_ECIRCULAR - The node can't be moved because that would create a circular linkage. <br> * - MegaError.API_ENOENT - The node or the target does not exist in the account. <br> * - MegaError.API_EARGS - Invalid parameters. */ public MegaError checkMove(MegaNode node, MegaNode target) { return megaApi.checkMove(node, target); } /** * Check if the MEGA filesystem is available in the local computer * * This function returns true after a successful call to MegaApi::fetchNodes, * otherwise it returns false * * @return True if the MEGA filesystem is available */ public boolean isFilesystemAvailable() { return megaApi.isFilesystemAvailable(); } /** * Returns the root node of the account. * <p> * If you haven't successfully called MegaApiJava.fetchNodes() before, * this function returns null. * * @return Root node of the account. */ public MegaNode getRootNode() { return megaApi.getRootNode(); } /** * Check if a node is in the Cloud Drive tree * * @param node Node to check * @return True if the node is in the cloud drive */ public boolean isInCloud(MegaNode node){ return megaApi.isInCloud(node); } /** * Check if a node is in the Rubbish bin tree * * @param node Node to check * @return True if the node is in the Rubbish bin */ public boolean isInRubbish(MegaNode node){ return megaApi.isInRubbish(node); } /** * Check if a node is in the Inbox tree * * @param node Node to check * @return True if the node is in the Inbox */ public boolean isInInbox(MegaNode node){ return megaApi.isInInbox(node); } /** * Returns the inbox node of the account. * <p> * If you haven't successfully called MegaApiJava.fetchNodes() before, * this function returns null. * * @return Inbox node of the account. */ public MegaNode getInboxNode() { return megaApi.getInboxNode(); } /** * Returns the rubbish node of the account. * <p> * If you haven't successfully called MegaApiJava.fetchNodes() before, * this function returns null. * * @return Rubbish node of the account. */ public MegaNode getRubbishNode() { return megaApi.getRubbishNode(); } /** * Get the time (in seconds) during which transfers will be stopped due to a bandwidth overquota * @return Time (in seconds) during which transfers will be stopped, otherwise 0 */ public long getBandwidthOverquotaDelay() { return megaApi.getBandwidthOverquotaDelay(); } /** * Search nodes containing a search string in their name * * The search is case-insensitive. * * You take the ownership of the returned value. * * This function allows to cancel the processing at any time by passing a MegaCancelToken and calling * to MegaCancelToken::setCancelFlag(true). If a valid object is passed, it must be kept alive until * this method returns. * * @param node The parent node of the tree to explore * @param searchString Search string. The search is case-insensitive * @param cancelToken MegaCancelToken to be able to cancel the processing at any time. * @param recursive True if you want to search recursively in the node tree. * False if you want to search in the children of the node only * @param order Order for the returned list * Valid values for this parameter are: * - MegaApi::ORDER_NONE = 0 * Undefined order * * - MegaApi::ORDER_DEFAULT_ASC = 1 * Folders first in alphabetical order, then files in the same order * * - MegaApi::ORDER_DEFAULT_DESC = 2 * Files first in reverse alphabetical order, then folders in the same order * * - MegaApi::ORDER_SIZE_ASC = 3 * Sort by size, ascending * * - MegaApi::ORDER_SIZE_DESC = 4 * Sort by size, descending * * - MegaApi::ORDER_CREATION_ASC = 5 * Sort by creation time in MEGA, ascending * * - MegaApi::ORDER_CREATION_DESC = 6 * Sort by creation time in MEGA, descending * * - MegaApi::ORDER_MODIFICATION_ASC = 7 * Sort by modification time of the original file, ascending * * - MegaApi::ORDER_MODIFICATION_DESC = 8 * Sort by modification time of the original file, descending * * - MegaApi::ORDER_ALPHABETICAL_ASC = 9 * Same behavior than MegaApi::ORDER_DEFAULT_ASC * * - MegaApi::ORDER_ALPHABETICAL_DESC = 10 * Same behavior than MegaApi::ORDER_DEFAULT_DESC * * Deprecated: MegaApi::ORDER_ALPHABETICAL_ASC and MegaApi::ORDER_ALPHABETICAL_DESC * are equivalent to MegaApi::ORDER_DEFAULT_ASC and MegaApi::ORDER_DEFAULT_DESC. * They will be eventually removed. * * - MegaApi::ORDER_PHOTO_ASC = 11 * Sort with photos first, then by date ascending * * - MegaApi::ORDER_PHOTO_DESC = 12 * Sort with photos first, then by date descending * * - MegaApi::ORDER_VIDEO_ASC = 13 * Sort with videos first, then by date ascending * * - MegaApi::ORDER_VIDEO_DESC = 14 * Sort with videos first, then by date descending * * - MegaApi::ORDER_LABEL_ASC = 17 * Sort by color label, ascending. With this order, folders are returned first, then files * * - MegaApi::ORDER_LABEL_DESC = 18 * Sort by color label, descending. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_ASC = 19 * Sort nodes with favourite attr first. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_DESC = 20 * Sort nodes with favourite attr last. With this order, folders are returned first, then files * * @return List of nodes that contain the desired string in their name */ public ArrayList<MegaNode> search(MegaNode node, String searchString, @NotNull MegaCancelToken cancelToken, boolean recursive, int order) { return nodeListToArray(megaApi.search(node, searchString, cancelToken, recursive, order)); } /** * Search nodes containing a search string in their name * * The search is case-insensitive. * * The search will consider every accessible node for the account: * - Cloud drive * - Inbox * - Rubbish bin * - Incoming shares from other users * * This function allows to cancel the processing at any time by passing a MegaCancelToken and calling * to MegaCancelToken::setCancelFlag(true). If a valid object is passed, it must be kept alive until * this method returns. * * You take the ownership of the returned value. * * @param searchString Search string. The search is case-insensitive * @param cancelToken MegaCancelToken to be able to cancel the processing at any time. * @param order Order for the returned list * Valid values for this parameter are: * - MegaApi::ORDER_NONE = 0 * Undefined order * * - MegaApi::ORDER_DEFAULT_ASC = 1 * Folders first in alphabetical order, then files in the same order * * - MegaApi::ORDER_DEFAULT_DESC = 2 * Files first in reverse alphabetical order, then folders in the same order * * - MegaApi::ORDER_SIZE_ASC = 3 * Sort by size, ascending * * - MegaApi::ORDER_SIZE_DESC = 4 * Sort by size, descending * * - MegaApi::ORDER_CREATION_ASC = 5 * Sort by creation time in MEGA, ascending * * - MegaApi::ORDER_CREATION_DESC = 6 * Sort by creation time in MEGA, descending * * - MegaApi::ORDER_MODIFICATION_ASC = 7 * Sort by modification time of the original file, ascending * * - MegaApi::ORDER_MODIFICATION_DESC = 8 * Sort by modification time of the original file, descending * * - MegaApi::ORDER_ALPHABETICAL_ASC = 9 * Same behavior than MegaApi::ORDER_DEFAULT_ASC * * - MegaApi::ORDER_ALPHABETICAL_DESC = 10 * Same behavior than MegaApi::ORDER_DEFAULT_DESC * * Deprecated: MegaApi::ORDER_ALPHABETICAL_ASC and MegaApi::ORDER_ALPHABETICAL_DESC * are equivalent to MegaApi::ORDER_DEFAULT_ASC and MegaApi::ORDER_DEFAULT_DESC. * They will be eventually removed. * * - MegaApi::ORDER_PHOTO_ASC = 11 * Sort with photos first, then by date ascending * * - MegaApi::ORDER_PHOTO_DESC = 12 * Sort with photos first, then by date descending * * - MegaApi::ORDER_VIDEO_ASC = 13 * Sort with videos first, then by date ascending * * - MegaApi::ORDER_VIDEO_DESC = 14 * Sort with videos first, then by date descending * * - MegaApi::ORDER_LABEL_ASC = 17 * Sort by color label, ascending. With this order, folders are returned first, then files * * - MegaApi::ORDER_LABEL_DESC = 18 * Sort by color label, descending. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_ASC = 19 * Sort nodes with favourite attr first. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_DESC = 20 * Sort nodes with favourite attr last. With this order, folders are returned first, then files * * @return List of nodes that contain the desired string in their name */ public ArrayList<MegaNode> search(String searchString, @NotNull MegaCancelToken cancelToken, int order) { return nodeListToArray(megaApi.search(searchString, cancelToken, order)); } /** * Search nodes on incoming shares containing a search string in their name * * The search is case-insensitive. * * The method will search exclusively on incoming shares * * This function allows to cancel the processing at any time by passing a MegaCancelToken and calling * to MegaCancelToken::setCancelFlag(true). If a valid object is passed, it must be kept alive until * this method returns. * * You take the ownership of the returned value. * * @param searchString Search string. The search is case-insensitive * @param cancelToken MegaCancelToken to be able to cancel the processing at any time. * @param order Order for the returned list * Valid values for this parameter are: * - MegaApi::ORDER_NONE = 0 * Undefined order * * - MegaApi::ORDER_DEFAULT_ASC = 1 * Folders first in alphabetical order, then files in the same order * * - MegaApi::ORDER_DEFAULT_DESC = 2 * Files first in reverse alphabetical order, then folders in the same order * * - MegaApi::ORDER_SIZE_ASC = 3 * Sort by size, ascending * * - MegaApi::ORDER_SIZE_DESC = 4 * Sort by size, descending * * - MegaApi::ORDER_CREATION_ASC = 5 * Sort by creation time in MEGA, ascending * * - MegaApi::ORDER_CREATION_DESC = 6 * Sort by creation time in MEGA, descending * * - MegaApi::ORDER_MODIFICATION_ASC = 7 * Sort by modification time of the original file, ascending * * - MegaApi::ORDER_MODIFICATION_DESC = 8 * Sort by modification time of the original file, descending * * - MegaApi::ORDER_ALPHABETICAL_ASC = 9 * Same behavior than MegaApi::ORDER_DEFAULT_ASC * * - MegaApi::ORDER_ALPHABETICAL_DESC = 10 * Same behavior than MegaApi::ORDER_DEFAULT_DESC * * Deprecated: MegaApi::ORDER_ALPHABETICAL_ASC and MegaApi::ORDER_ALPHABETICAL_DESC * are equivalent to MegaApi::ORDER_DEFAULT_ASC and MegaApi::ORDER_DEFAULT_DESC. * They will be eventually removed. * * - MegaApi::ORDER_PHOTO_ASC = 11 * Sort with photos first, then by date ascending * * - MegaApi::ORDER_PHOTO_DESC = 12 * Sort with photos first, then by date descending * * - MegaApi::ORDER_VIDEO_ASC = 13 * Sort with videos first, then by date ascending * * - MegaApi::ORDER_VIDEO_DESC = 14 * Sort with videos first, then by date descending * * - MegaApi::ORDER_LABEL_ASC = 17 * Sort by color label, ascending. With this order, folders are returned first, then files * * - MegaApi::ORDER_LABEL_DESC = 18 * Sort by color label, descending. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_ASC = 19 * Sort nodes with favourite attr first. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_DESC = 20 * Sort nodes with favourite attr last. With this order, folders are returned first, then files * * @return List of nodes that contain the desired string in their name */ public ArrayList<MegaNode> searchOnInShares(String searchString, @NotNull MegaCancelToken cancelToken, int order) { return nodeListToArray(megaApi.searchOnInShares(searchString, cancelToken, order)); } /** * Search nodes on outbound shares containing a search string in their name * * The search is case-insensitive. * * The method will search exclusively on outbound shares * * This function allows to cancel the processing at any time by passing a MegaCancelToken and calling * to MegaCancelToken::setCancelFlag(true). If a valid object is passed, it must be kept alive until * this method returns. * * You take the ownership of the returned value. * * @param searchString Search string. The search is case-insensitive * @param cancelToken MegaCancelToken to be able to cancel the processing at any time. * @param order Order for the returned list * Valid values for this parameter are: * - MegaApi::ORDER_NONE = 0 * Undefined order * * - MegaApi::ORDER_DEFAULT_ASC = 1 * Folders first in alphabetical order, then files in the same order * * - MegaApi::ORDER_DEFAULT_DESC = 2 * Files first in reverse alphabetical order, then folders in the same order * * - MegaApi::ORDER_SIZE_ASC = 3 * Sort by size, ascending * * - MegaApi::ORDER_SIZE_DESC = 4 * Sort by size, descending * * - MegaApi::ORDER_CREATION_ASC = 5 * Sort by creation time in MEGA, ascending * * - MegaApi::ORDER_CREATION_DESC = 6 * Sort by creation time in MEGA, descending * * - MegaApi::ORDER_MODIFICATION_ASC = 7 * Sort by modification time of the original file, ascending * * - MegaApi::ORDER_MODIFICATION_DESC = 8 * Sort by modification time of the original file, descending * * - MegaApi::ORDER_ALPHABETICAL_ASC = 9 * Same behavior than MegaApi::ORDER_DEFAULT_ASC * * - MegaApi::ORDER_ALPHABETICAL_DESC = 10 * Same behavior than MegaApi::ORDER_DEFAULT_DESC * * Deprecated: MegaApi::ORDER_ALPHABETICAL_ASC and MegaApi::ORDER_ALPHABETICAL_DESC * are equivalent to MegaApi::ORDER_DEFAULT_ASC and MegaApi::ORDER_DEFAULT_DESC. * They will be eventually removed. * * - MegaApi::ORDER_PHOTO_ASC = 11 * Sort with photos first, then by date ascending * * - MegaApi::ORDER_PHOTO_DESC = 12 * Sort with photos first, then by date descending * * - MegaApi::ORDER_VIDEO_ASC = 13 * Sort with videos first, then by date ascending * * - MegaApi::ORDER_VIDEO_DESC = 14 * Sort with videos first, then by date descending * * - MegaApi::ORDER_LABEL_ASC = 17 * Sort by color label, ascending. With this order, folders are returned first, then files * * - MegaApi::ORDER_LABEL_DESC = 18 * Sort by color label, descending. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_ASC = 19 * Sort nodes with favourite attr first. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_DESC = 20 * Sort nodes with favourite attr last. With this order, folders are returned first, then files * * @return List of nodes that contain the desired string in their name */ public ArrayList<MegaNode> searchOnOutShares(String searchString, @NotNull MegaCancelToken cancelToken, int order) { return nodeListToArray(megaApi.searchOnOutShares(searchString, cancelToken, order)); } /** * Search nodes on public links containing a search string in their name * * The search is case-insensitive. * * The method will search exclusively on public links * * This function allows to cancel the processing at any time by passing a MegaCancelToken and calling * to MegaCancelToken::setCancelFlag(true). If a valid object is passed, it must be kept alive until * this method returns. * * You take the ownership of the returned value. * * @param searchString Search string. The search is case-insensitive * @param cancelToken MegaCancelToken to be able to cancel the processing at any time. * @param order Order for the returned list * Valid values for this parameter are: * - MegaApi::ORDER_NONE = 0 * Undefined order * * - MegaApi::ORDER_DEFAULT_ASC = 1 * Folders first in alphabetical order, then files in the same order * * - MegaApi::ORDER_DEFAULT_DESC = 2 * Files first in reverse alphabetical order, then folders in the same order * * - MegaApi::ORDER_SIZE_ASC = 3 * Sort by size, ascending * * - MegaApi::ORDER_SIZE_DESC = 4 * Sort by size, descending * * - MegaApi::ORDER_CREATION_ASC = 5 * Sort by creation time in MEGA, ascending * * - MegaApi::ORDER_CREATION_DESC = 6 * Sort by creation time in MEGA, descending * * - MegaApi::ORDER_MODIFICATION_ASC = 7 * Sort by modification time of the original file, ascending * * - MegaApi::ORDER_MODIFICATION_DESC = 8 * Sort by modification time of the original file, descending * * - MegaApi::ORDER_ALPHABETICAL_ASC = 9 * Same behavior than MegaApi::ORDER_DEFAULT_ASC * * - MegaApi::ORDER_ALPHABETICAL_DESC = 10 * Same behavior than MegaApi::ORDER_DEFAULT_DESC * * Deprecated: MegaApi::ORDER_ALPHABETICAL_ASC and MegaApi::ORDER_ALPHABETICAL_DESC * are equivalent to MegaApi::ORDER_DEFAULT_ASC and MegaApi::ORDER_DEFAULT_DESC. * They will be eventually removed. * * - MegaApi::ORDER_PHOTO_ASC = 11 * Sort with photos first, then by date ascending * * - MegaApi::ORDER_PHOTO_DESC = 12 * Sort with photos first, then by date descending * * - MegaApi::ORDER_VIDEO_ASC = 13 * Sort with videos first, then by date ascending * * - MegaApi::ORDER_VIDEO_DESC = 14 * Sort with videos first, then by date descending * * - MegaApi::ORDER_LABEL_ASC = 17 * Sort by color label, ascending. With this order, folders are returned first, then files * * - MegaApi::ORDER_LABEL_DESC = 18 * Sort by color label, descending. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_ASC = 19 * Sort nodes with favourite attr first. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_DESC = 20 * Sort nodes with favourite attr last. With this order, folders are returned first, then files * * @return List of nodes that contain the desired string in their name */ public ArrayList<MegaNode> searchOnPublicLinks(String searchString, @NotNull MegaCancelToken cancelToken, int order) { return nodeListToArray(megaApi.searchOnPublicLinks(searchString, cancelToken, order)); } /** * Allow to search nodes with the following options: * - Search given a parent node of the tree to explore, or on the contrary search in a * specific target (root nodes, inshares, outshares, public links) * - Search recursively * - Containing a search string in their name * - Filter by the type of the node * - Order the returned list * * If node is provided, it will be the parent node of the tree to explore, * search string and/or nodeType can be added to search parameters * * If node and searchString are not provided, and node type is not valid, this method will * return an empty list. * * If parameter type is different of MegaApi::FILE_TYPE_DEFAULT, the following values for parameter * order are invalid: MegaApi::ORDER_PHOTO_ASC, MegaApi::ORDER_PHOTO_DESC, * MegaApi::ORDER_VIDEO_ASC, MegaApi::ORDER_VIDEO_DESC * * The search is case-insensitive. If the search string is not provided but type has any value * defined at nodefiletype_t (except FILE_TYPE_DEFAULT), * this method will return a list that contains nodes of the same type as provided. * * You take the ownership of the returned value. * * This function allows to cancel the processing at any time by passing a MegaCancelToken and calling * to MegaCancelToken::setCancelFlag(true). If a valid object is passed, it must be kept alive until * this method returns. * * @param node The parent node of the tree to explore * @param searchString Search string. The search is case-insensitive * @param cancelToken MegaCancelToken to be able to cancel the processing at any time. * @param recursive True if you want to search recursively in the node tree. * False if you want to search in the children of the node only * @param order Order for the returned list * Valid values for this parameter are: * - MegaApi::ORDER_NONE = 0 * Undefined order * * - MegaApi::ORDER_DEFAULT_ASC = 1 * Folders first in alphabetical order, then files in the same order * * - MegaApi::ORDER_DEFAULT_DESC = 2 * Files first in reverse alphabetical order, then folders in the same order * * - MegaApi::ORDER_SIZE_ASC = 3 * Sort by size, ascending * * - MegaApi::ORDER_SIZE_DESC = 4 * Sort by size, descending * * - MegaApi::ORDER_CREATION_ASC = 5 * Sort by creation time in MEGA, ascending * * - MegaApi::ORDER_CREATION_DESC = 6 * Sort by creation time in MEGA, descending * * - MegaApi::ORDER_MODIFICATION_ASC = 7 * Sort by modification time of the original file, ascending * * - MegaApi::ORDER_MODIFICATION_DESC = 8 * Sort by modification time of the original file, descending * * - MegaApi::ORDER_PHOTO_ASC = 11 * Sort with photos first, then by date ascending * * - MegaApi::ORDER_PHOTO_DESC = 12 * Sort with photos first, then by date descending * * - MegaApi::ORDER_VIDEO_ASC = 13 * Sort with videos first, then by date ascending * * - MegaApi::ORDER_VIDEO_DESC = 14 * Sort with videos first, then by date descending * * - MegaApi::ORDER_LABEL_ASC = 17 * Sort by color label, ascending. With this order, folders are returned first, then files * * - MegaApi::ORDER_LABEL_DESC = 18 * Sort by color label, descending. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_ASC = 19 * Sort nodes with favourite attr first. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_DESC = 20 * Sort nodes with favourite attr last. With this order, folders are returned first, then files * * @param type Type of nodes requested in the search * Valid values for this parameter are: * - MegaApi::FILE_TYPE_DEFAULT = 0 --> all types * - MegaApi::FILE_TYPE_PHOTO = 1 * - MegaApi::FILE_TYPE_AUDIO = 2 * - MegaApi::FILE_TYPE_VIDEO = 3 * - MegaApi::FILE_TYPE_DOCUMENT = 4 * @param target Target type where this method will search * Valid values for this parameter are * - SEARCH_TARGET_INSHARE = 0 * - SEARCH_TARGET_OUTSHARE = 1 * - SEARCH_TARGET_PUBLICLINK = 2 * - SEARCH_TARGET_ROOTNODE = 3 * - SEARCH_TARGET_ALL = 4 * @return List of nodes that match with the search parameters */ public ArrayList<MegaNode> searchByType(MegaNode node, String searchString, @NotNull MegaCancelToken cancelToken, boolean recursive, int order, int type, int target) { return nodeListToArray(megaApi.searchByType(node, searchString, cancelToken, recursive, order, type, target)); } /** * Allow to search nodes with the following options: * - Search in a specific target (root nodes, inshares, outshares, public links) * - Filter by the type of the node * - Order the returned list * * If node type is not valid, this method will return an empty list. * * If parameter type is different of MegaApi::FILE_TYPE_DEFAULT, the following values for parameter * order are invalid: MegaApi::ORDER_PHOTO_ASC, MegaApi::ORDER_PHOTO_DESC, * MegaApi::ORDER_VIDEO_ASC, MegaApi::ORDER_VIDEO_DESC * * The search is case-insensitive. If the type has any value defined at nodefiletype_t * (except FILE_TYPE_DEFAULT), this method will return a list * that contains nodes of the same type as provided. * * You take the ownership of the returned value. * * @param order Order for the returned list * Valid values for this parameter are: * - MegaApi::ORDER_NONE = 0 * Undefined order * * - MegaApi::ORDER_DEFAULT_ASC = 1 * Folders first in alphabetical order, then files in the same order * * - MegaApi::ORDER_DEFAULT_DESC = 2 * Files first in reverse alphabetical order, then folders in the same order * * - MegaApi::ORDER_SIZE_ASC = 3 * Sort by size, ascending * * - MegaApi::ORDER_SIZE_DESC = 4 * Sort by size, descending * * - MegaApi::ORDER_CREATION_ASC = 5 * Sort by creation time in MEGA, ascending * * - MegaApi::ORDER_CREATION_DESC = 6 * Sort by creation time in MEGA, descending * * - MegaApi::ORDER_MODIFICATION_ASC = 7 * Sort by modification time of the original file, ascending * * - MegaApi::ORDER_MODIFICATION_DESC = 8 * Sort by modification time of the original file, descending * * - MegaApi::ORDER_PHOTO_ASC = 11 * Sort with photos first, then by date ascending * * - MegaApi::ORDER_PHOTO_DESC = 12 * Sort with photos first, then by date descending * * - MegaApi::ORDER_VIDEO_ASC = 13 * Sort with videos first, then by date ascending * * - MegaApi::ORDER_VIDEO_DESC = 14 * Sort with videos first, then by date descending * * - MegaApi::ORDER_LABEL_ASC = 17 * Sort by color label, ascending. With this order, folders are returned first, then files * * - MegaApi::ORDER_LABEL_DESC = 18 * Sort by color label, descending. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_ASC = 19 * Sort nodes with favourite attr first. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_DESC = 20 * Sort nodes with favourite attr last. With this order, folders are returned first, then files * * @param type Type of nodes requested in the search * Valid values for this parameter are: * - MegaApi::FILE_TYPE_DEFAULT = 0 --> all types * - MegaApi::FILE_TYPE_PHOTO = 1 * - MegaApi::FILE_TYPE_AUDIO = 2 * - MegaApi::FILE_TYPE_VIDEO = 3 * - MegaApi::FILE_TYPE_DOCUMENT = 4 * * @param target Target type where this method will search * Valid values for this parameter are * - SEARCH_TARGET_INSHARE = 0 * - SEARCH_TARGET_OUTSHARE = 1 * - SEARCH_TARGET_PUBLICLINK = 2 * - SEARCH_TARGET_ROOTNODE = 3 * - SEARCH_TARGET_ALL = 4 * * @return List of nodes that match with the search parameters */ public ArrayList<MegaNode> searchByType(@NotNull MegaCancelToken cancelToken, int order, int type, int target) { return nodeListToArray(megaApi.searchByType(null, null, cancelToken, true, order, type, target)); } /** * Allow to search nodes with the following options: * - Search given a parent node of the tree to explore * - Search recursively * - Containing a search string in their name * - Filter by the type of the node * - Order the returned list * * If node is provided, it will be the parent node of the tree to explore, * search string and/or nodeType can be added to search parameters * * If node and searchString are not provided, and node type is not valid, this method will * return an empty list. * * If parameter type is different of MegaApi::FILE_TYPE_DEFAULT, the following values for parameter * order are invalid: MegaApi::ORDER_PHOTO_ASC, MegaApi::ORDER_PHOTO_DESC, * MegaApi::ORDER_VIDEO_ASC, MegaApi::ORDER_VIDEO_DESC * * The search is case-insensitive. If the search string is not provided but type has any value * defined at nodefiletype_t (except FILE_TYPE_DEFAULT), * this method will return a list that contains nodes of the same type as provided. * * You take the ownership of the returned value. * * This function allows to cancel the processing at any time by passing a MegaCancelToken and calling * to MegaCancelToken::setCancelFlag(true). If a valid object is passed, it must be kept alive until * this method returns. * * @param node The parent node of the tree to explore * @param searchString Search string. The search is case-insensitive * @param cancelToken MegaCancelToken to be able to cancel the processing at any time. * @param recursive True if you want to seach recursively in the node tree. * False if you want to seach in the children of the node only * @param order Order for the returned list * Valid values for this parameter are: * - MegaApi::ORDER_NONE = 0 * Undefined order * * - MegaApi::ORDER_DEFAULT_ASC = 1 * Folders first in alphabetical order, then files in the same order * * - MegaApi::ORDER_DEFAULT_DESC = 2 * Files first in reverse alphabetical order, then folders in the same order * * - MegaApi::ORDER_SIZE_ASC = 3 * Sort by size, ascending * * - MegaApi::ORDER_SIZE_DESC = 4 * Sort by size, descending * * - MegaApi::ORDER_CREATION_ASC = 5 * Sort by creation time in MEGA, ascending * * - MegaApi::ORDER_CREATION_DESC = 6 * Sort by creation time in MEGA, descending * * - MegaApi::ORDER_MODIFICATION_ASC = 7 * Sort by modification time of the original file, ascending * * - MegaApi::ORDER_MODIFICATION_DESC = 8 * Sort by modification time of the original file, descending * * - MegaApi::ORDER_PHOTO_ASC = 11 * Sort with photos first, then by date ascending * * - MegaApi::ORDER_PHOTO_DESC = 12 * Sort with photos first, then by date descending * * - MegaApi::ORDER_VIDEO_ASC = 13 * Sort with videos first, then by date ascending * * - MegaApi::ORDER_VIDEO_DESC = 14 * Sort with videos first, then by date descending * * - MegaApi::ORDER_LABEL_ASC = 17 * Sort by color label, ascending. With this order, folders are returned first, then files * * - MegaApi::ORDER_LABEL_DESC = 18 * Sort by color label, descending. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_ASC = 19 * Sort nodes with favourite attr first. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_DESC = 20 * Sort nodes with favourite attr last. With this order, folders are returned first, then files * * @param type Type of nodes requested in the search * Valid values for this parameter are: * - MegaApi::FILE_TYPE_DEFAULT = 0 --> all types * - MegaApi::FILE_TYPE_PHOTO = 1 * - MegaApi::FILE_TYPE_AUDIO = 2 * - MegaApi::FILE_TYPE_VIDEO = 3 * - MegaApi::FILE_TYPE_DOCUMENT = 4 * * @return List of nodes that match with the search parameters */ public ArrayList<MegaNode> searchByType(MegaNode node, String searchString, @NotNull MegaCancelToken cancelToken, boolean recursive, int order, int type) { return nodeListToArray(megaApi.searchByType(node, searchString, cancelToken, recursive, order, type)); } /** * Allow to search nodes with the following options: * - Search given a parent node of the tree to explore * - Search recursively * - Containing a search string in their name * - Order the returned list * * If node is provided, it will be the parent node of the tree to explore, * search string can be added to search parameters * * If node and searchString are not provided, this method will * return an empty list. * * You take the ownership of the returned value. * * This function allows to cancel the processing at any time by passing a MegaCancelToken and calling * to MegaCancelToken::setCancelFlag(true). If a valid object is passed, it must be kept alive until * this method returns. * * @param node The parent node of the tree to explore * @param searchString Search string. The search is case-insensitive * @param cancelToken MegaCancelToken to be able to cancel the processing at any time. * @param recursive True if you want to seach recursively in the node tree. * False if you want to seach in the children of the node only * @param order Order for the returned list * Valid values for this parameter are: * - MegaApi::ORDER_NONE = 0 * Undefined order * * - MegaApi::ORDER_DEFAULT_ASC = 1 * Folders first in alphabetical order, then files in the same order * * - MegaApi::ORDER_DEFAULT_DESC = 2 * Files first in reverse alphabetical order, then folders in the same order * * - MegaApi::ORDER_SIZE_ASC = 3 * Sort by size, ascending * * - MegaApi::ORDER_SIZE_DESC = 4 * Sort by size, descending * * - MegaApi::ORDER_CREATION_ASC = 5 * Sort by creation time in MEGA, ascending * * - MegaApi::ORDER_CREATION_DESC = 6 * Sort by creation time in MEGA, descending * * - MegaApi::ORDER_MODIFICATION_ASC = 7 * Sort by modification time of the original file, ascending * * - MegaApi::ORDER_MODIFICATION_DESC = 8 * Sort by modification time of the original file, descending * * - MegaApi::ORDER_PHOTO_ASC = 11 * Sort with photos first, then by date ascending * * - MegaApi::ORDER_PHOTO_DESC = 12 * Sort with photos first, then by date descending * * - MegaApi::ORDER_VIDEO_ASC = 13 * Sort with videos first, then by date ascending * * - MegaApi::ORDER_VIDEO_DESC = 14 * Sort with videos first, then by date descending * * - MegaApi::ORDER_LABEL_ASC = 17 * Sort by color label, ascending. With this order, folders are returned first, then files * * - MegaApi::ORDER_LABEL_DESC = 18 * Sort by color label, descending. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_ASC = 19 * Sort nodes with favourite attr first. With this order, folders are returned first, then files * * - MegaApi::ORDER_FAV_DESC = 20 * Sort nodes with favourite attr last. With this order, folders are returned first, then files * * @return List of nodes that match with the search parameters */ public ArrayList<MegaNode> searchByType(MegaNode node, String searchString, @NotNull MegaCancelToken cancelToken, boolean recursive, int order) { return nodeListToArray(megaApi.searchByType(node, searchString, cancelToken, recursive, order)); } /** * Allow to search nodes with the following options: * - Search given a parent node of the tree to explore * - Search recursively * - Containing a search string in their name * * If node is provided, it will be the parent node of the tree to explore, * search string can be added to search parameters * * If node and searchString are not provided, this method will * return an empty list. * * You take the ownership of the returned value. * * This function allows to cancel the processing at any time by passing a MegaCancelToken and calling * to MegaCancelToken::setCancelFlag(true). If a valid object is passed, it must be kept alive until * this method returns. * * @param node The parent node of the tree to explore * @param searchString Search string. The search is case-insensitive * @param cancelToken MegaCancelToken to be able to cancel the processing at any time. * @param recursive True if you want to seach recursively in the node tree. * False if you want to seach in the children of the node only * * @return List of nodes that match with the search parameters */ public ArrayList<MegaNode> searchByType(MegaNode node, String searchString, @NotNull MegaCancelToken cancelToken, boolean recursive) { return nodeListToArray(megaApi.searchByType(node, searchString, cancelToken, recursive)); } /** * Allow to search nodes with the following options: * - Search given a parent node of the tree to explore * - Containing a search string in their name * * If node is provided, it will be the parent node of the tree to explore, * search string can be added to search parameters * * If node and searchString are not provided, this method will * return an empty list. * * You take the ownership of the returned value. * * This function allows to cancel the processing at any time by passing a MegaCancelToken and calling * to MegaCancelToken::setCancelFlag(true). If a valid object is passed, it must be kept alive until * this method returns. * * @param node The parent node of the tree to explore * @param searchString Search string. The search is case-insensitive * @param cancelToken MegaCancelToken to be able to cancel the processing at any time. * * @return List of nodes that match with the search parameters */ public ArrayList<MegaNode> searchByType(MegaNode node, String searchString, @NotNull MegaCancelToken cancelToken) { return nodeListToArray(megaApi.searchByType(node, searchString, cancelToken)); } /** * Return a list of buckets, each bucket containing a list of recently added/modified nodes * * Each bucket contains files that were added/modified in a set, by a single user. * * @param days Age of actions since added/modified nodes will be considered (in days) * @param maxnodes Maximum amount of nodes to be considered * * @return List of buckets containing nodes that were added/modifed as a set */ public ArrayList<MegaRecentActionBucket> getRecentActions (long days, long maxnodes) { return recentActionsToArray(megaApi.getRecentActions(days, maxnodes)); } /** * Return a list of buckets, each bucket containing a list of recently added/modified nodes * * Each bucket contains files that were added/modified in a set, by a single user. * * This function uses the default parameters for the MEGA apps, which consider (currently) * interactions during the last 90 days and max 10.000 nodes. * * @return List of buckets containing nodes that were added/modifed as a set */ public ArrayList<MegaRecentActionBucket> getRecentActions () { return recentActionsToArray(megaApi.getRecentActions()); } /** * Process a node tree using a MegaTreeProcessor implementation. * * @param parent * The parent node of the tree to explore. * @param processor * MegaTreeProcessor that will receive callbacks for every node in the tree. * @param recursive * true if you want to recursively process the whole node tree. * false if you want to process the children of the node only. * * @return true if all nodes were processed. false otherwise (the operation can be * cancelled by MegaTreeProcessor.processMegaNode()). */ public boolean processMegaTree(MegaNode parent, MegaTreeProcessorInterface processor, boolean recursive) { DelegateMegaTreeProcessor delegateListener = new DelegateMegaTreeProcessor(this, processor); activeMegaTreeProcessors.add(delegateListener); boolean result = megaApi.processMegaTree(parent, delegateListener, recursive); activeMegaTreeProcessors.remove(delegateListener); return result; } /** * Process a node tree using a MegaTreeProcessor implementation. * * @param parent * The parent node of the tree to explore. * @param processor * MegaTreeProcessor that will receive callbacks for every node in the tree. * * @return true if all nodes were processed. false otherwise (the operation can be * cancelled by MegaTreeProcessor.processMegaNode()). */ public boolean processMegaTree(MegaNode parent, MegaTreeProcessorInterface processor) { DelegateMegaTreeProcessor delegateListener = new DelegateMegaTreeProcessor(this, processor); activeMegaTreeProcessors.add(delegateListener); boolean result = megaApi.processMegaTree(parent, delegateListener); activeMegaTreeProcessors.remove(delegateListener); return result; } /** * Returns a MegaNode that can be downloaded with any instance of MegaApi * * This function only allows to authorize file nodes. * * You can use MegaApi::startDownload with the resulting node with any instance * of MegaApi, even if it's logged into another account, a public folder, or not * logged in. * * If the first parameter is a public node or an already authorized node, this * function returns a copy of the node, because it can be already downloaded * with any MegaApi instance. * * If the node in the first parameter belongs to the account or public folder * in which the current MegaApi object is logged in, this funtion returns an * authorized node. * * If the first parameter is NULL or a node that is not a public node, is not * already authorized and doesn't belong to the current MegaApi, this function * returns NULL. * * You take the ownership of the returned value. * * @param node MegaNode to authorize * @return Authorized node, or NULL if the node can't be authorized or is not a file */ public MegaNode authorizeNode(MegaNode node){ return megaApi.authorizeNode(node); } /** * * Returns a MegaNode that can be downloaded/copied with a chat-authorization * * During preview of chat-links, you need to call this method to authorize the MegaNode * from a node-attachment message, so the API allows to access to it. The parameter to * authorize the access can be retrieved from MegaChatRoom::getAuthorizationToken when * the chatroom in in preview mode. * * You can use MegaApi::startDownload and/or MegaApi::copyNode with the resulting * node with any instance of MegaApi, even if it's logged into another account, * a public folder, or not logged in. * * You take the ownership of the returned value. * * @param node MegaNode to authorize * @param cauth Authorization token (public handle of the chatroom in B64url encoding) * @return Authorized node, or NULL if the node can't be authorized */ public MegaNode authorizeChatNode(MegaNode node, String cauth){ return megaApi.authorizeChatNode(node, cauth); } /** * Get the SDK version. * * @return SDK version. */ public String getVersion() { return megaApi.getVersion(); } /** * Get the User-Agent header used by the SDK. * * @return User-Agent used by the SDK. */ public String getUserAgent() { return megaApi.getUserAgent(); } /** * Changes the API URL. * * @param apiURL The API URL to change. * @param disablepkp boolean. Disable public key pinning if true. Do not disable public key pinning if false. */ public void changeApiUrl(String apiURL, boolean disablepkp) { megaApi.changeApiUrl(apiURL, disablepkp); } /** * Changes the API URL. * <p> * Please note, this method does not disable public key pinning. * * @param apiURL The API URL to change. */ public void changeApiUrl(String apiURL) { megaApi.changeApiUrl(apiURL); } /** * Set the language code used by the app * @param languageCode code used by the app * * @return True if the language code is known for the SDK, otherwise false */ public boolean setLanguage(String languageCode){ return megaApi.setLanguage(languageCode); } /** * Set the preferred language of the user * * Valid data in the MegaRequest object received in onRequestFinish: * - MegaRequest::getText - Return the language code * * If the language code is unknown for the SDK, the error code will be MegaError::API_ENOENT * * This attribute is automatically created by the server. Apps only need * to set the new value when the user changes the language. * * @param Language code to be set * @param listener MegaRequestListener to track this request */ public void setLanguagePreference(String languageCode, MegaRequestListenerInterface listener){ megaApi.setLanguagePreference(languageCode, createDelegateRequestListener(listener)); } /** * Get the preferred language of the user * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - Return the language code * * @param listener MegaRequestListener to track this request */ public void getLanguagePreference(MegaRequestListenerInterface listener){ megaApi.getLanguagePreference(createDelegateRequestListener(listener)); } /** * Enable or disable file versioning * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the value MegaApi::USER_ATTR_DISABLE_VERSIONS * * Valid data in the MegaRequest object received in onRequestFinish: * - MegaRequest::getText - "1" for disable, "0" for enable * * @param disable True to disable file versioning. False to enable it * @param listener MegaRequestListener to track this request */ public void setFileVersionsOption(boolean disable, MegaRequestListenerInterface listener){ megaApi.setFileVersionsOption(disable, createDelegateRequestListener(listener)); } /** * Enable or disable the automatic approval of incoming contact requests using a contact link * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the value MegaApi::USER_ATTR_CONTACT_LINK_VERIFICATION * * Valid data in the MegaRequest object received in onRequestFinish: * - MegaRequest::getText - "0" for disable, "1" for enable * * @param disable True to disable the automatic approval of incoming contact requests using a contact link * @param listener MegaRequestListener to track this request */ public void setContactLinksOption(boolean disable, MegaRequestListenerInterface listener){ megaApi.setContactLinksOption(disable, createDelegateRequestListener(listener)); } /** * Check if file versioning is enabled or disabled * * If the option has never been set, the error code will be MegaError::API_ENOENT. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the value MegaApi::USER_ATTR_DISABLE_VERSIONS * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - "1" for disable, "0" for enable * - MegaRequest::getFlag - True if disabled, false if enabled * * @param listener MegaRequestListener to track this request */ public void getFileVersionsOption(MegaRequestListenerInterface listener){ megaApi.getFileVersionsOption(createDelegateRequestListener(listener)); } /** * Check if the automatic approval of incoming contact requests using contact links is enabled or disabled * * If the option has never been set, the error code will be MegaError::API_ENOENT. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the value MegaApi::USER_ATTR_CONTACT_LINK_VERIFICATION * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getText - "0" for disable, "1" for enable * - MegaRequest::getFlag - false if disabled, true if enabled * * @param listener MegaRequestListener to track this request */ public void getContactLinksOption(MegaRequestListenerInterface listener){ megaApi.getContactLinksOption(createDelegateRequestListener(listener)); } /** * Keep retrying when public key pinning fails * * By default, when the check of the MEGA public key fails, it causes an automatic * logout. Pass false to this function to disable that automatic logout and * keep the SDK retrying the request. * * Even if the automatic logout is disabled, a request of the type MegaRequest::TYPE_LOGOUT * will be automatically created and callbacks (onRequestStart, onRequestFinish) will * be sent. However, logout won't be really executed and in onRequestFinish the error code * for the request will be MegaError::API_EINCOMPLETE * * @param enable true to keep retrying failed requests due to a fail checking the MEGA public key * or false to perform an automatic logout in that case */ public void retrySSLerrors(boolean enable) { megaApi.retrySSLerrors(enable); } /** * Enable / disable the public key pinning * * Public key pinning is enabled by default for all sensible communications. * It is strongly discouraged to disable this feature. * * @param enable true to keep public key pinning enabled, false to disable it */ public void setPublicKeyPinning(boolean enable) { megaApi.setPublicKeyPinning(enable); } /** * Make a name suitable for a file name in the local filesystem * * This function escapes (%xx) forbidden characters in the local filesystem if needed. * You can revert this operation using MegaApi::unescapeFsIncompatible * * If no dstPath is provided or filesystem type it's not supported this method will * escape characters contained in the following list: \/:?\"<>|* * Otherwise it will check forbidden characters for local filesystem type * * The input string must be UTF8 encoded. The returned value will be UTF8 too. * * You take the ownership of the returned value * * @param filename Name to convert (UTF8) * @param dstPath Destination path * @return Converted name (UTF8) */ public String escapeFsIncompatible(String filename, String dstPath) { return megaApi.escapeFsIncompatible(filename, dstPath); } /** * Unescape a file name escaped with MegaApi::escapeFsIncompatible * * If no localPath is provided or filesystem type it's not supported, this method will * unescape those sequences that once has been unescaped results in any character * of the following list: \/:?\"<>|* * Otherwise it will unescape those characters forbidden in local filesystem type * * The input string must be UTF8 encoded. The returned value will be UTF8 too. * You take the ownership of the returned value * * @param name Escaped name to convert (UTF8) * @param localPath Local path * @return Converted name (UTF8) */ String unescapeFsIncompatible(String name, String localPath) { return megaApi.unescapeFsIncompatible(name, localPath); } /** * Create a thumbnail for an image. * * @param imagePath Image path. * @param dstPath Destination path for the thumbnail (including the file name). * @return true if the thumbnail was successfully created, otherwise false. */ public boolean createThumbnail(String imagePath, String dstPath) { return megaApi.createThumbnail(imagePath, dstPath); } /** * Create a preview for an image. * * @param imagePath Image path. * @param dstPath Destination path for the preview (including the file name). * @return true if the preview was successfully created, otherwise false. */ public boolean createPreview(String imagePath, String dstPath) { return megaApi.createPreview(imagePath, dstPath); } /** * Convert a Base64 string to Base32. * <p> * If the input pointer is null, this function will return null. * If the input character array is not a valid base64 string * the effect is undefined. * * @param base64 * null-terminated Base64 character array. * @return null-terminated Base32 character array. */ public static String base64ToBase32(String base64) { return MegaApi.base64ToBase32(base64); } /** * Convert a Base32 string to Base64. * * If the input pointer is null, this function will return null. * If the input character array is not a valid base32 string * the effect is undefined. * * @param base32 * null-terminated Base32 character array. * @return null-terminated Base64 character array. */ public static String base32ToBase64(String base32) { return MegaApi.base32ToBase64(base32); } /** * Recursively remove all local files/folders inside a local path * @param path Local path of a folder to start the recursive deletion * The folder itself is not deleted */ public static void removeRecursively(String localPath) { MegaApi.removeRecursively(localPath); } /** * Check if the connection with MEGA servers is OK * * It can briefly return false even if the connection is good enough when * some storage servers are temporarily not available or the load of API * servers is high. * * @return true if the connection is perfectly OK, otherwise false */ public boolean isOnline() { return megaApi.isOnline(); } /** * Start an HTTP proxy server in specified port * * If this function returns true, that means that the server is * ready to accept connections. The initialization is synchronous. * * The server will serve files using this URL format: * http://127.0.0.1/<NodeHandle>/<NodeName> * * The node name must be URL encoded and must match with the node handle. * You can generate a correct link for a MegaNode using MegaApi::httpServerGetLocalLink * * If the node handle belongs to a folder node, a web with the list of files * inside the folder is returned. * * It's important to know that the HTTP proxy server has several configuration options * that can restrict the nodes that will be served and the connections that will be accepted. * * These are the default options: * - The restricted mode of the server is set to MegaApi::HTTP_SERVER_ALLOW_CREATED_LOCAL_LINKS * (see MegaApi::httpServerSetRestrictedMode) * * - Folder nodes are NOT allowed to be served (see MegaApi::httpServerEnableFolderServer) * - File nodes are allowed to be served (see MegaApi::httpServerEnableFileServer) * - Subtitles support is disabled (see MegaApi::httpServerEnableSubtitlesSupport) * * The HTTP server will only stream a node if it's allowed by all configuration options. * * @param localOnly true to listen on 127.0.0.1 only, false to listen on all network interfaces * @param port Port in which the server must accept connections * @return True is the server is ready, false if the initialization failed */ public boolean httpServerStart(boolean localOnly, int port) { return megaApi.httpServerStart(localOnly, port); } /** * Start an HTTP proxy server in specified port * * If this function returns true, that means that the server is * ready to accept connections. The initialization is synchronous. * * The server will serve files using this URL format: * http://127.0.0.1/<NodeHandle>/<NodeName> * * The node name must be URL encoded and must match with the node handle. * You can generate a correct link for a MegaNode using MegaApi::httpServerGetLocalLink * * If the node handle belongs to a folder node, a web with the list of files * inside the folder is returned. * * It's important to know that the HTTP proxy server has several configuration options * that can restrict the nodes that will be served and the connections that will be accepted. * * These are the default options: * - The restricted mode of the server is set to MegaApi::HTTP_SERVER_ALLOW_CREATED_LOCAL_LINKS * (see MegaApi::httpServerSetRestrictedMode) * * - Folder nodes are NOT allowed to be served (see MegaApi::httpServerEnableFolderServer) * - File nodes are allowed to be served (see MegaApi::httpServerEnableFileServer) * - Subtitles support is disabled (see MegaApi::httpServerEnableSubtitlesSupport) * * The HTTP server will only stream a node if it's allowed by all configuration options. * * @param localOnly true to listen on 127.0.0.1 only, false to listen on all network interfaces * @return True is the server is ready, false if the initialization failed */ public boolean httpServerStart(boolean localOnly) { return megaApi.httpServerStart(localOnly); } /** * Start an HTTP proxy server in specified port * * If this function returns true, that means that the server is * ready to accept connections. The initialization is synchronous. * * The server will serve files using this URL format: * http://127.0.0.1/<NodeHandle>/<NodeName> * * The node name must be URL encoded and must match with the node handle. * You can generate a correct link for a MegaNode using MegaApi::httpServerGetLocalLink * * If the node handle belongs to a folder node, a web with the list of files * inside the folder is returned. * * It's important to know that the HTTP proxy server has several configuration options * that can restrict the nodes that will be served and the connections that will be accepted. * * These are the default options: * - The restricted mode of the server is set to MegaApi::HTTP_SERVER_ALLOW_CREATED_LOCAL_LINKS * (see MegaApi::httpServerSetRestrictedMode) * * - Folder nodes are NOT allowed to be served (see MegaApi::httpServerEnableFolderServer) * - File nodes are allowed to be served (see MegaApi::httpServerEnableFileServer) * - Subtitles support is disabled (see MegaApi::httpServerEnableSubtitlesSupport) * * The HTTP server will only stream a node if it's allowed by all configuration options. * * @return True is the server is ready, false if the initialization failed */ public boolean httpServerStart() { return megaApi.httpServerStart(); } /** * Stop the HTTP proxy server * * When this function returns, the server is already shutdown. * If the HTTP proxy server isn't running, this functions does nothing */ public void httpServerStop(){ megaApi.httpServerStop(); } /** * Check if the HTTP proxy server is running * @return 0 if the server is not running. Otherwise the port in which it's listening to */ public int httpServerIsRunning(){ return megaApi.httpServerIsRunning(); } /** * Check if the HTTP proxy server is listening on all network interfaces * @return true if the HTTP proxy server is listening on 127.0.0.1 only, or it's not started. * If it's started and listening on all network interfaces, this function returns false */ public boolean httpServerIsLocalOnly() { return megaApi.httpServerIsLocalOnly(); } /** * Allow/forbid to serve files * * By default, files are served (when the server is running) * * Even if files are allowed to be served by this function, restrictions related to * other configuration options (MegaApi::httpServerSetRestrictedMode) are still applied. * * @param enable true to allow to server files, false to forbid it */ public void httpServerEnableFileServer(boolean enable) { megaApi.httpServerEnableFileServer(enable); } /** * Check if it's allowed to serve files * * This function can return true even if the HTTP proxy server is not running * * Even if files are allowed to be served by this function, restrictions related to * other configuration options (MegaApi::httpServerSetRestrictedMode) are still applied. * * @return true if it's allowed to serve files, otherwise false */ public boolean httpServerIsFileServerEnabled() { return megaApi.httpServerIsFileServerEnabled(); } /** * Allow/forbid to serve folders * * By default, folders are NOT served * * Even if folders are allowed to be served by this function, restrictions related to * other configuration options (MegaApi::httpServerSetRestrictedMode) are still applied. * * @param enable true to allow to server folders, false to forbid it */ public void httpServerEnableFolderServer(boolean enable) { megaApi.httpServerEnableFolderServer(enable); } /** * Check if it's allowed to serve folders * * This function can return true even if the HTTP proxy server is not running * * Even if folders are allowed to be served by this function, restrictions related to * other configuration options (MegaApi::httpServerSetRestrictedMode) are still applied. * * @return true if it's allowed to serve folders, otherwise false */ public boolean httpServerIsFolderServerEnabled() { return megaApi.httpServerIsFolderServerEnabled(); } /** * Enable/disable the restricted mode of the HTTP server * * This function allows to restrict the nodes that are allowed to be served. * For not allowed links, the server will return "407 Forbidden". * * Possible values are: * - HTTP_SERVER_DENY_ALL = -1 * All nodes are forbidden * * - HTTP_SERVER_ALLOW_ALL = 0 * All nodes are allowed to be served * * - HTTP_SERVER_ALLOW_CREATED_LOCAL_LINKS = 1 (default) * Only links created with MegaApi::httpServerGetLocalLink are allowed to be served * * - HTTP_SERVER_ALLOW_LAST_LOCAL_LINK = 2 * Only the last link created with MegaApi::httpServerGetLocalLink is allowed to be served * * If a different value from the list above is passed to this function, it won't have any effect and the previous * state of this option will be preserved. * * The default value of this property is MegaApi::HTTP_SERVER_ALLOW_CREATED_LOCAL_LINKS * * The state of this option is preserved even if the HTTP server is restarted, but the * the HTTP proxy server only remembers the generated links since the last call to * MegaApi::httpServerStart * * Even if nodes are allowed to be served by this function, restrictions related to * other configuration options (MegaApi::httpServerEnableFileServer, * MegaApi::httpServerEnableFolderServer) are still applied. * * @param mode Required state for the restricted mode of the HTTP proxy server */ public void httpServerSetRestrictedMode(int mode) { megaApi.httpServerSetRestrictedMode(mode); } /** * Check if the HTTP proxy server is working in restricted mode * * Possible return values are: * - HTTP_SERVER_DENY_ALL = -1 * All nodes are forbidden * * - HTTP_SERVER_ALLOW_ALL = 0 * All nodes are allowed to be served * * - HTTP_SERVER_ALLOW_CREATED_LOCAL_LINKS = 1 * Only links created with MegaApi::httpServerGetLocalLink are allowed to be served * * - HTTP_SERVER_ALLOW_LAST_LOCAL_LINK = 2 * Only the last link created with MegaApi::httpServerGetLocalLink is allowed to be served * * The default value of this property is MegaApi::HTTP_SERVER_ALLOW_CREATED_LOCAL_LINKS * * See MegaApi::httpServerEnableRestrictedMode and MegaApi::httpServerStart * * Even if nodes are allowed to be served by this function, restrictions related to * other configuration options (MegaApi::httpServerEnableFileServer, * MegaApi::httpServerEnableFolderServer) are still applied. * * @return State of the restricted mode of the HTTP proxy server */ public int httpServerGetRestrictedMode() { return megaApi.httpServerGetRestrictedMode(); } /** * Enable/disable the support for subtitles * * Subtitles support allows to stream some special links that otherwise wouldn't be valid. * For example, let's suppose that the server is streaming this video: * http://120.0.0.1:4443/<Base64Handle>/MyHolidays.avi * * Some media players scan HTTP servers looking for subtitle files and request links like these ones: * http://120.0.0.1:4443/<Base64Handle>/MyHolidays.txt * http://120.0.0.1:4443/<Base64Handle>/MyHolidays.srt * * Even if a file with that name is in the same folder of the MEGA account, the node wouldn't be served because * the node handle wouldn't match. * * When this feature is enabled, the HTTP proxy server will check if there are files with that name * in the same folder as the node corresponding to the handle in the link. * * If a matching file is found, the name is exactly the same as the the node with the specified handle * (except the extension), the node with that handle is allowed to be streamed and this feature is enabled * the HTTP proxy server will serve that file. * * This feature is disabled by default. * * @param enable True to enable subtitles support, false to disable it */ public void httpServerEnableSubtitlesSupport(boolean enable) { megaApi.httpServerEnableSubtitlesSupport(enable); } /** * Check if the support for subtitles is enabled * * See MegaApi::httpServerEnableSubtitlesSupport. * * This feature is disabled by default. * * @return true of the support for subtibles is enables, otherwise false */ public boolean httpServerIsSubtitlesSupportEnabled() { return megaApi.httpServerIsSubtitlesSupportEnabled(); } /** * Add a listener to receive information about the HTTP proxy server * * This is the valid data that will be provided on callbacks: * - MegaTransfer::getType - It will be MegaTransfer::TYPE_LOCAL_HTTP_DOWNLOAD * - MegaTransfer::getPath - URL requested to the HTTP proxy server * - MegaTransfer::getFileName - Name of the requested file (if any, otherwise NULL) * - MegaTransfer::getNodeHandle - Handle of the requested file (if any, otherwise NULL) * - MegaTransfer::getTotalBytes - Total bytes of the response (response headers + file, if required) * - MegaTransfer::getStartPos - Start position (for range requests only, otherwise -1) * - MegaTransfer::getEndPos - End position (for range requests only, otherwise -1) * * On the onTransferFinish error, the error code associated to the MegaError can be: * - MegaError::API_EINCOMPLETE - If the whole response wasn't sent * (it's normal to get this error code sometimes because media players close connections when they have * the data that they need) * * - MegaError::API_EREAD - If the connection with MEGA storage servers failed * - MegaError::API_EAGAIN - If the download speed is too slow for streaming * - A number > 0 means an HTTP error code returned to the client * * @param listener Listener to receive information about the HTTP proxy server */ public void httpServerAddListener(MegaTransferListenerInterface listener) { megaApi.httpServerAddListener(createDelegateHttpServerListener(listener, false)); } /** * Stop the reception of callbacks related to the HTTP proxy server on this listener * @param listener Listener that won't continue receiving information */ public void httpServerRemoveListener(MegaTransferListenerInterface listener) { ArrayList<DelegateMegaTransferListener> listenersToRemove = new ArrayList<DelegateMegaTransferListener>(); synchronized (activeHttpServerListeners) { Iterator<DelegateMegaTransferListener> it = activeHttpServerListeners.iterator(); while (it.hasNext()) { DelegateMegaTransferListener delegate = it.next(); if (delegate.getUserListener() == listener) { listenersToRemove.add(delegate); it.remove(); } } } for (int i=0;i<listenersToRemove.size();i++){ megaApi.httpServerRemoveListener(listenersToRemove.get(i)); } } /** * Returns a URL to a node in the local HTTP proxy server * * The HTTP proxy server must be running before using this function, otherwise * it will return NULL. * * You take the ownership of the returned value * * @param node Node to generate the local HTTP link * @return URL to the node in the local HTTP proxy server, otherwise NULL */ public String httpServerGetLocalLink(MegaNode node) { return megaApi.httpServerGetLocalLink(node); } /** * Set the maximum buffer size for the internal buffer * * The HTTP proxy server has an internal buffer to store the data received from MEGA * while it's being sent to clients. When the buffer is full, the connection with * the MEGA storage server is closed, when the buffer has few data, the connection * with the MEGA storage server is started again. * * Even with very fast connections, due to the possible latency starting new connections, * if this buffer is small the streaming can have problems due to the overhead caused by * the excessive number of POST requests. * * It's recommended to set this buffer at least to 1MB * * For connections that request less data than the buffer size, the HTTP proxy server * will only allocate the required memory to complete the request to minimize the * memory usage. * * The new value will be taken into account since the next request received by * the HTTP proxy server, not for ongoing requests. It's possible and effective * to call this function even before the server has been started, and the value * will be still active even if the server is stopped and started again. * * @param bufferSize Maximum buffer size (in bytes) or a number <= 0 to use the * internal default value */ public void httpServerSetMaxBufferSize(int bufferSize) { megaApi.httpServerSetMaxBufferSize(bufferSize); } /** * Get the maximum size of the internal buffer size * * See MegaApi::httpServerSetMaxBufferSize * * @return Maximum size of the internal buffer size (in bytes) */ public int httpServerGetMaxBufferSize() { return megaApi.httpServerGetMaxBufferSize(); } /** * Set the maximum size of packets sent to clients * * For each connection, the HTTP proxy server only sends one write to the underlying * socket at once. This parameter allows to set the size of that write. * * A small value could cause a lot of writes and would lower the performance. * * A big value could send too much data to the output buffer of the socket. That could * keep the internal buffer full of data that hasn't been sent to the client yet, * preventing the retrieval of additional data from the MEGA storage server. In that * circumstances, the client could read a lot of data at once and the HTTP server * could not have enough time to get more data fast enough. * * It's recommended to set this value to at least 8192 and no more than the 25% of * the maximum buffer size (MegaApi::httpServerSetMaxBufferSize). * * The new value will be takein into account since the next request received by * the HTTP proxy server, not for ongoing requests. It's possible and effective * to call this function even before the server has been started, and the value * will be still active even if the server is stopped and started again. * * @param outputSize Maximun size of data packets sent to clients (in bytes) or * a number <= 0 to use the internal default value */ public void httpServerSetMaxOutputSize(int outputSize) { megaApi.httpServerSetMaxOutputSize(outputSize); } /** * Get the maximum size of the packets sent to clients * * See MegaApi::httpServerSetMaxOutputSize * * @return Maximum size of the packets sent to clients (in bytes) */ public int httpServerGetMaxOutputSize() { return megaApi.httpServerGetMaxOutputSize(); } /** * Get the MIME type associated with the extension * * You take the ownership of the returned value * * @param extension File extension (with or without a leading dot) * @return MIME type associated with the extension */ public static String getMimeType(String extension) { return MegaApi.getMimeType(extension); } /** * Register a token for push notifications * * This function attach a token to the current session, which is intended to get push notifications * on mobile platforms like Android and iOS. * * The associated request type with this request is MegaRequest::TYPE_REGISTER_PUSH_NOTIFICATION * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getText - Returns the token provided. * - MegaRequest::getNumber - Returns the device type provided. * * @param deviceType Integer id for the provider. 1 for Android, 2 for iOS * @param token Character array representing the token to be registered. * @param listener MegaRequestListenerInterface to track this request */ public void registerPushNotifications(int deviceType, String token, MegaRequestListenerInterface listener) { megaApi.registerPushNotifications(deviceType, token, createDelegateRequestListener(listener)); } /** * Register a token for push notifications * * This function attach a token to the current session, which is intended to get push notifications * on mobile platforms like Android and iOS. * * @param deviceType Integer id for the provider. 1 for Android, 2 for iOS * @param token Character array representing the token to be registered. */ public void registerPushNotifications(int deviceType, String token) { megaApi.registerPushNotifications(deviceType, token); } /** * Get the MEGA Achievements of the account logged in * * The associated request type with this request is MegaRequest::TYPE_GET_ACHIEVEMENTS * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getFlag - Always false * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaAchievementsDetails - Details of the MEGA Achievements of this account * * @param listener MegaRequestListenerInterface to track this request */ public void getAccountAchievements(MegaRequestListenerInterface listener) { megaApi.getAccountAchievements(createDelegateRequestListener(listener)); } /** * Get the MEGA Achievements of the account logged in * * The associated request type with this request is MegaRequest::TYPE_GET_ACHIEVEMENTS * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getFlag - Always false * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaAchievementsDetails - Details of the MEGA Achievements of this account */ public void getAccountAchievements(){ megaApi.getAccountAchievements(); } /** * Get the list of existing MEGA Achievements * * Similar to MegaApi::getAccountAchievements, this method returns only the base storage and * the details for the different achievement classes, but not awards or rewards related to the * account that is logged in. * This function can be used to give an indication of what is available for advertising * for unregistered users, despite it can be used with a logged in account with no difference. * * @note: if the IP address is not achievement enabled (it belongs to a country where MEGA * Achievements are not enabled), the request will fail with MegaError::API_EACCESS. * * The associated request type with this request is MegaRequest::TYPE_GET_ACHIEVEMENTS * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getFlag - Always true * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaAchievementsDetails - Details of the list of existing MEGA Achievements * * @param listener MegaRequestListenerInterface to track this request */ public void getMegaAchievements(MegaRequestListenerInterface listener) { megaApi.getMegaAchievements(createDelegateRequestListener(listener)); } /** * Get the list of existing MEGA Achievements * * Similar to MegaApi::getAccountAchievements, this method returns only the base storage and * the details for the different achievement classes, but not awards or rewards related to the * account that is logged in. * This function can be used to give an indication of what is available for advertising * for unregistered users, despite it can be used with a logged in account with no difference. * * @note: if the IP address is not achievement enabled (it belongs to a country where MEGA * Achievements are not enabled), the request will fail with MegaError::API_EACCESS. * * The associated request type with this request is MegaRequest::TYPE_GET_ACHIEVEMENTS * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getFlag - Always true * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaAchievementsDetails - Details of the list of existing MEGA Achievements */ public void getMegaAchievements() { megaApi.getMegaAchievements(); } /** * Set original fingerprint for MegaNode * * @param node * @param fingerprint * @param listener */ public void setOriginalFingerprint(MegaNode node, String fingerprint, MegaRequestListenerInterface listener){ megaApi.setOriginalFingerprint(node,fingerprint,createDelegateRequestListener(listener)); } /** * Get MegaNode list by original fingerprint * * @param originalfingerprint * @param parent */ public MegaNodeList getNodesByOriginalFingerprint(String originalfingerprint, MegaNode parent){ return megaApi.getNodesByOriginalFingerprint(originalfingerprint, parent); } /** * @brief Retrieve basic information about a folder link * * This function retrieves basic information from a folder link, like the number of files / folders * and the name of the folder. For folder links containing a lot of files/folders, * this function is more efficient than a fetchnodes. * * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getLink() - Returns the public link to the folder * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaFolderInfo() - Returns information about the contents of the folder * - MegaRequest::getNodeHandle() - Returns the public handle of the folder * - MegaRequest::getParentHandle() - Returns the handle of the owner of the folder * - MegaRequest::getText() - Returns the name of the folder. * If there's no name, it returns the special status string "CRYPTO_ERROR". * If the length of the name is zero, it returns the special status string "BLANK". * * On the onRequestFinish error, the error code associated to the MegaError can be: * - MegaError::API_EARGS - If the link is not a valid folder link * - MegaError::API_EKEY - If the public link does not contain the key or it is invalid * * @param megaFolderLink Public link to a folder in MEGA * @param listener MegaRequestListener to track this request */ public void getPublicLinkInformation(String megaFolderLink, MegaRequestListenerInterface listener) { megaApi.getPublicLinkInformation(megaFolderLink, createDelegateRequestListener(listener)); } /** * @brief Retrieve basic information about a folder link * * This function retrieves basic information from a folder link, like the number of files / folders * and the name of the folder. For folder links containing a lot of files/folders, * this function is more efficient than a fetchnodes. * * Valid data in the MegaRequest object received on all callbacks: * - MegaRequest::getLink() - Returns the public link to the folder * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaFolderInfo() - Returns information about the contents of the folder * - MegaRequest::getNodeHandle() - Returns the public handle of the folder * - MegaRequest::getParentHandle() - Returns the handle of the owner of the folder * - MegaRequest::getText() - Returns the name of the folder. * If there's no name, it returns the special status string "CRYPTO_ERROR". * If the length of the name is zero, it returns the special status string "BLANK". * * On the onRequestFinish error, the error code associated to the MegaError can be: * - MegaError::API_EARGS - If the link is not a valid folder link * - MegaError::API_EKEY - If the public link does not contain the key or it is invalid * * @param megaFolderLink Public link to a folder in MEGA */ public void getPublicLinkInformation(String megaFolderLink) { megaApi.getPublicLinkInformation(megaFolderLink); } /** * Call the low level function getrlimit() for NOFILE, needed for some platforms. * * @return The current limit for the number of open files (and sockets) for the app, or -1 if error. */ public int platformGetRLimitNumFile() { return megaApi.platformGetRLimitNumFile(); } /** * Call the low level function setrlimit() for NOFILE, needed for some platforms. * * Particularly on phones, the system default limit for the number of open files (and sockets) * is quite low. When the SDK can be working on many files and many sockets at once, * we need a higher limit. Those limits need to take into account the needs of the whole * app and not just the SDK, of course. This function is provided in order that the app * can make that call and set appropriate limits. * * @param newNumFileLimit The new limit of file and socket handles for the whole app. * * @return True when there were no errors setting the new limit (even when clipped to the maximum * allowed value). It returns false when setting a new limit failed. */ public boolean platformSetRLimitNumFile(int newNumFileLimit) { return megaApi.platformSetRLimitNumFile(newNumFileLimit); } /** * Requests a list of all Smart Banners available for current user. * * The response value is stored as a MegaBannerList. * * The associated request type with this request is MegaRequest::TYPE_GET_BANNERS * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaBannerList: the list of banners * * On the onRequestFinish error, the error code associated to the MegaError can be: * - MegaError::API_EACCESS - If called with no user being logged in. * - MegaError::API_EINTERNAL - If the internally used user attribute exists but can't be decoded. * - MegaError::API_ENOENT if there are no banners to return to the user. * * @param listener MegaRequestListener to track this request */ public void getBanners(MegaRequestListenerInterface listener) { megaApi.getBanners(createDelegateRequestListener(listener)); } /** * Requests a list of all Smart Banners available for current user. * * The response value is stored as a MegaBannerList. * * The associated request type with this request is MegaRequest::TYPE_GET_BANNERS * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaBannerList: the list of banners * * On the onRequestFinish error, the error code associated to the MegaError can be: * - MegaError::API_EACCESS - If called with no user being logged in. * - MegaError::API_EINTERNAL - If the internally used user attribute exists but can't be decoded. * - MegaError::API_ENOENT if there are no banners to return to the user. */ public void getBanners() { megaApi.getBanners(); } /** * No longer show the Smart Banner with the specified id to the current user. * * @param listener MegaRequestListener to track this request */ public void dismissBanner(int id, MegaRequestListenerInterface listener) { megaApi.dismissBanner(id, createDelegateRequestListener(listener)); } /** * No longer show the Smart Banner with the specified id to the current user. */ public void dismissBanner(int id) { megaApi.dismissBanner(id); } /****************************************************************************************************/ // INTERNAL METHODS /****************************************************************************************************/ private MegaRequestListener createDelegateRequestListener(MegaRequestListenerInterface listener) { DelegateMegaRequestListener delegateListener = new DelegateMegaRequestListener(this, listener, true); activeRequestListeners.add(delegateListener); return delegateListener; } private MegaRequestListener createDelegateRequestListener(MegaRequestListenerInterface listener, boolean singleListener) { DelegateMegaRequestListener delegateListener = new DelegateMegaRequestListener(this, listener, singleListener); activeRequestListeners.add(delegateListener); return delegateListener; } private MegaTransferListener createDelegateTransferListener(MegaTransferListenerInterface listener) { DelegateMegaTransferListener delegateListener = new DelegateMegaTransferListener(this, listener, true); activeTransferListeners.add(delegateListener); return delegateListener; } private MegaTransferListener createDelegateTransferListener(MegaTransferListenerInterface listener, boolean singleListener) { DelegateMegaTransferListener delegateListener = new DelegateMegaTransferListener(this, listener, singleListener); activeTransferListeners.add(delegateListener); return delegateListener; } private MegaGlobalListener createDelegateGlobalListener(MegaGlobalListenerInterface listener) { DelegateMegaGlobalListener delegateListener = new DelegateMegaGlobalListener(this, listener); activeGlobalListeners.add(delegateListener); return delegateListener; } private MegaListener createDelegateMegaListener(MegaListenerInterface listener) { DelegateMegaListener delegateListener = new DelegateMegaListener(this, listener); activeMegaListeners.add(delegateListener); return delegateListener; } private static MegaLogger createDelegateMegaLogger(MegaLoggerInterface listener){ DelegateMegaLogger delegateLogger = new DelegateMegaLogger(listener); activeMegaLoggers.add(delegateLogger); return delegateLogger; } private MegaTransferListener createDelegateHttpServerListener(MegaTransferListenerInterface listener) { DelegateMegaTransferListener delegateListener = new DelegateMegaTransferListener(this, listener, true); activeHttpServerListeners.add(delegateListener); return delegateListener; } private MegaTransferListener createDelegateHttpServerListener(MegaTransferListenerInterface listener, boolean singleListener) { DelegateMegaTransferListener delegateListener = new DelegateMegaTransferListener(this, listener, singleListener); activeHttpServerListeners.add(delegateListener); return delegateListener; } void privateFreeRequestListener(DelegateMegaRequestListener listener) { activeRequestListeners.remove(listener); } void privateFreeTransferListener(DelegateMegaTransferListener listener) { activeTransferListeners.remove(listener); } static public ArrayList<MegaNode> nodeListToArray(MegaNodeList nodeList) { if (nodeList == null) { return null; } ArrayList<MegaNode> result = new ArrayList<MegaNode>(nodeList.size()); for (int i = 0; i < nodeList.size(); i++) { result.add(nodeList.get(i).copy()); } return result; } static ArrayList<MegaShare> shareListToArray(MegaShareList shareList) { if (shareList == null) { return null; } ArrayList<MegaShare> result = new ArrayList<MegaShare>(shareList.size()); for (int i = 0; i < shareList.size(); i++) { result.add(shareList.get(i).copy()); } return result; } static ArrayList<MegaContactRequest> contactRequestListToArray(MegaContactRequestList contactRequestList) { if (contactRequestList == null) { return null; } ArrayList<MegaContactRequest> result = new ArrayList<MegaContactRequest>(contactRequestList.size()); for(int i=0; i<contactRequestList.size(); i++) { result.add(contactRequestList.get(i).copy()); } return result; } static ArrayList<MegaTransfer> transferListToArray(MegaTransferList transferList) { if (transferList == null) { return null; } ArrayList<MegaTransfer> result = new ArrayList<MegaTransfer>(transferList.size()); for (int i = 0; i < transferList.size(); i++) { result.add(transferList.get(i).copy()); } return result; } static ArrayList<MegaUser> userListToArray(MegaUserList userList) { if (userList == null) { return null; } ArrayList<MegaUser> result = new ArrayList<MegaUser>(userList.size()); for (int i = 0; i < userList.size(); i++) { result.add(userList.get(i).copy()); } return result; } static ArrayList<MegaUserAlert> userAlertListToArray(MegaUserAlertList userAlertList){ if (userAlertList == null){ return null; } ArrayList<MegaUserAlert> result = new ArrayList<MegaUserAlert>(userAlertList.size()); for (int i = 0; i < userAlertList.size(); i++){ result.add(userAlertList.get(i).copy()); } return result; } static ArrayList<MegaRecentActionBucket> recentActionsToArray(MegaRecentActionBucketList recentActionList) { if (recentActionList == null) { return null; } ArrayList<MegaRecentActionBucket> result = new ArrayList<>(recentActionList.size()); for (int i = 0; i< recentActionList.size(); i++) { result.add(recentActionList.get(i).copy()); } return result; } /** * Returns whether notifications about a chat have to be generated. * * @param chatid MegaHandle that identifies the chat room. * @return true if notification has to be created. */ public boolean isChatNotifiable(long chatid) { return megaApi.isChatNotifiable(chatid); } /** * Provide a phone number to get verification code. * * @param phoneNumber the phone number to receive the txt with verification code. * @param listener callback of this request. */ public void sendSMSVerificationCode(String phoneNumber,nz.mega.sdk.MegaRequestListenerInterface listener) { megaApi.sendSMSVerificationCode(phoneNumber,createDelegateRequestListener(listener)); } public void sendSMSVerificationCode(String phoneNumber,nz.mega.sdk.MegaRequestListenerInterface listener,boolean reverifying_whitelisted) { megaApi.sendSMSVerificationCode(phoneNumber,createDelegateRequestListener(listener),reverifying_whitelisted); } /** * Send the verification code to verifiy phone number. * * @param verificationCode received 6 digits verification code. * @param listener callback of this request. */ public void checkSMSVerificationCode(String verificationCode,nz.mega.sdk.MegaRequestListenerInterface listener) { megaApi.checkSMSVerificationCode(verificationCode,createDelegateRequestListener(listener)); } /** * Get the verified phone number of the mega account. * * @return verified phone number. */ public String smsVerifiedPhoneNumber() { return megaApi.smsVerifiedPhoneNumber(); } /** * Requests the contacts that are registered at MEGA (currently verified through SMS) * * @param contacts The map of contacts to get registered contacts from * @param listener MegaRequestListener to track this request */ public void getRegisteredContacts(MegaStringMap contacts, nz.mega.sdk.MegaRequestListenerInterface listener) { megaApi.getRegisteredContacts(contacts, createDelegateRequestListener(listener)); } /** * Requests the currently available country calling codes * * @param listener MegaRequestListener to track this request */ public void getCountryCallingCodes(nz.mega.sdk.MegaRequestListenerInterface listener) { megaApi.getCountryCallingCodes(createDelegateRequestListener(listener)); } /** * Get the state to see whether blocked account could do SMS verification * * @return the state */ public int smsAllowedState() { return megaApi.smsAllowedState(); } /** * Returns the email of the user who made the changes * * The SDK retains the ownership of the returned value. It will be valid until * the MegaRecentActionBucket object is deleted. * * @return The associated user's email */ public void getUserEmail(long handle, nz.mega.sdk.MegaRequestListenerInterface listener) { megaApi.getUserEmail(handle, createDelegateRequestListener(listener)); } /** * Resume a registration process for an Ephemeral++ account * * When a user begins the account registration process by calling * MegaApi::createEphemeralAccountPlusPlus an ephemeral++ account is created. * * Until the user successfully confirms the signup link sent to the provided email address, * you can resume the ephemeral session in order to change the email address, resend the * signup link (@see MegaApi::sendSignupLink) and also to receive notifications in case the * user confirms the account using another client (MegaGlobalListener::onAccountUpdate or * MegaListener::onAccountUpdate). It is also possible to cancel the registration process by * MegaApi::cancelCreateAccount, which invalidates the signup link associated to the ephemeral * session (the session will be still valid). * * The associated request type with this request is MegaRequest::TYPE_CREATE_ACCOUNT. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getSessionKey - Returns the session id to resume the process * - MegaRequest::getParamType - Returns the value MegaApi::RESUME_EPLUSPLUS_ACCOUNT * * In case the account is already confirmed, the associated request will fail with * error MegaError::API_EARGS. * * @param sid Session id valid for the ephemeral++ account (@see MegaApi::createEphemeralAccountPlusPlus) * @param listener MegaRequestListener to track this request */ public void resumeCreateAccountEphemeralPlusPlus(String sid, MegaRequestListenerInterface listener) { megaApi.resumeCreateAccountEphemeralPlusPlus(sid, createDelegateRequestListener(listener)); } /** * Cancel a registration process * * If a signup link has been generated during registration process, call this function * to invalidate it. The ephemeral session will not be invalidated, only the signup link. * * The associated request type with this request is MegaRequest::TYPE_CREATE_ACCOUNT. * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the value MegaApi::CANCEL_ACCOUNT * * @param listener MegaRequestListener to track this request */ public void cancelCreateAccount(MegaRequestListenerInterface listener){ megaApi.cancelCreateAccount(createDelegateRequestListener(listener)); } /** * @brief Registers a backup to display in Backup Centre * * Apps should register backups, like CameraUploads, in order to be listed in the * BackupCentre. The client should send heartbeats to indicate the progress of the * backup (see \c MegaApi::sendBackupHeartbeats). * * Possible types of backups: * BACKUP_TYPE_CAMERA_UPLOADS = 3, * BACKUP_TYPE_MEDIA_UPLOADS = 4, // Android has a secondary CU * * Note that the backup name is not registered in the API as part of the data of this * backup. It will be stored in a user's attribute after this request finished. For * more information, see \c MegaApi::setBackupName and MegaApi::getBackupName. * * The associated request type with this request is MegaRequest::TYPE_BACKUP_PUT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParentHandle - Returns the backupId * - MegaRequest::getNodeHandle - Returns the target node of the backup * - MegaRequest::getName - Returns the backup name of the remote location * - MegaRequest::getAccess - Returns the backup state * - MegaRequest::getFile - Returns the path of the local folder * - MegaRequest::getTotalBytes - Returns the backup type * - MegaRequest::getNumDetails - Returns the backup substate * - MegaRequest::getFlag - Returns true * - MegaRequest::getListener - Returns the MegaRequestListener to track this request * * @param backupType back up type requested for the service * @param targetNode MEGA folder to hold the backups * @param localFolder Local path of the folder * @param backupName Name of the backup * @param state state * @param subState subState * @param listener MegaRequestListener to track this request */ public void setBackup(int backupType, long targetNode, String localFolder, String backupName, int state, int subState, MegaRequestListenerInterface listener) { megaApi.setBackup(backupType, targetNode, localFolder, backupName, state, subState, createDelegateRequestListener(listener)); } /** * @brief Update the information about a registered backup for Backup Centre * * Possible types of backups: * BACKUP_TYPE_INVALID = -1, * BACKUP_TYPE_CAMERA_UPLOADS = 3, * BACKUP_TYPE_MEDIA_UPLOADS = 4, // Android has a secondary CU * * Params that keep the same value are passed with invalid value to avoid to send to the server * Invalid values: * - type: BACKUP_TYPE_INVALID * - nodeHandle: UNDEF * - localFolder: nullptr * - deviceId: nullptr * - state: -1 * - subState: -1 * - extraData: nullptr * * If you want to update the backup name, use \c MegaApi::setBackupName. * * The associated request type with this request is MegaRequest::TYPE_BACKUP_PUT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParentHandle - Returns the backupId * - MegaRequest::getTotalBytes - Returns the backup type * - MegaRequest::getNodeHandle - Returns the target node of the backup * - MegaRequest::getFile - Returns the path of the local folder * - MegaRequest::getAccess - Returns the backup state * - MegaRequest::getNumDetails - Returns the backup substate * - MegaRequest::getListener - Returns the MegaRequestListener to track this request * * @param backupId backup id identifying the backup to be updated * @param backupType back up type requested for the service * @param targetNode MEGA folder to hold the backups * @param localFolder Local path of the folder * @param state backup state * @param subState backup subState * @param listener MegaRequestListener to track this request */ public void updateBackup(long backupId, int backupType, long targetNode, String localFolder, String backupName, int state, int subState, MegaRequestListenerInterface listener) { megaApi.updateBackup(backupId, backupType, targetNode, localFolder, backupName, state, subState, createDelegateRequestListener(listener)); } /** * @brief Unregister a backup already registered for the Backup Centre * * This method allows to remove a backup from the list of backups displayed in the * Backup Centre. @see \c MegaApi::setBackup. * * The associated request type with this request is MegaRequest::TYPE_BACKUP_REMOVE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParentHandle - Returns the backupId * - MegaRequest::getListener - Returns the MegaRequestListener to track this request * * @param backupId backup id identifying the backup to be removed * @param listener MegaRequestListener to track this request */ public void removeBackup(long backupId, MegaRequestListenerInterface listener) { megaApi.removeBackup(backupId, createDelegateRequestListener(listener)); } /** * @brief Send heartbeat associated with an existing backup * * The client should call this method regularly for every registered backup, in order to * inform about the status of the backup. * * Progress, last timestamp and last node are not always meaningful (ie. when the Camera * Uploads starts a new batch, there isn't a last node, or when the CU up to date and * inactive for long time, the progress doesn't make sense). In consequence, these parameters * are optional. They will not be sent to API if they take the following values: * - lastNode = INVALID_HANDLE * - lastTs = -1 * - progress = -1 * * The associated request type with this request is MegaRequest::TYPE_BACKUP_PUT_HEART_BEAT * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParentHandle - Returns the backupId * - MegaRequest::getAccess - Returns the backup state * - MegaRequest::getNumDetails - Returns the backup substate * - MegaRequest::getParamType - Returns the number of pending upload transfers * - MegaRequest::getTransferTag - Returns the number of pending download transfers * - MegaRequest::getNumber - Returns the last action timestamp * - MegaRequest::getNodeHandle - Returns the last node handle to be synced * * @param backupId backup id identifying the backup * @param state backup state * @param progress backup progress * @param ups Number of pending upload transfers * @param downs Number of pending download transfers * @param ts Last action timestamp * @param lastNode Last node handle to be synced * @param listener MegaRequestListener to track this request */ public void sendBackupHeartbeat(long backupId, int status, int progress, int ups, int downs, long ts, long lastNode, MegaRequestListenerInterface listener) { megaApi.sendBackupHeartbeat(backupId, status, progress, ups, downs, ts, lastNode, createDelegateRequestListener(listener)); } /** * @brief Fetch Google ads * * The associated request type with this request is MegaRequest::TYPE_FETCH_GOOGLE_ADS * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNumber A bitmap flag used to communicate with the API * - MegaRequest::getMegaStringList List of the adslot ids to fetch * - MegaRequest::getNodeHandle Public handle that the user is visiting * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaStringMap: map with relationship between ids and ius * * @param adFlags A bitmap flag used to communicate with the API * Valid values are: * - GOOGLE_ADS_DEFAULT = 0x0 * - GOOGLE_ADS_FORCE_ADS = 0x200 * - GOOGLE_ADS_IGNORE_MEGA = 0x400 * - GOOGLE_ADS_IGNORE_COUNTRY = 0x800 * - GOOGLE_ADS_IGNORE_IP = 0x1000 * - GOOGLE_ADS_IGNORE_PRO = 0x2000 * - GOOGLE_ADS_FLAG_IGNORE_ROLLOUT = 0x4000 * @param adUnits A list of the adslot ids to fetch * @param publicHandle Provide the public handle that the user is visiting * @param listener MegaRequestListener to track this request */ public void fetchGoogleAds(int adFlags, MegaStringList adUnits, long publicHandle, MegaRequestListenerInterface listener) { megaApi.fetchGoogleAds(adFlags, adUnits, publicHandle, createDelegateRequestListener(listener)); } /** * @brief Fetch Google ads * * The associated request type with this request is MegaRequest::TYPE_FETCH_GOOGLE_ADS * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNumber A bitmap flag used to communicate with the API * - MegaRequest::getMegaStringList List of the adslot ids to fetch * - MegaRequest::getNodeHandle Public handle that the user is visiting * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaStringMap: map with relationship between ids and ius * * @param adFlags A bitmap flag used to communicate with the API * Valid values are: * - GOOGLE_ADS_DEFAULT = 0x0 * - GOOGLE_ADS_FORCE_ADS = 0x200 * - GOOGLE_ADS_IGNORE_MEGA = 0x400 * - GOOGLE_ADS_IGNORE_COUNTRY = 0x800 * - GOOGLE_ADS_IGNORE_IP = 0x1000 * - GOOGLE_ADS_IGNORE_PRO = 0x2000 * - GOOGLE_ADS_FLAG_IGNORE_ROLLOUT = 0x4000 * @param adUnits A list of the adslot ids to fetch * @param publicHandle Provide the public handle that the user is visiting */ public void fetchGoogleAds(int adFlags, MegaStringList adUnits, long publicHandle) { megaApi.fetchGoogleAds(adFlags, adUnits, publicHandle); } /** * @brief Fetch Google ads * * The associated request type with this request is MegaRequest::TYPE_FETCH_GOOGLE_ADS * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNumber A bitmap flag used to communicate with the API * - MegaRequest::getMegaStringList List of the adslot ids to fetch * - MegaRequest::getNodeHandle Public handle that the user is visiting * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaStringMap: map with relationship between ids and ius * * @param adFlags A bitmap flag used to communicate with the API * Valid values are: * - GOOGLE_ADS_DEFAULT = 0x0 * - GOOGLE_ADS_FORCE_ADS = 0x200 * - GOOGLE_ADS_IGNORE_MEGA = 0x400 * - GOOGLE_ADS_IGNORE_COUNTRY = 0x800 * - GOOGLE_ADS_IGNORE_IP = 0x1000 * - GOOGLE_ADS_IGNORE_PRO = 0x2000 * - GOOGLE_ADS_FLAG_IGNORE_ROLLOUT = 0x4000 * @param adUnits A list of the adslot ids to fetch */ public void fetchGoogleAds(int adFlags, MegaStringList adUnits) { megaApi.fetchGoogleAds(adFlags, adUnits); } /** * @brief Check if Google ads should show or not * * The associated request type with this request is MegaRequest::TYPE_QUERY_GOOGLE_ADS * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNumber A bitmap flag used to communicate with the API * - MegaRequest::getNodeHandle Public handle that the user is visiting * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNumDetails Return if ads should be show or not * * @param adFlags A bitmap flag used to communicate with the API * Valid values are: * - GOOGLE_ADS_DEFAULT = 0x0 * - GOOGLE_ADS_FORCE_ADS = 0x200 * - GOOGLE_ADS_IGNORE_MEGA = 0x400 * - GOOGLE_ADS_IGNORE_COUNTRY = 0x800 * - GOOGLE_ADS_IGNORE_IP = 0x1000 * - GOOGLE_ADS_IGNORE_PRO = 0x2000 * - GOOGLE_ADS_FLAG_IGNORE_ROLLOUT 0x4000 * @param publicHandle Provide the public handle that the user is visiting * @param listener MegaRequestListener to track this request */ public void queryGoogleAds(int adFlags, long publicHandle, MegaRequestListenerInterface listener) { megaApi.queryGoogleAds(adFlags, publicHandle, createDelegateRequestListener(listener)); } /** * @brief Check if Google ads should show or not * * The associated request type with this request is MegaRequest::TYPE_QUERY_GOOGLE_ADS * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNumber A bitmap flag used to communicate with the API * - MegaRequest::getNodeHandle Public handle that the user is visiting * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNumDetails Return if ads should be show or not * * @param adFlags A bitmap flag used to communicate with the API * Valid values are: * - GOOGLE_ADS_DEFAULT = 0x0 * - GOOGLE_ADS_FORCE_ADS = 0x200 * - GOOGLE_ADS_IGNORE_MEGA = 0x400 * - GOOGLE_ADS_IGNORE_COUNTRY = 0x800 * - GOOGLE_ADS_IGNORE_IP = 0x1000 * - GOOGLE_ADS_IGNORE_PRO = 0x2000 * - GOOGLE_ADS_FLAG_IGNORE_ROLLOUT 0x4000 * @param publicHandle Provide the public handle that the user is visiting */ public void queryGoogleAds(int adFlags, long publicHandle) { megaApi.queryGoogleAds(adFlags, publicHandle); } /** * @brief Check if Google ads should show or not * * The associated request type with this request is MegaRequest::TYPE_QUERY_GOOGLE_ADS * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNumber A bitmap flag used to communicate with the API * - MegaRequest::getNodeHandle Public handle that the user is visiting * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNumDetails Return if ads should be show or not * * @param adFlags A bitmap flag used to communicate with the API * Valid values are: * - GOOGLE_ADS_DEFAULT = 0x0 * - GOOGLE_ADS_FORCE_ADS = 0x200 * - GOOGLE_ADS_IGNORE_MEGA = 0x400 * - GOOGLE_ADS_IGNORE_COUNTRY = 0x800 * - GOOGLE_ADS_IGNORE_IP = 0x1000 * - GOOGLE_ADS_IGNORE_PRO = 0x2000 * - GOOGLE_ADS_FLAG_IGNORE_ROLLOUT 0x4000 */ public void queryGoogleAds(int adFlags) { megaApi.queryGoogleAds(adFlags); } /** * @brief Set a bitmap to indicate whether some cookies are enabled or not * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_COOKIE_SETTINGS * - MegaRequest::getNumDetails - Return a bitmap with cookie settings * - MegaRequest::getListener - Returns the MegaRequestListener to track this request * * @param settings A bitmap with cookie settings * Valid bits are: * - Bit 0: essential * - Bit 1: preference * - Bit 2: analytics * - Bit 3: ads * - Bit 4: thirdparty * @param listener MegaRequestListener to track this request */ public void setCookieSettings(int settings, MegaRequestListenerInterface listener) { megaApi.setCookieSettings(settings, createDelegateRequestListener(listener)); } /** * @brief Set a bitmap to indicate whether some cookies are enabled or not * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_COOKIE_SETTINGS * - MegaRequest::getNumDetails - Return a bitmap with cookie settings * - MegaRequest::getListener - Returns the MegaRequestListener to track this request * * @param settings A bitmap with cookie settings * Valid bits are: * - Bit 0: essential * - Bit 1: preference * - Bit 2: analytics * - Bit 3: ads * - Bit 4: thirdparty */ public void setCookieSettings(int settings) { megaApi.setCookieSettings(settings); } /** * @brief Get a bitmap to indicate whether some cookies are enabled or not * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the value USER_ATTR_COOKIE_SETTINGS * - MegaRequest::getListener - Returns the MegaRequestListener to track this request * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNumDetails Return the bitmap with cookie settings * Valid bits are: * - Bit 0: essential * - Bit 1: preference * - Bit 2: analytics * - Bit 3: ads * - Bit 4: thirdparty * * On the onRequestFinish error, the error code associated to the MegaError can be: * - MegaError::API_EINTERNAL - If the value for cookie settings bitmap was invalid * * @param listener MegaRequestListener to track this request */ public void getCookieSettings(MegaRequestListenerInterface listener) { megaApi.getCookieSettings(createDelegateRequestListener(listener)); } /** * @brief Get a bitmap to indicate whether some cookies are enabled or not * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the value USER_ATTR_COOKIE_SETTINGS * - MegaRequest::getListener - Returns the MegaRequestListener to track this request * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNumDetails Return the bitmap with cookie settings * Valid bits are: * - Bit 0: essential * - Bit 1: preference * - Bit 2: analytics * - Bit 3: ads * - Bit 4: thirdparty * * On the onRequestFinish error, the error code associated to the MegaError can be: * - MegaError::API_EINTERNAL - If the value for cookie settings bitmap was invalid */ public void getCookieSettings() { megaApi.getCookieSettings(); } /** * @brief Check if the app can start showing the cookie banner * * This function will NOT return a valid value until the callback onEvent with * type MegaApi::EVENT_MISC_FLAGS_READY is received. You can also rely on the completion of * a fetchnodes to check this value, but only when it follows a login with user and password, * not when an existing session is resumed. * * For not logged-in mode, you need to call MegaApi::getMiscFlags first. * * @return True if this feature is enabled. Otherwise, false. */ public boolean isCookieBannerEnabled() { return megaApi.cookieBannerEnabled(); } /** * @brief Set My Backups folder. * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_MY_BACKUPS_FOLDER * - MegaRequest::getFlag - Returns false * - MegaRequest::getNodehandle - Returns the provided node handle * - MegaRequest::getMegaStringMap - Returns a MegaStringMap. * The key "h" in the map contains the nodehandle specified as parameter encoded in B64 * * If the folder is not private to the current account, or is in Rubbish, or is in a synced folder, * the request will fail with the error code MegaError::API_EACCESS. * * @param handle MegaHandle of the node to be used as target folder * @param listener MegaRequestListener to track this request */ public void setMyBackupsFolder(long handle, MegaRequestListenerInterface listener) { megaApi.setMyBackupsFolder(handle, createDelegateRequestListener(listener)); } /** * @brief Set My Backups folder. * * The associated request type with this request is MegaRequest::TYPE_SET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_MY_BACKUPS_FOLDER * - MegaRequest::getFlag - Returns false * - MegaRequest::getNodehandle - Returns the provided node handle * - MegaRequest::getMegaStringMap - Returns a MegaStringMap. * The key "h" in the map contains the nodehandle specified as parameter encoded in B64 * * If the folder is not private to the current account, or is in Rubbish, or is in a synced folder, * the request will fail with the error code MegaError::API_EACCESS. * * @param handle MegaHandle of the node to be used as target folder */ public void setMyBackupsFolder(long handle) { megaApi.setMyBackupsFolder(handle); } /** * @brief Gets My Backups target folder. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_MY_BACKUPS_FOLDER * - MegaRequest::getFlag - Returns false * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodehandle - Returns the handle of the node where My Backups files are stored * * If the folder was not set, the request will fail with the error code MegaError::API_ENOENT. * * @param listener MegaRequestListener to track this request */ public void getMyBackupsFolder(MegaRequestListenerInterface listener) { megaApi.getMyBackupsFolder(createDelegateRequestListener(listener)); } /** * @brief Gets My Backups target folder. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_USER * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getParamType - Returns the attribute type MegaApi::USER_ATTR_MY_BACKUPS_FOLDER * - MegaRequest::getFlag - Returns false * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getNodehandle - Returns the handle of the node where My Backups files are stored * * If the folder was not set, the request will fail with the error code MegaError::API_ENOENT. */ public void getMyBackupsFolder() { megaApi.getMyBackupsFolder(); } /** * @brief Get a list of favourite nodes. * * @param node Node and its children that will be searched for favourites. Search all nodes if null * @param count if count is zero return all favourite nodes, otherwise return only 'count' favourite nodes */ public void getFavourites(MegaNode node, int count) { megaApi.getFavourites(node, count); } /** * @brief Get a list of favourite nodes. * * The associated request type with this request is MegaRequest::TYPE_GET_ATTR_NODE * Valid data in the MegaRequest object received on callbacks: * - MegaRequest::getNodeHandle - Returns the handle of the node provided * - MegaRequest::getParamType - Returns MegaApi::NODE_ATTR_FAV * - MegaRequest::getNumDetails - Returns the count requested * * Valid data in the MegaRequest object received in onRequestFinish when the error code * is MegaError::API_OK: * - MegaRequest::getMegaHandleList - List of handles of favourite nodes * * @param node Node and its children that will be searched for favourites. Search all nodes if null * @param count if count is zero return all favourite nodes, otherwise return only 'count' favourite nodes * @param listener MegaRequestListener to track this request */ public void getFavourites(MegaNode node, int count, MegaRequestListenerInterface listener) { megaApi.getFavourites(node, count, createDelegateRequestListener(listener)); } }
Remove the getFavourites function that doesn't include MegaRequestListenerInterface parameter.
bindings/java/nz/mega/sdk/MegaApiJava.java
Remove the getFavourites function that doesn't include MegaRequestListenerInterface parameter.
Java
mit
468141b4c6f0431baaa2d30c4740eaf2fb173a45
0
Appstax/appstax-java,Appstax/appstax-java
package com.appstax; import org.json.JSONObject; public class AxEvent { private AxClient client; private JSONObject payload; protected AxEvent(AxClient client, JSONObject payload) { this.client = client; this.payload = payload; } public String getType() { return payload.optString("event"); } public String getChannel() { return payload.optString("channel"); } public String getString() { return payload.optString("message"); } public AxObject getObject() { String msg = this.getString(); if (!msg.startsWith("{")) { return null; } return AxObject.unmarshal(client, msg); } }
src/main/java/com/appstax/AxEvent.java
package com.appstax; import org.json.JSONObject; public class AxEvent { private AxClient client; private JSONObject payload; protected AxEvent(AxClient client, JSONObject payload) { this.client = client; this.payload = payload; } public String getType() { return payload.getString("event"); } public String getChannel() { return payload.getString("channel"); } public String getString() { return payload.getString("message"); } public AxObject getObject() { return AxObject.unmarshal(client, getString()); } }
Avoid unnecessary throws from event.getObject.
src/main/java/com/appstax/AxEvent.java
Avoid unnecessary throws from event.getObject.
Java
mit
ce4bfb7b0b644eb5ed90bc6d2971a33ffb16ed9b
0
dbunibas/BART,dbunibas/BART
package bart.model; import bart.BartConstants; import speedy.model.database.AttributeRef; import bart.model.errorgenerator.operator.valueselectors.IDirtyStrategy; import java.util.HashMap; import java.util.Map; import java.util.Set; public class EGTaskConfiguration { private boolean printLog = false; private boolean debug = false; private Long queryExecutionTimeout; private boolean useDeltaDBForChanges = true; private boolean recreateDBOnStart = false; private boolean checkCleanInstance = false; private boolean checkChanges = false; private boolean excludeCrossProducts = false; private boolean avoidInteractions = true; private boolean applyCellChanges = false; private boolean exportCellChanges = false; private String exportCellChangesPath = null; private boolean exportDirtyDB = false; private String exportDirtyDBType = BartConstants.CSV; private String exportDirtyDBPath = null; private boolean estimateRepairability = false; private boolean cloneTargetSchema = true; private String cloneSuffix = BartConstants.DIRTY_SUFFIX; private boolean useSymmetricOptimization = true; private boolean generateAllChanges = false; private String sampleStrategyForStandardQueries = BartConstants.SAMPLE_STRATEGY_TABLE_SIZE; private String sampleStrategyForSymmetricQueries = BartConstants.SAMPLE_STRATEGY_TABLE_SIZE; private String sampleStrategyForInequalityQueries = BartConstants.SAMPLE_STRATEGY_TABLE_SIZE; private boolean detectEntireEquivalenceClasses = true; // private Integer maxNumberOfInequalitiesInSymmetricQueries = null; private double sizeFactorReduction = 0.7; private Map<String, Double> vioGenQueryProbabilities = new HashMap<String, Double>(); private Map<String, String> vioGenQueryStrategy = new HashMap<String, String>(); private VioGenQueryConfiguration defaultVioGenQueryConfiguration = new VioGenQueryConfiguration(); private boolean randomErrors = false; private Map<String, Set<String>> tablesForRandomErrors = new HashMap<String, Set<String>>(); // key: tableName values: attributesToDirty private Map<String, Integer> tablesPercentageForRandomErrors = new HashMap<String, Integer>(); // key: tableName values: percentage; private boolean outlierErrors = false; private OutlierErrorConfiguration outlierErrorConfiguration = new OutlierErrorConfiguration(); private IDirtyStrategy defaultDirtyStrategy; private Map<AttributeRef, IDirtyStrategy> dirtyStrategiesMap = new HashMap<AttributeRef, IDirtyStrategy>(); public boolean isRecreateDBOnStart() { return recreateDBOnStart; } public void setRecreateDBOnStart(boolean recreateDBOnStart) { this.recreateDBOnStart = recreateDBOnStart; } public boolean isUseSymmetricOptimization() { return useSymmetricOptimization; } public void setUseSymmetricOptimization(boolean useSymmetricOptimization) { this.useSymmetricOptimization = useSymmetricOptimization; } public boolean isUseDeltaDBForChanges() { return useDeltaDBForChanges; } public void setUseDeltaDBForChanges(boolean useDeltaDBForChanges) { this.useDeltaDBForChanges = useDeltaDBForChanges; } public Long getQueryExecutionTimeout() { return queryExecutionTimeout; } public void setQueryExecutionTimeout(Long queryExecutionTimeout) { this.queryExecutionTimeout = queryExecutionTimeout; } public String getSampleStrategyForStandardQueries() { return sampleStrategyForStandardQueries; } public void setSampleStrategyForStandardQueries(String sampleStrategyForStandardQueries) { this.sampleStrategyForStandardQueries = sampleStrategyForStandardQueries; } public String getSampleStrategyForSymmetricQueries() { return sampleStrategyForSymmetricQueries; } public void setSampleStrategyForSymmetricQueries(String sampleStrategyForSymmetricQueries) { this.sampleStrategyForSymmetricQueries = sampleStrategyForSymmetricQueries; } public String getSampleStrategyForInequalityQueries() { return sampleStrategyForInequalityQueries; } public void setSampleStrategyForInequalityQueries(String sampleStrategyForInequalityQueries) { this.sampleStrategyForInequalityQueries = sampleStrategyForInequalityQueries; } public boolean isCheckCleanInstance() { return checkCleanInstance; } public void setCheckCleanInstance(boolean checkCleanInstance) { this.checkCleanInstance = checkCleanInstance; } public boolean isAvoidInteractions() { return avoidInteractions; } public void setAvoidInteractions(boolean avoidInteractions) { this.avoidInteractions = avoidInteractions; } public boolean isPrintLog() { return printLog; } public void setPrintLog(boolean printLog) { this.printLog = printLog; } public boolean isApplyCellChanges() { return applyCellChanges; } public void setApplyCellChanges(boolean applyCellChanges) { this.applyCellChanges = applyCellChanges; } public boolean isExportCellChanges() { return exportCellChanges; } public void setExportCellChanges(boolean exportCellChanges) { this.exportCellChanges = exportCellChanges; } public String getExportCellChangesPath() { return exportCellChangesPath; } public void setExportCellChangesPath(String exportCellChangesPath) { this.exportCellChangesPath = exportCellChangesPath; } public boolean isExportDirtyDB() { return exportDirtyDB; } public void setExportDirtyDB(boolean exportDirtyDB) { this.exportDirtyDB = exportDirtyDB; } public String getExportDirtyDBType() { return exportDirtyDBType; } public void setExportDirtyDBType(String exportDirtyDBType) { this.exportDirtyDBType = exportDirtyDBType; } public String getExportDirtyDBPath() { return exportDirtyDBPath; } public void setExportDirtyDBPath(String exportDirtyDBPath) { this.exportDirtyDBPath = exportDirtyDBPath; } public VioGenQueryConfiguration getDefaultVioGenQueryConfiguration() { return defaultVioGenQueryConfiguration; } public boolean isGenerateAllChanges() { return generateAllChanges; } public void setGenerateAllChanges(boolean generateAllChanges) { this.generateAllChanges = generateAllChanges; } public double getSizeFactorReduction() { return sizeFactorReduction; } public void setSizeFactorReduction(double sizeFactorReduction) { this.sizeFactorReduction = sizeFactorReduction; } public void addVioGenQueryProbabilities(String vioGenKey, double percentage) { this.vioGenQueryProbabilities.put(vioGenKey, percentage); } public Map<String, Double> getVioGenQueryProbabilities() { return vioGenQueryProbabilities; } public void setVioGenQueryProbabilities(Map<String, Double> vioGenQueryProbabilities) { this.vioGenQueryProbabilities = vioGenQueryProbabilities; } public void addVioGenQueryStrategy(String vioGenKey, String strategy) { this.vioGenQueryStrategy.put(vioGenKey, strategy); } public Map<String, String> getVioGenQueryStrategy() { return vioGenQueryStrategy; } public boolean isEstimateRepairability() { return estimateRepairability; } public void setEstimateRepairability(boolean estimateRepairability) { this.estimateRepairability = estimateRepairability; } public boolean isDebug() { return debug; } public void setDebug(boolean debug) { this.debug = debug; } public boolean isCloneTargetSchema() { return cloneTargetSchema; } public void setCloneTargetSchema(boolean cloneTargetSchema) { this.cloneTargetSchema = cloneTargetSchema; } public String getCloneSuffix() { return cloneSuffix; } public void setCloneSuffix(String cloneSuffix) { this.cloneSuffix = cloneSuffix; } public boolean isExcludeCrossProducts() { return excludeCrossProducts; } public void setExcludeCrossProducts(boolean excludeCrossProducts) { this.excludeCrossProducts = excludeCrossProducts; } public boolean isDetectEntireEquivalenceClasses() { return detectEntireEquivalenceClasses; } public void setDetectEntireEquivalenceClasses(boolean detectEntireEquivalenceClasses) { this.detectEntireEquivalenceClasses = detectEntireEquivalenceClasses; } public boolean isCheckChanges() { return checkChanges; } public void setCheckChanges(boolean checkChanges) { this.checkChanges = checkChanges; } public boolean isRandomErrors() { return randomErrors; } public void setRandomErrors(boolean randomErrors) { this.randomErrors = randomErrors; } public Set<String> getTablesForRandomErrors() { return tablesForRandomErrors.keySet(); } public void addTableForRandomErrors(String tableName, Set<String> attributes) { this.tablesForRandomErrors.put(tableName, attributes); } public Set<String> getAttributesForRandomErrors(String tableName) { return tablesForRandomErrors.get(tableName); } public void addPercentageForRandomErrors(String tableName, int percentage) { this.tablesPercentageForRandomErrors.put(tableName, percentage); } public int getPercentageForRandomErrors(String tableName) { return tablesPercentageForRandomErrors.get(tableName); } public boolean isOutlierErrors() { return outlierErrors; } public void setOutlierErrors(boolean outlierErrors) { this.outlierErrors = outlierErrors; } public OutlierErrorConfiguration getOutlierErrorConfiguration() { return outlierErrorConfiguration; } public void setOutlierErrorConfiguration(OutlierErrorConfiguration outlierErrorConfiguration) { this.outlierErrorConfiguration = outlierErrorConfiguration; } public IDirtyStrategy getDefaultDirtyStrategy() { return defaultDirtyStrategy; } public void setDefaultDirtyStrategy(IDirtyStrategy defaultDirtyStrategy) { this.defaultDirtyStrategy = defaultDirtyStrategy; } public void addDirtyStrategyForAttribute(AttributeRef attribute, IDirtyStrategy dirtyStrategy) { this.dirtyStrategiesMap.put(attribute, dirtyStrategy); } public IDirtyStrategy getDirtyStrategy(AttributeRef attribute) { IDirtyStrategy dirtyStrategy = this.dirtyStrategiesMap.get(attribute); if (dirtyStrategy != null) return dirtyStrategy; return defaultDirtyStrategy; } public Map<AttributeRef, IDirtyStrategy> getDirtyStrategy() { return dirtyStrategiesMap; } // public Integer getMaxNumberOfInequalitiesInSymmetricQueries() { // return maxNumberOfInequalitiesInSymmetricQueries; // } // // public void setMaxNumberOfInequalitiesInSymmetricQueries(Integer maxNumberOfInequalitiesInSymmetricQueries) { // this.maxNumberOfInequalitiesInSymmetricQueries = maxNumberOfInequalitiesInSymmetricQueries; // } @Override public String toString() { return toShortString() + "\n" + defaultVioGenQueryConfiguration.toString(); } public Object toShortString() { String configuration = "Configuration:" + "\n\t printLog=" + printLog + "\n\t recreateDBOnStart=" + recreateDBOnStart + "\n\t useDeltaDBForChanges=" + useDeltaDBForChanges + "\n\t applyCellChanges=" + applyCellChanges + "\n\t cloneTargetSchema=" + cloneTargetSchema + "\n\t generateAllChanges=" + generateAllChanges + "\n\t avoidInteractions=" + avoidInteractions + "\n\t checkCleanInstance=" + checkCleanInstance + "\n\t excludeCrossProducts=" + excludeCrossProducts + "\n\t useSymmetricOptimization=" + useSymmetricOptimization + "\n\t sampleStrategyForStandardQueries=" + sampleStrategyForStandardQueries + "\n\t sampleStrategyForSymmetricQueries=" + sampleStrategyForSymmetricQueries + "\n\t sampleStrategyForInequalityQueries=" + sampleStrategyForInequalityQueries // + "\n\t maxNumberOfInequalitiesInSymmetricQueries=" + maxNumberOfInequalitiesInSymmetricQueries + "\n\t detectEntireEquivalenceClasses=" + detectEntireEquivalenceClasses + "\n\t defaultDirtyStrategy " + defaultDirtyStrategy + printDetailedDirtyAttributeStrategy() + "\n\t randomErrors=" + randomErrors + printDetailedRandomErrorsForTables() + "\n\t outlierErrors=" + outlierErrors + printDetaileOutlierErrors(); return configuration.trim(); } private String printDetailedRandomErrorsForTables() { StringBuilder sb = new StringBuilder(); if (randomErrors) { for (String table : getTablesForRandomErrors()) { sb.append("\n\t\t Table: ").append(table) .append("\n\t\t\t Random error(%)=").append(tablesPercentageForRandomErrors.get(table)) .append("\n\t\t\t Attributes to dirty=").append(tablesForRandomErrors.get(table)); } } return sb.toString(); } private String printDetailedDirtyAttributeStrategy() { StringBuilder sb = new StringBuilder(); for (AttributeRef attribute : dirtyStrategiesMap.keySet()) { sb.append("\n\t\t Attribute: ").append(attribute.getTableName()).append(".").append(attribute.getName()).append("=").append(dirtyStrategiesMap.get(attribute)); } return sb.toString(); } private String printDetaileOutlierErrors() { if (!outlierErrors) return ""; return "\n\t" + outlierErrorConfiguration.toString(); } }
src/bart/model/EGTaskConfiguration.java
package bart.model; import bart.BartConstants; import speedy.model.database.AttributeRef; import bart.model.errorgenerator.operator.valueselectors.IDirtyStrategy; import java.util.HashMap; import java.util.Map; import java.util.Set; public class EGTaskConfiguration { private boolean printLog = false; private boolean debug = false; private Long queryExecutionTimeout; private boolean useDeltaDBForChanges = true; private boolean recreateDBOnStart = false; private boolean checkCleanInstance = false; private boolean checkChanges = false; private boolean excludeCrossProducts = false; private boolean avoidInteractions = true; private boolean applyCellChanges = false; private boolean exportCellChanges = false; private String exportCellChangesPath = null; private boolean exportDirtyDB = false; private String exportDirtyDBType = BartConstants.CSV; private String exportDirtyDBPath = null; private boolean estimateRepairability = false; private boolean cloneTargetSchema = true; private String cloneSuffix = BartConstants.DIRTY_SUFFIX; private boolean useSymmetricOptimization = true; private boolean generateAllChanges = false; private String sampleStrategyForStandardQueries = BartConstants.SAMPLE_STRATEGY_TABLE_SIZE; private String sampleStrategyForSymmetricQueries = BartConstants.SAMPLE_STRATEGY_TABLE_SIZE; private String sampleStrategyForInequalityQueries = BartConstants.SAMPLE_STRATEGY_TABLE_SIZE; private boolean detectEntireEquivalenceClasses = true; // private Integer maxNumberOfInequalitiesInSymmetricQueries = null; private double sizeFactorReduction = 0.7; private Map<String, Double> vioGenQueryProbabilities = new HashMap<String, Double>(); private Map<String, String> vioGenQueryStrategy = new HashMap<String, String>(); private VioGenQueryConfiguration defaultVioGenQueryConfiguration = new VioGenQueryConfiguration(); private boolean randomErrors = false; private Map<String, Set<String>> tablesForRandomErrors = new HashMap<String, Set<String>>(); // key: tableName values: attributesToDirty private Map<String, Integer> tablesPercentageForRandomErrors = new HashMap<String, Integer>(); // key: tableName values: percentage; private boolean outlierErrors = false; private OutlierErrorConfiguration outlierErrorConfiguration = new OutlierErrorConfiguration(); private IDirtyStrategy defaultDirtyStrategy; private Map<AttributeRef, IDirtyStrategy> dirtyStrategiesMap = new HashMap<AttributeRef, IDirtyStrategy>(); public boolean isRecreateDBOnStart() { return recreateDBOnStart; } public void setRecreateDBOnStart(boolean recreateDBOnStart) { this.recreateDBOnStart = recreateDBOnStart; } public boolean isUseSymmetricOptimization() { return useSymmetricOptimization; } public void setUseSymmetricOptimization(boolean useSymmetricOptimization) { this.useSymmetricOptimization = useSymmetricOptimization; } public boolean isUseDeltaDBForChanges() { return useDeltaDBForChanges; } public void setUseDeltaDBForChanges(boolean useDeltaDBForChanges) { this.useDeltaDBForChanges = useDeltaDBForChanges; } public Long getQueryExecutionTimeout() { return queryExecutionTimeout; } public void setQueryExecutionTimeout(Long queryExecutionTimeout) { this.queryExecutionTimeout = queryExecutionTimeout; } public String getSampleStrategyForStandardQueries() { return sampleStrategyForStandardQueries; } public void setSampleStrategyForStandardQueries(String sampleStrategyForStandardQueries) { this.sampleStrategyForStandardQueries = sampleStrategyForStandardQueries; } public String getSampleStrategyForSymmetricQueries() { return sampleStrategyForSymmetricQueries; } public void setSampleStrategyForSymmetricQueries(String sampleStrategyForSymmetricQueries) { this.sampleStrategyForSymmetricQueries = sampleStrategyForSymmetricQueries; } public String getSampleStrategyForInequalityQueries() { return sampleStrategyForInequalityQueries; } public void setSampleStrategyForInequalityQueries(String sampleStrategyForInequalityQueries) { this.sampleStrategyForInequalityQueries = sampleStrategyForInequalityQueries; } public boolean isCheckCleanInstance() { return checkCleanInstance; } public void setCheckCleanInstance(boolean checkCleanInstance) { this.checkCleanInstance = checkCleanInstance; } public boolean isAvoidInteractions() { return avoidInteractions; } public void setAvoidInteractions(boolean avoidInteractions) { this.avoidInteractions = avoidInteractions; } public boolean isPrintLog() { return printLog; } public void setPrintLog(boolean printLog) { this.printLog = printLog; } public boolean isApplyCellChanges() { return applyCellChanges; } public void setApplyCellChanges(boolean applyCellChanges) { this.applyCellChanges = applyCellChanges; } public boolean isExportCellChanges() { return exportCellChanges; } public void setExportCellChanges(boolean exportCellChanges) { this.exportCellChanges = exportCellChanges; } public String getExportCellChangesPath() { return exportCellChangesPath; } public void setExportCellChangesPath(String exportCellChangesPath) { this.exportCellChangesPath = exportCellChangesPath; } public boolean isExportDirtyDB() { return exportDirtyDB; } public void setExportDirtyDB(boolean exportDirtyDB) { this.exportDirtyDB = exportDirtyDB; } public String getExportDirtyDBType() { return exportDirtyDBType; } public void setExportDirtyDBType(String exportDirtyDBType) { this.exportDirtyDBType = exportDirtyDBType; } public String getExportDirtyDBPath() { return exportDirtyDBPath; } public void setExportDirtyDBPath(String exportDirtyDBPath) { this.exportDirtyDBPath = exportDirtyDBPath; } public VioGenQueryConfiguration getDefaultVioGenQueryConfiguration() { return defaultVioGenQueryConfiguration; } public boolean isGenerateAllChanges() { return generateAllChanges; } public void setGenerateAllChanges(boolean generateAllChanges) { this.generateAllChanges = generateAllChanges; } public double getSizeFactorReduction() { return sizeFactorReduction; } public void setSizeFactorReduction(double sizeFactorReduction) { this.sizeFactorReduction = sizeFactorReduction; } public void addVioGenQueryProbabilities(String vioGenKey, double percentage) { this.vioGenQueryProbabilities.put(vioGenKey, percentage); } public Map<String, Double> getVioGenQueryProbabilities() { return vioGenQueryProbabilities; } public void setVioGenQueryProbabilities(Map<String, Double> vioGenQueryProbabilities) { this.vioGenQueryProbabilities = vioGenQueryProbabilities; } public void addVioGenQueryStrategy(String vioGenKey, String strategy) { this.vioGenQueryStrategy.put(vioGenKey, strategy); } public Map<String, String> getVioGenQueryStrategy() { return vioGenQueryStrategy; } public boolean isEstimateRepairability() { return estimateRepairability; } public void setEstimateRepairability(boolean estimateRepairability) { this.estimateRepairability = estimateRepairability; } public boolean isDebug() { return debug; } public void setDebug(boolean debug) { this.debug = debug; } public boolean isCloneTargetSchema() { return cloneTargetSchema; } public void setCloneTargetSchema(boolean cloneTargetSchema) { this.cloneTargetSchema = cloneTargetSchema; } public String getCloneSuffix() { return cloneSuffix; } public void setCloneSuffix(String cloneSuffix) { this.cloneSuffix = cloneSuffix; } public boolean isExcludeCrossProducts() { return excludeCrossProducts; } public void setExcludeCrossProducts(boolean excludeCrossProducts) { this.excludeCrossProducts = excludeCrossProducts; } public boolean isDetectEntireEquivalenceClasses() { return detectEntireEquivalenceClasses; } public void setDetectEntireEquivalenceClasses(boolean detectEntireEquivalenceClasses) { this.detectEntireEquivalenceClasses = detectEntireEquivalenceClasses; } public boolean isCheckChanges() { return checkChanges; } public void setCheckChanges(boolean checkChanges) { this.checkChanges = checkChanges; } public boolean isRandomErrors() { return randomErrors; } public void setRandomErrors(boolean randomErrors) { this.randomErrors = randomErrors; } public Set<String> getTablesForRandomErrors() { return tablesForRandomErrors.keySet(); } public void addTableForRandomErrors(String tableName, Set<String> attributes) { this.tablesForRandomErrors.put(tableName, attributes); } public Set<String> getAttributesForRandomErrors(String tableName) { return tablesForRandomErrors.get(tableName); } public void addPercentageForRandomErrors(String tableName, int percentage) { this.tablesPercentageForRandomErrors.put(tableName, percentage); } public int getPercentageForRandomErrors(String tableName) { return tablesPercentageForRandomErrors.get(tableName); } public boolean isOutlierErrors() { return outlierErrors; } public void setOutlierErrors(boolean outlierErrors) { this.outlierErrors = outlierErrors; } public OutlierErrorConfiguration getOutlierErrorConfiguration() { return outlierErrorConfiguration; } public void setOutlierErrorConfiguration(OutlierErrorConfiguration outlierErrorConfiguration) { this.outlierErrorConfiguration = outlierErrorConfiguration; } public IDirtyStrategy getDefaultDirtyStrategy() { return defaultDirtyStrategy; } public void setDefaultDirtyStrategy(IDirtyStrategy defaultDirtyStrategy) { this.defaultDirtyStrategy = defaultDirtyStrategy; } public void addDirtyStrategyForAttribute(AttributeRef attribute, IDirtyStrategy dirtyStrategy) { this.dirtyStrategiesMap.put(attribute, dirtyStrategy); } public IDirtyStrategy getDirtyStrategy(AttributeRef attribute) { IDirtyStrategy dirtyStrategy = this.dirtyStrategiesMap.get(attribute); if (dirtyStrategy != null) return dirtyStrategy; return defaultDirtyStrategy; } // public Integer getMaxNumberOfInequalitiesInSymmetricQueries() { // return maxNumberOfInequalitiesInSymmetricQueries; // } // // public void setMaxNumberOfInequalitiesInSymmetricQueries(Integer maxNumberOfInequalitiesInSymmetricQueries) { // this.maxNumberOfInequalitiesInSymmetricQueries = maxNumberOfInequalitiesInSymmetricQueries; // } @Override public String toString() { return toShortString() + "\n" + defaultVioGenQueryConfiguration.toString(); } public Object toShortString() { String configuration = "Configuration:" + "\n\t printLog=" + printLog + "\n\t recreateDBOnStart=" + recreateDBOnStart + "\n\t useDeltaDBForChanges=" + useDeltaDBForChanges + "\n\t applyCellChanges=" + applyCellChanges + "\n\t cloneTargetSchema=" + cloneTargetSchema + "\n\t generateAllChanges=" + generateAllChanges + "\n\t avoidInteractions=" + avoidInteractions + "\n\t checkCleanInstance=" + checkCleanInstance + "\n\t excludeCrossProducts=" + excludeCrossProducts + "\n\t useSymmetricOptimization=" + useSymmetricOptimization + "\n\t sampleStrategyForStandardQueries=" + sampleStrategyForStandardQueries + "\n\t sampleStrategyForSymmetricQueries=" + sampleStrategyForSymmetricQueries + "\n\t sampleStrategyForInequalityQueries=" + sampleStrategyForInequalityQueries // + "\n\t maxNumberOfInequalitiesInSymmetricQueries=" + maxNumberOfInequalitiesInSymmetricQueries + "\n\t detectEntireEquivalenceClasses=" + detectEntireEquivalenceClasses + "\n\t defaultDirtyStrategy " + defaultDirtyStrategy + printDetailedDirtyAttributeStrategy() + "\n\t randomErrors=" + randomErrors + printDetailedRandomErrorsForTables() + "\n\t outlierErrors=" + outlierErrors + printDetaileOutlierErrors(); return configuration.trim(); } private String printDetailedRandomErrorsForTables() { StringBuilder sb = new StringBuilder(); if (randomErrors) { for (String table : getTablesForRandomErrors()) { sb.append("\n\t\t Table: ").append(table) .append("\n\t\t\t Random error(%)=").append(tablesPercentageForRandomErrors.get(table)) .append("\n\t\t\t Attributes to dirty=").append(tablesForRandomErrors.get(table)); } } return sb.toString(); } private String printDetailedDirtyAttributeStrategy() { StringBuilder sb = new StringBuilder(); for (AttributeRef attribute : dirtyStrategiesMap.keySet()) { sb.append("\n\t\t Attribute: ").append(attribute.getTableName()).append(".").append(attribute.getName()).append("=").append(dirtyStrategiesMap.get(attribute)); } return sb.toString(); } private String printDetaileOutlierErrors() { if (!outlierErrors) return ""; return "\n\t" + outlierErrorConfiguration.toString(); } }
Update EGTaskConfiguration.java
src/bart/model/EGTaskConfiguration.java
Update EGTaskConfiguration.java
Java
mit
06a9c5eec7d24372c8f0d4e070a94c53eea31556
0
ProfAmesBC/Game2013
package game; public class GameSounds { public static void footstepNoise() { System.out.println("Footstep"); } }
src/game/GameSounds.java
package game; public class GameSounds { public static void footstepNoise() { System.out.println("Footstep"); } }
Added Game Sounds
src/game/GameSounds.java
Added Game Sounds
Java
mit
5329246a3eecce1bcee62ff94f9d02f1ef9fc876
0
ZedTheYeti/SKS-Bot
/* Copyright (c) 2014-Onwards, Yeti Games * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name Yeti Games nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package yeti.bot; import yeti.bot.cmds.Command; import yeti.bot.gui.ChatFrame; import yeti.bot.gui.SendListener; import yeti.bot.gui.StartDialog; import yeti.bot.util.Logger; import yeti.bot.util.Options; import yeti.bot.util.Util; import yeti.irc.IRCServer; import yeti.irc.Parser; import javax.swing.*; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.Map.Entry; import java.util.Timer; import java.util.TimerTask; import static yeti.bot.Globals.*; public class JIRC { private static ChatFrame frame; private static Options save; private static boolean saved = false; private static boolean saving = false; public static void main(String args[]) { try { String logging = System.getProperty("logging", "none"); switch(logging.toLowerCase()) { case "error": Logger.setLevel(Logger.ERROR); break; case "debug": Logger.setLevel(Logger.DEBUG); break; case "all": Logger.setLevel(Logger.ALL); break; default: Logger.setLevel(Logger.NONE); break; } main(); } catch (Exception ex) { Logger.logError("An unhandled exception has occurred: " + ex.getMessage()); ex.printStackTrace(); if (save != null) saveAll(); } } public static void saveAll() { if (saving) return; saving = true; try { Files.copy(save.getFile().toPath(), new File(save.getPath() + ".bkp").toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (User usr : offlineUsers.values()) save.set(usr.name, usr.getInfo()); for (User usr : users.values()) save.set(usr.name, usr.getInfo()); save.save(); Logger.logDebug("Finished saving all users"); saving = false; } public static void sendMessage(String channel, String msg) { if (server != null) server.sendMessage(channel, msg); if (frame != null) frame.addText(username + ": " + msg + "\n"); } public static void main() { Util.setSystemLAF(); try { EventQueue.invokeAndWait(new Runnable() { @Override public void run() { try { frame = new ChatFrame(); frame.setVisible(true); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { Logger.logDebug("Saving on close."); saveAll(); } }); frame.setSendListener(new SendListener() { @Override public void send(String text) { if (text.startsWith("/") && !text.startsWith("/me")) server.processCmd(text.substring(1)); else sendMessage(Globals.channel, text); } }); } catch (Exception e) { e.printStackTrace(); } } }); } catch (Exception e1) { e1.printStackTrace(); } final Options options = new Options("sksbot/settings.opt"); frame.addText(options.getPath() + "\n"); options.load(); try { EventQueue.invokeAndWait(new Runnable() { @Override public void run() { try { StartDialog dialog = new StartDialog(frame, true, options); dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); dialog.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } username = options.get("username").toLowerCase(); String oauth = options.get("oauth"); serverName = options.get("server"); port = Integer.parseInt(options.get("port")); channel = options.get("channel").toLowerCase(); if (channel.charAt(0) != '#') channel = "#" + channel; server = new IRCServer(serverName, port); server.setNick(username); server.setIdent(username); server.setRealName(username); server.setServerPass(oauth); server.addMsgParser(new Parser() { @Override public void parse(String input) { if (input.startsWith("PING ")) server.sendLine("PONG " + input.substring(5)); else if (input.contains(":jtv PRIVMSG " + server.getNick() + " :SPECIALUSER")) { String[] args = input.substring(input.indexOf(':', 1) + 1).split(" "); if (args[0].equals("SPECIALUSER")) { User user = getOrCreateUser(args[1]); user.inChannel = true; user.isSub = true; } } else if (input.contains(":jtv MODE ")) { String[] parts = input.substring(input.indexOf("MODE") + "MODE ".length()).split(" "); if (parts[1].equalsIgnoreCase("+o")) { User sub = getOrCreateUser(parts[2]); sub.captain = true; Logger.logDebug(sub.name + " is a mod " + sub.captain); } else if (parts[1].equalsIgnoreCase("-o")) { User sub = users.get(parts[2]); if (sub != null) { sub.captain = false; Logger.logDebug(sub.name + " is no longer a mod " + sub.captain); } } } else if (input.contains(" PRIVMSG " + channel)) { String name = input.substring(1, input.indexOf("!")); String msg = input.substring(input.indexOf(':', 1) + 1); frame.addText(name + ": " + msg + "\n"); if (msg.length() == 0 || msg.charAt(0) != '!') return; User user = users.get(name); if (user != null && user.captain) if (msg.startsWith("!beta")) { sendMessage(channel, "/me The faction portion of this bot is still in a VERY early beta. So expect hiccups ;) Zedtheyeti is monitoring things and will do his best to fix any bugs that pop up. Most importantly just have fun and don't worry about it koolWALLY"); return; } boolean isSub = user != null && user.isSub; boolean isMod = user != null && user.captain; if (isMod) for (Command cmd : modCommands) if (cmd.check(name, msg.toLowerCase(), isSub)) { cmd.process(name, msg); return; } if (isSub || isMod) for (Command cmd : subCommands) if (cmd.check(name, msg.toLowerCase(), isSub)) { cmd.process(name, msg); return; } for (Command cmd : commands) if (cmd.check(name, msg.toLowerCase(), isSub)) { cmd.process(name, msg); break; } } else if (input.contains(" JOIN ")) { String name = input.substring(1, input.indexOf('!')); Logger.logDebug(name + " joined"); User user = getOrCreateUser(name); user.inChannel = true; long time = System.currentTimeMillis(); // No idea how this would happen, but oh well if (user.joinTime > time || user.joinTime == 0) user.joinTime = time; } else if (input.contains(" PART ")) { String name = input.substring(1, input.indexOf('!')); Logger.logDebug(name + " left"); User user = users.remove(name); if (user != null) { Logger.logDebug("Moving " + name + " from online users to offline users"); user.inChannel = false; offlineUsers.put(name, user); } } // 353 wallythewizard = #sourkoolaidshow : else if (input.contains("353 " + Globals.username + " = " + channel + " :")) { int index = input.indexOf(':', 1); String[] names = input.substring(index + 1).split(" "); for (String name : names) { User usr = getOrCreateUser(name); usr.inChannel = true; usr.joinTime = System.currentTimeMillis(); } } } }); server.addCmdParser(new Parser() { @Override public void parse(String line) { String[] parts = line.split(" "); if (parts.length >= 2 && parts[0].equalsIgnoreCase("join")) server.sendLine("JOIN " + parts[1]); else if (parts.length >= 2 && parts[0].equalsIgnoreCase("leave")) server.sendLine("PART " + parts[1]); else if (parts.length >= 2 && parts[0].equalsIgnoreCase("pm")) server.sendMessage(parts[1], parts[2]); else if (parts[0].equalsIgnoreCase("exit")) System.exit(0); else if (parts[0].equalsIgnoreCase("raw")) server.sendLine(line.substring(line.indexOf(' ') + 1)); } }); Logger.logDebug("Loading user info.."); save = new Options("sksbot/user.info"); save.load(); frame.addText(save.getPath() + "\n"); for (Entry<String, String> entry : save.getAllOptions()) { //Logger.logDebug(entry.getValue()); String name = entry.getKey().toLowerCase(); User sub = new User(name); String[] parts = entry.getValue().split(","); sub.faction = Faction.valueOf(parts[0]); sub.level = Integer.parseInt(parts[1]); sub.exp = Float.valueOf(parts[2]); if (parts.length > 3) sub.userClass = UserClass.valueOf(parts[3]); // sub.exp = 0f; offlineUsers.put(name, sub); } Logger.logDebug("Done."); Logger.logDebug("Connecting to " + server + ":" + port + "..."); server.connect(); server.joinChannel(channel); server.sendLine("TWITCHCLIENT 1"); sendMessage(channel, "/me has returned from the astral plane!"); Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { if (!trackXp) { if (!saved) saveAll(); saved = !saved; return; } if (!saved) for (User usr : offlineUsers.values()) save.set(usr.name, usr.getInfo()); long time = System.currentTimeMillis(); for (User sub : users.values()) { if (sub.joinTime == 0) { if (sub.inChannel) { Logger.logError("0 JOIN TIME " + sub.name); sub.joinTime = time; } else Logger.logError("NOT IN CHANNEL " + sub.name); continue; } long diff = time - sub.joinTime; if (diff >= XP_AWARD_TIME) { Logger.logDebug(sub.name + " joined at " + sub.joinTime + " the difference between then and now is " + diff + " award time is " + XP_AWARD_TIME); Logger.logDebug(sub.name + " is at " + sub.exp + "10xp"); Logger.logDebug("We are " + (diff - XP_AWARD_TIME) + " behind"); sub.exp += XP_AWARD_AMOUNT; sub.joinTime += XP_AWARD_TIME; } if (!saved) save.set(sub.name, sub.getInfo()); } if (xpTrackTime != 0) { if (time - xpStartTime >= xpTrackTime) { trackXp = false; JIRC.sendMessage(Globals.channel, "XP tracking has been turned off."); } } if (!saved) { Logger.logDebug("Saving..."); try { Files.copy(save.getFile().toPath(), new File(save.getPath() + ".bkp").toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { e.printStackTrace(); } save.save(); Logger.logDebug("Done."); } saved = !saved; } }; timer.scheduleAtFixedRate(task, 4 * 60 * 1000, 1 * 60 * 1000); } }
src/yeti/bot/JIRC.java
/* Copyright (c) 2014-Onwards, Yeti Games * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name Yeti Games nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package yeti.bot; import yeti.bot.cmds.Command; import yeti.bot.gui.ChatFrame; import yeti.bot.gui.SendListener; import yeti.bot.gui.StartDialog; import yeti.bot.util.Logger; import yeti.bot.util.Options; import yeti.bot.util.Util; import yeti.irc.IRCServer; import yeti.irc.Parser; import javax.swing.*; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.Map.Entry; import java.util.Timer; import java.util.TimerTask; import static yeti.bot.Globals.*; public class JIRC { private static ChatFrame frame; private static Options save; private static boolean saved = false; private static boolean saving = false; public static void main(String args[]) { try { String logging = System.getProperty("logging", "none"); if (logging.equalsIgnoreCase("none")) Logger.setLevel(Logger.NONE); else if (logging.equalsIgnoreCase("error")) Logger.setLevel(Logger.ERROR); else if (logging.equalsIgnoreCase("DEBUG")) Logger.setLevel(Logger.DEBUG); else if (logging.equalsIgnoreCase("ALL")) Logger.setLevel(Logger.ALL); main(); } catch (Exception ex) { Logger.logError("An unhandled exception has occurred: " + ex.getMessage()); ex.printStackTrace(); if (save != null) saveAll(); } } public static void saveAll() { if (saving) return; saving = true; try { Files.copy(save.getFile().toPath(), new File(save.getPath() + ".bkp").toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (User usr : offlineUsers.values()) save.set(usr.name, usr.getInfo()); for (User usr : users.values()) save.set(usr.name, usr.getInfo()); save.save(); Logger.logDebug("Finished saving all users"); saving = false; } public static void sendMessage(String channel, String msg) { if (server != null) server.sendMessage(channel, msg); if (frame != null) frame.addText(username + ": " + msg + "\n"); } public static void main() { Util.setSystemLAF(); try { EventQueue.invokeAndWait(new Runnable() { @Override public void run() { try { frame = new ChatFrame(); frame.setVisible(true); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { Logger.logDebug("Saving on close."); saveAll(); } }); frame.setSendListener(new SendListener() { @Override public void send(String text) { if (text.startsWith("/") && !text.startsWith("/me")) server.processCmd(text.substring(1)); else sendMessage(Globals.channel, text); } }); } catch (Exception e) { e.printStackTrace(); } } }); } catch (Exception e1) { e1.printStackTrace(); } final Options options = new Options("sksbot/settings.opt"); frame.addText(options.getPath() + "\n"); options.load(); try { EventQueue.invokeAndWait(new Runnable() { @Override public void run() { try { StartDialog dialog = new StartDialog(frame, true, options); dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); dialog.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } username = options.get("username").toLowerCase(); String oauth = options.get("oauth"); serverName = options.get("server"); port = Integer.parseInt(options.get("port")); channel = options.get("channel").toLowerCase(); if (channel.charAt(0) != '#') channel = "#" + channel; server = new IRCServer(serverName, port); server.setNick(username); server.setIdent(username); server.setRealName(username); server.setServerPass(oauth); server.addMsgParser(new Parser() { @Override public void parse(String input) { if (input.startsWith("PING ")) server.sendLine("PONG " + input.substring(5)); else if (input.contains(":jtv PRIVMSG " + server.getNick() + " :SPECIALUSER")) { String[] args = input.substring(input.indexOf(':', 1) + 1).split(" "); if (args[0].equals("SPECIALUSER")) { User user = getOrCreateUser(args[1]); user.inChannel = true; user.isSub = true; } } else if (input.contains(":jtv MODE ")) { String[] parts = input.substring(input.indexOf("MODE") + "MODE ".length()).split(" "); if (parts[1].equalsIgnoreCase("+o")) { User sub = getOrCreateUser(parts[2]); sub.captain = true; Logger.logDebug(sub.name + " is a mod " + sub.captain); } else if (parts[1].equalsIgnoreCase("-o")) { User sub = users.get(parts[2]); if (sub != null) { sub.captain = false; Logger.logDebug(sub.name + " is no longer a mod " + sub.captain); } } } else if (input.contains(" PRIVMSG " + channel)) { String name = input.substring(1, input.indexOf("!")); String msg = input.substring(input.indexOf(':', 1) + 1); frame.addText(name + ": " + msg + "\n"); if (msg.length() == 0 || msg.charAt(0) != '!') return; User user = users.get(name); if (user != null && user.captain) if (msg.startsWith("!beta")) { sendMessage(channel, "/me The faction portion of this bot is still in a VERY early beta. So expect hiccups ;) Zedtheyeti is monitoring things and will do his best to fix any bugs that pop up. Most importantly just have fun and don't worry about it koolWALLY"); return; } boolean isSub = user != null && user.isSub; boolean isMod = user != null && user.captain; if (isMod) for (Command cmd : modCommands) if (cmd.check(name, msg.toLowerCase(), isSub)) { cmd.process(name, msg); return; } if (isSub || isMod) for (Command cmd : subCommands) if (cmd.check(name, msg.toLowerCase(), isSub)) { cmd.process(name, msg); return; } for (Command cmd : commands) if (cmd.check(name, msg.toLowerCase(), isSub)) { cmd.process(name, msg); break; } } else if (input.contains(" JOIN ")) { String name = input.substring(1, input.indexOf('!')); Logger.logDebug(name + " joined"); User user = getOrCreateUser(name); user.inChannel = true; long time = System.currentTimeMillis(); // No idea how this would happen, but oh well if (user.joinTime > time || user.joinTime == 0) user.joinTime = time; } else if (input.contains(" PART ")) { String name = input.substring(1, input.indexOf('!')); Logger.logDebug(name + " left"); User user = users.remove(name); if (user != null) { Logger.logDebug("Moving " + name + " from online users to offline users"); user.inChannel = false; offlineUsers.put(name, user); } } // 353 wallythewizard = #sourkoolaidshow : else if (input.contains("353 " + Globals.username + " = " + channel + " :")) { int index = input.indexOf(':', 1); String[] names = input.substring(index + 1).split(" "); for (String name : names) { User usr = getOrCreateUser(name); usr.inChannel = true; usr.joinTime = System.currentTimeMillis(); } } } }); server.addCmdParser(new Parser() { @Override public void parse(String line) { String[] parts = line.split(" "); if (parts.length >= 2 && parts[0].equalsIgnoreCase("join")) server.sendLine("JOIN " + parts[1]); else if (parts.length >= 2 && parts[0].equalsIgnoreCase("leave")) server.sendLine("PART " + parts[1]); else if (parts.length >= 2 && parts[0].equalsIgnoreCase("pm")) server.sendMessage(parts[1], parts[2]); else if (parts[0].equalsIgnoreCase("exit")) System.exit(0); else if (parts[0].equalsIgnoreCase("raw")) server.sendLine(line.substring(line.indexOf(' ') + 1)); } }); Logger.logDebug("Loading user info.."); save = new Options("sksbot/user.info"); save.load(); frame.addText(save.getPath() + "\n"); for (Entry<String, String> entry : save.getAllOptions()) { //Logger.logDebug(entry.getValue()); String name = entry.getKey().toLowerCase(); User sub = new User(name); String[] parts = entry.getValue().split(","); sub.faction = Faction.valueOf(parts[0]); sub.level = Integer.parseInt(parts[1]); sub.exp = Float.valueOf(parts[2]); if (parts.length > 3) sub.userClass = UserClass.valueOf(parts[3]); // sub.exp = 0f; offlineUsers.put(name, sub); } Logger.logDebug("Done."); Logger.logDebug("Connecting to " + server + ":" + port + "..."); server.connect(); server.joinChannel(channel); server.sendLine("TWITCHCLIENT 1"); sendMessage(channel, "/me has returned from the astral plane!"); Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { if (!trackXp) { if (!saved) saveAll(); saved = !saved; return; } if (!saved) for (User usr : offlineUsers.values()) save.set(usr.name, usr.getInfo()); long time = System.currentTimeMillis(); for (User sub : users.values()) { if (sub.joinTime == 0) { if (sub.inChannel) { Logger.logError("0 JOIN TIME " + sub.name); sub.joinTime = time; } else Logger.logError("NOT IN CHANNEL " + sub.name); continue; } long diff = time - sub.joinTime; if (diff >= XP_AWARD_TIME) { Logger.logDebug(sub.name + " joined at " + sub.joinTime + " the difference between then and now is " + diff + " award time is " + XP_AWARD_TIME); Logger.logDebug(sub.name + " is at " + sub.exp + "10xp"); Logger.logDebug("We are " + (diff - XP_AWARD_TIME) + " behind"); sub.exp += XP_AWARD_AMOUNT; sub.joinTime += XP_AWARD_TIME; } if (!saved) save.set(sub.name, sub.getInfo()); } if (xpTrackTime != 0) { if (time - xpStartTime >= xpTrackTime) { trackXp = false; JIRC.sendMessage(Globals.channel, "XP tracking has been turned off."); } } if (!saved) { Logger.logDebug("Saving..."); try { Files.copy(save.getFile().toPath(), new File(save.getPath() + ".bkp").toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { e.printStackTrace(); } save.save(); Logger.logDebug("Done."); } saved = !saved; } }; timer.scheduleAtFixedRate(task, 4 * 60 * 1000, 1 * 60 * 1000); } }
* Switched to Java 8 String case() for setting debugging level
src/yeti/bot/JIRC.java
* Switched to Java 8 String case() for setting debugging level
Java
mit
828a6a99097fca8e3473d4692a36fa238023fb4c
0
JCloudYu/CordovaEnableViewportScaleSupport
/* The MIT License (MIT) Copyright (c) 2014 J. Cloud Yu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.purimize.cordova.viewportfix; import android.webkit.WebView; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaArgs; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; public class EnableViewportScaleFix extends CordovaPlugin { /* Set the referenced webview content */ @Override public void initialize(final CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); WebView view = (WebView)webView.getView(); view.getSettings().setUseWideViewPort( this.preferences.getBoolean("EnableViewportScale", false) ); view.getSettings().setLoadWithOverviewMode( this.preferences.getBoolean("LoadWithOverviewMode", false) ); } /* Do nothing... */ @Override public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) { return false; } }
src/android/EnableViewportScaleFix.java
/* The MIT License (MIT) Copyright (c) 2014 J. Cloud Yu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.purimize.cordova.viewportfix; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaArgs; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; public class EnableViewportScaleFix extends CordovaPlugin { /* Set the referenced webview content */ @Override public void initialize(final CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); WebView view = (WebView)webView.getView(); view.getSettings().setUseWideViewPort( this.preferences.getBoolean("EnableViewportScale", false) ); view.getSettings().setLoadWithOverviewMode( this.preferences.getBoolean("LoadWithOverviewMode", false) ); } /* Do nothing... */ @Override public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) { return false; } }
Add missing package inclusion statement
src/android/EnableViewportScaleFix.java
Add missing package inclusion statement
Java
mit
3ce3eccda27592bd0693e9b142931a212885f26a
0
openregister/register,openregister/register,openregister/register
package functional.yaml; import functional.ApplicationTests; import org.junit.Test; import play.libs.ws.WSResponse; import static org.fest.assertions.Assertions.assertThat; import static play.mvc.Http.Status.OK; public class YamlSanityTest extends ApplicationTests { public static final String TEST_JSON = "{\"test-register\":\"testregisterkey\",\"name\":\"The Entry\",\"key1\": \"value1\",\"key2\": [\"A\",\"B\"]}"; public static final String EXPECTED_HASH = "4686f89b9c983f331c7deef476fda719148de4fb"; public static final String EXPECTED_YAML = "---\n" + "hash: \"4686f89b9c983f331c7deef476fda719148de4fb\"\n" + "entry:\n" + " key1: \"value1\"\n" + " key2:\n" + " - \"A\"\n" + " - \"B\"\n" + " name: \"The Entry\"\n" + " test-register: \"testregisterkey\"\n"; @Test public void testFindOneByKey() throws Exception { postJson("/create", TEST_JSON); WSResponse response = getByKV("key1", "value1", "yaml"); assertThat(response.getStatus()).isEqualTo(OK); assertThat(response.getHeader("Content-type")).isEqualTo("text/yaml; charset=utf-8"); assertThat(response.getBody()).isEqualTo(EXPECTED_YAML); } @Test public void testFindOneByHash() throws Exception { postJson("/create", TEST_JSON); WSResponse response = getByHash(EXPECTED_HASH, "yaml"); assertThat(response.getStatus()).isEqualTo(OK); assertThat(response.getHeader("Content-type")).isEqualTo("text/yaml; charset=utf-8"); assertThat(response.getBody()).isEqualTo(EXPECTED_YAML); } @Test public void test404ErrorResponse() throws Exception { WSResponse response = get("/idonotexist?_representation=yaml"); assertThat(response.getStatus()).isEqualTo(404); assertThat(response.getBody()).isEqualTo( "---\n" + "message: \"Page not found\"\n" + "errors: []\n" + "status: 404\n"); } }
test/functional/yaml/YamlSanityTest.java
package functional.yaml; import functional.ApplicationTests; import org.junit.Test; import play.libs.ws.WSResponse; import static org.fest.assertions.Assertions.assertThat; import static play.mvc.Http.Status.OK; public class YamlSanityTest extends ApplicationTests { public static final String TEST_JSON = "{\"test-register\":\"testregisterkey\",\"name\":\"The Entry\",\"key1\": \"value1\",\"key2\": [\"A\",\"B\"]}"; public static final String EXPECTED_HASH = "4686f89b9c983f331c7deef476fda719148de4fb"; public static final String EXPECTED_YAML = "---\n" + "hash: \"4686f89b9c983f331c7deef476fda719148de4fb\"\n" + "entry:\n" + " key1: \"value1\"\n" + " key2:\n" + " - \"A\"\n" + " - \"B\"\n" + " name: \"The Entry\"\n" + " test-register: \"testregisterkey\"\n"; @Test public void testFindOneByKey() throws Exception { postJson("/create", TEST_JSON); WSResponse response = getByKV("key1", "value1", "yaml"); assertThat(response.getStatus()).isEqualTo(OK); assertThat(response.getBody()).isEqualTo(EXPECTED_YAML); } @Test public void testFindOneByHash() throws Exception { postJson("/create", TEST_JSON); WSResponse response = getByHash(EXPECTED_HASH, "yaml"); assertThat(response.getStatus()).isEqualTo(OK); assertThat(response.getBody()).isEqualTo(EXPECTED_YAML); } @Test public void test404ErrorResponse() throws Exception { WSResponse response = get("/idonotexist?_representation=yaml"); assertThat(response.getStatus()).isEqualTo(404); assertThat(response.getBody()).isEqualTo( "---\n" + "message: \"Page not found\"\n" + "errors: []\n" + "status: 404\n"); } }
test yaml content-types
test/functional/yaml/YamlSanityTest.java
test yaml content-types
Java
mit
5404e8c24784f4603be30ba8588422b30a76895b
0
simonpoole1/metrical
package restlessrobot.metrical; import org.junit.Before; import org.junit.Test; import restlessrobot.metrical.handlers.TextCaptureMetricalHandler; import static org.junit.Assert.assertEquals; import static restlessrobot.metrical.Metrical.d; import static restlessrobot.metrical.Metrical.m; import static restlessrobot.metrical.Metrical.c; /** * Created by simon on 09/06/14. */ public class MetricalIntegTest { public static final long MOCK_TIME = 1_400_000_000_000L; private final TextCaptureMetricalHandler handler = new TextCaptureMetricalHandler(); private final Metrical a = new Metrical(handler); @Before public void setUp() throws Exception { MetricalEvent.setTimeProvider(buildTimeProvider(MOCK_TIME)); } private TimeProvider buildTimeProvider(final long mockTime) { return new TimeProvider() { @Override public long currentTimeMillis() { return mockTime; } }; } @Test public void testSimpleEvent() { a.event("my-event"); assertEquals("@v:restlessrobot.metrical:1\n" + "@e:1400000000000:my-event:\n", handler.get()); } @Test public void testSimpleIntegerEvent() { a.event("my-event", m("my-metric", 10, Unit.MILLISECONDS)); assertEquals("@v:restlessrobot.metrical:1\n" + "@e:1400000000000:my-event:\n" + "@m:1400000000000:my-event:my-metric:10:ms:\n", handler.get()); } @Test public void testSimpleFloatEvent() { a.event("my-event", m("my-metric", 3.51471f, Unit.PERCENT)); assertEquals("@v:restlessrobot.metrical:1\n" + "@e:1400000000000:my-event:\n" + "@m:1400000000000:my-event:my-metric:3.515:%:\n", handler.get()); } @Test public void testMultiMetricEvent() { a.event("my-event", m("metric1", 10, Unit.MILLISECONDS), m("metric2", 3.5f, Unit.PERCENT)); assertEquals("@v:restlessrobot.metrical:1\n" + "@e:1400000000000:my-event:\n" + "@m:1400000000000:my-event:metric1:10:ms:\n" + "@m:1400000000000:my-event:metric2:3.500:%:\n", handler.get()); } @Test public void testSingleContextNoDimensions() { MetricalContext platformContext = c("platform", true); a.addContexts(platformContext); a.event("my-event", m("metric1", 10, Unit.MILLISECONDS)); assertEquals("@v:restlessrobot.metrical:1\n" + "@c:platform:g\n" + "@e:1400000000000:my-event:platform\n" + "@m:1400000000000:my-event:metric1:10:ms:platform\n", handler.get()); } @Test public void testSingleContextStringDimension() { MetricalContext platformContext = c("platform", true, d("screen-size", "1024x768")); a.addContexts(platformContext); a.event("my-event", m("metric1", 10, Unit.MILLISECONDS)); assertEquals("@v:restlessrobot.metrical:1\n" + "@c:platform:g\n" + "@d:platform:screen-size:1024x768:\n" + "@e:1400000000000:my-event:platform\n" + "@m:1400000000000:my-event:metric1:10:ms:platform\n", handler.get()); } @Test public void testSingleContextIntDimension() { MetricalContext platformContext = c("platform", true, d("ram", 4, Unit.GIGABYTES)); a.addContexts(platformContext); a.event("my-event", m("metric1", 10, Unit.MILLISECONDS)); assertEquals("@v:restlessrobot.metrical:1\n" + "@c:platform:g\n" + "@d:platform:ram:4:GB\n" + "@e:1400000000000:my-event:platform\n" + "@m:1400000000000:my-event:metric1:10:ms:platform\n", handler.get()); } @Test public void testSingleContextFloatDimension() { MetricalContext platformContext = c("platform", true, d("ram", 2.4f, Unit.GIGABYTES)); a.addContexts(platformContext); a.event("my-event", m("metric1", 10, Unit.MILLISECONDS)); assertEquals("@v:restlessrobot.metrical:1\n" + "@c:platform:g\n" + "@d:platform:ram:2.400:GB\n" + "@e:1400000000000:my-event:platform\n" + "@m:1400000000000:my-event:metric1:10:ms:platform\n", handler.get()); } @Test public void testSingleContextWithManyDimensions() { MetricalContext platformContext = c("platform", true, d("screen-size", "1024x768"), d("ram", 1, Unit.GIGABYTES), d("os", "Android"), d("os-version", "4.4.3"), d("my-float", 98.2567f, Unit.NONE)); a.addContexts(platformContext); a.event("my-event", m("metric1", 10, Unit.MILLISECONDS)); assertEquals("@v:restlessrobot.metrical:1\n" + "@c:platform:g\n" + "@d:platform:screen-size:1024x768:\n" + "@d:platform:ram:1:GB\n" + "@d:platform:os:Android:\n" + "@d:platform:os-version:4.4.3:\n" + "@d:platform:my-float:98.26:\n" + "@e:1400000000000:my-event:platform\n" + "@m:1400000000000:my-event:metric1:10:ms:platform\n", handler.get()); } @Test public void testMultipleContexts() { MetricalContext platformContext = c("platform", true, d("screen-size", "1024x768"), d("ram", 1, Unit.GIGABYTES)); MetricalContext requestContext = c("request", false, d("operation", "get"), d("type", "my-type")); a.addContexts(platformContext, requestContext); a.event("my-event", m("metric1", 10, Unit.MILLISECONDS)); assertEquals("@v:restlessrobot.metrical:1\n" + "@c:platform:g\n" + "@d:platform:screen-size:1024x768:\n" + "@d:platform:ram:1:GB\n" + "@c:request:\n" + "@d:request:operation:get:\n" + "@d:request:type:my-type:\n" + "@e:1400000000000:my-event:platform,request\n" + "@m:1400000000000:my-event:metric1:10:ms:platform,request\n", handler.get()); } @Test public void testWithContextsNoOuterContext() { MetricalContext requestContext = c("request", false, d("operation", "get"), d("type", "my-type")); Metrical a2 = a.withContexts(requestContext); a2.event("event1", m("metric1", 10, Unit.MILLISECONDS)); a.event("event2", m("metric2", 1, Unit.PERCENT)); assertEquals("@v:restlessrobot.metrical:1\n" + "@c:request:\n" + "@d:request:operation:get:\n" + "@d:request:type:my-type:\n" + "@e:1400000000000:event1:request\n" + "@m:1400000000000:event1:metric1:10:ms:request\n" + "@e:1400000000000:event2:\n" + "@m:1400000000000:event2:metric2:1:%:\n", handler.get()); } @Test public void testWithContextsWithOuterContext() { MetricalContext platformContext = c("platform", true, d("screen-size", "1024x768"), d("ram", 1, Unit.GIGABYTES)); a.addContexts(platformContext); a.event("event1", m("metric1", 1, Unit.PERCENT)); MetricalContext requestContext = c("request", false, d("operation", "get"), d("type", "my-type")); Metrical a2 = a.withContexts(requestContext); a2.event("event2", m("metric2", 10, Unit.MILLISECONDS)); a.event("event3", m("metric3", 1, Unit.PERCENT)); assertEquals("@v:restlessrobot.metrical:1\n" + "@c:platform:g\n" + "@d:platform:screen-size:1024x768:\n" + "@d:platform:ram:1:GB\n" + "@e:1400000000000:event1:platform\n" + "@m:1400000000000:event1:metric1:1:%:platform\n" + "@c:request:\n" + "@d:request:operation:get:\n" + "@d:request:type:my-type:\n" + "@e:1400000000000:event2:platform,request\n" + "@m:1400000000000:event2:metric2:10:ms:platform,request\n" + "@e:1400000000000:event3:platform\n" + "@m:1400000000000:event3:metric3:1:%:platform\n", handler.get()); } @Test public void testWithContextsAndLogRotation() { TimeProvider timeProvider = buildTimeProvider(MOCK_TIME); MetricalEvent.setTimeProvider(timeProvider); handler.setTimeProvider(timeProvider); MetricalContext platformContext = c("platform", true, d("screen-size", "1024x768"), d("ram", 1, Unit.GIGABYTES)); a.addContexts(platformContext); a.event("event1", m("metric1", 1, Unit.PERCENT)); timeProvider = buildTimeProvider(MOCK_TIME + 1_000); MetricalEvent.setTimeProvider(timeProvider); handler.setTimeProvider(timeProvider); a.event("event1", m("metric1", 5, Unit.PERCENT)); timeProvider = buildTimeProvider(MOCK_TIME + 600_000); MetricalEvent.setTimeProvider(timeProvider); handler.setTimeProvider(timeProvider); a.event("event1", m("metric1", 2, Unit.PERCENT)); assertEquals( "@v:restlessrobot.metrical:1\n" + "@c:platform:g\n" + "@d:platform:screen-size:1024x768:\n" + "@d:platform:ram:1:GB\n" + "@e:1400000000000:event1:platform\n" + "@m:1400000000000:event1:metric1:1:%:platform\n" + "@e:1400000001000:event1:platform\n" + "@m:1400000001000:event1:metric1:5:%:platform\n" + "@v:restlessrobot.metrical:1\n" + "@c:platform:g\n" + "@d:platform:screen-size:1024x768:\n" + "@d:platform:ram:1:GB\n" + "@e:1400000600000:event1:platform\n" + "@m:1400000600000:event1:metric1:2:%:platform\n", handler.get()); } }
src/test/java/restlessrobot/metrical/MetricalIntegTest.java
package restlessrobot.metrical; import org.junit.Before; import org.junit.Test; import restlessrobot.metrical.handlers.TextCaptureMetricalHandler; import static org.junit.Assert.assertEquals; import static restlessrobot.metrical.Metrical.d; import static restlessrobot.metrical.Metrical.m; import static restlessrobot.metrical.Metrical.c; /** * Created by simon on 09/06/14. */ public class MetricalIntegTest { public static final long MOCK_TIME = 1_400_000_000_000L; private final TextCaptureMetricalHandler handler = new TextCaptureMetricalHandler(); private final Metrical a = new Metrical(handler); @Before public void setUp() throws Exception { MetricalEvent.setTimeProvider(buildTimeProvider(MOCK_TIME)); } private TimeProvider buildTimeProvider(final long mockTime) { return new TimeProvider() { @Override public long currentTimeMillis() { return mockTime; } }; } @Test public void testSimpleIntegerEvent() { a.event("my-event", m("my-metric", 10, Unit.MILLISECONDS)); assertEquals("@v:restlessrobot.metrical:1\n" + "@e:1400000000000:my-event:\n" + "@m:1400000000000:my-event:my-metric:10:ms:\n", handler.get()); } @Test public void testSimpleFloatEvent() { a.event("my-event", m("my-metric", 3.51471f, Unit.PERCENT)); assertEquals("@v:restlessrobot.metrical:1\n" + "@e:1400000000000:my-event:\n" + "@m:1400000000000:my-event:my-metric:3.515:%:\n", handler.get()); } @Test public void testMultiMetricEvent() { a.event("my-event", m("metric1", 10, Unit.MILLISECONDS), m("metric2", 3.5f, Unit.PERCENT)); assertEquals("@v:restlessrobot.metrical:1\n" + "@e:1400000000000:my-event:\n" + "@m:1400000000000:my-event:metric1:10:ms:\n" + "@m:1400000000000:my-event:metric2:3.500:%:\n", handler.get()); } @Test public void testSingleContextNoDimensions() { MetricalContext platformContext = c("platform", true); a.addContexts(platformContext); a.event("my-event", m("metric1", 10, Unit.MILLISECONDS)); assertEquals("@v:restlessrobot.metrical:1\n" + "@c:platform:g\n" + "@e:1400000000000:my-event:platform\n" + "@m:1400000000000:my-event:metric1:10:ms:platform\n", handler.get()); } @Test public void testSingleContextStringDimension() { MetricalContext platformContext = c("platform", true, d("screen-size", "1024x768")); a.addContexts(platformContext); a.event("my-event", m("metric1", 10, Unit.MILLISECONDS)); assertEquals("@v:restlessrobot.metrical:1\n" + "@c:platform:g\n" + "@d:platform:screen-size:1024x768:\n" + "@e:1400000000000:my-event:platform\n" + "@m:1400000000000:my-event:metric1:10:ms:platform\n", handler.get()); } @Test public void testSingleContextIntDimension() { MetricalContext platformContext = c("platform", true, d("ram", 4, Unit.GIGABYTES)); a.addContexts(platformContext); a.event("my-event", m("metric1", 10, Unit.MILLISECONDS)); assertEquals("@v:restlessrobot.metrical:1\n" + "@c:platform:g\n" + "@d:platform:ram:4:GB\n" + "@e:1400000000000:my-event:platform\n" + "@m:1400000000000:my-event:metric1:10:ms:platform\n", handler.get()); } @Test public void testSingleContextFloatDimension() { MetricalContext platformContext = c("platform", true, d("ram", 2.4f, Unit.GIGABYTES)); a.addContexts(platformContext); a.event("my-event", m("metric1", 10, Unit.MILLISECONDS)); assertEquals("@v:restlessrobot.metrical:1\n" + "@c:platform:g\n" + "@d:platform:ram:2.400:GB\n" + "@e:1400000000000:my-event:platform\n" + "@m:1400000000000:my-event:metric1:10:ms:platform\n", handler.get()); } @Test public void testSingleContextWithManyDimensions() { MetricalContext platformContext = c("platform", true, d("screen-size", "1024x768"), d("ram", 1, Unit.GIGABYTES), d("os", "Android"), d("os-version", "4.4.3"), d("my-float", 98.2567f, Unit.NONE)); a.addContexts(platformContext); a.event("my-event", m("metric1", 10, Unit.MILLISECONDS)); assertEquals("@v:restlessrobot.metrical:1\n" + "@c:platform:g\n" + "@d:platform:screen-size:1024x768:\n" + "@d:platform:ram:1:GB\n" + "@d:platform:os:Android:\n" + "@d:platform:os-version:4.4.3:\n" + "@d:platform:my-float:98.26:\n" + "@e:1400000000000:my-event:platform\n" + "@m:1400000000000:my-event:metric1:10:ms:platform\n", handler.get()); } @Test public void testMultipleContexts() { MetricalContext platformContext = c("platform", true, d("screen-size", "1024x768"), d("ram", 1, Unit.GIGABYTES)); MetricalContext requestContext = c("request", false, d("operation", "get"), d("type", "my-type")); a.addContexts(platformContext, requestContext); a.event("my-event", m("metric1", 10, Unit.MILLISECONDS)); assertEquals("@v:restlessrobot.metrical:1\n" + "@c:platform:g\n" + "@d:platform:screen-size:1024x768:\n" + "@d:platform:ram:1:GB\n" + "@c:request:\n" + "@d:request:operation:get:\n" + "@d:request:type:my-type:\n" + "@e:1400000000000:my-event:platform,request\n" + "@m:1400000000000:my-event:metric1:10:ms:platform,request\n", handler.get()); } @Test public void testWithContextsNoOuterContext() { MetricalContext requestContext = c("request", false, d("operation", "get"), d("type", "my-type")); Metrical a2 = a.withContexts(requestContext); a2.event("event1", m("metric1", 10, Unit.MILLISECONDS)); a.event("event2", m("metric2", 1, Unit.PERCENT)); assertEquals("@v:restlessrobot.metrical:1\n" + "@c:request:\n" + "@d:request:operation:get:\n" + "@d:request:type:my-type:\n" + "@e:1400000000000:event1:request\n" + "@m:1400000000000:event1:metric1:10:ms:request\n" + "@e:1400000000000:event2:\n" + "@m:1400000000000:event2:metric2:1:%:\n", handler.get()); } @Test public void testWithContextsWithOuterContext() { MetricalContext platformContext = c("platform", true, d("screen-size", "1024x768"), d("ram", 1, Unit.GIGABYTES)); a.addContexts(platformContext); a.event("event1", m("metric1", 1, Unit.PERCENT)); MetricalContext requestContext = c("request", false, d("operation", "get"), d("type", "my-type")); Metrical a2 = a.withContexts(requestContext); a2.event("event2", m("metric2", 10, Unit.MILLISECONDS)); a.event("event3", m("metric3", 1, Unit.PERCENT)); assertEquals("@v:restlessrobot.metrical:1\n" + "@c:platform:g\n" + "@d:platform:screen-size:1024x768:\n" + "@d:platform:ram:1:GB\n" + "@e:1400000000000:event1:platform\n" + "@m:1400000000000:event1:metric1:1:%:platform\n" + "@c:request:\n" + "@d:request:operation:get:\n" + "@d:request:type:my-type:\n" + "@e:1400000000000:event2:platform,request\n" + "@m:1400000000000:event2:metric2:10:ms:platform,request\n" + "@e:1400000000000:event3:platform\n" + "@m:1400000000000:event3:metric3:1:%:platform\n", handler.get()); } @Test public void testWithContextsAndLogRotation() { TimeProvider timeProvider = buildTimeProvider(MOCK_TIME); MetricalEvent.setTimeProvider(timeProvider); handler.setTimeProvider(timeProvider); MetricalContext platformContext = c("platform", true, d("screen-size", "1024x768"), d("ram", 1, Unit.GIGABYTES)); a.addContexts(platformContext); a.event("event1", m("metric1", 1, Unit.PERCENT)); timeProvider = buildTimeProvider(MOCK_TIME + 1_000); MetricalEvent.setTimeProvider(timeProvider); handler.setTimeProvider(timeProvider); a.event("event1", m("metric1", 5, Unit.PERCENT)); timeProvider = buildTimeProvider(MOCK_TIME + 600_000); MetricalEvent.setTimeProvider(timeProvider); handler.setTimeProvider(timeProvider); a.event("event1", m("metric1", 2, Unit.PERCENT)); assertEquals( "@v:restlessrobot.metrical:1\n" + "@c:platform:g\n" + "@d:platform:screen-size:1024x768:\n" + "@d:platform:ram:1:GB\n" + "@e:1400000000000:event1:platform\n" + "@m:1400000000000:event1:metric1:1:%:platform\n" + "@e:1400000001000:event1:platform\n" + "@m:1400000001000:event1:metric1:5:%:platform\n" + "@v:restlessrobot.metrical:1\n" + "@c:platform:g\n" + "@d:platform:screen-size:1024x768:\n" + "@d:platform:ram:1:GB\n" + "@e:1400000600000:event1:platform\n" + "@m:1400000600000:event1:metric1:2:%:platform\n", handler.get()); } }
Add test case
src/test/java/restlessrobot/metrical/MetricalIntegTest.java
Add test case
Java
mit
b80a1721550dd04c1f4c2078a49664058623c2af
0
conveyal/r5,conveyal/r5,conveyal/r5,conveyal/r5,conveyal/r5
package com.conveyal.file; import com.conveyal.r5.analyst.PersistenceBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.file.FileSystemException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.PosixFilePermission; import java.util.Set; /** * This implementation of FileStorage stores files in a local directory hierarchy and does not mirror anything to * cloud storage. */ public class LocalFileStorage implements FileStorage { private static final Logger LOG = LoggerFactory.getLogger(LocalFileStorage.class); public interface Config { // The local directory where files will be stored, even if they are being mirrored to a remote storage service. String localCacheDirectory (); // The port where the browser can fetch files. Parameter name aligned with the HttpApi server port parameter. int serverPort (); } public final String directory; private final String urlPrefix; public LocalFileStorage (Config config) { this.directory = config.localCacheDirectory(); this.urlPrefix = String.format("http://localhost:%s/files", config.serverPort()); new File(directory).mkdirs(); } /** * Move the File into the FileStorage by moving the passed in file to the Path represented by the FileStorageKey. */ @Override public void moveIntoStorage(FileStorageKey key, File file) { // Get a pointer to the local file File storedFile = getFile(key); // Ensure the directories exist storedFile.getParentFile().mkdirs(); try { try { // Move the temporary file to the permanent file location. Files.move(file.toPath(), storedFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (FileSystemException e) { // The default Windows filesystem (NTFS) does not unlock memory-mapped files, so certain files (e.g. // mapdb) cannot be moved or deleted. This workaround may cause temporary files to accumulate, but it // should not be triggered for default Linux filesystems (ext). // See https://github.com/jankotek/MapDB/issues/326 Files.copy(file.toPath(), storedFile.toPath(), StandardCopyOption.REPLACE_EXISTING); LOG.info("Could not move {} because of FileSystem restrictions (probably NTFS). Copying instead.", file.getName()); } // Set the file to be read-only and accessible only by the current user. Files.setPosixFilePermissions(file.toPath(), Set.of(PosixFilePermission.OWNER_READ)); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void moveIntoStorage (FileStorageKey fileStorageKey, PersistenceBuffer persistenceBuffer) { throw new UnsupportedOperationException("In-memory buffers are only persisted to cloud storage."); } @Override public File getFile(FileStorageKey key) { return new File(String.join("/", directory, key.category.directoryName(), key.path)); } /** * Return a URL for the file as accessed through the backend's own static file server. * (Registered in HttpApi at .get("/files/:category/*")) * This exists to allow the same UI to work locally and in cloud deployments. */ @Override public String getURL (FileStorageKey key) { return String.join("/", urlPrefix, key.category.directoryName(), key.path); } @Override public void delete (FileStorageKey key) { getFile(key).delete(); } @Override public boolean exists(FileStorageKey key) { return getFile(key).exists(); } }
src/main/java/com/conveyal/file/LocalFileStorage.java
package com.conveyal.file; import com.conveyal.r5.analyst.PersistenceBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.file.FileSystemException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; /** * This implementation of FileStorage stores files in a local directory hierarchy and does not mirror anything to * cloud storage. */ public class LocalFileStorage implements FileStorage { private static final Logger LOG = LoggerFactory.getLogger(LocalFileStorage.class); public interface Config { // The local directory where files will be stored, even if they are being mirrored to a remote storage service. String localCacheDirectory (); // The port where the browser can fetch files. Parameter name aligned with the HttpApi server port parameter. int serverPort (); } public final String directory; private final String urlPrefix; public LocalFileStorage (Config config) { this.directory = config.localCacheDirectory(); this.urlPrefix = String.format("http://localhost:%s/files", config.serverPort()); new File(directory).mkdirs(); } /** * Move the File into the FileStorage by moving the passed in file to the Path represented by the FileStorageKey. */ @Override public void moveIntoStorage(FileStorageKey key, File file) { // Get a pointer to the local file File storedFile = getFile(key); // Ensure the directories exist storedFile.getParentFile().mkdirs(); try { try { // Move the temporary file to the permanent file location. Files.move(file.toPath(), storedFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (FileSystemException e) { // The default Windows filesystem (NTFS) does not unlock memory-mapped files, so certain files (e.g. // mapdb) cannot be moved or deleted. This workaround may cause temporary files to accumulate, but it // should not be triggered for default Linux filesystems (ext). // See https://github.com/jankotek/MapDB/issues/326 Files.copy(file.toPath(), storedFile.toPath(), StandardCopyOption.REPLACE_EXISTING); LOG.info("Could not move {} because of FileSystem restrictions (probably NTFS). Copying instead.", file.getName()); } } catch (IOException e) { throw new RuntimeException(e); } } @Override public void moveIntoStorage (FileStorageKey fileStorageKey, PersistenceBuffer persistenceBuffer) { throw new UnsupportedOperationException("In-memory buffers are only persisted to cloud storage."); } @Override public File getFile(FileStorageKey key) { return new File(String.join("/", directory, key.category.directoryName(), key.path)); } /** * Return a URL for the file as accessed through the backend's own static file server. * (Registered in HttpApi at .get("/files/:category/*")) * This exists to allow the same UI to work locally and in cloud deployments. */ @Override public String getURL (FileStorageKey key) { return String.join("/", urlPrefix, key.category.directoryName(), key.path); } @Override public void delete (FileStorageKey key) { getFile(key).delete(); } @Override public boolean exists(FileStorageKey key) { return getFile(key).exists(); } }
set stored file permissions to read only by user
src/main/java/com/conveyal/file/LocalFileStorage.java
set stored file permissions to read only by user
Java
mit
7b4b2c8133418ad8c5d6510b56155b22c155688d
0
sewerk/Bill-Calculator,sewerk/Bill-Calculator
package pl.srw.billcalculator.util; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.os.Build; import android.support.annotation.NonNull; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.view.View; import android.view.animation.AccelerateDecelerateInterpolator; public final class Animations { private static final long DURATION_LONG = 1000; private static final long DURATION_SHORT = 200; private static final float ROTATION_TO_ANGLE = 135f; private static final AccelerateDecelerateInterpolator INTERPOLATOR = new AccelerateDecelerateInterpolator(); private static final ObjectAnimator SHAKE = ObjectAnimator .ofFloat(null, "translationX", 0, 25, -25, 25, -25, 15, -15, 6, -6, 0) .setDuration(DURATION_LONG); private Animations() { } public static void shake(View target) { SHAKE.setTarget(target); SHAKE.start(); } public static AnimatorSet getExpandFabs(final FloatingActionButton baseFab, final FloatingActionButton... fabs) { final ValueAnimator fabRotation = rotationAnimator(baseFab, 0f, ROTATION_TO_ANGLE); final ValueAnimator translationY = translationYAnimator(fabs, true, getShift(baseFab, fabs.length)); final ValueAnimator alpha = alphaAnimator(0f, 1f, fabs); AnimatorSet animatorSet = new AnimatorSet(); animatorSet.playTogether(fabRotation, translationY, alpha); animatorSet.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { for (FloatingActionButton fab : fabs) { fab.setLayerType(View.LAYER_TYPE_HARDWARE, null); fab.setVisibility(View.VISIBLE); } } @Override public void onAnimationEnd(Animator animation) { for (FloatingActionButton fab : fabs) { fab.setLayerType(View.LAYER_TYPE_NONE, null); fab.setClickable(true); } } }); animatorSet.setDuration(DURATION_SHORT); animatorSet.setInterpolator(INTERPOLATOR); return animatorSet; } public static AnimatorSet getCollapseFabs(final FloatingActionButton baseFab, final FloatingActionButton... fabs) { final ValueAnimator fabRotation = rotationAnimator(baseFab, ROTATION_TO_ANGLE, 0f); final ValueAnimator translationY = translationYAnimator(fabs, false, getShift(baseFab, fabs.length)); final ValueAnimator alpha = alphaAnimator(1f, 0f, fabs); AnimatorSet animatorSet = new AnimatorSet(); animatorSet.playTogether(fabRotation, translationY, alpha); animatorSet.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { for (FloatingActionButton fab : fabs) { fab.setLayerType(View.LAYER_TYPE_HARDWARE, null); fab.setClickable(false); } } @Override public void onAnimationEnd(Animator animation) { for (int i = 0, fabsLength = fabs.length; i < fabsLength; i++) { FloatingActionButton fab = fabs[i]; fab.setVisibility(View.GONE); fab.setLayerType(View.LAYER_TYPE_NONE, null); } } }); animatorSet.setDuration(DURATION_SHORT); animatorSet.setInterpolator(INTERPOLATOR); return animatorSet; } @NonNull private static ValueAnimator rotationAnimator(final FloatingActionButton target, float from, float to) { final ValueAnimator fabRotation = ValueAnimator.ofFloat(from, to); fabRotation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { final float animatedValue = (float) animation.getAnimatedValue(); target.setRotation(animatedValue); } }); return fabRotation; } @NonNull private static ValueAnimator translationYAnimator(final FloatingActionButton[] targets, final boolean topDirection, int shift) { final ValueAnimator translationY = topDirection ? ValueAnimator.ofInt(0, shift) : ValueAnimator.ofInt(shift, 0); translationY.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { final int dY = (int) animation.getAnimatedValue(); for (int i = 0; i < targets.length; i++) targets[i].setTranslationY((i + 1) * -dY); } }); return translationY; } private static int getShift(FloatingActionButton source, int count) { final int bottomMargin = ((CoordinatorLayout.LayoutParams) source.getLayoutParams()).bottomMargin; int shift = source.getHeight() + bottomMargin; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) shift -= source.getPaddingBottom() / 2; // check if targets are not off screen final int targetMaxTop = source.getTop() - (count * shift); if (targetMaxTop < 0) { int maxShiftForAllTargetFullyVisible = shift - Math.abs(targetMaxTop / count); int minShiftForAllTargetFullyVisible = source.getHeight() - source.getPaddingBottom(); shift = Math.max(maxShiftForAllTargetFullyVisible, minShiftForAllTargetFullyVisible); } return shift; } @NonNull private static ValueAnimator alphaAnimator(float from, float to, final FloatingActionButton[] targets) { final ValueAnimator alpha = ValueAnimator.ofFloat(from, to); alpha.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { final float value = (float) animation.getAnimatedValue(); if (value >= 0.0f && value <= 1.0) for (FloatingActionButton target : targets) target.setAlpha(value); } }); return alpha; } //TODO // public static void reveal() { // Animator reveal = ViewAnimationUtils.createCircularReveal( // viewToReveal, // The new View to reveal // centerX, // x co-ordinate to start the mask from // centerY, // y co-ordinate to start the mask from // startRadius, // radius of the starting mask // endRadius); // radius of the final mask // reveal.start(); // } }
app/src/main/java/pl/srw/billcalculator/util/Animations.java
package pl.srw.billcalculator.util; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.os.Build; import android.support.annotation.NonNull; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.view.View; import android.view.animation.AccelerateDecelerateInterpolator; public final class Animations { private static final long DURATION_LONG = 1000; private static final long DURATION_SHORT = 200; private static final float ROTATION_TO_ANGLE = 135f; private static final AccelerateDecelerateInterpolator INTERPOLATOR = new AccelerateDecelerateInterpolator(); private static final ObjectAnimator SHAKE = ObjectAnimator .ofFloat(null, "translationX", 0, 25, -25, 25, -25, 15, -15, 6, -6, 0) .setDuration(DURATION_LONG); private Animations() { } public static void shake(View target) { SHAKE.setTarget(target); SHAKE.start(); } public static AnimatorSet getExpandFabs(final FloatingActionButton baseFab, final FloatingActionButton... fabs) { final ValueAnimator fabRotation = rotationAnimator(baseFab, 0f, ROTATION_TO_ANGLE); final ValueAnimator translationY = translationYAnimator(true, fabs); final ValueAnimator alpha = alphaAnimator(0f, 1f, fabs); AnimatorSet animatorSet = new AnimatorSet(); animatorSet.playTogether(fabRotation, translationY, alpha); animatorSet.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { for (FloatingActionButton fab : fabs) { fab.setLayerType(View.LAYER_TYPE_HARDWARE, null); fab.setVisibility(View.VISIBLE); } } @Override public void onAnimationEnd(Animator animation) { for (FloatingActionButton fab : fabs) { fab.setLayerType(View.LAYER_TYPE_NONE, null); fab.setClickable(true); } } }); animatorSet.setDuration(DURATION_SHORT); animatorSet.setInterpolator(INTERPOLATOR); return animatorSet; } public static AnimatorSet getCollapseFabs(final FloatingActionButton baseFab, final FloatingActionButton... fabs) { final ValueAnimator fabRotation = rotationAnimator(baseFab, ROTATION_TO_ANGLE, 0f); final ValueAnimator translationY = translationYAnimator(false, fabs); final ValueAnimator alpha = alphaAnimator(1f, 0f, fabs); AnimatorSet animatorSet = new AnimatorSet(); animatorSet.playTogether(fabRotation, translationY, alpha); animatorSet.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { for (FloatingActionButton fab : fabs) { fab.setLayerType(View.LAYER_TYPE_HARDWARE, null); fab.setClickable(false); } } @Override public void onAnimationEnd(Animator animation) { for (int i = 0, fabsLength = fabs.length; i < fabsLength; i++) { FloatingActionButton fab = fabs[i]; fab.setVisibility(View.GONE); fab.setLayerType(View.LAYER_TYPE_NONE, null); } } }); animatorSet.setDuration(DURATION_SHORT); animatorSet.setInterpolator(INTERPOLATOR); return animatorSet; } @NonNull private static ValueAnimator rotationAnimator(final FloatingActionButton target, float from, float to) { final ValueAnimator fabRotation = ValueAnimator.ofFloat(from, to); fabRotation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { final float animatedValue = (float) animation.getAnimatedValue(); target.setRotation(animatedValue); } }); return fabRotation; } @NonNull private static ValueAnimator translationYAnimator(final boolean topDirection, final FloatingActionButton[] targets) { int shift = getShift(targets); final ValueAnimator translationY = topDirection ? ValueAnimator.ofInt(0, shift) : ValueAnimator.ofInt(shift, 0); translationY.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { final int dY = (int) animation.getAnimatedValue(); for (int i = 0; i < targets.length; i++) targets[i].setTranslationY((i + 1) * -dY); } }); return translationY; } private static int getShift(FloatingActionButton[] targets) { FloatingActionButton source = targets[0]; final int bottomMargin = ((CoordinatorLayout.LayoutParams) source.getLayoutParams()).bottomMargin; int shift = source.getHeight() + bottomMargin; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) shift -= source.getPaddingBottom() / 2; // check if targets are not off screen final int targetMaxTop = source.getTop() - (targets.length * shift); if (targetMaxTop < 0) { int maxShiftForAllTargetFullyVisible = shift - Math.abs(targetMaxTop / targets.length); int minShiftForAllTargetFullyVisible = source.getHeight() - source.getPaddingBottom(); shift = Math.max(maxShiftForAllTargetFullyVisible, minShiftForAllTargetFullyVisible); } return shift; } @NonNull private static ValueAnimator alphaAnimator(float from, float to, final FloatingActionButton[] targets) { final ValueAnimator alpha = ValueAnimator.ofFloat(from, to); alpha.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { final float value = (float) animation.getAnimatedValue(); if (value >= 0.0f && value <= 1.0) for (FloatingActionButton target : targets) target.setAlpha(value); } }); return alpha; } //TODO // public static void reveal() { // Animator reveal = ViewAnimationUtils.createCircularReveal( // viewToReveal, // The new View to reveal // centerX, // x co-ordinate to start the mask from // centerY, // y co-ordinate to start the mask from // startRadius, // radius of the starting mask // endRadius); // radius of the final mask // reveal.start(); // } }
Fix FAB animation shift count after support lib upgrade
app/src/main/java/pl/srw/billcalculator/util/Animations.java
Fix FAB animation shift count after support lib upgrade
Java
mit
587f26a6df40e3743a805e59deb179f824d4c4d6
0
ystviren/mustached-tyrion,ystviren/mustached-tyrion,ystviren/mustached-tyrion,ystviren/mustached-tyrion,ystviren/mustached-tyrion,ystviren/mustached-tyrion,ystviren/mustached-tyrion
import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; /* Copyright (C) 2004 Geoffrey Alan Washburn This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /** * A skeleton for those {@link Client}s that correspond to clients on other computers. * @author Geoffrey Washburn &lt;<a href="mailto:geoffw@cis.upenn.edu">geoffw@cis.upenn.edu</a>&gt; * @version $Id: RemoteClient.java 342 2004-01-23 21:35:52Z geoffw $ */ public class RemoteClient extends Client implements Runnable{ private Thread thread = null; private Socket outSocket = null; private ObjectOutputStream myOut = null; private Socket inSocket = null; private ObjectInputStream myIn = null; private String hostname; private int port; /** * Create a remotely controlled {@link Client}. * @param name Name of this {@link RemoteClient}. */ public RemoteClient(String name, String hostname, int port, int ID) { super(name, ID); this.hostname = hostname; this.port = port; thread = new Thread(this); } public RemoteClient(String name, int ID) { super(name, ID); thread = new Thread(this); } public void writeObject(MazewarPacket outPacket) { // TODO Auto-generated method stub if (outSocket == null) { try { outSocket = new Socket(hostname, port); myOut = new ObjectOutputStream(outSocket.getOutputStream()); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { myOut.writeObject(outPacket); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void setInSocket(Socket socket, ObjectInputStream in) { // TODO Auto-generated method stub inSocket = socket; try { if (in == null) { myIn = new ObjectInputStream(inSocket.getInputStream()); } else { myIn = in; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void run() { // TODO Auto-generated method stub boolean gotByePacket = false; try { MazewarPacket remotePacket = null; while ((remotePacket = (MazewarPacket)myIn.readObject()) != null) { //System.out.println("Recieved Packet " + packetFromClient.type); /** process message **/ if (remotePacket.type == MazewarPacket.RING_TOKEN){ //TODO tell client manager that it can run event? synchronized (Client.actionQueue){ Client.actionQueue.addAll(remotePacket.eventQueue); //Set execution flag } }else if (remotePacket.type == MazewarPacket.CLIENT_REGISTER){ //TODO player join logic }else if (remotePacket.type == MazewarPacket.CLIENT_BYE){ //TODO change connection to maintain ring }else if(remotePacket.type == MazewarPacket.CLIENT_TEST){ System.out.println("Recieved packeted from " + remotePacket.clientName); }else{ System.out.println("Unknown packet type" + remotePacket.type); } /* quit case */ if (remotePacket.type == MazewarPacket.PACKET_NULL || remotePacket.type == MazewarPacket.CLIENT_BYE) { gotByePacket = true; break; } } /* cleanup when client exits */ myIn.close(); inSocket.close(); } catch (IOException e) { if (!gotByePacket) e.printStackTrace(); } catch (ClassNotFoundException e) { if (!gotByePacket) e.printStackTrace(); } } public void startThread() { // TODO Auto-generated method stub thread.start(); } public MazewarPacket readObject() { // TODO Auto-generated method stub MazewarPacket ret = null; try { ret = (MazewarPacket)myIn.readObject(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ret; } public ObjectOutputStream getOutStream() { // TODO Auto-generated method stub if (outSocket == null) { try { outSocket = new Socket(hostname, port); myOut = new ObjectOutputStream(outSocket.getOutputStream()); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return myOut; } public void setOutSocket(String hostname, int port) { this.hostname = hostname; this.port = port; if (outSocket == null) { try { outSocket = new Socket(hostname, port); myOut = new ObjectOutputStream(outSocket.getOutputStream()); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
Lab3/RemoteClient.java
import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; /* Copyright (C) 2004 Geoffrey Alan Washburn This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /** * A skeleton for those {@link Client}s that correspond to clients on other computers. * @author Geoffrey Washburn &lt;<a href="mailto:geoffw@cis.upenn.edu">geoffw@cis.upenn.edu</a>&gt; * @version $Id: RemoteClient.java 342 2004-01-23 21:35:52Z geoffw $ */ public class RemoteClient extends Client implements Runnable{ private Thread thread = null; private Socket outSocket = null; private ObjectOutputStream myOut = null; private Socket inSocket = null; private ObjectInputStream myIn = null; private String hostname; private int port; /** * Create a remotely controlled {@link Client}. * @param name Name of this {@link RemoteClient}. */ public RemoteClient(String name, String hostname, int port, int ID) { super(name, ID); this.hostname = hostname; this.port = port; thread = new Thread(this); } public RemoteClient(String name, int ID) { super(name, ID); thread = new Thread(this); } public void writeObject(MazewarPacket outPacket) { // TODO Auto-generated method stub if (outSocket == null) { try { outSocket = new Socket(hostname, port); myOut = new ObjectOutputStream(outSocket.getOutputStream()); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { myOut.writeObject(outPacket); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void setInSocket(Socket socket, ObjectInputStream in) { // TODO Auto-generated method stub inSocket = socket; try { if (in == null) { myIn = new ObjectInputStream(inSocket.getInputStream()); } else { myIn = in; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void run() { // TODO Auto-generated method stub boolean gotByePacket = false; try { MazewarPacket remotePacket = null; while ((remotePacket = (MazewarPacket)myIn.readObject()) != null) { //System.out.println("Recieved Packet " + packetFromClient.type); /** process message **/ if (remotePacket.type == MazewarPacket.RING_TOKEN){ //TODO tell client manager that it can run event? synchronized (Client.actionQueue){ Client.actionQueue.addAll(remotePacket.eventQueue); //Set execution flag } }else if (remotePacket.type == MazewarPacket.CLIENT_REGISTER){ //TODO player join logic }else if (remotePacket.type == MazewarPacket.CLIENT_BYE){ //TODO change connection to maintain ring }else if(remotePacket.type == MazewarPacket.CLIENT_TEST){ //System.out.println("Size of queue is " + remotePacket.eventQueue.size() + ", from " + remotePacket.clientName); }else{ System.out.println("Unknown packet type" + remotePacket.type); } /* quit case */ if (remotePacket.type == MazewarPacket.PACKET_NULL || remotePacket.type == MazewarPacket.CLIENT_BYE) { gotByePacket = true; break; } } /* cleanup when client exits */ myIn.close(); inSocket.close(); } catch (IOException e) { if (!gotByePacket) e.printStackTrace(); } catch (ClassNotFoundException e) { if (!gotByePacket) e.printStackTrace(); } } public void startThread() { // TODO Auto-generated method stub thread.start(); } public MazewarPacket readObject() { // TODO Auto-generated method stub MazewarPacket ret = null; try { ret = (MazewarPacket)myIn.readObject(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ret; } public ObjectOutputStream getOutStream() { // TODO Auto-generated method stub if (outSocket == null) { try { outSocket = new Socket(hostname, port); myOut = new ObjectOutputStream(outSocket.getOutputStream()); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return myOut; } public void setOutSocket(String hostname, int port) { this.hostname = hostname; this.port = port; if (outSocket == null) { try { outSocket = new Socket(hostname, port); myOut = new ObjectOutputStream(outSocket.getOutputStream()); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
Uncommented line, changed message to display sender
Lab3/RemoteClient.java
Uncommented line, changed message to display sender
Java
lgpl-2.1
b7610e3075052dc7a53172abe7777707b6931def
0
MenZil/opencms-core,victos/opencms-core,gallardo/opencms-core,mediaworx/opencms-core,MenZil/opencms-core,serrapos/opencms-core,gallardo/opencms-core,gallardo/opencms-core,serrapos/opencms-core,victos/opencms-core,ggiudetti/opencms-core,serrapos/opencms-core,victos/opencms-core,sbonoc/opencms-core,mediaworx/opencms-core,mediaworx/opencms-core,serrapos/opencms-core,serrapos/opencms-core,ggiudetti/opencms-core,ggiudetti/opencms-core,MenZil/opencms-core,it-tavis/opencms-core,sbonoc/opencms-core,sbonoc/opencms-core,victos/opencms-core,alkacon/opencms-core,it-tavis/opencms-core,it-tavis/opencms-core,serrapos/opencms-core,sbonoc/opencms-core,it-tavis/opencms-core,alkacon/opencms-core,mediaworx/opencms-core,alkacon/opencms-core,alkacon/opencms-core,serrapos/opencms-core,gallardo/opencms-core,ggiudetti/opencms-core,MenZil/opencms-core
/* * File : $Source: /alkacon/cvs/opencms/src/com/opencms/workplace/Attic/CmsNewResourcePage.java,v $ * Date : $Date: 2001/09/25 06:55:08 $ * Version: $Revision: 1.45 $ * * This library is part of OpenCms - * the Open Source Content Mananagement System * * Copyright (C) 2001 The OpenCms Group * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about OpenCms, please see the * OpenCms Website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.opencms.workplace; import com.opencms.file.*; import com.opencms.core.*; import com.opencms.util.*; import com.opencms.template.*; import org.w3c.dom.*; import org.xml.sax.*; import javax.servlet.http.*; import java.util.*; import java.io.*; /** * Template class for displaying the new resource screen for a new page * of the OpenCms workplace.<P> * Reads template files of the content type <code>CmsXmlWpTemplateFile</code>. * * @author Michael Emmerich * @version $Revision: 1.45 $ $Date: 2001/09/25 06:55:08 $ */ public class CmsNewResourcePage extends CmsWorkplaceDefault implements I_CmsWpConstants,I_CmsConstants { /** Definition of the class */ private final static String C_CLASSNAME = "com.opencms.template.CmsXmlTemplate"; private static final String C_DEFAULTBODY = "<?xml version=\"1.0\"?>\n<XMLTEMPLATE>\n<TEMPLATE/>\n</XMLTEMPLATE>"; /** * Create the pagefile for this new page. * @classname The name of the class used by this page. * @template The name of the template (content) used by this page. * @return Bytearray containgin the XML code for the pagefile. */ private byte[] createPagefile(String classname, String template, String contenttemplate) throws CmsException { byte[] xmlContent = null; try { I_CmsXmlParser parser = A_CmsXmlContent.getXmlParser(); Document docXml = parser.createEmptyDocument("page"); Element firstElement = docXml.getDocumentElement(); // add element CLASS Element elClass = docXml.createElement("CLASS"); firstElement.appendChild(elClass); Node noClass = docXml.createTextNode(classname); elClass.appendChild(noClass); // add element MASTERTEMPLATE Element elTempl = docXml.createElement("MASTERTEMPLATE"); firstElement.appendChild(elTempl); Node noTempl = docXml.createTextNode(template); elTempl.appendChild(noTempl); //add element ELEMENTDEF Element elEldef = docXml.createElement("ELEMENTDEF"); elEldef.setAttribute("name", "body"); firstElement.appendChild(elEldef); //add element ELEMENTDEF.CLASS Element elElClass = docXml.createElement("CLASS"); elEldef.appendChild(elElClass); Node noElClass = docXml.createTextNode(classname); elElClass.appendChild(noElClass); //add element ELEMENTDEF.TEMPLATE Element elElTempl = docXml.createElement("TEMPLATE"); elEldef.appendChild(elElTempl); Node noElTempl = docXml.createTextNode(contenttemplate); elElTempl.appendChild(noElTempl); // generate the output StringWriter writer = new StringWriter(); parser.getXmlText(docXml, writer); xmlContent = writer.toString().getBytes(); } catch(Exception e) { throw new CmsException(e.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, e); } return xmlContent; } /** * Overwrites the getContent method of the CmsWorkplaceDefault.<br> * Gets the content of the new resource page template and processed the data input. * @param cms The CmsObject. * @param templateFile The new page template file * @param elementName not used * @param parameters Parameters of the request and the template. * @param templateSelector Selector of the template tag to be displayed. * @return Bytearry containing the processed data of the template. * @exception Throws CmsException if something goes wrong. */ public byte[] getContent(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) throws CmsException { // the template to be displayed String template = null; // get the document to display CmsXmlWpTemplateFile xmlTemplateDocument = new CmsXmlWpTemplateFile(cms, templateFile); // TODO: check, if this is neede: String type=null; byte[] content = new byte[0]; CmsFile contentFile = null; I_CmsSession session = cms.getRequestContext().getSession(true); //get the current filelist String currentFilelist = (String)session.getValue(C_PARA_FILELIST); if(currentFilelist == null) { currentFilelist = cms.rootFolder().getAbsolutePath(); } // get request parameters String newFile = (String)parameters.get(C_PARA_NEWFILE); String title = (String)parameters.get(C_PARA_TITLE); String keywords = (String)parameters.get(C_PARA_KEYWORDS); String description = (String)parameters.get(C_PARA_DESCRIPTION); // look if createFolder called us, then we have to preselect index.html as name String fromFolder = (String)parameters.get("fromFolder"); if((fromFolder != null) && ("true".equals(fromFolder))){ xmlTemplateDocument.setData("name", "index.html"); // deaktivate the linklayer xmlTemplateDocument.setData("doOnload", "checkInTheBox();"); }else{ xmlTemplateDocument.setData("name", ""); xmlTemplateDocument.setData("doOnload", ""); } // TODO: check, if this is neede: String flags=(String)parameters.get(C_PARA_FLAGS); String templatefile = (String)parameters.get(C_PARA_TEMPLATE); String navtitle = (String)parameters.get(C_PARA_NAVTEXT); String navpos = (String)parameters.get(C_PARA_NAVPOS); String layoutFilePath = (String)parameters.get(C_PARA_LAYOUT); // get the current phase of this wizard String step = cms.getRequestContext().getRequest().getParameter("step"); if(step != null) { if(step.equals("1")) { //check if the fielname has a file extension if(newFile.indexOf(".") == -1) { newFile += ".html"; } try { // create the content for the page file content = createPagefile(C_CLASSNAME, templatefile, C_CONTENTBODYPATH + currentFilelist.substring(1, currentFilelist.length()) + newFile); // check if the nescessary folders for the content files are existing. // if not, create the missing folders. //checkFolders(cms, currentFilelist); // create the page file Hashtable prop = new Hashtable(); prop.put(C_PROPERTY_TITLE, title); CmsResourceTypePage rtpage = new CmsResourceTypePage(); CmsResource file = rtpage.createResource(cms, currentFilelist, newFile, prop, "".getBytes(), templatefile); if( keywords != null && !keywords.equals("") ) { cms.writeProperty(file.getAbsolutePath(), C_PROPERTY_KEYWORDS, keywords); } if( description != null && !description.equals("") ) { cms.writeProperty(file.getAbsolutePath(), C_PROPERTY_DESCRIPTION, description); } byte[] bodyBytes = null; if (layoutFilePath == null || layoutFilePath.equals("")) { // layout not specified, use default body bodyBytes = C_DEFAULTBODY.getBytes(); } else { // do not catch exceptions, a specified layout should exist CmsFile layoutFile = cms.readFile(layoutFilePath); bodyBytes = layoutFile.getContents(); } CmsFile bodyFile = cms.readFile(C_CONTENTBODYPATH + currentFilelist.substring(1, currentFilelist.length()), newFile); bodyFile.setContents(bodyBytes); cms.writeFile(bodyFile); // now check if navigation informations have to be added to the new page. if(navtitle != null) { cms.writeProperty(file.getAbsolutePath(), C_PROPERTY_NAVTEXT, navtitle); // update the navposition. if(navpos != null) { updateNavPos(cms, file, navpos); } } } catch(CmsException ex) { throw new CmsException("Error while creating new Page" + ex.getMessage(), ex.getType(), ex); } // TODO: ErrorHandling // now return to filelist try { cms.getRequestContext().getResponse().sendCmsRedirect(getConfigFile(cms).getWorkplaceActionPath() + C_WP_EXPLORER_FILELIST); } catch(Exception e) { throw new CmsException("Redirect fails :" + getConfigFile(cms).getWorkplaceActionPath() + C_WP_EXPLORER_FILELIST, CmsException.C_UNKNOWN_EXCEPTION, e); } return null; } } else { session.removeValue(C_PARA_FILE); } // process the selected template return startProcessing(cms, xmlTemplateDocument, "", parameters, template); } /** * Gets all required navigation information from the files and subfolders of a folder. * A file list of all files and folder is created, for all those resources, the navigation * property is read. The list is sorted by their navigation position. * @param cms The CmsObject. * @return Hashtable including three arrays of strings containing the filenames, * nicenames and navigation positions. * @exception Throws CmsException if something goes wrong. */ private Hashtable getNavData(CmsObject cms) throws CmsException { I_CmsSession session = cms.getRequestContext().getSession(true); CmsXmlLanguageFile lang = new CmsXmlLanguageFile(cms); String[] filenames; String[] nicenames; String[] positions; Hashtable storage = new Hashtable(); CmsFolder folder = null; CmsFile file = null; String nicename = null; String currentFilelist = null; int count = 1; float max = 0; // get the current folder currentFilelist = (String)session.getValue(C_PARA_FILELIST); if(currentFilelist == null) { currentFilelist = cms.rootFolder().getAbsolutePath(); } // get all files and folders in the current filelist. Vector files = cms.getFilesInFolder(currentFilelist); Vector folders = cms.getSubFolders(currentFilelist); // combine folder and file vector Vector filefolders = new Vector(); Enumeration enum = folders.elements(); while(enum.hasMoreElements()) { folder = (CmsFolder)enum.nextElement(); filefolders.addElement(folder); } enum = files.elements(); while(enum.hasMoreElements()) { file = (CmsFile)enum.nextElement(); filefolders.addElement(file); } if(filefolders.size() > 0) { // Create some arrays to store filename, nicename and position for the // nav in there. The dimension of this arrays is set to the number of // found files and folders plus two more entrys for the first and last // element. filenames = new String[filefolders.size() + 2]; nicenames = new String[filefolders.size() + 2]; positions = new String[filefolders.size() + 2]; //now check files and folders that are not deleted and include navigation // information enum = filefolders.elements(); while(enum.hasMoreElements()) { CmsResource res = (CmsResource)enum.nextElement(); // check if the resource is not marked as deleted if(res.getState() != C_STATE_DELETED) { String navpos = cms.readProperty(res.getAbsolutePath(), C_PROPERTY_NAVPOS); // check if there is a navpos for this file/folder if(navpos != null) { nicename = cms.readProperty(res.getAbsolutePath(), C_PROPERTY_NAVTEXT); if(nicename == null) { nicename = res.getName(); } // add this file/folder to the storage. filenames[count] = res.getAbsolutePath(); nicenames[count] = nicename; positions[count] = navpos; if(new Float(navpos).floatValue() > max) { max = new Float(navpos).floatValue(); } count++; } } } } else { filenames = new String[2]; nicenames = new String[2]; positions = new String[2]; } // now add the first and last value filenames[0] = "FIRSTENTRY"; nicenames[0] = lang.getDataValue("input.firstelement"); positions[0] = "0"; filenames[count] = "LASTENTRY"; nicenames[count] = lang.getDataValue("input.lastelement"); positions[count] = new Float(max + 1).toString(); // finally sort the nav information. sort(cms, filenames, nicenames, positions, count); // put all arrays into a hashtable to return them to the calling method. storage.put("FILENAMES", filenames); storage.put("NICENAMES", nicenames); storage.put("POSITIONS", positions); storage.put("COUNT", new Integer(count)); return storage; } /** * Gets the files displayed in the navigation select box. * @param cms The CmsObject. * @param lang The langauge definitions. * @param names The names of the new rescources. * @param values The links that are connected with each resource. * @param parameters Hashtable of parameters (not used yet). * @returns The vectors names and values are filled with data for building the navigation. * @exception Throws CmsException if something goes wrong. */ public Integer getNavPos(CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values, Hashtable parameters) throws CmsException { // get the nav information Hashtable storage = getNavData(cms); if(storage.size() > 0) { String[] nicenames = (String[])storage.get("NICENAMES"); int count = ((Integer)storage.get("COUNT")).intValue(); // finally fill the result vectors for(int i = 0;i <= count;i++) { names.addElement(nicenames[i]); values.addElement(nicenames[i]); } } else { values = new Vector(); } return new Integer(values.size() - 1); } /** * Gets the templates displayed in the template select box. * @param cms The CmsObject. * @param lang The langauge definitions. * @param names The names of the new rescources. * @param values The links that are connected with each resource. * @param parameters Hashtable of parameters (not used yet). * @returns The vectors names and values are filled with the information found in the * workplace.ini. * @exception Throws CmsException if something goes wrong. */ public Integer getTemplates(CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values, Hashtable parameters) throws CmsException { return CmsHelperMastertemplates.getTemplates(cms, names, values, null); } /** * Indicates if the results of this class are cacheable. * * @param cms CmsObject Object for accessing system resources * @param templateFile Filename of the template file * @param elementName Element name of this template in our parent template. * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. * @return <EM>true</EM> if cacheable, <EM>false</EM> otherwise. */ public boolean isCacheable(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) { return false; } /** * Sorts a set of three String arrays containing navigation information depending on * their navigation positions. * @param cms Cms Object for accessign files. * @param filenames Array of filenames * @param nicenames Array of well formed navigation names * @param positions Array of navpostions */ private void sort(CmsObject cms, String[] filenames, String[] nicenames, String[] positions, int max) { // Sorting algorithm // This method uses an bubble sort, so replace this with something more // efficient for(int i = max - 1;i > 1;i--) { for(int j = 1;j < i;j++) { float a = new Float(positions[j]).floatValue(); float b = new Float(positions[j + 1]).floatValue(); if(a > b) { String tempfilename = filenames[j]; String tempnicename = nicenames[j]; String tempposition = positions[j]; filenames[j] = filenames[j + 1]; nicenames[j] = nicenames[j + 1]; positions[j] = positions[j + 1]; filenames[j + 1] = tempfilename; nicenames[j + 1] = tempnicename; positions[j + 1] = tempposition; } } } } /** * Updates the navigation position of all resources in the actual folder. * @param cms The CmsObject. * @param newfile The new file added to the nav. * @param navpos The file after which the new entry is sorted. */ private void updateNavPos(CmsObject cms, CmsResource newfile, String newpos) throws CmsException { float newPos = 0; // get the nav information Hashtable storage = getNavData(cms); if(storage.size() > 0) { String[] nicenames = (String[])storage.get("NICENAMES"); String[] positions = (String[])storage.get("POSITIONS"); int count = ((Integer)storage.get("COUNT")).intValue(); // now find the file after which the new file is sorted int pos = 0; for(int i = 0;i < nicenames.length;i++) { if(newpos.equals((String)nicenames[i])) { pos = i; } } if(pos < count) { float low = new Float(positions[pos]).floatValue(); float high = new Float(positions[pos + 1]).floatValue(); newPos = (high + low) / 2; } else { newPos = new Float(positions[pos]).floatValue() + 1; } } else { newPos = 1; } cms.writeProperty(newfile.getAbsolutePath(), C_PROPERTY_NAVPOS, new Float(newPos).toString()); } /** * Gets the content layouts displayed in the content layouts select box. * @param cms The CmsObject. * @param lang The langauge definitions. * @param names The names of the new rescources. * @param values The links that are connected with each resource. * @param parameters Hashtable of parameters (not used yet). * @returns The vectors names and values are filled with the information found in the * workplace.ini. * @exception Throws CmsException if something goes wrong. */ public Integer getLayouts(CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values, Hashtable parameters) throws CmsException { Vector files = cms.getFilesInFolder(C_CONTENTLAYOUTPATH); // get all default bodies from the modules Vector modules = new Vector(); modules = cms.getSubFolders(C_MODULES_PATH); for(int i = 0;i < modules.size();i++) { Vector moduleTemplateFiles = new Vector(); moduleTemplateFiles = cms.getFilesInFolder(((CmsFolder)modules.elementAt(i)).getAbsolutePath() + "default_bodies/"); for(int j = 0;j < moduleTemplateFiles.size();j++) { files.addElement(moduleTemplateFiles.elementAt(j)); } } Enumeration enum = files.elements(); while(enum.hasMoreElements()) { CmsFile file = (CmsFile)enum.nextElement(); if(file.getState() != C_STATE_DELETED) { String nicename = cms.readProperty(file.getAbsolutePath(), C_PROPERTY_TITLE); if(nicename == null) { nicename = file.getName(); } names.addElement(nicename); values.addElement(file.getAbsolutePath()); } } bubblesort(names, values); return new Integer(0); } }
src/com/opencms/workplace/CmsNewResourcePage.java
/* * File : $Source: /alkacon/cvs/opencms/src/com/opencms/workplace/Attic/CmsNewResourcePage.java,v $ * Date : $Date: 2001/09/10 08:32:51 $ * Version: $Revision: 1.44 $ * * This library is part of OpenCms - * the Open Source Content Mananagement System * * Copyright (C) 2001 The OpenCms Group * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about OpenCms, please see the * OpenCms Website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.opencms.workplace; import com.opencms.file.*; import com.opencms.core.*; import com.opencms.util.*; import com.opencms.template.*; import org.w3c.dom.*; import org.xml.sax.*; import javax.servlet.http.*; import java.util.*; import java.io.*; /** * Template class for displaying the new resource screen for a new page * of the OpenCms workplace.<P> * Reads template files of the content type <code>CmsXmlWpTemplateFile</code>. * * @author Michael Emmerich * @version $Revision: 1.44 $ $Date: 2001/09/10 08:32:51 $ */ public class CmsNewResourcePage extends CmsWorkplaceDefault implements I_CmsWpConstants,I_CmsConstants { /** Definition of the class */ private final static String C_CLASSNAME = "com.opencms.template.CmsXmlTemplate"; private static final String C_DEFAULTBODY = "<?xml version=\"1.0\"?>\n<XMLTEMPLATE>\n<TEMPLATE/>\n</XMLTEMPLATE>"; /** * Create the pagefile for this new page. * @classname The name of the class used by this page. * @template The name of the template (content) used by this page. * @return Bytearray containgin the XML code for the pagefile. */ private byte[] createPagefile(String classname, String template, String contenttemplate) throws CmsException { byte[] xmlContent = null; try { I_CmsXmlParser parser = A_CmsXmlContent.getXmlParser(); Document docXml = parser.createEmptyDocument("page"); Element firstElement = docXml.getDocumentElement(); // add element CLASS Element elClass = docXml.createElement("CLASS"); firstElement.appendChild(elClass); Node noClass = docXml.createTextNode(classname); elClass.appendChild(noClass); // add element MASTERTEMPLATE Element elTempl = docXml.createElement("MASTERTEMPLATE"); firstElement.appendChild(elTempl); Node noTempl = docXml.createTextNode(template); elTempl.appendChild(noTempl); //add element ELEMENTDEF Element elEldef = docXml.createElement("ELEMENTDEF"); elEldef.setAttribute("name", "body"); firstElement.appendChild(elEldef); //add element ELEMENTDEF.CLASS Element elElClass = docXml.createElement("CLASS"); elEldef.appendChild(elElClass); Node noElClass = docXml.createTextNode(classname); elElClass.appendChild(noElClass); //add element ELEMENTDEF.TEMPLATE Element elElTempl = docXml.createElement("TEMPLATE"); elEldef.appendChild(elElTempl); Node noElTempl = docXml.createTextNode(contenttemplate); elElTempl.appendChild(noElTempl); // generate the output StringWriter writer = new StringWriter(); parser.getXmlText(docXml, writer); xmlContent = writer.toString().getBytes(); } catch(Exception e) { throw new CmsException(e.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, e); } return xmlContent; } /** * Overwrites the getContent method of the CmsWorkplaceDefault.<br> * Gets the content of the new resource page template and processed the data input. * @param cms The CmsObject. * @param templateFile The new page template file * @param elementName not used * @param parameters Parameters of the request and the template. * @param templateSelector Selector of the template tag to be displayed. * @return Bytearry containing the processed data of the template. * @exception Throws CmsException if something goes wrong. */ public byte[] getContent(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) throws CmsException { // the template to be displayed String template = null; // get the document to display CmsXmlWpTemplateFile xmlTemplateDocument = new CmsXmlWpTemplateFile(cms, templateFile); // TODO: check, if this is neede: String type=null; byte[] content = new byte[0]; CmsFile contentFile = null; I_CmsSession session = cms.getRequestContext().getSession(true); //get the current filelist String currentFilelist = (String)session.getValue(C_PARA_FILELIST); if(currentFilelist == null) { currentFilelist = cms.rootFolder().getAbsolutePath(); } // get request parameters String newFile = (String)parameters.get(C_PARA_NEWFILE); String title = (String)parameters.get(C_PARA_TITLE); String keywords = (String)parameters.get(C_PARA_KEYWORDS); String description = (String)parameters.get(C_PARA_DESCRIPTION); // look if createFolder called us, then we have to preselect index.html as name String fromFolder = (String)parameters.get("fromFolder"); if((fromFolder != null) && ("true".equals(fromFolder))){ xmlTemplateDocument.setData("name", "index.html"); // deaktivate the linklayer xmlTemplateDocument.setData("doOnload", "checkInTheBox();"); }else{ xmlTemplateDocument.setData("name", ""); xmlTemplateDocument.setData("doOnload", ""); } // TODO: check, if this is neede: String flags=(String)parameters.get(C_PARA_FLAGS); String templatefile = (String)parameters.get(C_PARA_TEMPLATE); String navtitle = (String)parameters.get(C_PARA_NAVTEXT); String navpos = (String)parameters.get(C_PARA_NAVPOS); String layoutFilePath = (String)parameters.get(C_PARA_LAYOUT); // get the current phase of this wizard String step = cms.getRequestContext().getRequest().getParameter("step"); if(step != null) { if(step.equals("1")) { //check if the fielname has a file extension if(newFile.indexOf(".") == -1) { newFile += ".html"; } try { // create the content for the page file content = createPagefile(C_CLASSNAME, templatefile, C_CONTENTBODYPATH + currentFilelist.substring(1, currentFilelist.length()) + newFile); // check if the nescessary folders for the content files are existing. // if not, create the missing folders. //checkFolders(cms, currentFilelist); // create the page file Hashtable prop = new Hashtable(); prop.put(C_PROPERTY_TITLE, title); CmsResourceTypePage rtpage = new CmsResourceTypePage(); CmsResource file = rtpage.createResource(cms, currentFilelist, newFile, prop, "".getBytes(), templatefile); if( keywords != null && !keywords.equals("") ) { cms.writeProperty(file.getAbsolutePath(), C_PROPERTY_KEYWORDS, keywords); } if( description != null && !description.equals("") ) { cms.writeProperty(file.getAbsolutePath(), C_PROPERTY_DESCRIPTION, description); } byte[] bodyBytes = null; if (layoutFilePath == null || layoutFilePath.equals("")) { // layout not specified, use default body bodyBytes = C_DEFAULTBODY.getBytes(); } else { // do not catch exceptions, a specified layout should exist CmsFile layoutFile = cms.readFile(layoutFilePath); bodyBytes = layoutFile.getContents(); } // now check if navigation informations have to be added to the new page. if(navtitle != null) { cms.writeProperty(file.getAbsolutePath(), C_PROPERTY_NAVTEXT, navtitle); // update the navposition. if(navpos != null) { updateNavPos(cms, file, navpos); } } } catch(CmsException ex) { throw new CmsException("Error while creating new Page" + ex.getMessage(), ex.getType(), ex); } // TODO: ErrorHandling // now return to filelist try { cms.getRequestContext().getResponse().sendCmsRedirect(getConfigFile(cms).getWorkplaceActionPath() + C_WP_EXPLORER_FILELIST); } catch(Exception e) { throw new CmsException("Redirect fails :" + getConfigFile(cms).getWorkplaceActionPath() + C_WP_EXPLORER_FILELIST, CmsException.C_UNKNOWN_EXCEPTION, e); } return null; } } else { session.removeValue(C_PARA_FILE); } // process the selected template return startProcessing(cms, xmlTemplateDocument, "", parameters, template); } /** * Gets all required navigation information from the files and subfolders of a folder. * A file list of all files and folder is created, for all those resources, the navigation * property is read. The list is sorted by their navigation position. * @param cms The CmsObject. * @return Hashtable including three arrays of strings containing the filenames, * nicenames and navigation positions. * @exception Throws CmsException if something goes wrong. */ private Hashtable getNavData(CmsObject cms) throws CmsException { I_CmsSession session = cms.getRequestContext().getSession(true); CmsXmlLanguageFile lang = new CmsXmlLanguageFile(cms); String[] filenames; String[] nicenames; String[] positions; Hashtable storage = new Hashtable(); CmsFolder folder = null; CmsFile file = null; String nicename = null; String currentFilelist = null; int count = 1; float max = 0; // get the current folder currentFilelist = (String)session.getValue(C_PARA_FILELIST); if(currentFilelist == null) { currentFilelist = cms.rootFolder().getAbsolutePath(); } // get all files and folders in the current filelist. Vector files = cms.getFilesInFolder(currentFilelist); Vector folders = cms.getSubFolders(currentFilelist); // combine folder and file vector Vector filefolders = new Vector(); Enumeration enum = folders.elements(); while(enum.hasMoreElements()) { folder = (CmsFolder)enum.nextElement(); filefolders.addElement(folder); } enum = files.elements(); while(enum.hasMoreElements()) { file = (CmsFile)enum.nextElement(); filefolders.addElement(file); } if(filefolders.size() > 0) { // Create some arrays to store filename, nicename and position for the // nav in there. The dimension of this arrays is set to the number of // found files and folders plus two more entrys for the first and last // element. filenames = new String[filefolders.size() + 2]; nicenames = new String[filefolders.size() + 2]; positions = new String[filefolders.size() + 2]; //now check files and folders that are not deleted and include navigation // information enum = filefolders.elements(); while(enum.hasMoreElements()) { CmsResource res = (CmsResource)enum.nextElement(); // check if the resource is not marked as deleted if(res.getState() != C_STATE_DELETED) { String navpos = cms.readProperty(res.getAbsolutePath(), C_PROPERTY_NAVPOS); // check if there is a navpos for this file/folder if(navpos != null) { nicename = cms.readProperty(res.getAbsolutePath(), C_PROPERTY_NAVTEXT); if(nicename == null) { nicename = res.getName(); } // add this file/folder to the storage. filenames[count] = res.getAbsolutePath(); nicenames[count] = nicename; positions[count] = navpos; if(new Float(navpos).floatValue() > max) { max = new Float(navpos).floatValue(); } count++; } } } } else { filenames = new String[2]; nicenames = new String[2]; positions = new String[2]; } // now add the first and last value filenames[0] = "FIRSTENTRY"; nicenames[0] = lang.getDataValue("input.firstelement"); positions[0] = "0"; filenames[count] = "LASTENTRY"; nicenames[count] = lang.getDataValue("input.lastelement"); positions[count] = new Float(max + 1).toString(); // finally sort the nav information. sort(cms, filenames, nicenames, positions, count); // put all arrays into a hashtable to return them to the calling method. storage.put("FILENAMES", filenames); storage.put("NICENAMES", nicenames); storage.put("POSITIONS", positions); storage.put("COUNT", new Integer(count)); return storage; } /** * Gets the files displayed in the navigation select box. * @param cms The CmsObject. * @param lang The langauge definitions. * @param names The names of the new rescources. * @param values The links that are connected with each resource. * @param parameters Hashtable of parameters (not used yet). * @returns The vectors names and values are filled with data for building the navigation. * @exception Throws CmsException if something goes wrong. */ public Integer getNavPos(CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values, Hashtable parameters) throws CmsException { // get the nav information Hashtable storage = getNavData(cms); if(storage.size() > 0) { String[] nicenames = (String[])storage.get("NICENAMES"); int count = ((Integer)storage.get("COUNT")).intValue(); // finally fill the result vectors for(int i = 0;i <= count;i++) { names.addElement(nicenames[i]); values.addElement(nicenames[i]); } } else { values = new Vector(); } return new Integer(values.size() - 1); } /** * Gets the templates displayed in the template select box. * @param cms The CmsObject. * @param lang The langauge definitions. * @param names The names of the new rescources. * @param values The links that are connected with each resource. * @param parameters Hashtable of parameters (not used yet). * @returns The vectors names and values are filled with the information found in the * workplace.ini. * @exception Throws CmsException if something goes wrong. */ public Integer getTemplates(CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values, Hashtable parameters) throws CmsException { return CmsHelperMastertemplates.getTemplates(cms, names, values, null); } /** * Indicates if the results of this class are cacheable. * * @param cms CmsObject Object for accessing system resources * @param templateFile Filename of the template file * @param elementName Element name of this template in our parent template. * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. * @return <EM>true</EM> if cacheable, <EM>false</EM> otherwise. */ public boolean isCacheable(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) { return false; } /** * Sorts a set of three String arrays containing navigation information depending on * their navigation positions. * @param cms Cms Object for accessign files. * @param filenames Array of filenames * @param nicenames Array of well formed navigation names * @param positions Array of navpostions */ private void sort(CmsObject cms, String[] filenames, String[] nicenames, String[] positions, int max) { // Sorting algorithm // This method uses an bubble sort, so replace this with something more // efficient for(int i = max - 1;i > 1;i--) { for(int j = 1;j < i;j++) { float a = new Float(positions[j]).floatValue(); float b = new Float(positions[j + 1]).floatValue(); if(a > b) { String tempfilename = filenames[j]; String tempnicename = nicenames[j]; String tempposition = positions[j]; filenames[j] = filenames[j + 1]; nicenames[j] = nicenames[j + 1]; positions[j] = positions[j + 1]; filenames[j + 1] = tempfilename; nicenames[j + 1] = tempnicename; positions[j + 1] = tempposition; } } } } /** * Updates the navigation position of all resources in the actual folder. * @param cms The CmsObject. * @param newfile The new file added to the nav. * @param navpos The file after which the new entry is sorted. */ private void updateNavPos(CmsObject cms, CmsResource newfile, String newpos) throws CmsException { float newPos = 0; // get the nav information Hashtable storage = getNavData(cms); if(storage.size() > 0) { String[] nicenames = (String[])storage.get("NICENAMES"); String[] positions = (String[])storage.get("POSITIONS"); int count = ((Integer)storage.get("COUNT")).intValue(); // now find the file after which the new file is sorted int pos = 0; for(int i = 0;i < nicenames.length;i++) { if(newpos.equals((String)nicenames[i])) { pos = i; } } if(pos < count) { float low = new Float(positions[pos]).floatValue(); float high = new Float(positions[pos + 1]).floatValue(); newPos = (high + low) / 2; } else { newPos = new Float(positions[pos]).floatValue() + 1; } } else { newPos = 1; } cms.writeProperty(newfile.getAbsolutePath(), C_PROPERTY_NAVPOS, new Float(newPos).toString()); } /** * Gets the content layouts displayed in the content layouts select box. * @param cms The CmsObject. * @param lang The langauge definitions. * @param names The names of the new rescources. * @param values The links that are connected with each resource. * @param parameters Hashtable of parameters (not used yet). * @returns The vectors names and values are filled with the information found in the * workplace.ini. * @exception Throws CmsException if something goes wrong. */ public Integer getLayouts(CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values, Hashtable parameters) throws CmsException { Vector files = cms.getFilesInFolder(C_CONTENTLAYOUTPATH); // get all default bodies from the modules Vector modules = new Vector(); modules = cms.getSubFolders(C_MODULES_PATH); for(int i = 0;i < modules.size();i++) { Vector moduleTemplateFiles = new Vector(); moduleTemplateFiles = cms.getFilesInFolder(((CmsFolder)modules.elementAt(i)).getAbsolutePath() + "default_bodies/"); for(int j = 0;j < moduleTemplateFiles.size();j++) { files.addElement(moduleTemplateFiles.elementAt(j)); } } Enumeration enum = files.elements(); while(enum.hasMoreElements()) { CmsFile file = (CmsFile)enum.nextElement(); if(file.getState() != C_STATE_DELETED) { String nicename = cms.readProperty(file.getAbsolutePath(), C_PROPERTY_TITLE); if(nicename == null) { nicename = file.getName(); } names.addElement(nicename); values.addElement(file.getAbsolutePath()); } } bubblesort(names, values); return new Integer(0); } }
Bugfix: write the body content after the files are created.
src/com/opencms/workplace/CmsNewResourcePage.java
Bugfix: write the body content after the files are created.
Java
lgpl-2.1
994456b2280c0e2170d50c374e964004a9f424c8
0
xyzz/vcmi-build,xyzz/vcmi-build,def-/commandergenius,sexroute/commandergenius,sexroute/commandergenius,sexroute/commandergenius,xyzz/vcmi-build,xyzz/vcmi-build,def-/commandergenius,dd00/commandergenius,dd00/commandergenius,dd00/commandergenius,sexroute/commandergenius,def-/commandergenius,pelya/commandergenius,pelya/commandergenius,sexroute/commandergenius,xyzz/vcmi-build,dd00/commandergenius,def-/commandergenius,sexroute/commandergenius,pelya/commandergenius,dd00/commandergenius,pelya/commandergenius,sexroute/commandergenius,dd00/commandergenius,def-/commandergenius,xyzz/vcmi-build,def-/commandergenius,def-/commandergenius,dd00/commandergenius,pelya/commandergenius,def-/commandergenius,pelya/commandergenius,xyzz/vcmi-build,pelya/commandergenius,dd00/commandergenius,pelya/commandergenius,sexroute/commandergenius
/* Simple DirectMedia Layer Java source code (C) 2009-2012 Sergii Pylypenko This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ package net.sourceforge.clonekeenplus; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import javax.microedition.khronos.opengles.GL11Ext; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGL11; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.MotionEvent; import android.view.KeyEvent; import android.view.InputDevice; import android.view.Window; import android.view.WindowManager; import android.os.Environment; import java.io.File; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.content.res.Resources; import android.content.res.AssetManager; import android.widget.Toast; import android.util.Log; import android.widget.TextView; import java.lang.Thread; import java.util.concurrent.locks.ReentrantLock; import android.os.Build; import java.lang.reflect.Method; import java.util.LinkedList; import java.nio.ByteBuffer; import java.nio.ByteOrder; class Mouse { public static final int LEFT_CLICK_NORMAL = 0; public static final int LEFT_CLICK_NEAR_CURSOR = 1; public static final int LEFT_CLICK_WITH_MULTITOUCH = 2; public static final int LEFT_CLICK_WITH_PRESSURE = 3; public static final int LEFT_CLICK_WITH_KEY = 4; public static final int LEFT_CLICK_WITH_TIMEOUT = 5; public static final int LEFT_CLICK_WITH_TAP = 6; public static final int LEFT_CLICK_WITH_TAP_OR_TIMEOUT = 7; public static final int RIGHT_CLICK_NONE = 0; public static final int RIGHT_CLICK_WITH_MULTITOUCH = 1; public static final int RIGHT_CLICK_WITH_PRESSURE = 2; public static final int RIGHT_CLICK_WITH_KEY = 3; public static final int RIGHT_CLICK_WITH_TIMEOUT = 4; public static final int SDL_FINGER_DOWN = 0; public static final int SDL_FINGER_UP = 1; public static final int SDL_FINGER_MOVE = 2; public static final int SDL_FINGER_HOVER = 3; public static final int ZOOM_NONE = 0; public static final int ZOOM_MAGNIFIER = 1; public static final int ZOOM_SCREEN_TRANSFORM = 2; public static final int ZOOM_FULLSCREEN_MAGNIFIER = 3; } abstract class DifferentTouchInput { public abstract void process(final MotionEvent event); public abstract void processGenericEvent(final MotionEvent event); public static boolean ExternalMouseDetected = false; public static DifferentTouchInput getInstance() { boolean multiTouchAvailable1 = false; boolean multiTouchAvailable2 = false; // Not checking for getX(int), getY(int) etc 'cause I'm lazy Method methods [] = MotionEvent.class.getDeclaredMethods(); for(Method m: methods) { if( m.getName().equals("getPointerCount") ) multiTouchAvailable1 = true; if( m.getName().equals("getPointerId") ) multiTouchAvailable2 = true; } try { Log.i("SDL", "Device model: " + android.os.Build.MODEL); if( android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH ) { if( DetectCrappyDragonRiseDatexGamepad() ) return CrappyDragonRiseDatexGamepadInputWhichNeedsItsOwnHandlerBecauseImTooCheapAndStupidToBuyProperGamepad.Holder.sInstance; return IcsTouchInput.Holder.sInstance; } if( android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD ) return GingerbreadTouchInput.Holder.sInstance; if (multiTouchAvailable1 && multiTouchAvailable2) return MultiTouchInput.Holder.sInstance; else return SingleTouchInput.Holder.sInstance; } catch( Exception e ) { try { if (multiTouchAvailable1 && multiTouchAvailable2) return MultiTouchInput.Holder.sInstance; else return SingleTouchInput.Holder.sInstance; } catch( Exception ee ) { return SingleTouchInput.Holder.sInstance; } } } private static boolean DetectCrappyDragonRiseDatexGamepad() { if( CrappyDragonRiseDatexGamepadInputWhichNeedsItsOwnHandlerBecauseImTooCheapAndStupidToBuyProperGamepad.Holder.sInstance == null ) return false; return CrappyDragonRiseDatexGamepadInputWhichNeedsItsOwnHandlerBecauseImTooCheapAndStupidToBuyProperGamepad.Holder.sInstance.detect(); } private static class SingleTouchInput extends DifferentTouchInput { private static class Holder { private static final SingleTouchInput sInstance = new SingleTouchInput(); } @Override public void processGenericEvent(final MotionEvent event) { process(event); } public void process(final MotionEvent event) { int action = -1; if( event.getAction() == MotionEvent.ACTION_DOWN ) action = Mouse.SDL_FINGER_DOWN; if( event.getAction() == MotionEvent.ACTION_UP ) action = Mouse.SDL_FINGER_UP; if( event.getAction() == MotionEvent.ACTION_MOVE ) action = Mouse.SDL_FINGER_MOVE; if ( action >= 0 ) DemoGLSurfaceView.nativeMotionEvent( (int)event.getX(), (int)event.getY(), action, 0, (int)(event.getPressure() * 1024.0f), (int)(event.getSize() * 1024.0f) ); } } private static class MultiTouchInput extends DifferentTouchInput { public static final int TOUCH_EVENTS_MAX = 16; // Max multitouch pointers private class touchEvent { public boolean down = false; public int x = 0; public int y = 0; public int pressure = 0; public int size = 0; } protected touchEvent touchEvents[]; MultiTouchInput() { touchEvents = new touchEvent[TOUCH_EVENTS_MAX]; for( int i = 0; i < TOUCH_EVENTS_MAX; i++ ) touchEvents[i] = new touchEvent(); } private static class Holder { private static final MultiTouchInput sInstance = new MultiTouchInput(); } public void processGenericEvent(final MotionEvent event) { process(event); } public void process(final MotionEvent event) { int action = -1; //Log.i("SDL", "Got motion event, type " + (int)(event.getAction()) + " X " + (int)event.getX() + " Y " + (int)event.getY()); if( (event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP || (event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_CANCEL ) { action = Mouse.SDL_FINGER_UP; for( int i = 0; i < TOUCH_EVENTS_MAX; i++ ) { if( touchEvents[i].down ) { touchEvents[i].down = false; DemoGLSurfaceView.nativeMotionEvent( touchEvents[i].x, touchEvents[i].y, action, i, touchEvents[i].pressure, touchEvents[i].size ); } } } if( (event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN ) { action = Mouse.SDL_FINGER_DOWN; for( int i = 0; i < event.getPointerCount(); i++ ) { int id = event.getPointerId(i); if( id >= TOUCH_EVENTS_MAX ) id = TOUCH_EVENTS_MAX - 1; touchEvents[id].down = true; touchEvents[id].x = (int)event.getX(i); touchEvents[id].y = (int)event.getY(i); touchEvents[id].pressure = (int)(event.getPressure(i) * 1024.0f); touchEvents[id].size = (int)(event.getSize(i) * 1024.0f); DemoGLSurfaceView.nativeMotionEvent( touchEvents[id].x, touchEvents[id].y, action, id, touchEvents[id].pressure, touchEvents[id].size ); } } if( (event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_MOVE || (event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_POINTER_DOWN || (event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_POINTER_UP ) { /* String s = "MOVE: ptrs " + event.getPointerCount(); for( int i = 0 ; i < event.getPointerCount(); i++ ) { s += " p" + event.getPointerId(i) + "=" + (int)event.getX(i) + ":" + (int)event.getY(i); } Log.i("SDL", s); */ int pointerReleased = -1; if( (event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_POINTER_UP ) pointerReleased = (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; for( int id = 0; id < TOUCH_EVENTS_MAX; id++ ) { int ii; for( ii = 0; ii < event.getPointerCount(); ii++ ) { if( id == event.getPointerId(ii) ) break; } if( ii >= event.getPointerCount() ) { // Up event if( touchEvents[id].down ) { action = Mouse.SDL_FINGER_UP; touchEvents[id].down = false; DemoGLSurfaceView.nativeMotionEvent( touchEvents[id].x, touchEvents[id].y, action, id, touchEvents[id].pressure, touchEvents[id].size ); } } else { if( pointerReleased == id && touchEvents[pointerReleased].down ) { action = Mouse.SDL_FINGER_UP; touchEvents[id].down = false; } else if( touchEvents[id].down ) { action = Mouse.SDL_FINGER_MOVE; } else { action = Mouse.SDL_FINGER_DOWN; touchEvents[id].down = true; } touchEvents[id].x = (int)event.getX(ii); touchEvents[id].y = (int)event.getY(ii); touchEvents[id].pressure = (int)(event.getPressure(ii) * 1024.0f); touchEvents[id].size = (int)(event.getSize(ii) * 1024.0f); DemoGLSurfaceView.nativeMotionEvent( touchEvents[id].x, touchEvents[id].y, action, id, touchEvents[id].pressure, touchEvents[id].size ); } } } if( (event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_HOVER_MOVE ) // Support bluetooth/USB mouse - available since Android 3.1 { // TODO: it is possible that multiple pointers return that event, but we're handling only pointer #0 if( touchEvents[0].down ) action = Mouse.SDL_FINGER_UP; else action = Mouse.SDL_FINGER_HOVER; touchEvents[0].down = false; touchEvents[0].x = (int)event.getX(); touchEvents[0].y = (int)event.getY(); touchEvents[0].pressure = 0; touchEvents[0].size = 0; DemoGLSurfaceView.nativeMotionEvent( touchEvents[0].x, touchEvents[0].y, action, 0, touchEvents[0].pressure, touchEvents[0].size ); } } } private static class GingerbreadTouchInput extends MultiTouchInput { private static class Holder { private static final GingerbreadTouchInput sInstance = new GingerbreadTouchInput(); } GingerbreadTouchInput() { super(); } public void process(final MotionEvent event) { boolean hwMouseEvent = ( (event.getSource() & InputDevice.SOURCE_MOUSE) == InputDevice.SOURCE_MOUSE || (event.getSource() & InputDevice.SOURCE_STYLUS) == InputDevice.SOURCE_STYLUS || (event.getMetaState() & KeyEvent.FLAG_TRACKING) != 0 ); // Hack to recognize Galaxy Note Gingerbread stylus if( ExternalMouseDetected != hwMouseEvent ) { ExternalMouseDetected = hwMouseEvent; DemoGLSurfaceView.nativeHardwareMouseDetected(hwMouseEvent ? 1 : 0); } super.process(event); } public void processGenericEvent(final MotionEvent event) { process(event); } } private static class IcsTouchInput extends GingerbreadTouchInput { private static class Holder { private static final IcsTouchInput sInstance = new IcsTouchInput(); } private int buttonState = 0; public void process(final MotionEvent event) { //Log.i("SDL", "Got motion event, type " + (int)(event.getAction()) + " X " + (int)event.getX() + " Y " + (int)event.getY() + " buttons " + buttonState + " source " + event.getSource()); int buttonStateNew = event.getButtonState(); if( buttonStateNew != buttonState ) { for( int i = 1; i <= MotionEvent.BUTTON_FORWARD; i *= 2 ) { if( (buttonStateNew & i) != (buttonState & i) ) DemoGLSurfaceView.nativeMouseButtonsPressed(i, ((buttonStateNew & i) == 0) ? 0 : 1); } buttonState = buttonStateNew; } super.process(event); // Push mouse coordinate first } public void processGenericEvent(final MotionEvent event) { // Joysticks are supported since Honeycomb, but I don't care about it, because very little devices have it if( (event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) == InputDevice.SOURCE_CLASS_JOYSTICK ) { DemoGLSurfaceView.nativeGamepadAnalogJoystickInput( event.getAxisValue(MotionEvent.AXIS_X), event.getAxisValue(MotionEvent.AXIS_Y), event.getAxisValue(MotionEvent.AXIS_Z), event.getAxisValue(MotionEvent.AXIS_RZ), event.getAxisValue(MotionEvent.AXIS_RTRIGGER), event.getAxisValue(MotionEvent.AXIS_LTRIGGER) ); return; } // Process mousewheel if( event.getAction() == MotionEvent.ACTION_SCROLL ) { int scrollX = Math.round(event.getAxisValue(MotionEvent.AXIS_HSCROLL)); int scrollY = Math.round(event.getAxisValue(MotionEvent.AXIS_VSCROLL)); DemoGLSurfaceView.nativeMouseWheel(scrollX, scrollY); return; } super.processGenericEvent(event); } } private static class CrappyDragonRiseDatexGamepadInputWhichNeedsItsOwnHandlerBecauseImTooCheapAndStupidToBuyProperGamepad extends IcsTouchInput { private static class Holder { private static final CrappyDragonRiseDatexGamepadInputWhichNeedsItsOwnHandlerBecauseImTooCheapAndStupidToBuyProperGamepad sInstance = new CrappyDragonRiseDatexGamepadInputWhichNeedsItsOwnHandlerBecauseImTooCheapAndStupidToBuyProperGamepad(); } float hatX = 0.0f, hatY = 0.0f; public void processGenericEvent(final MotionEvent event) { // Joysticks are supported since Honeycomb, but I don't care about it, because very little devices have it if( (event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) == InputDevice.SOURCE_CLASS_JOYSTICK ) { // event.getAxisValue(AXIS_HAT_X) and event.getAxisValue(AXIS_HAT_Y) are joystick arrow keys, they also send keyboard events DemoGLSurfaceView.nativeGamepadAnalogJoystickInput( event.getAxisValue(MotionEvent.AXIS_X), event.getAxisValue(MotionEvent.AXIS_Y), event.getAxisValue(MotionEvent.AXIS_RX), event.getAxisValue(MotionEvent.AXIS_RZ), 0, 0); if( event.getAxisValue(MotionEvent.AXIS_HAT_X) != hatX ) { hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X); if( hatX == 0.0f ) { DemoGLSurfaceView.nativeKey(KeyEvent.KEYCODE_DPAD_LEFT, 0); DemoGLSurfaceView.nativeKey(KeyEvent.KEYCODE_DPAD_RIGHT, 0); } else DemoGLSurfaceView.nativeKey(hatX < 0.0f ? KeyEvent.KEYCODE_DPAD_LEFT : KeyEvent.KEYCODE_DPAD_RIGHT, 1); } if( event.getAxisValue(MotionEvent.AXIS_HAT_Y) != hatY ) { hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y); if( hatY == 0.0f ) { DemoGLSurfaceView.nativeKey(KeyEvent.KEYCODE_DPAD_UP, 0); DemoGLSurfaceView.nativeKey(KeyEvent.KEYCODE_DPAD_DOWN, 0); } else DemoGLSurfaceView.nativeKey(hatY < 0.0f ? KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN, 1); } return; } super.processGenericEvent(event); } public boolean detect() { int[] devIds = InputDevice.getDeviceIds(); for( int id : devIds ) { InputDevice device = InputDevice.getDevice(id); if( device == null ) continue; System.out.println("libSDL: input device ID " + id + " type " + device.getSources() + " name " + device.getName() ); if( (device.getSources() & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD && (device.getSources() & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK && device.getName().indexOf("DragonRise Inc") == 0 ) { System.out.println("libSDL: Detected crappy DragonRise gamepad, enabling special hack for it. Please press button labeled 'Analog', otherwise it won't work, because it's cheap and crappy"); return true; } } return false; } } } class DemoRenderer extends GLSurfaceView_SDL.Renderer { public DemoRenderer(MainActivity _context) { context = _context; } public void onSurfaceCreated(GL10 gl, EGLConfig config) { Log.i("SDL", "libSDL: DemoRenderer.onSurfaceCreated(): paused " + mPaused + " mFirstTimeStart " + mFirstTimeStart ); mGlSurfaceCreated = true; mGl = gl; if( ! mPaused && ! mFirstTimeStart ) nativeGlContextRecreated(); mFirstTimeStart = false; } public void onSurfaceChanged(GL10 gl, int w, int h) { Log.i("SDL", "libSDL: DemoRenderer.onSurfaceChanged(): paused " + mPaused + " mFirstTimeStart " + mFirstTimeStart + " w " + w + " h " + h); if( w < h && Globals.HorizontalOrientation ) { // Sometimes when Android awakes from lockscreen, portrait orientation is kept int x = w; w = h; h = x; } mWidth = w; mHeight = h; mGl = gl; nativeResize(w, h, Globals.KeepAspectRatio ? 1 : 0); } public void onSurfaceDestroyed() { Log.i("SDL", "libSDL: DemoRenderer.onSurfaceDestroyed(): paused " + mPaused + " mFirstTimeStart " + mFirstTimeStart ); mGlSurfaceCreated = false; mGlContextLost = true; nativeGlContextLost(); }; public void onDrawFrame(GL10 gl) { mGl = gl; DrawLogo(mGl); SwapBuffers(); nativeInitJavaCallbacks(); // Make main thread priority lower so audio thread won't get underrun // Thread.currentThread().setPriority((Thread.currentThread().getPriority() + Thread.MIN_PRIORITY)/2); mGlContextLost = false; if(Globals.CompatibilityHacksStaticInit) MainActivity.LoadApplicationLibrary(context); Settings.Apply(context); accelerometer = new AccelerometerReader(context); // Tweak video thread priority, if user selected big audio buffer if(Globals.AudioBufferConfig >= 2) Thread.currentThread().setPriority( (Thread.NORM_PRIORITY + Thread.MIN_PRIORITY) / 2 ); // Lower than normal // Calls main() and never returns, hehe - we'll call eglSwapBuffers() from native code nativeInit( Globals.DataDir, Globals.CommandLine, ( (Globals.SwVideoMode && Globals.MultiThreadedVideo) || Globals.CompatibilityHacksVideo ) ? 1 : 0, android.os.Debug.isDebuggerConnected() ? 1 : 0 ); System.exit(0); // The main() returns here - I don't bother with deinit stuff, just terminate process } public int swapBuffers() // Called from native code { if( ! super.SwapBuffers() && Globals.NonBlockingSwapBuffers ) { if(mRatelimitTouchEvents) { synchronized(this) { this.notify(); } } return 0; } if(mGlContextLost) { mGlContextLost = false; Settings.SetupTouchscreenKeyboardGraphics(context); // Reload on-screen buttons graphics DrawLogo(mGl); super.SwapBuffers(); } // Unblock event processing thread only after we've finished rendering if(mRatelimitTouchEvents) { synchronized(this) { this.notify(); } } if( context.isScreenKeyboardShown() ) { try { Thread.sleep(50); // Give some time to the keyboard input thread } catch(Exception e) { }; } return 1; } public void showScreenKeyboardWithoutTextInputField() // Called from native code { class Callback implements Runnable { public MainActivity parent; public void run() { parent.showScreenKeyboardWithoutTextInputField(); } } Callback cb = new Callback(); cb.parent = context; context.runOnUiThread(cb); } public void showScreenKeyboard(final String oldText, int sendBackspace) // Called from native code { class Callback implements Runnable { public MainActivity parent; public String oldText; public boolean sendBackspace; public void run() { parent.showScreenKeyboard(oldText, sendBackspace); } } Callback cb = new Callback(); cb.parent = context; cb.oldText = oldText; cb.sendBackspace = (sendBackspace != 0); context.runOnUiThread(cb); } public void hideScreenKeyboard() // Called from native code { class Callback implements Runnable { public MainActivity parent; public void run() { parent.hideScreenKeyboard(); } } Callback cb = new Callback(); cb.parent = context; context.runOnUiThread(cb); } public int isScreenKeyboardShown() // Called from native code { return context.isScreenKeyboardShown() ? 1 : 0; } public void setScreenKeyboardHintMessage(String s) { context.setScreenKeyboardHintMessage(s); } public void startAccelerometerGyroscope(int started) { accelerometer.openedBySDL = (started != 0); if( accelerometer.openedBySDL && !mPaused ) accelerometer.start(); else accelerometer.stop(); } public void exitApp() { nativeDone(); } public void getAdvertisementParams(int params[]) { context.getAdvertisementParams(params); } public void setAdvertisementVisible(int visible) { context.setAdvertisementVisible(visible); } public void setAdvertisementPosition(int left, int top) { context.setAdvertisementPosition(left, top); } public void requestNewAdvertisement() { context.requestNewAdvertisement(); } private int PowerOf2(int i) { int value = 1; while (value < i) value <<= 1; return value; } public void DrawLogo(GL10 gl) { /* // TODO: this not quite works, as it seems BitmapDrawable bmp = null; try { bmp = new BitmapDrawable(context.getAssets().open("logo.png")); } catch(Exception e) { bmp = new BitmapDrawable(context.getResources().openRawResource(R.drawable.publisherlogo)); } int width = bmp.getBitmap().getWidth(); int height = bmp.getBitmap().getHeight(); ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4 * width * height); //byteBuffer.order(ByteOrder.BIG_ENDIAN); bmp.getBitmap().copyPixelsToBuffer(byteBuffer); byteBuffer.position(0); gl.glViewport(0, 0, mWidth, mHeight); gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT); gl.glColor4x(0x10000, 0x10000, 0x10000, 0x10000); gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1); gl.glEnable(GL10.GL_TEXTURE_2D); int textureName = -1; int mTextureNameWorkspace[] = new int[1]; int mCropWorkspace[] = new int[4]; gl.glGenTextures(1, mTextureNameWorkspace, 0); textureName = mTextureNameWorkspace[0]; gl.glBindTexture(GL10.GL_TEXTURE_2D, textureName); gl.glActiveTexture(textureName); gl.glClientActiveTexture(textureName); gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, GL10.GL_RGBA, PowerOf2(width), PowerOf2(height), 0, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, null); gl.glTexSubImage2D(GL10.GL_TEXTURE_2D, 0, 0, 0, width, height, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, byteBuffer); mCropWorkspace[0] = 0; // u mCropWorkspace[1] = height; // v mCropWorkspace[2] = width; mCropWorkspace[3] = -height; ((GL11) gl).glTexParameteriv(GL10.GL_TEXTURE_2D, GL11Ext.GL_TEXTURE_CROP_RECT_OES, mCropWorkspace, 0); ((GL11Ext) gl).glDrawTexiOES(0, -mHeight, 0, mWidth, mHeight); gl.glActiveTexture(0); gl.glClientActiveTexture(0); gl.glBindTexture(GL10.GL_TEXTURE_2D, 0); gl.glDeleteTextures(1, mTextureNameWorkspace, 0); gl.glFlush(); */ } private native void nativeInitJavaCallbacks(); private native void nativeInit(String CurrentPath, String CommandLine, int multiThreadedVideo, int isDebuggerConnected); private native void nativeResize(int w, int h, int keepAspectRatio); private native void nativeDone(); private native void nativeGlContextLost(); public native void nativeGlContextRecreated(); public native void nativeGlContextLostAsyncEvent(); public static native void nativeTextInput( int ascii, int unicode ); public static native void nativeTextInputFinished(); private MainActivity context = null; public AccelerometerReader accelerometer = null; private GL10 mGl = null; private EGL10 mEgl = null; private EGLDisplay mEglDisplay = null; private EGLSurface mEglSurface = null; private EGLContext mEglContext = null; private boolean mGlContextLost = false; public boolean mGlSurfaceCreated = false; public boolean mPaused = false; private boolean mFirstTimeStart = true; public int mWidth = 0; public int mHeight = 0; public static final boolean mRatelimitTouchEvents = true; //(Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO); } class DemoGLSurfaceView extends GLSurfaceView_SDL { public DemoGLSurfaceView(MainActivity context) { super(context); mParent = context; touchInput = DifferentTouchInput.getInstance(); setEGLConfigChooser(Globals.VideoDepthBpp, Globals.NeedDepthBuffer, Globals.NeedStencilBuffer, Globals.NeedGles2); mRenderer = new DemoRenderer(context); setRenderer(mRenderer); } @Override public boolean onTouchEvent(final MotionEvent event) { touchInput.process(event); if( DemoRenderer.mRatelimitTouchEvents ) { limitEventRate(event); } return true; }; @Override public boolean onGenericMotionEvent (final MotionEvent event) { touchInput.processGenericEvent(event); if( DemoRenderer.mRatelimitTouchEvents ) { limitEventRate(event); } return true; } public void limitEventRate(final MotionEvent event) { // Wait a bit, and try to synchronize to app framerate, or event thread will eat all CPU and we'll lose FPS // With Froyo the rate of touch events seems to be limited by OS, but they are arriving faster then we're redrawing anyway if((event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_HOVER_MOVE)) { synchronized(mRenderer) { try { mRenderer.wait(300L); // And sometimes the app decides not to render at all, so this timeout should not be big. } catch (InterruptedException e) { } } } } public void exitApp() { mRenderer.exitApp(); }; @Override public void onPause() { if(mRenderer.mPaused) return; mRenderer.mPaused = true; mRenderer.nativeGlContextLostAsyncEvent(); if( mRenderer.accelerometer != null ) // For some reason it crashes here often - are we getting this event before initialization? mRenderer.accelerometer.stop(); super.onPause(); }; public boolean isPaused() { return mRenderer.mPaused; } @Override public void onResume() { if(!mRenderer.mPaused) return; mRenderer.mPaused = false; super.onResume(); Log.i("SDL", "libSDL: DemoGLSurfaceView.onResume(): mRenderer.mGlSurfaceCreated " + mRenderer.mGlSurfaceCreated + " mRenderer.mPaused " + mRenderer.mPaused); if( mRenderer.mGlSurfaceCreated && ! mRenderer.mPaused || Globals.NonBlockingSwapBuffers ) mRenderer.nativeGlContextRecreated(); if( mRenderer.accelerometer != null && mRenderer.accelerometer.openedBySDL ) // For some reason it crashes here often - are we getting this event before initialization? mRenderer.accelerometer.start(); }; // This seems like redundant code - it handled in MainActivity.java @Override public boolean onKeyDown(int keyCode, final KeyEvent event) { //Log.i("SDL", "Got key down event, id " + keyCode + " meta " + event.getMetaState() + " event " + event.toString()); if( nativeKey( keyCode, 1 ) == 0 ) return super.onKeyDown(keyCode, event); return true; } @Override public boolean onKeyUp(int keyCode, final KeyEvent event) { //Log.i("SDL", "Got key up event, id " + keyCode + " meta " + event.getMetaState()); if( nativeKey( keyCode, 0 ) == 0 ) return super.onKeyUp(keyCode, event); return true; } DemoRenderer mRenderer; MainActivity mParent; DifferentTouchInput touchInput = null; public static native void nativeMotionEvent( int x, int y, int action, int pointerId, int pressure, int radius ); public static native int nativeKey( int keyCode, int down ); public static native void nativeTouchpad( int x, int y, int down, int multitouch ); public static native void initJavaCallbacks(); public static native void nativeHardwareMouseDetected( int detected ); public static native void nativeMouseButtonsPressed( int buttonId, int pressedState ); public static native void nativeMouseWheel( int scrollX, int scrollY ); public static native void nativeGamepadAnalogJoystickInput( float stick1x, float stick1y, float stick2x, float stick2y, float rtrigger, float ltrigger ); }
project/java/Video.java
/* Simple DirectMedia Layer Java source code (C) 2009-2012 Sergii Pylypenko This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ package net.sourceforge.clonekeenplus; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import javax.microedition.khronos.opengles.GL11Ext; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGL11; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.MotionEvent; import android.view.KeyEvent; import android.view.InputDevice; import android.view.Window; import android.view.WindowManager; import android.os.Environment; import java.io.File; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.content.res.Resources; import android.content.res.AssetManager; import android.widget.Toast; import android.util.Log; import android.widget.TextView; import java.lang.Thread; import java.util.concurrent.locks.ReentrantLock; import android.os.Build; import java.lang.reflect.Method; import java.util.LinkedList; import java.nio.ByteBuffer; import java.nio.ByteOrder; class Mouse { public static final int LEFT_CLICK_NORMAL = 0; public static final int LEFT_CLICK_NEAR_CURSOR = 1; public static final int LEFT_CLICK_WITH_MULTITOUCH = 2; public static final int LEFT_CLICK_WITH_PRESSURE = 3; public static final int LEFT_CLICK_WITH_KEY = 4; public static final int LEFT_CLICK_WITH_TIMEOUT = 5; public static final int LEFT_CLICK_WITH_TAP = 6; public static final int LEFT_CLICK_WITH_TAP_OR_TIMEOUT = 7; public static final int RIGHT_CLICK_NONE = 0; public static final int RIGHT_CLICK_WITH_MULTITOUCH = 1; public static final int RIGHT_CLICK_WITH_PRESSURE = 2; public static final int RIGHT_CLICK_WITH_KEY = 3; public static final int RIGHT_CLICK_WITH_TIMEOUT = 4; public static final int SDL_FINGER_DOWN = 0; public static final int SDL_FINGER_UP = 1; public static final int SDL_FINGER_MOVE = 2; public static final int SDL_FINGER_HOVER = 3; public static final int ZOOM_NONE = 0; public static final int ZOOM_MAGNIFIER = 1; public static final int ZOOM_SCREEN_TRANSFORM = 2; public static final int ZOOM_FULLSCREEN_MAGNIFIER = 3; } abstract class DifferentTouchInput { public abstract void process(final MotionEvent event); public abstract void processGenericEvent(final MotionEvent event); public static boolean ExternalMouseDetected = false; public static DifferentTouchInput getInstance() { boolean multiTouchAvailable1 = false; boolean multiTouchAvailable2 = false; // Not checking for getX(int), getY(int) etc 'cause I'm lazy Method methods [] = MotionEvent.class.getDeclaredMethods(); for(Method m: methods) { if( m.getName().equals("getPointerCount") ) multiTouchAvailable1 = true; if( m.getName().equals("getPointerId") ) multiTouchAvailable2 = true; } try { Log.i("SDL", "Device model: " + android.os.Build.MODEL); if( android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH ) { if( DetectCrappyDragonRiseDatexGamepad() ) return CrappyDragonRiseDatexGamepadInputWhichNeedsItsOwnHandlerBecauseImTooCheapAndStupidToBuyProperGamepad.Holder.sInstance; return IcsTouchInput.Holder.sInstance; } if( android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD ) return GingerbreadTouchInput.Holder.sInstance; if (multiTouchAvailable1 && multiTouchAvailable2) return MultiTouchInput.Holder.sInstance; else return SingleTouchInput.Holder.sInstance; } catch( Exception e ) { try { if (multiTouchAvailable1 && multiTouchAvailable2) return MultiTouchInput.Holder.sInstance; else return SingleTouchInput.Holder.sInstance; } catch( Exception ee ) { return SingleTouchInput.Holder.sInstance; } } } private static boolean DetectCrappyDragonRiseDatexGamepad() { if( CrappyDragonRiseDatexGamepadInputWhichNeedsItsOwnHandlerBecauseImTooCheapAndStupidToBuyProperGamepad.Holder.sInstance == null ) return false; return CrappyDragonRiseDatexGamepadInputWhichNeedsItsOwnHandlerBecauseImTooCheapAndStupidToBuyProperGamepad.Holder.sInstance.detect(); } private static class SingleTouchInput extends DifferentTouchInput { private static class Holder { private static final SingleTouchInput sInstance = new SingleTouchInput(); } @Override public void processGenericEvent(final MotionEvent event) { process(event); } public void process(final MotionEvent event) { int action = -1; if( event.getAction() == MotionEvent.ACTION_DOWN ) action = Mouse.SDL_FINGER_DOWN; if( event.getAction() == MotionEvent.ACTION_UP ) action = Mouse.SDL_FINGER_UP; if( event.getAction() == MotionEvent.ACTION_MOVE ) action = Mouse.SDL_FINGER_MOVE; if ( action >= 0 ) DemoGLSurfaceView.nativeMotionEvent( (int)event.getX(), (int)event.getY(), action, 0, (int)(event.getPressure() * 1000.0), (int)(event.getSize() * 1000.0) ); } } private static class MultiTouchInput extends DifferentTouchInput { public static final int TOUCH_EVENTS_MAX = 16; // Max multitouch pointers private class touchEvent { public boolean down = false; public int x = 0; public int y = 0; public int pressure = 0; public int size = 0; } protected touchEvent touchEvents[]; MultiTouchInput() { touchEvents = new touchEvent[TOUCH_EVENTS_MAX]; for( int i = 0; i < TOUCH_EVENTS_MAX; i++ ) touchEvents[i] = new touchEvent(); } private static class Holder { private static final MultiTouchInput sInstance = new MultiTouchInput(); } public void processGenericEvent(final MotionEvent event) { process(event); } public void process(final MotionEvent event) { int action = -1; //Log.i("SDL", "Got motion event, type " + (int)(event.getAction()) + " X " + (int)event.getX() + " Y " + (int)event.getY()); if( (event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP || (event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_CANCEL ) { action = Mouse.SDL_FINGER_UP; for( int i = 0; i < TOUCH_EVENTS_MAX; i++ ) { if( touchEvents[i].down ) { touchEvents[i].down = false; DemoGLSurfaceView.nativeMotionEvent( touchEvents[i].x, touchEvents[i].y, action, i, touchEvents[i].pressure, touchEvents[i].size ); } } } if( (event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN ) { action = Mouse.SDL_FINGER_DOWN; for( int i = 0; i < event.getPointerCount(); i++ ) { int id = event.getPointerId(i); if( id >= TOUCH_EVENTS_MAX ) id = TOUCH_EVENTS_MAX - 1; touchEvents[id].down = true; touchEvents[id].x = (int)event.getX(i); touchEvents[id].y = (int)event.getY(i); touchEvents[id].pressure = (int)(event.getPressure(i) * 1000.0); touchEvents[id].size = (int)(event.getSize(i) * 1000.0); DemoGLSurfaceView.nativeMotionEvent( touchEvents[id].x, touchEvents[id].y, action, id, touchEvents[id].pressure, touchEvents[id].size ); } } if( (event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_MOVE || (event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_POINTER_DOWN || (event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_POINTER_UP ) { /* String s = "MOVE: ptrs " + event.getPointerCount(); for( int i = 0 ; i < event.getPointerCount(); i++ ) { s += " p" + event.getPointerId(i) + "=" + (int)event.getX(i) + ":" + (int)event.getY(i); } Log.i("SDL", s); */ int pointerReleased = -1; if( (event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_POINTER_UP ) pointerReleased = (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; for( int id = 0; id < TOUCH_EVENTS_MAX; id++ ) { int ii; for( ii = 0; ii < event.getPointerCount(); ii++ ) { if( id == event.getPointerId(ii) ) break; } if( ii >= event.getPointerCount() ) { // Up event if( touchEvents[id].down ) { action = Mouse.SDL_FINGER_UP; touchEvents[id].down = false; DemoGLSurfaceView.nativeMotionEvent( touchEvents[id].x, touchEvents[id].y, action, id, touchEvents[id].pressure, touchEvents[id].size ); } } else { if( pointerReleased == id && touchEvents[pointerReleased].down ) { action = Mouse.SDL_FINGER_UP; touchEvents[id].down = false; } else if( touchEvents[id].down ) { action = Mouse.SDL_FINGER_MOVE; } else { action = Mouse.SDL_FINGER_DOWN; touchEvents[id].down = true; } touchEvents[id].x = (int)event.getX(ii); touchEvents[id].y = (int)event.getY(ii); touchEvents[id].pressure = (int)(event.getPressure(ii) * 1000.0); touchEvents[id].size = (int)(event.getSize(ii) * 1000.0); DemoGLSurfaceView.nativeMotionEvent( touchEvents[id].x, touchEvents[id].y, action, id, touchEvents[id].pressure, touchEvents[id].size ); } } } if( (event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_HOVER_MOVE ) // Support bluetooth/USB mouse - available since Android 3.1 { // TODO: it is possible that multiple pointers return that event, but we're handling only pointer #0 if( touchEvents[0].down ) action = Mouse.SDL_FINGER_UP; else action = Mouse.SDL_FINGER_HOVER; touchEvents[0].down = false; touchEvents[0].x = (int)event.getX(); touchEvents[0].y = (int)event.getY(); touchEvents[0].pressure = 0; touchEvents[0].size = 0; DemoGLSurfaceView.nativeMotionEvent( touchEvents[0].x, touchEvents[0].y, action, 0, touchEvents[0].pressure, touchEvents[0].size ); } } } private static class GingerbreadTouchInput extends MultiTouchInput { private static class Holder { private static final GingerbreadTouchInput sInstance = new GingerbreadTouchInput(); } GingerbreadTouchInput() { super(); } public void process(final MotionEvent event) { boolean hwMouseEvent = ( (event.getSource() & InputDevice.SOURCE_MOUSE) == InputDevice.SOURCE_MOUSE || (event.getSource() & InputDevice.SOURCE_STYLUS) == InputDevice.SOURCE_STYLUS || (event.getMetaState() & KeyEvent.FLAG_TRACKING) != 0 ); // Hack to recognize Galaxy Note Gingerbread stylus if( ExternalMouseDetected != hwMouseEvent ) { ExternalMouseDetected = hwMouseEvent; DemoGLSurfaceView.nativeHardwareMouseDetected(hwMouseEvent ? 1 : 0); } super.process(event); } public void processGenericEvent(final MotionEvent event) { process(event); } } private static class IcsTouchInput extends GingerbreadTouchInput { private static class Holder { private static final IcsTouchInput sInstance = new IcsTouchInput(); } private int buttonState = 0; public void process(final MotionEvent event) { //Log.i("SDL", "Got motion event, type " + (int)(event.getAction()) + " X " + (int)event.getX() + " Y " + (int)event.getY() + " buttons " + buttonState + " source " + event.getSource()); int buttonStateNew = event.getButtonState(); if( buttonStateNew != buttonState ) { for( int i = 1; i <= MotionEvent.BUTTON_FORWARD; i *= 2 ) { if( (buttonStateNew & i) != (buttonState & i) ) DemoGLSurfaceView.nativeMouseButtonsPressed(i, ((buttonStateNew & i) == 0) ? 0 : 1); } buttonState = buttonStateNew; } super.process(event); // Push mouse coordinate first } public void processGenericEvent(final MotionEvent event) { // Joysticks are supported since Honeycomb, but I don't care about it, because very little devices have it if( (event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) == InputDevice.SOURCE_CLASS_JOYSTICK ) { DemoGLSurfaceView.nativeGamepadAnalogJoystickInput( event.getAxisValue(MotionEvent.AXIS_X), event.getAxisValue(MotionEvent.AXIS_Y), event.getAxisValue(MotionEvent.AXIS_Z), event.getAxisValue(MotionEvent.AXIS_RZ), event.getAxisValue(MotionEvent.AXIS_RTRIGGER), event.getAxisValue(MotionEvent.AXIS_LTRIGGER) ); return; } // Process mousewheel if( event.getAction() == MotionEvent.ACTION_SCROLL ) { int scrollX = Math.round(event.getAxisValue(MotionEvent.AXIS_HSCROLL)); int scrollY = Math.round(event.getAxisValue(MotionEvent.AXIS_VSCROLL)); DemoGLSurfaceView.nativeMouseWheel(scrollX, scrollY); return; } super.processGenericEvent(event); } } private static class CrappyDragonRiseDatexGamepadInputWhichNeedsItsOwnHandlerBecauseImTooCheapAndStupidToBuyProperGamepad extends IcsTouchInput { private static class Holder { private static final CrappyDragonRiseDatexGamepadInputWhichNeedsItsOwnHandlerBecauseImTooCheapAndStupidToBuyProperGamepad sInstance = new CrappyDragonRiseDatexGamepadInputWhichNeedsItsOwnHandlerBecauseImTooCheapAndStupidToBuyProperGamepad(); } float hatX = 0.0f, hatY = 0.0f; public void processGenericEvent(final MotionEvent event) { // Joysticks are supported since Honeycomb, but I don't care about it, because very little devices have it if( (event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) == InputDevice.SOURCE_CLASS_JOYSTICK ) { // event.getAxisValue(AXIS_HAT_X) and event.getAxisValue(AXIS_HAT_Y) are joystick arrow keys, they also send keyboard events DemoGLSurfaceView.nativeGamepadAnalogJoystickInput( event.getAxisValue(MotionEvent.AXIS_X), event.getAxisValue(MotionEvent.AXIS_Y), event.getAxisValue(MotionEvent.AXIS_RX), event.getAxisValue(MotionEvent.AXIS_RZ), 0, 0); if( event.getAxisValue(MotionEvent.AXIS_HAT_X) != hatX ) { hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X); if( hatX == 0.0f ) { DemoGLSurfaceView.nativeKey(KeyEvent.KEYCODE_DPAD_LEFT, 0); DemoGLSurfaceView.nativeKey(KeyEvent.KEYCODE_DPAD_RIGHT, 0); } else DemoGLSurfaceView.nativeKey(hatX < 0.0f ? KeyEvent.KEYCODE_DPAD_LEFT : KeyEvent.KEYCODE_DPAD_RIGHT, 1); } if( event.getAxisValue(MotionEvent.AXIS_HAT_Y) != hatY ) { hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y); if( hatY == 0.0f ) { DemoGLSurfaceView.nativeKey(KeyEvent.KEYCODE_DPAD_UP, 0); DemoGLSurfaceView.nativeKey(KeyEvent.KEYCODE_DPAD_DOWN, 0); } else DemoGLSurfaceView.nativeKey(hatY < 0.0f ? KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN, 1); } return; } super.processGenericEvent(event); } public boolean detect() { int[] devIds = InputDevice.getDeviceIds(); for( int id : devIds ) { InputDevice device = InputDevice.getDevice(id); if( device == null ) continue; System.out.println("libSDL: input device ID " + id + " type " + device.getSources() + " name " + device.getName() ); if( (device.getSources() & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD && (device.getSources() & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK && device.getName().indexOf("DragonRise Inc") == 0 ) { System.out.println("libSDL: Detected crappy DragonRise gamepad, enabling special hack for it. Please press button labeled 'Analog', otherwise it won't work, because it's cheap and crappy"); return true; } } return false; } } } class DemoRenderer extends GLSurfaceView_SDL.Renderer { public DemoRenderer(MainActivity _context) { context = _context; } public void onSurfaceCreated(GL10 gl, EGLConfig config) { Log.i("SDL", "libSDL: DemoRenderer.onSurfaceCreated(): paused " + mPaused + " mFirstTimeStart " + mFirstTimeStart ); mGlSurfaceCreated = true; mGl = gl; if( ! mPaused && ! mFirstTimeStart ) nativeGlContextRecreated(); mFirstTimeStart = false; } public void onSurfaceChanged(GL10 gl, int w, int h) { Log.i("SDL", "libSDL: DemoRenderer.onSurfaceChanged(): paused " + mPaused + " mFirstTimeStart " + mFirstTimeStart + " w " + w + " h " + h); if( w < h && Globals.HorizontalOrientation ) { // Sometimes when Android awakes from lockscreen, portrait orientation is kept int x = w; w = h; h = x; } mWidth = w; mHeight = h; mGl = gl; nativeResize(w, h, Globals.KeepAspectRatio ? 1 : 0); } public void onSurfaceDestroyed() { Log.i("SDL", "libSDL: DemoRenderer.onSurfaceDestroyed(): paused " + mPaused + " mFirstTimeStart " + mFirstTimeStart ); mGlSurfaceCreated = false; mGlContextLost = true; nativeGlContextLost(); }; public void onDrawFrame(GL10 gl) { mGl = gl; DrawLogo(mGl); SwapBuffers(); nativeInitJavaCallbacks(); // Make main thread priority lower so audio thread won't get underrun // Thread.currentThread().setPriority((Thread.currentThread().getPriority() + Thread.MIN_PRIORITY)/2); mGlContextLost = false; if(Globals.CompatibilityHacksStaticInit) MainActivity.LoadApplicationLibrary(context); Settings.Apply(context); accelerometer = new AccelerometerReader(context); // Tweak video thread priority, if user selected big audio buffer if(Globals.AudioBufferConfig >= 2) Thread.currentThread().setPriority( (Thread.NORM_PRIORITY + Thread.MIN_PRIORITY) / 2 ); // Lower than normal // Calls main() and never returns, hehe - we'll call eglSwapBuffers() from native code nativeInit( Globals.DataDir, Globals.CommandLine, ( (Globals.SwVideoMode && Globals.MultiThreadedVideo) || Globals.CompatibilityHacksVideo ) ? 1 : 0, android.os.Debug.isDebuggerConnected() ? 1 : 0 ); System.exit(0); // The main() returns here - I don't bother with deinit stuff, just terminate process } public int swapBuffers() // Called from native code { if( ! super.SwapBuffers() && Globals.NonBlockingSwapBuffers ) { if(mRatelimitTouchEvents) { synchronized(this) { this.notify(); } } return 0; } if(mGlContextLost) { mGlContextLost = false; Settings.SetupTouchscreenKeyboardGraphics(context); // Reload on-screen buttons graphics DrawLogo(mGl); super.SwapBuffers(); } // Unblock event processing thread only after we've finished rendering if(mRatelimitTouchEvents) { synchronized(this) { this.notify(); } } if( context.isScreenKeyboardShown() ) { try { Thread.sleep(50); // Give some time to the keyboard input thread } catch(Exception e) { }; } return 1; } public void showScreenKeyboardWithoutTextInputField() // Called from native code { class Callback implements Runnable { public MainActivity parent; public void run() { parent.showScreenKeyboardWithoutTextInputField(); } } Callback cb = new Callback(); cb.parent = context; context.runOnUiThread(cb); } public void showScreenKeyboard(final String oldText, int sendBackspace) // Called from native code { class Callback implements Runnable { public MainActivity parent; public String oldText; public boolean sendBackspace; public void run() { parent.showScreenKeyboard(oldText, sendBackspace); } } Callback cb = new Callback(); cb.parent = context; cb.oldText = oldText; cb.sendBackspace = (sendBackspace != 0); context.runOnUiThread(cb); } public void hideScreenKeyboard() // Called from native code { class Callback implements Runnable { public MainActivity parent; public void run() { parent.hideScreenKeyboard(); } } Callback cb = new Callback(); cb.parent = context; context.runOnUiThread(cb); } public int isScreenKeyboardShown() // Called from native code { return context.isScreenKeyboardShown() ? 1 : 0; } public void setScreenKeyboardHintMessage(String s) { context.setScreenKeyboardHintMessage(s); } public void startAccelerometerGyroscope(int started) { accelerometer.openedBySDL = (started != 0); if( accelerometer.openedBySDL && !mPaused ) accelerometer.start(); else accelerometer.stop(); } public void exitApp() { nativeDone(); } public void getAdvertisementParams(int params[]) { context.getAdvertisementParams(params); } public void setAdvertisementVisible(int visible) { context.setAdvertisementVisible(visible); } public void setAdvertisementPosition(int left, int top) { context.setAdvertisementPosition(left, top); } public void requestNewAdvertisement() { context.requestNewAdvertisement(); } private int PowerOf2(int i) { int value = 1; while (value < i) value <<= 1; return value; } public void DrawLogo(GL10 gl) { /* // TODO: this not quite works, as it seems BitmapDrawable bmp = null; try { bmp = new BitmapDrawable(context.getAssets().open("logo.png")); } catch(Exception e) { bmp = new BitmapDrawable(context.getResources().openRawResource(R.drawable.publisherlogo)); } int width = bmp.getBitmap().getWidth(); int height = bmp.getBitmap().getHeight(); ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4 * width * height); //byteBuffer.order(ByteOrder.BIG_ENDIAN); bmp.getBitmap().copyPixelsToBuffer(byteBuffer); byteBuffer.position(0); gl.glViewport(0, 0, mWidth, mHeight); gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT); gl.glColor4x(0x10000, 0x10000, 0x10000, 0x10000); gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1); gl.glEnable(GL10.GL_TEXTURE_2D); int textureName = -1; int mTextureNameWorkspace[] = new int[1]; int mCropWorkspace[] = new int[4]; gl.glGenTextures(1, mTextureNameWorkspace, 0); textureName = mTextureNameWorkspace[0]; gl.glBindTexture(GL10.GL_TEXTURE_2D, textureName); gl.glActiveTexture(textureName); gl.glClientActiveTexture(textureName); gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, GL10.GL_RGBA, PowerOf2(width), PowerOf2(height), 0, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, null); gl.glTexSubImage2D(GL10.GL_TEXTURE_2D, 0, 0, 0, width, height, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, byteBuffer); mCropWorkspace[0] = 0; // u mCropWorkspace[1] = height; // v mCropWorkspace[2] = width; mCropWorkspace[3] = -height; ((GL11) gl).glTexParameteriv(GL10.GL_TEXTURE_2D, GL11Ext.GL_TEXTURE_CROP_RECT_OES, mCropWorkspace, 0); ((GL11Ext) gl).glDrawTexiOES(0, -mHeight, 0, mWidth, mHeight); gl.glActiveTexture(0); gl.glClientActiveTexture(0); gl.glBindTexture(GL10.GL_TEXTURE_2D, 0); gl.glDeleteTextures(1, mTextureNameWorkspace, 0); gl.glFlush(); */ } private native void nativeInitJavaCallbacks(); private native void nativeInit(String CurrentPath, String CommandLine, int multiThreadedVideo, int isDebuggerConnected); private native void nativeResize(int w, int h, int keepAspectRatio); private native void nativeDone(); private native void nativeGlContextLost(); public native void nativeGlContextRecreated(); public native void nativeGlContextLostAsyncEvent(); public static native void nativeTextInput( int ascii, int unicode ); public static native void nativeTextInputFinished(); private MainActivity context = null; public AccelerometerReader accelerometer = null; private GL10 mGl = null; private EGL10 mEgl = null; private EGLDisplay mEglDisplay = null; private EGLSurface mEglSurface = null; private EGLContext mEglContext = null; private boolean mGlContextLost = false; public boolean mGlSurfaceCreated = false; public boolean mPaused = false; private boolean mFirstTimeStart = true; public int mWidth = 0; public int mHeight = 0; public static final boolean mRatelimitTouchEvents = true; //(Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO); } class DemoGLSurfaceView extends GLSurfaceView_SDL { public DemoGLSurfaceView(MainActivity context) { super(context); mParent = context; touchInput = DifferentTouchInput.getInstance(); setEGLConfigChooser(Globals.VideoDepthBpp, Globals.NeedDepthBuffer, Globals.NeedStencilBuffer, Globals.NeedGles2); mRenderer = new DemoRenderer(context); setRenderer(mRenderer); } @Override public boolean onTouchEvent(final MotionEvent event) { touchInput.process(event); if( DemoRenderer.mRatelimitTouchEvents ) { limitEventRate(event); } return true; }; @Override public boolean onGenericMotionEvent (final MotionEvent event) { touchInput.processGenericEvent(event); if( DemoRenderer.mRatelimitTouchEvents ) { limitEventRate(event); } return true; } public void limitEventRate(final MotionEvent event) { // Wait a bit, and try to synchronize to app framerate, or event thread will eat all CPU and we'll lose FPS // With Froyo the rate of touch events seems to be limited by OS, but they are arriving faster then we're redrawing anyway if((event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_HOVER_MOVE)) { synchronized(mRenderer) { try { mRenderer.wait(300L); // And sometimes the app decides not to render at all, so this timeout should not be big. } catch (InterruptedException e) { } } } } public void exitApp() { mRenderer.exitApp(); }; @Override public void onPause() { if(mRenderer.mPaused) return; mRenderer.mPaused = true; mRenderer.nativeGlContextLostAsyncEvent(); if( mRenderer.accelerometer != null ) // For some reason it crashes here often - are we getting this event before initialization? mRenderer.accelerometer.stop(); super.onPause(); }; public boolean isPaused() { return mRenderer.mPaused; } @Override public void onResume() { if(!mRenderer.mPaused) return; mRenderer.mPaused = false; super.onResume(); Log.i("SDL", "libSDL: DemoGLSurfaceView.onResume(): mRenderer.mGlSurfaceCreated " + mRenderer.mGlSurfaceCreated + " mRenderer.mPaused " + mRenderer.mPaused); if( mRenderer.mGlSurfaceCreated && ! mRenderer.mPaused || Globals.NonBlockingSwapBuffers ) mRenderer.nativeGlContextRecreated(); if( mRenderer.accelerometer != null && mRenderer.accelerometer.openedBySDL ) // For some reason it crashes here often - are we getting this event before initialization? mRenderer.accelerometer.start(); }; // This seems like redundant code - it handled in MainActivity.java @Override public boolean onKeyDown(int keyCode, final KeyEvent event) { //Log.i("SDL", "Got key down event, id " + keyCode + " meta " + event.getMetaState() + " event " + event.toString()); if( nativeKey( keyCode, 1 ) == 0 ) return super.onKeyDown(keyCode, event); return true; } @Override public boolean onKeyUp(int keyCode, final KeyEvent event) { //Log.i("SDL", "Got key up event, id " + keyCode + " meta " + event.getMetaState()); if( nativeKey( keyCode, 0 ) == 0 ) return super.onKeyUp(keyCode, event); return true; } DemoRenderer mRenderer; MainActivity mParent; DifferentTouchInput touchInput = null; public static native void nativeMotionEvent( int x, int y, int action, int pointerId, int pressure, int radius ); public static native int nativeKey( int keyCode, int down ); public static native void nativeTouchpad( int x, int y, int down, int multitouch ); public static native void initJavaCallbacks(); public static native void nativeHardwareMouseDetected( int detected ); public static native void nativeMouseButtonsPressed( int buttonId, int pressedState ); public static native void nativeMouseWheel( int scrollX, int scrollY ); public static native void nativeGamepadAnalogJoystickInput( float stick1x, float stick1y, float stick2x, float stick2y, float rtrigger, float ltrigger ); }
Make touch pressure in-line with "1024 levels of sensitivity" Galaxy Note claims
project/java/Video.java
Make touch pressure in-line with "1024 levels of sensitivity" Galaxy Note claims
Java
lgpl-2.1
eafe4a07d895fc727cd4fc976edc4afb57d65978
0
rcook/DesignLab,rcook/DesignLab,rcook/DesignLab,rcook/DesignLab,rcook/DesignLab,rcook/DesignLab,rcook/DesignLab
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Processing project - http://processing.org Copyright (c) 2004-10 Ben Fry and Casey Reas Copyright (c) 2001-04 Massachusetts Institute of Technology This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package processing.app; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import java.util.List; import javax.swing.*; import processing.app.debug.TargetPackage; import processing.app.debug.TargetPlatform; import processing.app.helpers.FileUtils; import processing.app.helpers.Maps; import processing.app.helpers.PreferencesMap; import processing.app.helpers.filefilters.OnlyDirs; import processing.app.helpers.filefilters.OnlyFilesWithExtension; import processing.app.javax.swing.filechooser.FileNameExtensionFilter;import processing.app.tools.MapWithSubkeys; import processing.app.tools.ZipDeflater; import processing.core.*; import static processing.app.I18n._; /** * The base class for the main processing application. * Primary role of this class is for platform identification and * general interaction with the system (launching URLs, loading * files and images, etc) that comes from that. */ public class Base { public static final int REVISION = 152; /** This might be replaced by main() if there's a lib/version.txt file. */ static String VERSION_NAME = "0152"; /** Set true if this a proper release rather than a numbered revision. */ static public boolean RELEASE = false; static Map<Integer, String> platformNames = new HashMap<Integer, String>(); static { platformNames.put(PConstants.WINDOWS, "windows"); platformNames.put(PConstants.MACOSX, "macosx"); platformNames.put(PConstants.LINUX, "linux"); } static HashMap<String, Integer> platformIndices = new HashMap<String, Integer>(); static { platformIndices.put("windows", PConstants.WINDOWS); platformIndices.put("macosx", PConstants.MACOSX); platformIndices.put("linux", PConstants.LINUX); } static Platform platform; static private boolean commandLine; // A single instance of the preferences window Preferences preferencesFrame; // set to true after the first time the menu is built. // so that the errors while building don't show up again. boolean builtOnce; static File buildFolder; // these are static because they're used by Sketch static private File examplesFolder; static private File toolsFolder; static private List<File> librariesFolders; // maps library name to their library folder static private Map<String, File> libraries; // maps #included files to their library folder static Map<String, File> importToLibraryTable; // classpath for all known libraries for p5 // (both those in the p5/libs folder and those with lib subfolders // found in the sketchbook) static public String librariesClassPath; static public Map<String, TargetPackage> packages; // Location for untitled items static File untitledFolder; // p5 icon for the window // static Image icon; // int editorCount; List<Editor> editors = Collections.synchronizedList(new ArrayList<Editor>()); Editor activeEditor; static File portableFolder = null; static final String portableSketchbookFolder = "sketchbook"; static public void main(String args[]) throws Exception { initPlatform(); // Portable folder portableFolder = getContentFile("portable"); if (!portableFolder.exists()) portableFolder = null; // run static initialization that grabs all the prefs Preferences.init(null); try { File versionFile = getContentFile("lib/version.txt"); if (versionFile.exists()) { String version = PApplet.loadStrings(versionFile)[0]; if (!version.equals(VERSION_NAME)) { VERSION_NAME = version; RELEASE = true; } } } catch (Exception e) { e.printStackTrace(); } // if (System.getProperty("mrj.version") != null) { // //String jv = System.getProperty("java.version"); // String ov = System.getProperty("os.version"); // if (ov.startsWith("10.5")) { // System.setProperty("apple.laf.useScreenMenuBar", "true"); // } // } /* commandLine = false; if (args.length >= 2) { if (args[0].startsWith("--")) { commandLine = true; } } if (PApplet.javaVersion < 1.5f) { //System.err.println("no way man"); Base.showError("Need to install Java 1.5", "This version of Processing requires \n" + "Java 1.5 or later to run properly.\n" + "Please visit java.com to upgrade.", null); } */ // // Set the look and feel before opening the window // try { // platform.setLookAndFeel(); // } catch (Exception e) { // System.err.println("Non-fatal error while setting the Look & Feel."); // System.err.println("The error message follows, however Processing should run fine."); // System.err.println(e.getMessage()); // //e.printStackTrace(); // } // Use native popups so they don't look so crappy on osx JPopupMenu.setDefaultLightWeightPopupEnabled(false); // Don't put anything above this line that might make GUI, // because the platform has to be inited properly first. // Make sure a full JDK is installed //initRequirements(); // setup the theme coloring fun Theme.init(); // Set the look and feel before opening the window try { platform.setLookAndFeel(); } catch (Exception e) { String mess = e.getMessage(); if (mess.indexOf("ch.randelshofer.quaqua.QuaquaLookAndFeel") == -1) { System.err.println(_("Non-fatal error while setting the Look & Feel.")); System.err.println(_("The error message follows, however Arduino should run fine.")); System.err.println(mess); } } // Create a location for untitled sketches untitledFolder = createTempFolder("untitled"); untitledFolder.deleteOnExit(); new Base(args); } static protected void setCommandLine() { commandLine = true; } static protected boolean isCommandLine() { return commandLine; } static protected void initPlatform() { try { Class<?> platformClass = Class.forName("processing.app.Platform"); if (Base.isMacOS()) { platformClass = Class.forName("processing.app.macosx.Platform"); } else if (Base.isWindows()) { platformClass = Class.forName("processing.app.windows.Platform"); } else if (Base.isLinux()) { platformClass = Class.forName("processing.app.linux.Platform"); } platform = (Platform) platformClass.newInstance(); } catch (Exception e) { Base.showError(_("Problem Setting the Platform"), _("An unknown error occurred while trying to load\n" + "platform-specific code for your machine."), e); } } static protected void initRequirements() { try { Class.forName("com.sun.jdi.VirtualMachine"); } catch (ClassNotFoundException cnfe) { Base.showPlatforms(); Base.showError(_("Please install JDK 1.5 or later"), _("Arduino requires a full JDK (not just a JRE)\n" + "to run. Please install JDK 1.5 or later.\n" + "More information can be found in the reference."), cnfe); } } public Base(String[] args) throws Exception { platform.init(this); // Get the sketchbook path, and make sure it's set properly String sketchbookPath = Preferences.get("sketchbook.path"); // If a value is at least set, first check to see if the folder exists. // If it doesn't, warn the user that the sketchbook folder is being reset. if (sketchbookPath != null) { File sketchbookFolder; if (portableFolder != null) sketchbookFolder = new File(portableFolder, sketchbookPath); else sketchbookFolder = new File(sketchbookPath); if (!sketchbookFolder.exists()) { Base.showWarning(_("Sketchbook folder disappeared"), _("The sketchbook folder no longer exists.\n" + "Arduino will switch to the default sketchbook\n" + "location, and create a new sketchbook folder if\n" + "necessary. Arduino will then stop talking about\n" + "himself in the third person."), null); sketchbookPath = null; } } // If no path is set, get the default sketchbook folder for this platform if (sketchbookPath == null) { File defaultFolder = getDefaultSketchbookFolder(); if (portableFolder != null) Preferences.set("sketchbook.path", portableSketchbookFolder); else Preferences.set("sketchbook.path", defaultFolder.getAbsolutePath()); if (!defaultFolder.exists()) { defaultFolder.mkdirs(); } } packages = new HashMap<String, TargetPackage>(); loadHardware(getHardwareFolder()); loadHardware(getSketchbookHardwareFolder()); // Setup board-dependent variables. onBoardOrPortChange(); boolean opened = false; boolean doUpload = false; boolean doVerify = false; boolean doVerbose = false; String selectBoard = null; String selectPort = null; // Check if any files were passed in on the command line for (int i = 0; i < args.length; i++) { if (args[i].equals("--upload")) { doUpload = true; continue; } if (args[i].equals("--verify")) { doVerify = true; continue; } if (args[i].equals("--verbose") || args[i].equals("-v")) { doVerbose = true; continue; } if (args[i].equals("--board")) { i++; if (i < args.length) selectBoard = args[i]; continue; } if (args[i].equals("--port")) { i++; if (i < args.length) selectPort = args[i]; continue; } String path = args[i]; // Fix a problem with systems that use a non-ASCII languages. Paths are // being passed in with 8.3 syntax, which makes the sketch loader code // unhappy, since the sketch folder naming doesn't match up correctly. // http://dev.processing.org/bugs/show_bug.cgi?id=1089 if (isWindows()) { try { File file = new File(args[i]); path = file.getCanonicalPath(); } catch (IOException e) { e.printStackTrace(); } } if (handleOpen(path) != null) { opened = true; } } if (doUpload || doVerify) { if (!opened) { System.out.println(_("Can't open source sketch!")); System.exit(2); } // Set verbosity for command line build Preferences.set("build.verbose", "" + doVerbose); Preferences.set("upload.verbose", "" + doVerbose); Editor editor = editors.get(0); // Wait until editor is initialized while (!editor.status.isInitialized()) Thread.sleep(10); // Do board selection if requested if (selectBoard != null) selectBoard(selectBoard, editor); if (doUpload) { // Build and upload if (selectPort != null) editor.selectSerialPort(selectPort); editor.exportHandler.run(); } else { // Build only editor.runHandler.run(); } // Error during build or upload int res = editor.status.mode; if (res == EditorStatus.ERR) System.exit(1); // No errors exit gracefully System.exit(0); } // Check if there were previously opened sketches to be restored if (restoreSketches()) opened = true; // Create a new empty window (will be replaced with any files to be opened) if (!opened) { handleNew(); } // Check for updates if (Preferences.getBoolean("update.check")) { new UpdateCheck(this); } } /** * Post-constructor setup for the editor area. Loads the last * sketch that was used (if any), and restores other Editor settings. * The complement to "storePreferences", this is called when the * application is first launched. */ protected boolean restoreSketches() { // figure out window placement Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); boolean windowPositionValid = true; if (Preferences.get("last.screen.height") != null) { // if screen size has changed, the window coordinates no longer // make sense, so don't use them unless they're identical int screenW = Preferences.getInteger("last.screen.width"); int screenH = Preferences.getInteger("last.screen.height"); if ((screen.width != screenW) || (screen.height != screenH)) { windowPositionValid = false; } /* int windowX = Preferences.getInteger("last.window.x"); int windowY = Preferences.getInteger("last.window.y"); if ((windowX < 0) || (windowY < 0) || (windowX > screenW) || (windowY > screenH)) { windowPositionValid = false; } */ } else { windowPositionValid = false; } // Iterate through all sketches that were open last time p5 was running. // If !windowPositionValid, then ignore the coordinates found for each. // Save the sketch path and window placement for each open sketch int count = Preferences.getInteger("last.sketch.count"); int opened = 0; for (int i = 0; i < count; i++) { String path = Preferences.get("last.sketch" + i + ".path"); if (portableFolder != null) { File absolute = new File(portableFolder, path); try { path = absolute.getCanonicalPath(); } catch (IOException e) { // path unchanged. } } int[] location; if (windowPositionValid) { String locationStr = Preferences.get("last.sketch" + i + ".location"); location = PApplet.parseInt(PApplet.split(locationStr, ',')); } else { location = nextEditorLocation(); } // If file did not exist, null will be returned for the Editor if (handleOpen(path, location) != null) { opened++; } } return (opened > 0); } /** * Store list of sketches that are currently open. * Called when the application is quitting and documents are still open. */ protected void storeSketches() { // Save the width and height of the screen Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); Preferences.setInteger("last.screen.width", screen.width); Preferences.setInteger("last.screen.height", screen.height); String untitledPath = untitledFolder.getAbsolutePath(); // Save the sketch path and window placement for each open sketch int index = 0; for (Editor editor : editors) { String path = editor.getSketch().getMainFilePath(); // In case of a crash, save untitled sketches if they contain changes. // (Added this for release 0158, may not be a good idea.) if (path.startsWith(untitledPath) && !editor.getSketch().isModified()) { continue; } if (portableFolder != null) { path = FileUtils.relativePath(portableFolder.toString(), path); if (path == null) continue; } Preferences.set("last.sketch" + index + ".path", path); int[] location = editor.getPlacement(); String locationStr = PApplet.join(PApplet.str(location), ","); Preferences.set("last.sketch" + index + ".location", locationStr); index++; } Preferences.setInteger("last.sketch.count", index); } // If a sketch is untitled on quit, may need to store the new name // rather than the location from the temp folder. protected void storeSketchPath(Editor editor, int index) { String path = editor.getSketch().getMainFilePath(); String untitledPath = untitledFolder.getAbsolutePath(); if (path.startsWith(untitledPath)) { path = ""; } else if (portableFolder != null) { path = FileUtils.relativePath(portableFolder.toString(), path); if (path == null) path = ""; } Preferences.set("last.sketch" + index + ".path", path); } /* public void storeSketch(Editor editor) { int index = -1; for (int i = 0; i < editorCount; i++) { if (editors[i] == editor) { index = i; break; } } if (index == -1) { System.err.println("Problem storing sketch " + editor.sketch.name); } else { String path = editor.sketch.getMainFilePath(); Preferences.set("last.sketch" + index + ".path", path); } } */ // ................................................................. // Because of variations in native windowing systems, no guarantees about // changes to the focused and active Windows can be made. Developers must // never assume that this Window is the focused or active Window until this // Window receives a WINDOW_GAINED_FOCUS or WINDOW_ACTIVATED event. protected void handleActivated(Editor whichEditor) { activeEditor = whichEditor; // set the current window to be the console that's getting output EditorConsole.setEditor(activeEditor); } protected int[] nextEditorLocation() { Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); int defaultWidth = Preferences.getInteger("editor.window.width.default"); int defaultHeight = Preferences.getInteger("editor.window.height.default"); if (activeEditor == null) { // If no current active editor, use default placement return new int[] { (screen.width - defaultWidth) / 2, (screen.height - defaultHeight) / 2, defaultWidth, defaultHeight, 0 }; } else { // With a currently active editor, open the new window // using the same dimensions, but offset slightly. synchronized (editors) { final int OVER = 50; // In release 0160, don't //location = activeEditor.getPlacement(); Editor lastOpened = editors.get(editors.size() - 1); int[] location = lastOpened.getPlacement(); // Just in case the bounds for that window are bad location[0] += OVER; location[1] += OVER; if (location[0] == OVER || location[2] == OVER || location[0] + location[2] > screen.width || location[1] + location[3] > screen.height) { // Warp the next window to a randomish location on screen. return new int[] { (int) (Math.random() * (screen.width - defaultWidth)), (int) (Math.random() * (screen.height - defaultHeight)), defaultWidth, defaultHeight, 0 }; } return location; } } } // ................................................................. boolean breakTime = false; String[] months = { "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" }; /** * Handle creating a sketch folder, return its base .pde file * or null if the operation was canceled. * @param shift whether shift is pressed, which will invert prompt setting * @param noPrompt disable prompt, no matter the setting */ protected String createNewUntitled() throws IOException { File newbieDir = null; String newbieName = null; // In 0126, untitled sketches will begin in the temp folder, // and then moved to a new location because Save will default to Save As. File sketchbookDir = getSketchbookFolder(); File newbieParentDir = untitledFolder; // Use a generic name like sketch_031008a, the date plus a char int index = 0; //SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd"); //SimpleDateFormat formatter = new SimpleDateFormat("MMMdd"); //String purty = formatter.format(new Date()).toLowerCase(); Calendar cal = Calendar.getInstance(); int day = cal.get(Calendar.DAY_OF_MONTH); // 1..31 int month = cal.get(Calendar.MONTH); // 0..11 String purty = months[month] + PApplet.nf(day, 2); do { if (index == 26) { // In 0159, avoid running past z by sending people outdoors. if (!breakTime) { Base.showWarning(_("Time for a Break"), _("You've reached the limit for auto naming of new sketches\n" + "for the day. How about going for a walk instead?"), null); breakTime = true; } else { Base.showWarning(_("Sunshine"), _("No really, time for some fresh air for you."), null); } return null; } newbieName = "sketch_" + purty + ((char) ('a' + index)); newbieDir = new File(newbieParentDir, newbieName); index++; // Make sure it's not in the temp folder *and* it's not in the sketchbook } while (newbieDir.exists() || new File(sketchbookDir, newbieName).exists()); // Make the directory for the new sketch newbieDir.mkdirs(); // Make an empty pde file File newbieFile = new File(newbieDir, newbieName + ".ino"); if (!newbieFile.createNewFile()) { throw new IOException(); } FileUtils.copyFile(new File(getContentFile("examples"), "01.Basics" + File.separator + "BareMinimum" + File.separator + "BareMinimum.ino"), newbieFile); return newbieFile.getAbsolutePath(); } /** * Create a new untitled document in a new sketch window. */ public void handleNew() { try { String path = createNewUntitled(); if (path != null) { Editor editor = handleOpen(path); editor.untitled = true; } } catch (IOException e) { if (activeEditor != null) { activeEditor.statusError(e); } } } /** * Replace the sketch in the current window with a new untitled document. */ public void handleNewReplace() { if (!activeEditor.checkModified()) { return; // sketch was modified, and user canceled } // Close the running window, avoid window boogers with multiple sketches activeEditor.internalCloseRunner(); // Actually replace things handleNewReplaceImpl(); } protected void handleNewReplaceImpl() { try { String path = createNewUntitled(); if (path != null) { activeEditor.handleOpenInternal(path); activeEditor.untitled = true; } // return true; } catch (IOException e) { activeEditor.statusError(e); // return false; } } /** * Open a sketch, replacing the sketch in the current window. * @param path Location of the primary pde file for the sketch. */ public void handleOpenReplace(String path) { if (!activeEditor.checkModified()) { return; // sketch was modified, and user canceled } // Close the running window, avoid window boogers with multiple sketches activeEditor.internalCloseRunner(); boolean loaded = activeEditor.handleOpenInternal(path); if (!loaded) { // replace the document without checking if that's ok handleNewReplaceImpl(); } } /** * Prompt for a sketch to open, and open it in a new window. */ public void handleOpenPrompt() { // get the frontmost window frame for placing file dialog FileDialog fd = new FileDialog(activeEditor, _("Open an Arduino sketch..."), FileDialog.LOAD); // This was annoying people, so disabled it in 0125. //fd.setDirectory(Preferences.get("sketchbook.path")); //fd.setDirectory(getSketchbookPath()); // Only show .pde files as eligible bachelors fd.setFilenameFilter(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".ino") || name.toLowerCase().endsWith(".pde"); } }); fd.setVisible(true); String directory = fd.getDirectory(); String filename = fd.getFile(); // User canceled selection if (filename == null) return; File inputFile = new File(directory, filename); handleOpen(inputFile.getAbsolutePath()); } /** * Open a sketch in a new window. * @param path Path to the pde file for the sketch in question * @return the Editor object, so that properties (like 'untitled') * can be set by the caller */ public Editor handleOpen(String path) { return handleOpen(path, nextEditorLocation()); } protected Editor handleOpen(String path, int[] location) { // System.err.println("entering handleOpen " + path); File file = new File(path); if (!file.exists()) return null; // System.err.println(" editors: " + editors); // Cycle through open windows to make sure that it's not already open. for (Editor editor : editors) { if (editor.getSketch().getMainFilePath().equals(path)) { editor.toFront(); // System.err.println(" handleOpen: already opened"); return editor; } } // If the active editor window is an untitled, and un-modified document, // just replace it with the file that's being opened. // if (activeEditor != null) { // Sketch activeSketch = activeEditor.sketch; // if (activeSketch.isUntitled() && !activeSketch.isModified()) { // // if it's an untitled, unmodified document, it can be replaced. // // except in cases where a second blank window is being opened. // if (!path.startsWith(untitledFolder.getAbsolutePath())) { // activeEditor.handleOpenUnchecked(path, 0, 0, 0, 0); // return activeEditor; // } // } // } // System.err.println(" creating new editor"); Editor editor = new Editor(this, path, location); // Editor editor = null; // try { // editor = new Editor(this, path, location); // } catch (Exception e) { // e.printStackTrace(); // System.err.flush(); // System.out.flush(); // System.exit(1); // } // System.err.println(" done creating new editor"); // EditorConsole.systemErr.println(" done creating new editor"); // Make sure that the sketch actually loaded if (editor.getSketch() == null) { // System.err.println("sketch was null, getting out of handleOpen"); return null; // Just walk away quietly } // if (editors == null) { // editors = new Editor[5]; // } // if (editorCount == editors.length) { // editors = (Editor[]) PApplet.expand(editors); // } // editors[editorCount++] = editor; editors.add(editor); // if (markedForClose != null) { // Point p = markedForClose.getLocation(); // handleClose(markedForClose, false); // // open the new window in // editor.setLocation(p); // } // now that we're ready, show the window // (don't do earlier, cuz we might move it based on a window being closed) editor.setVisible(true); // System.err.println("exiting handleOpen"); return editor; } /** * Close a sketch as specified by its editor window. * @param editor Editor object of the sketch to be closed. * @return true if succeeded in closing, false if canceled. */ public boolean handleClose(Editor editor) { // Check if modified // boolean immediate = editors.size() == 1; if (!editor.checkModified()) { return false; } // Close the running window, avoid window boogers with multiple sketches editor.internalCloseRunner(); if (editors.size() == 1) { // For 0158, when closing the last window /and/ it was already an // untitled sketch, just give up and let the user quit. // if (Preferences.getBoolean("sketchbook.closing_last_window_quits") || // (editor.untitled && !editor.getSketch().isModified())) { if (Base.isMacOS()) { Object[] options = { "OK", "Cancel" }; String prompt = _("<html> " + "<head> <style type=\"text/css\">"+ "b { font: 13pt \"Lucida Grande\" }"+ "p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+ "</style> </head>" + "<b>Are you sure you want to Quit?</b>" + "<p>Closing the last open sketch will quit Arduino."); int result = JOptionPane.showOptionDialog(editor, prompt, _("Quit"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == JOptionPane.NO_OPTION || result == JOptionPane.CLOSED_OPTION) { return false; } } // This will store the sketch count as zero editors.remove(editor); Editor.serialMonitor.closeSerialPort(); storeSketches(); // Save out the current prefs state Preferences.save(); // Since this wasn't an actual Quit event, call System.exit() System.exit(0); } else { // More than one editor window open, // proceed with closing the current window. editor.setVisible(false); editor.dispose(); // for (int i = 0; i < editorCount; i++) { // if (editor == editors[i]) { // for (int j = i; j < editorCount-1; j++) { // editors[j] = editors[j+1]; // } // editorCount--; // // Set to null so that garbage collection occurs // editors[editorCount] = null; // } // } editors.remove(editor); } return true; } /** * Handler for File &rarr; Quit. * @return false if canceled, true otherwise. */ public boolean handleQuit() { // If quit is canceled, this will be replaced anyway // by a later handleQuit() that is not canceled. storeSketches(); Editor.serialMonitor.closeSerialPort(); if (handleQuitEach()) { // make sure running sketches close before quitting for (Editor editor : editors) { editor.internalCloseRunner(); } // Save out the current prefs state Preferences.save(); if (!Base.isMacOS()) { // If this was fired from the menu or an AppleEvent (the Finder), // then Mac OS X will send the terminate signal itself. System.exit(0); } return true; } return false; } /** * Attempt to close each open sketch in preparation for quitting. * @return false if canceled along the way */ protected boolean handleQuitEach() { int index = 0; for (Editor editor : editors) { if (editor.checkModified()) { // Update to the new/final sketch path for this fella storeSketchPath(editor, index); index++; } else { return false; } } return true; } // ................................................................. /** * Asynchronous version of menu rebuild to be used on save and rename * to prevent the interface from locking up until the menus are done. */ protected void rebuildSketchbookMenus() { //System.out.println("async enter"); //new Exception().printStackTrace(); SwingUtilities.invokeLater(new Runnable() { public void run() { //System.out.println("starting rebuild"); rebuildSketchbookMenu(Editor.sketchbookMenu); rebuildToolbarMenu(Editor.toolbarMenu); //System.out.println("done with rebuild"); } }); //System.out.println("async exit"); } protected void rebuildToolbarMenu(JMenu menu) { JMenuItem item; menu.removeAll(); // Add the single "Open" item item = Editor.newJMenuItem(_("Open..."), 'O'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleOpenPrompt(); } }); menu.add(item); menu.addSeparator(); // Add a list of all sketches and subfolders try { boolean sketches = addSketches(menu, getSketchbookFolder(), true); if (sketches) menu.addSeparator(); } catch (IOException e) { e.printStackTrace(); } // Add each of the subfolders of examples directly to the menu try { boolean found = addSketches(menu, examplesFolder, true); if (found) menu.addSeparator(); } catch (IOException e) { e.printStackTrace(); } } protected void rebuildSketchbookMenu(JMenu menu) { //System.out.println("rebuilding sketchbook menu"); //new Exception().printStackTrace(); try { menu.removeAll(); addSketches(menu, getSketchbookFolder(), false); //addSketches(menu, getSketchbookFolder()); } catch (IOException e) { e.printStackTrace(); } } public Map<String, File> getIDELibs() { if (libraries == null) return new HashMap<String, File>(); Map<String, File> ideLibs = new HashMap<String, File>(libraries); for (String lib : libraries.keySet()) { if (FileUtils.isSubDirectory(getSketchbookFolder(), libraries.get(lib))) ideLibs.remove(lib); } return ideLibs; } public Map<String, File> getUserLibs() { if (libraries == null) return new HashMap<String, File>(); Map<String, File> userLibs = new HashMap<String, File>(libraries); for (String lib : libraries.keySet()) { if (!FileUtils.isSubDirectory(getSketchbookFolder(), libraries.get(lib))) userLibs.remove(lib); } return userLibs; } public void rebuildImportMenu(JMenu importMenu, final Editor editor) { importMenu.removeAll(); JMenuItem addLibraryMenuItem = new JMenuItem(_("Add Library...")); addLibraryMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.this.handleAddLibrary(editor); Base.this.onBoardOrPortChange(); Base.this.rebuildImportMenu(Editor.importMenu, editor); Base.this.rebuildExamplesMenu(Editor.examplesMenu); } }); importMenu.add(addLibraryMenuItem); // Split between user supplied libraries and IDE libraries TargetPlatform targetPlatform = getTargetPlatform(); if (targetPlatform != null) { Map<String, File> ideLibs = getIDELibs(); Map<String, File> userLibs = getUserLibs(); try { // Find the current target. Get the platform, and then select the // correct name and core path. PreferencesMap prefs = targetPlatform.getPreferences(); String targetname = prefs.get("name"); if (false) { // Hack to extract these words by gettext tool. // These phrases are actually defined in the "platform.txt". String notused = _("Arduino AVR Boards"); notused = _("Arduino ARM (32-bits) Boards"); } JMenuItem platformItem = new JMenuItem(_(targetname)); platformItem.setEnabled(false); importMenu.add(platformItem); if (ideLibs.size() > 0) { importMenu.addSeparator(); addLibraries(importMenu, ideLibs); } if (userLibs.size() > 0) { importMenu.addSeparator(); addLibraries(importMenu, userLibs); } } catch (IOException e) { e.printStackTrace(); } } } public void rebuildExamplesMenu(JMenu menu) { try { menu.removeAll(); // Add examples from distribution "example" folder boolean found = addSketches(menu, examplesFolder, false); if (found) menu.addSeparator(); // Add examples from libraries Map<String, File> ideLibs = getIDELibs(); List<String> names = new ArrayList<String>(ideLibs.keySet()); Collections.sort(names, String.CASE_INSENSITIVE_ORDER); for (String name : names) { File folder = ideLibs.get(name); addSketchesSubmenu(menu, name, folder, false); // Allows "fat" libraries to have examples in the root folder if (folder.getName().equals(Base.getTargetPlatform().getName())) addSketchesSubmenu(menu, name, folder.getParentFile(), false); } Map<String, File> userLibs = getUserLibs(); if (userLibs.size()>0) { menu.addSeparator(); names = new ArrayList<String>(userLibs.keySet()); Collections.sort(names, String.CASE_INSENSITIVE_ORDER); for (String name : names) { File folder = userLibs.get(name); addSketchesSubmenu(menu, name, folder, false); // Allows "fat" libraries to have examples in the root folder if (folder.getName().equals(Base.getTargetPlatform().getName())) addSketchesSubmenu(menu, name, folder.getParentFile(), false); } } } catch (IOException e) { e.printStackTrace(); } } public Map<String, File> scanLibraries(List<File> folders) { Map<String, File> res = new HashMap<String, File>(); for (File folder : folders) res.putAll(scanLibraries(folder)); return res; } public Map<String, File> scanLibraries(File folder) { Map<String, File> res = new HashMap<String, File>(); String list[] = folder.list(new OnlyDirs()); // if a bad folder or something like that, this might come back null if (list == null) return res; for (String libName : list) { File subfolder = new File(folder, libName); if (!Sketch.isSanitaryName(libName)) { String mess = I18n.format(_("The library \"{0}\" cannot be used.\n" + "Library names must contain only basic letters and numbers.\n" + "(ASCII only and no spaces, and it cannot start with a number)"), libName); Base.showMessage(_("Ignoring bad library name"), mess); continue; } subfolder = scanFatLibrary(subfolder); // (also replace previously found libs with the same name) if (subfolder != null) res.put(libName, subfolder); } return res; } /** * Scans inside a "FAT" (multi-platform) library folder to see if it contains * a version suitable for the actual selected architecture. If a suitable * version is found the folder containing that version is returned, otherwise * <b>null</b> is returned.<br /> * <br /> * If a non-"FAT" library is detected, we assume that the library is suitable * for the current architecture and the libFolder parameter is returned.<br /> * * @param libFolder * @return */ public File scanFatLibrary(File libFolder) { // A library is considered "fat" if it contains a file called // "library.properties" File libraryPropFile = new File(libFolder, "library.properties"); if (!libraryPropFile.exists() || !libraryPropFile.isFile()) return libFolder; // Search for a subfolder for actual architecture, return null if not found File archSubfolder = new File(libFolder, Base.getTargetPlatform().getName()); if (!archSubfolder.exists() || !archSubfolder.isDirectory()) return null; return archSubfolder; } public void onBoardOrPortChange() { TargetPlatform targetPlatform = getTargetPlatform(); if (targetPlatform == null) return; // Calculate paths for libraries and examples examplesFolder = getContentFile("examples"); toolsFolder = getContentFile("tools"); File platformFolder = targetPlatform.getFolder(); librariesFolders = new ArrayList<File>(); librariesFolders.add(getContentFile("libraries")); librariesFolders.add(new File(platformFolder.getParentFile(), "libraries")); librariesFolders.add(new File(platformFolder, "libraries")); librariesFolders.add(getSketchbookLibrariesFolder()); // Scan for libraries in each library folder. // Libraries located in the latest folders on the list can override // other libraries with the same name. libraries = scanLibraries(librariesFolders); // Populate importToLibraryTable importToLibraryTable = new HashMap<String, File>(); for (File subfolder : libraries.values()) { try { String packages[] = headerListFromIncludePath(subfolder); for (String pkg : packages) { importToLibraryTable.put(pkg, subfolder); } } catch (IOException e) { showWarning(_("Error"), I18n.format("Unable to list header files in {0}", subfolder), e); } } // Update editors status bar for (Editor editor : editors) editor.onBoardOrPortChange(); } public void rebuildBoardsMenu(JMenu toolsMenu, final Editor editor) { JMenu boardsMenu = makeOrGetBoardMenu(toolsMenu, _("Board")); String selPackage = Preferences.get("target_package"); String selPlatform = Preferences.get("target_platform"); String selBoard = Preferences.get("board"); boolean first = true; List<JMenuItem> menuItemsToClickAfterStartup = new LinkedList<JMenuItem>(); JMenuItem lastResortItem = null; ButtonGroup boardsButtonGroup = new ButtonGroup(); Map<String, ButtonGroup> buttonGroupsMap = new HashMap<String, ButtonGroup>(); JMenu currentMenu = null; // Cycle through all packages for (TargetPackage targetPackage : packages.values()) { String packageName = targetPackage.getName(); // For every package cycle through all platform for (TargetPlatform targetPlatform : targetPackage.platforms()) { String platformName = targetPlatform.getName(); Map<String, PreferencesMap> boards = targetPlatform.getBoards(); if (targetPlatform.getPreferences().get("name") == null || targetPlatform.getBoards().isEmpty()) { continue; } /* // Add a title for each group of boards if (!first) { boardsMenu.add(new JSeparator()); } first = false; */ //JMenuItem separator = new JMenuItem(_(targetPlatform.getPreferences().get("name"))); currentMenu = new JMenu(_(targetPlatform.getPreferences().get("name"))); //separator.setEnabled(false); boardsMenu.add(currentMenu); // For every platform cycle through all boards for (final String boardID : targetPlatform.getBoards().keySet()) { // Setup a menu item for the current board String boardName = boards.get(boardID).get("name"); @SuppressWarnings("serial") Action action = new AbstractAction(boardName) { public void actionPerformed(ActionEvent actionevent) { selectBoard((String) getValue("b"), editor); } }; action.putValue("b", packageName + ":" + platformName + ":" + boardID); JRadioButtonMenuItem item = new JRadioButtonMenuItem(action); currentMenu.add(item); boardsButtonGroup.add(item); if (selBoard.equals(boardID) && selPackage.equals(packageName) && selPlatform.equals(platformName)) { menuItemsToClickAfterStartup.add(item); } else { if (boardID.equals("uno")) lastResortItem=item; } if (targetPlatform.getCustomMenus() != null) { List<String> customMenuIDs = new LinkedList<String>(targetPlatform.getCustomMenus().getKeys()); for (int i = 0; i < customMenuIDs.size(); i++) { final String customMenuID = customMenuIDs.get(i); JMenu menu = makeOrGetBoardMenu(toolsMenu, _(targetPlatform.getCustomMenus().getValueOf(customMenuID))); MapWithSubkeys customMenu = targetPlatform.getCustomMenus().get(customMenuID); if (customMenu.getKeys().contains(boardID)) { MapWithSubkeys boardCustomMenu = customMenu.get(boardID); final int currentIndex = i + 1 + 1; //plus 1 to skip the first board menu, plus 1 to keep the custom menu next to this one for (final String customMenuOption : boardCustomMenu.getKeys()) { @SuppressWarnings("serial") Action subAction = new AbstractAction(_(boardCustomMenu.getValueOf(customMenuOption))) { public void actionPerformed(ActionEvent e) { Preferences.set("target_package", (String) getValue("package")); Preferences.set("target_platform", (String) getValue("platform")); Preferences.set("board", (String) getValue("board")); Preferences.set("custom_" + customMenuID, boardID + "_" + (String) getValue("custom_menu_option")); filterVisibilityOfSubsequentBoardMenus((String) getValue("board"), currentIndex); onBoardOrPortChange(); Sketch.buildSettingChanged(); rebuildImportMenu(Editor.importMenu, editor); rebuildExamplesMenu(Editor.examplesMenu); } }; subAction.putValue("board", boardID); subAction.putValue("custom_menu_option", customMenuOption); subAction.putValue("package", packageName); subAction.putValue("platform", platformName); if (!buttonGroupsMap.containsKey(customMenuID)) { buttonGroupsMap.put(customMenuID, new ButtonGroup()); } item = new JRadioButtonMenuItem(subAction); menu.add(item); buttonGroupsMap.get(customMenuID).add(item); String selectedCustomMenuEntry = Preferences.get("custom_" + customMenuID); if (selBoard.equals(boardID) && (boardID + "_" + customMenuOption).equals(selectedCustomMenuEntry)) { menuItemsToClickAfterStartup.add(item); } } } } } } } } if (menuItemsToClickAfterStartup.isEmpty()) { menuItemsToClickAfterStartup.add(lastResortItem);//selectFirstEnabledMenuItem(boardsMenu)); } for (JMenuItem menuItemToClick : menuItemsToClickAfterStartup) { menuItemToClick.setSelected(true); menuItemToClick.getAction().actionPerformed(new ActionEvent(this, -1, "")); } } private static void filterVisibilityOfSubsequentBoardMenus(String boardID, int fromIndex) { for (int i = fromIndex; i < Editor.boardsMenus.size(); i++) { JMenu menu = Editor.boardsMenus.get(i); for (int m = 0; m < menu.getItemCount(); m++) { JMenuItem menuItem = menu.getItem(m); menuItem.setVisible(menuItem.getAction().getValue("board").equals(boardID)); } menu.setEnabled(ifThereAreVisibleItemsOn(menu)); if (menu.isEnabled()) { JMenuItem visibleSelectedOrFirstMenuItem = selectVisibleSelectedOrFirstMenuItem(menu); if (!visibleSelectedOrFirstMenuItem.isSelected()) { visibleSelectedOrFirstMenuItem.setSelected(true); visibleSelectedOrFirstMenuItem.getAction().actionPerformed(null); } } } } private static boolean ifThereAreVisibleItemsOn(JMenu menu) { for (int i = 0; i < menu.getItemCount(); i++) { if (menu.getItem(i).isVisible()) { return true; } } return false; } private JMenu makeOrGetBoardMenu(JMenu toolsMenu, String label) { for (JMenu menu : Editor.boardsMenus) { if (label.equals(menu.getText())) { return menu; } } JMenu menu = new JMenu(label); Editor.boardsMenus.add(menu); toolsMenu.add(menu); return menu; } private static JMenuItem selectVisibleSelectedOrFirstMenuItem(JMenu menu) { JMenuItem firstVisible = null; for (int i = 0; i < menu.getItemCount(); i++) { JMenuItem item = menu.getItem(i); if (item != null && item.isVisible()) { if (item.isSelected()) { return item; } if (firstVisible == null) { firstVisible = item; } } } if (firstVisible != null) { return firstVisible; } throw new IllegalStateException("Menu has no enabled items"); } private static JMenuItem selectFirstEnabledMenuItem(JMenu menu) { for (int i = 0; i < menu.getItemCount(); i++) { JMenuItem item = menu.getItem(i); if (item != null && item.isEnabled()) { return item; } } throw new IllegalStateException("Menu has no enabled items"); } private void selectBoard(String selectBoard, Editor editor) { String[] split = selectBoard.split(":"); Preferences.set("target_package", split[0]); Preferences.set("target_platform", split[1]); Preferences.set("board", split[2]); filterVisibilityOfSubsequentBoardMenus(split[2], 1); onBoardOrPortChange(); Sketch.buildSettingChanged(); rebuildImportMenu(Editor.importMenu, editor); rebuildExamplesMenu(Editor.examplesMenu); } public void rebuildProgrammerMenu(JMenu menu) { menu.removeAll(); ButtonGroup group = new ButtonGroup(); for (TargetPackage targetPackage : packages.values()) { for (TargetPlatform targetPlatform : targetPackage.platforms()) { for (String programmer : targetPlatform.getProgrammers().keySet()) { String id = targetPackage.getName() + ":" + programmer; @SuppressWarnings("serial") AbstractAction action = new AbstractAction(targetPlatform .getProgrammer(programmer).get("name")) { public void actionPerformed(ActionEvent actionevent) { Preferences.set("programmer", "" + getValue("id")); } }; action.putValue("id", id); JMenuItem item = new JRadioButtonMenuItem(action); if (Preferences.get("programmer").equals(id)) item.setSelected(true); group.add(item); menu.add(item); } } } } /** * Scan a folder recursively, and add any sketches found to the menu * specified. Set the openReplaces parameter to true when opening the sketch * should replace the sketch in the current window, or false when the * sketch should open in a new window. */ protected boolean addSketches(JMenu menu, File folder, final boolean replaceExisting) throws IOException { if (folder == null) return false; // skip .DS_Store files, etc (this shouldn't actually be necessary) if (!folder.isDirectory()) return false; String[] list = folder.list(); // If a bad folder or unreadable or whatever, this will come back null if (list == null) return false; // Alphabetize list, since it's not always alpha order Arrays.sort(list, String.CASE_INSENSITIVE_ORDER); boolean ifound = false; for (String name : list) { if ((name.charAt(0) == '.') || name.equals("CVS")) continue; File subfolder = new File(folder, name); if (!subfolder.isDirectory()) continue; if (addSketchesSubmenu(menu, name, subfolder, replaceExisting)) ifound = true; } return ifound; // actually ignored, but.. } private boolean addSketchesSubmenu(JMenu menu, String name, File folder, final boolean replaceExisting) throws IOException { ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent e) { String path = e.getActionCommand(); if (new File(path).exists()) { boolean replace = replaceExisting; if ((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0) { replace = !replace; } if (replace) { handleOpenReplace(path); } else { handleOpen(path); } } else { showWarning(_("Sketch Does Not Exist"), _("The selected sketch no longer exists.\n" + "You may need to restart Arduino to update\n" + "the sketchbook menu."), null); } } }; File entry = new File(folder, name + ".ino"); if (!entry.exists() && (new File(folder, name + ".pde")).exists()) entry = new File(folder, name + ".pde"); // if a .pde file of the same prefix as the folder exists.. if (entry.exists()) { if (!Sketch.isSanitaryName(name)) { if (!builtOnce) { String complaining = I18n .format( _("The sketch \"{0}\" cannot be used.\n" + "Sketch names must contain only basic letters and numbers\n" + "(ASCII-only with no spaces, " + "and it cannot start with a number).\n" + "To get rid of this message, remove the sketch from\n" + "{1}"), name, entry.getAbsolutePath()); Base.showMessage(_("Ignoring sketch with bad name"), complaining); } return false; } JMenuItem item = new JMenuItem(name); item.addActionListener(listener); item.setActionCommand(entry.getAbsolutePath()); menu.add(item); return true; } // don't create an extra menu level for a folder named "examples" if (folder.getName().equals("examples")) return addSketches(menu, folder, replaceExisting); // not a sketch folder, but maybe a subfolder containing sketches JMenu submenu = new JMenu(name); boolean found = addSketches(submenu, folder, replaceExisting); if (found) menu.add(submenu); return found; } protected void addLibraries(JMenu menu, Map<String, File> libs) throws IOException { List<String> list = new ArrayList<String>(libs.keySet()); Collections.sort(list, String.CASE_INSENSITIVE_ORDER); ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent event) { String jarPath = event.getActionCommand(); try { activeEditor.getSketch().importLibrary(jarPath); } catch (IOException e) { showWarning(_("Error"), I18n.format("Unable to list header files in {0}", jarPath), e); } } }; for (String name : list) { File folder = libs.get(name); // Add new element at the bottom JMenuItem item = new JMenuItem(name); item.addActionListener(listener); item.setActionCommand(folder.getAbsolutePath()); menu.add(item); // XXX: DAM: should recurse here so that library folders can be nested } } /** * Given a folder, return a list of the header files in that folder (but not * the header files in its sub-folders, as those should be included from * within the header files at the top-level). */ static public String[] headerListFromIncludePath(File path) throws IOException { String[] list = path.list(new OnlyFilesWithExtension(".h")); if (list == null) { throw new IOException(); } return list; } protected void loadHardware(File folder) { if (!folder.isDirectory()) return; String list[] = folder.list(new OnlyDirs()); // if a bad folder or something like that, this might come back null if (list == null) return; // alphabetize list, since it's not always alpha order // replaced hella slow bubble sort with this feller for 0093 Arrays.sort(list, String.CASE_INSENSITIVE_ORDER); for (String target : list) { // Skip reserved 'tools' folder. if (target.equals("tools")) continue; File subfolder = new File(folder, target); packages.put(target, new TargetPackage(target, subfolder)); } } // ................................................................. /** * Show the About box. */ @SuppressWarnings("serial") public void handleAbout() { final Image image = Base.getLibImage("about.jpg", activeEditor); final Window window = new Window(activeEditor) { public void paint(Graphics g) { g.drawImage(image, 0, 0, null); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); g.setFont(new Font("SansSerif", Font.PLAIN, 11)); g.setColor(Color.white); g.drawString(Base.VERSION_NAME, 50, 30); } }; window.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { window.dispose(); } }); int w = image.getWidth(activeEditor); int h = image.getHeight(activeEditor); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); window.setBounds((screen.width-w)/2, (screen.height-h)/2, w, h); window.setVisible(true); } /** * Show the Preferences window. */ public void handlePrefs() { if (preferencesFrame == null) preferencesFrame = new Preferences(); preferencesFrame.showFrame(activeEditor); } // ................................................................... /** * Get list of platform constants. */ // static public int[] getPlatforms() { // return platforms; // } // static public int getPlatform() { // String osname = System.getProperty("os.name"); // // if (osname.indexOf("Mac") != -1) { // return PConstants.MACOSX; // // } else if (osname.indexOf("Windows") != -1) { // return PConstants.WINDOWS; // // } else if (osname.equals("Linux")) { // true for the ibm vm // return PConstants.LINUX; // // } else { // return PConstants.OTHER; // } // } static public Platform getPlatform() { return platform; } static public String getPlatformName() { String osname = System.getProperty("os.name"); if (osname.indexOf("Mac") != -1) { return "macosx"; } else if (osname.indexOf("Windows") != -1) { return "windows"; } else if (osname.equals("Linux")) { // true for the ibm vm return "linux"; } else { return "other"; } } /** * Map a platform constant to its name. * @param which PConstants.WINDOWS, PConstants.MACOSX, PConstants.LINUX * @return one of "windows", "macosx", or "linux" */ static public String getPlatformName(int which) { return platformNames.get(which); } static public int getPlatformIndex(String what) { Integer entry = platformIndices.get(what); return (entry == null) ? -1 : entry.intValue(); } // These were changed to no longer rely on PApplet and PConstants because // of conflicts that could happen with older versions of core.jar, where // the MACOSX constant would instead read as the LINUX constant. /** * returns true if Processing is running on a Mac OS X machine. */ static public boolean isMacOS() { //return PApplet.platform == PConstants.MACOSX; return System.getProperty("os.name").indexOf("Mac") != -1; } /** * returns true if running on windows. */ static public boolean isWindows() { //return PApplet.platform == PConstants.WINDOWS; return System.getProperty("os.name").indexOf("Windows") != -1; } /** * true if running on linux. */ static public boolean isLinux() { //return PApplet.platform == PConstants.LINUX; return System.getProperty("os.name").indexOf("Linux") != -1; } // ................................................................. static public File getSettingsFolder() { if (portableFolder != null) return portableFolder; File settingsFolder = null; String preferencesPath = Preferences.get("settings.path"); if (preferencesPath != null) { settingsFolder = new File(preferencesPath); } else { try { settingsFolder = platform.getSettingsFolder(); } catch (Exception e) { showError(_("Problem getting data folder"), _("Error getting the Arduino data folder."), e); } } // create the folder if it doesn't exist already if (!settingsFolder.exists()) { if (!settingsFolder.mkdirs()) { showError(_("Settings issues"), _("Arduino cannot run because it could not\n" + "create a folder to store your settings."), null); } } return settingsFolder; } /** * Convenience method to get a File object for the specified filename inside * the settings folder. * For now, only used by Preferences to get the preferences.txt file. * @param filename A file inside the settings folder. * @return filename wrapped as a File object inside the settings folder */ static public File getSettingsFile(String filename) { return new File(getSettingsFolder(), filename); } static public File getBuildFolder() { if (buildFolder == null) { String buildPath = Preferences.get("build.path"); if (buildPath != null) { buildFolder = new File(buildPath); } else { //File folder = new File(getTempFolder(), "build"); //if (!folder.exists()) folder.mkdirs(); buildFolder = createTempFolder("build"); buildFolder.deleteOnExit(); } } return buildFolder; } /** * Get the path to the platform's temporary folder, by creating * a temporary temporary file and getting its parent folder. * <br/> * Modified for revision 0094 to actually make the folder randomized * to avoid conflicts in multi-user environments. (Bug 177) */ static public File createTempFolder(String name) { try { File folder = File.createTempFile(name, null); //String tempPath = ignored.getParent(); //return new File(tempPath); folder.delete(); folder.mkdirs(); return folder; } catch (Exception e) { e.printStackTrace(); } return null; } static public Map<String, File> getLibraries() { return libraries; } static public String getExamplesPath() { return examplesFolder.getAbsolutePath(); } static public List<File> getLibrariesPath() { return librariesFolders; } static public File getToolsFolder() { return toolsFolder; } static public String getToolsPath() { return toolsFolder.getAbsolutePath(); } static public File getHardwareFolder() { // calculate on the fly because it's needed by Preferences.init() to find // the boards.txt and programmers.txt preferences files (which happens // before the other folders / paths get cached). return getContentFile("hardware"); } //Get the core libraries static public File getCoreLibraries(String path) { return getContentFile(path); } static public String getHardwarePath() { return getHardwareFolder().getAbsolutePath(); } static public String getAvrBasePath() { String path = getHardwarePath() + File.separator + "tools" + File.separator + "avr" + File.separator + "bin" + File.separator; if (Base.isLinux() && !(new File(path)).exists()) { return ""; // use distribution provided avr tools if bundled tools missing } return path; } /** * Returns the currently selected TargetPlatform. * * @return */ static public TargetPlatform getTargetPlatform() { String packageName = Preferences.get("target_package"); String platformName = Preferences.get("target_platform"); return getTargetPlatform(packageName, platformName); } /** * Returns a specific TargetPlatform searching Package/Platform * * @param packageName * @param platformName * @return */ static public TargetPlatform getTargetPlatform(String packageName, String platformName) { TargetPackage p = packages.get(packageName); if (p == null) return null; return p.get(platformName); } static public TargetPlatform getCurrentTargetPlatformFromPackage(String pack) { return getTargetPlatform(pack, Preferences.get("target_platform")); } static public Map<String, String> getBoardPreferences() { TargetPlatform target = getTargetPlatform(); String board = Preferences.get("board"); Map<String, String> boardPreferences = Maps.merge(target.getBoards().get(board), new LinkedHashMap<String, String>()); if (target.getCustomMenus() != null) { for (String customMenuID : target.getCustomMenus().getKeys()) { MapWithSubkeys boardCustomMenu = target.getCustomMenus().get(customMenuID).get(board); String selectedCustomMenuEntry = Preferences.get("custom_" + customMenuID); if (boardCustomMenu != null && selectedCustomMenuEntry != null && selectedCustomMenuEntry.startsWith(board)) { String menuEntryId = selectedCustomMenuEntry.substring(selectedCustomMenuEntry.indexOf("_") + 1); Maps.merge(boardCustomMenu.get(menuEntryId).getValues(), boardPreferences); boardPreferences.put("name", boardPreferences.get("name") + ", " + boardCustomMenu.getValueOf(menuEntryId)); } } } return boardPreferences; } static public File getPortableFolder() { return portableFolder; } static public String getPortableSketchbookFolder() { return portableSketchbookFolder; } static public File getSketchbookFolder() { if (portableFolder != null) return new File(portableFolder, Preferences.get("sketchbook.path")); return new File(Preferences.get("sketchbook.path")); } static public File getSketchbookLibrariesFolder() { File libdir = new File(getSketchbookFolder(), "libraries"); if (!libdir.exists()) { try { libdir.mkdirs(); File readme = new File(libdir, "readme.txt"); FileWriter freadme = new FileWriter(readme); freadme.write(_("For information on installing libraries, see: " + "http://arduino.cc/en/Guide/Libraries\n")); freadme.close(); } catch (Exception e) { } } return libdir; } static public String getSketchbookLibrariesPath() { return getSketchbookLibrariesFolder().getAbsolutePath(); } static public File getSketchbookHardwareFolder() { return new File(getSketchbookFolder(), "hardware"); } protected File getDefaultSketchbookFolder() { if (portableFolder != null) return new File(portableFolder, portableSketchbookFolder); File sketchbookFolder = null; try { sketchbookFolder = platform.getDefaultSketchbookFolder(); } catch (Exception e) { } if (sketchbookFolder == null) { sketchbookFolder = promptSketchbookLocation(); } // create the folder if it doesn't exist already boolean result = true; if (!sketchbookFolder.exists()) { result = sketchbookFolder.mkdirs(); } if (!result) { showError(_("You forgot your sketchbook"), _("Arduino cannot run because it could not\n" + "create a folder to store your sketchbook."), null); } return sketchbookFolder; } /** * Check for a new sketchbook location. */ static protected File promptSketchbookLocation() { File folder = null; folder = new File(System.getProperty("user.home"), "sketchbook"); if (!folder.exists()) { folder.mkdirs(); return folder; } String prompt = _("Select (or create new) folder for sketches..."); folder = Base.selectFolder(prompt, null, null); if (folder == null) { System.exit(0); } return folder; } // ................................................................. /** * Implements the cross-platform headache of opening URLs * TODO This code should be replaced by PApplet.link(), * however that's not a static method (because it requires * an AppletContext when used as an applet), so it's mildly * trickier than just removing this method. */ static public void openURL(String url) { try { platform.openURL(url); } catch (Exception e) { showWarning(_("Problem Opening URL"), I18n.format(_("Could not open the URL\n{0}"), url), e); } } /** * Used to determine whether to disable the "Show Sketch Folder" option. * @return true If a means of opening a folder is known to be available. */ static protected boolean openFolderAvailable() { return platform.openFolderAvailable(); } /** * Implements the other cross-platform headache of opening * a folder in the machine's native file browser. */ static public void openFolder(File file) { try { platform.openFolder(file); } catch (Exception e) { showWarning(_("Problem Opening Folder"), I18n.format(_("Could not open the folder\n{0}"), file.getAbsolutePath()), e); } } // ................................................................. /** * Prompt for a fodler and return it as a File object (or null). * Implementation for choosing directories that handles both the * Mac OS X hack to allow the native AWT file dialog, or uses * the JFileChooser on other platforms. Mac AWT trick obtained from * <A HREF="http://lists.apple.com/archives/java-dev/2003/Jul/msg00243.html">this post</A> * on the OS X Java dev archive which explains the cryptic note in * Apple's Java 1.4 release docs about the special System property. */ static public File selectFolder(String prompt, File folder, Frame frame) { if (Base.isMacOS()) { if (frame == null) frame = new Frame(); //.pack(); FileDialog fd = new FileDialog(frame, prompt, FileDialog.LOAD); if (folder != null) { fd.setDirectory(folder.getParent()); //fd.setFile(folder.getName()); } System.setProperty("apple.awt.fileDialogForDirectories", "true"); fd.setVisible(true); System.setProperty("apple.awt.fileDialogForDirectories", "false"); if (fd.getFile() == null) { return null; } return new File(fd.getDirectory(), fd.getFile()); } else { JFileChooser fc = new JFileChooser(); fc.setDialogTitle(prompt); if (folder != null) { fc.setSelectedFile(folder); } fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int returned = fc.showOpenDialog(new JDialog()); if (returned == JFileChooser.APPROVE_OPTION) { return fc.getSelectedFile(); } } return null; } // ................................................................. /** * Give this Frame a Processing icon. */ static public void setIcon(Frame frame) { // don't use the low-res icon on Mac OS X; the window should // already have the right icon from the .app file. if (Base.isMacOS()) return; Image image = Toolkit.getDefaultToolkit().createImage(PApplet.ICON_IMAGE); frame.setIconImage(image); } // someone needs to be slapped //static KeyStroke closeWindowKeyStroke; /** * Return true if the key event was a Ctrl-W or an ESC, * both indicators to close the window. * Use as part of a keyPressed() event handler for frames. */ /* static public boolean isCloseWindowEvent(KeyEvent e) { if (closeWindowKeyStroke == null) { int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); closeWindowKeyStroke = KeyStroke.getKeyStroke('W', modifiers); } return ((e.getKeyCode() == KeyEvent.VK_ESCAPE) || KeyStroke.getKeyStrokeForEvent(e).equals(closeWindowKeyStroke)); } */ /** * Registers key events for a Ctrl-W and ESC with an ActionListener * that will take care of disposing the window. */ static public void registerWindowCloseKeys(JRootPane root, ActionListener disposer) { KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); root.registerKeyboardAction(disposer, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW); int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); stroke = KeyStroke.getKeyStroke('W', modifiers); root.registerKeyboardAction(disposer, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW); } // ................................................................. static public void showReference(String filename) { File referenceFolder = Base.getContentFile("reference"); File referenceFile = new File(referenceFolder, filename); openURL(referenceFile.getAbsolutePath()); } static public void showGettingStarted() { if (Base.isMacOS()) { Base.showReference(_("Guide_MacOSX.html")); } else if (Base.isWindows()) { Base.showReference(_("Guide_Windows.html")); } else { Base.openURL(_("http://www.arduino.cc/playground/Learning/Linux")); } } static public void showReference() { showReference(_("index.html")); } static public void showEnvironment() { showReference(_("Guide_Environment.html")); } static public void showPlatforms() { showReference(_("environment") + File.separator + _("platforms.html")); } static public void showTroubleshooting() { showReference(_("Guide_Troubleshooting.html")); } static public void showFAQ() { showReference(_("FAQ.html")); } // ................................................................. /** * "No cookie for you" type messages. Nothing fatal or all that * much of a bummer, but something to notify the user about. */ static public void showMessage(String title, String message) { if (title == null) title = _("Message"); if (commandLine) { System.out.println(title + ": " + message); } else { JOptionPane.showMessageDialog(new Frame(), message, title, JOptionPane.INFORMATION_MESSAGE); } } /** * Non-fatal error message with optional stack trace side dish. */ static public void showWarning(String title, String message, Exception e) { if (title == null) title = _("Warning"); if (commandLine) { System.out.println(title + ": " + message); } else { JOptionPane.showMessageDialog(new Frame(), message, title, JOptionPane.WARNING_MESSAGE); } if (e != null) e.printStackTrace(); } /** * Show an error message that's actually fatal to the program. * This is an error that can't be recovered. Use showWarning() * for errors that allow P5 to continue running. */ static public void showError(String title, String message, Throwable e) { if (title == null) title = _("Error"); if (commandLine) { System.err.println(title + ": " + message); } else { JOptionPane.showMessageDialog(new Frame(), message, title, JOptionPane.ERROR_MESSAGE); } if (e != null) e.printStackTrace(); System.exit(1); } // ................................................................... // incomplete static public int showYesNoCancelQuestion(Editor editor, String title, String primary, String secondary) { if (!Base.isMacOS()) { int result = JOptionPane.showConfirmDialog(null, primary + "\n" + secondary, title, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); return result; // if (result == JOptionPane.YES_OPTION) { // // } else if (result == JOptionPane.NO_OPTION) { // return true; // ok to continue // // } else if (result == JOptionPane.CANCEL_OPTION) { // return false; // // } else { // throw new IllegalStateException(); // } } else { // Pane formatting adapted from the Quaqua guide // http://www.randelshofer.ch/quaqua/guide/joptionpane.html JOptionPane pane = new JOptionPane("<html> " + "<head> <style type=\"text/css\">"+ "b { font: 13pt \"Lucida Grande\" }"+ "p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+ "</style> </head>" + "<b>Do you want to save changes to this sketch<BR>" + " before closing?</b>" + "<p>If you don't save, your changes will be lost.", JOptionPane.QUESTION_MESSAGE); String[] options = new String[] { "Save", "Cancel", "Don't Save" }; pane.setOptions(options); // highlight the safest option ala apple hig pane.setInitialValue(options[0]); // on macosx, setting the destructive property places this option // away from the others at the lefthand side pane.putClientProperty("Quaqua.OptionPane.destructiveOption", new Integer(2)); JDialog dialog = pane.createDialog(editor, null); dialog.setVisible(true); Object result = pane.getValue(); if (result == options[0]) { return JOptionPane.YES_OPTION; } else if (result == options[1]) { return JOptionPane.CANCEL_OPTION; } else if (result == options[2]) { return JOptionPane.NO_OPTION; } else { return JOptionPane.CLOSED_OPTION; } } } //if (result == JOptionPane.YES_OPTION) { // // } else if (result == JOptionPane.NO_OPTION) { // return true; // ok to continue // // } else if (result == JOptionPane.CANCEL_OPTION) { // return false; // // } else { // throw new IllegalStateException(); // } static public int showYesNoQuestion(Frame editor, String title, String primary, String secondary) { if (!Base.isMacOS()) { return JOptionPane.showConfirmDialog(editor, "<html><body>" + "<b>" + primary + "</b>" + "<br>" + secondary, title, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); } else { // Pane formatting adapted from the Quaqua guide // http://www.randelshofer.ch/quaqua/guide/joptionpane.html JOptionPane pane = new JOptionPane("<html> " + "<head> <style type=\"text/css\">"+ "b { font: 13pt \"Lucida Grande\" }"+ "p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+ "</style> </head>" + "<b>" + primary + "</b>" + "<p>" + secondary + "</p>", JOptionPane.QUESTION_MESSAGE); String[] options = new String[] { "Yes", "No" }; pane.setOptions(options); // highlight the safest option ala apple hig pane.setInitialValue(options[0]); JDialog dialog = pane.createDialog(editor, null); dialog.setVisible(true); Object result = pane.getValue(); if (result == options[0]) { return JOptionPane.YES_OPTION; } else if (result == options[1]) { return JOptionPane.NO_OPTION; } else { return JOptionPane.CLOSED_OPTION; } } } /** * Retrieve a path to something in the Processing folder. Eventually this * may refer to the Contents subfolder of Processing.app, if we bundle things * up as a single .app file with no additional folders. */ // static public String getContentsPath(String filename) { // String basePath = System.getProperty("user.dir"); // /* // // do this later, when moving to .app package // if (PApplet.platform == PConstants.MACOSX) { // basePath = System.getProperty("processing.contents"); // } // */ // return basePath + File.separator + filename; // } /** * Get a path for something in the Processing lib folder. */ /* static public String getLibContentsPath(String filename) { String libPath = getContentsPath("lib/" + filename); File libDir = new File(libPath); if (libDir.exists()) { return libPath; } // was looking into making this run from Eclipse, but still too much mess // libPath = getContents("build/shared/lib/" + what); // libDir = new File(libPath); // if (libDir.exists()) { // return libPath; // } return null; } */ static public File getContentFile(String name) { String path = System.getProperty("user.dir"); // Get a path to somewhere inside the .app folder if (Base.isMacOS()) { // <key>javaroot</key> // <string>$JAVAROOT</string> String javaroot = System.getProperty("javaroot"); if (javaroot != null) { path = javaroot; } } File working = new File(path); return new File(working, name); } /** * Get an image associated with the current color theme. */ static public Image getThemeImage(String name, Component who) { return getLibImage("theme/" + name, who); } /** * Return an Image object from inside the Processing lib folder. */ static public Image getLibImage(String name, Component who) { Image image = null; Toolkit tk = Toolkit.getDefaultToolkit(); File imageLocation = new File(getContentFile("lib"), name); image = tk.getImage(imageLocation.getAbsolutePath()); MediaTracker tracker = new MediaTracker(who); tracker.addImage(image, 0); try { tracker.waitForAll(); } catch (InterruptedException e) { } return image; } /** * Return an InputStream for a file inside the Processing lib folder. */ static public InputStream getLibStream(String filename) throws IOException { return new FileInputStream(new File(getContentFile("lib"), filename)); } // ................................................................... /** * Get the number of lines in a file by counting the number of newline * characters inside a String (and adding 1). */ static public int countLines(String what) { int count = 1; for (char c : what.toCharArray()) { if (c == '\n') count++; } return count; } /** * Same as PApplet.loadBytes(), however never does gzip decoding. */ static public byte[] loadBytesRaw(File file) throws IOException { int size = (int) file.length(); FileInputStream input = new FileInputStream(file); byte buffer[] = new byte[size]; int offset = 0; int bytesRead; while ((bytesRead = input.read(buffer, offset, size-offset)) != -1) { offset += bytesRead; if (bytesRead == 0) break; } input.close(); // weren't properly being closed input = null; return buffer; } /** * Read from a file with a bunch of attribute/value pairs * that are separated by = and ignore comments with #. */ static public HashMap<String,String> readSettings(File inputFile) { HashMap<String,String> outgoing = new HashMap<String,String>(); if (!inputFile.exists()) return outgoing; // return empty hash String lines[] = PApplet.loadStrings(inputFile); for (int i = 0; i < lines.length; i++) { int hash = lines[i].indexOf('#'); String line = (hash == -1) ? lines[i].trim() : lines[i].substring(0, hash).trim(); if (line.length() == 0) continue; int equals = line.indexOf('='); if (equals == -1) { System.err.println("ignoring illegal line in " + inputFile); System.err.println(" " + line); continue; } String attr = line.substring(0, equals).trim(); String valu = line.substring(equals + 1).trim(); outgoing.put(attr, valu); } return outgoing; } static public void copyFile(File sourceFile, File targetFile) throws IOException { InputStream from = new BufferedInputStream(new FileInputStream(sourceFile)); OutputStream to = new BufferedOutputStream(new FileOutputStream(targetFile)); byte[] buffer = new byte[16 * 1024]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) { to.write(buffer, 0, bytesRead); } to.flush(); from.close(); // ?? from = null; to.close(); // ?? to = null; targetFile.setLastModified(sourceFile.lastModified()); } /** * Grab the contents of a file as a string. */ static public String loadFile(File file) throws IOException { String[] contents = PApplet.loadStrings(file); if (contents == null) return null; return PApplet.join(contents, "\n"); } /** * Spew the contents of a String object out to a file. */ static public void saveFile(String str, File file) throws IOException { File temp = File.createTempFile(file.getName(), null, file.getParentFile()); PApplet.saveStrings(temp, new String[] { str }); if (file.exists()) { boolean result = file.delete(); if (!result) { throw new IOException( I18n.format( _("Could not remove old version of {0}"), file.getAbsolutePath() ) ); } } boolean result = temp.renameTo(file); if (!result) { throw new IOException( I18n.format( _("Could not replace {0}"), file.getAbsolutePath() ) ); } } /** * Copy a folder from one place to another. This ignores all dot files and * folders found in the source directory, to avoid copying silly .DS_Store * files and potentially troublesome .svn folders. */ static public void copyDir(File sourceDir, File targetDir) throws IOException { targetDir.mkdirs(); String files[] = sourceDir.list(); for (int i = 0; i < files.length; i++) { // Ignore dot files (.DS_Store), dot folders (.svn) while copying if (files[i].charAt(0) == '.') continue; //if (files[i].equals(".") || files[i].equals("..")) continue; File source = new File(sourceDir, files[i]); File target = new File(targetDir, files[i]); if (source.isDirectory()) { //target.mkdirs(); copyDir(source, target); target.setLastModified(source.lastModified()); } else { copyFile(source, target); } } } /** * Remove all files in a directory and the directory itself. */ static public void removeDir(File dir) { if (dir.exists()) { removeDescendants(dir); if (!dir.delete()) { System.err.println(I18n.format(_("Could not delete {0}"), dir)); } } } /** * Recursively remove all files within a directory, * used with removeDir(), or when the contents of a dir * should be removed, but not the directory itself. * (i.e. when cleaning temp files from lib/build) */ static public void removeDescendants(File dir) { if (!dir.exists()) return; String files[] = dir.list(); for (int i = 0; i < files.length; i++) { if (files[i].equals(".") || files[i].equals("..")) continue; File dead = new File(dir, files[i]); if (!dead.isDirectory()) { if (!Preferences.getBoolean("compiler.save_build_files")) { if (!dead.delete()) { // temporarily disabled System.err.println(I18n.format(_("Could not delete {0}"), dead)); } } } else { removeDir(dead); //dead.delete(); } } } /** * Calculate the size of the contents of a folder. * Used to determine whether sketches are empty or not. * Note that the function calls itself recursively. */ static public int calcFolderSize(File folder) { int size = 0; String files[] = folder.list(); // null if folder doesn't exist, happens when deleting sketch if (files == null) return -1; for (int i = 0; i < files.length; i++) { if (files[i].equals(".") || (files[i].equals("..")) || files[i].equals(".DS_Store")) continue; File fella = new File(folder, files[i]); if (fella.isDirectory()) { size += calcFolderSize(fella); } else { size += (int) fella.length(); } } return size; } /** * Recursively creates a list of all files within the specified folder, * and returns a list of their relative paths. * Ignores any files/folders prefixed with a dot. */ static public String[] listFiles(String path, boolean relative) { return listFiles(new File(path), relative); } static public String[] listFiles(File folder, boolean relative) { String path = folder.getAbsolutePath(); Vector<String> vector = new Vector<String>(); listFiles(relative ? (path + File.separator) : "", path, vector); String outgoing[] = new String[vector.size()]; vector.copyInto(outgoing); return outgoing; } static protected void listFiles(String basePath, String path, Vector<String> vector) { File folder = new File(path); String list[] = folder.list(); if (list == null) return; for (int i = 0; i < list.length; i++) { if (list[i].charAt(0) == '.') continue; File file = new File(path, list[i]); String newPath = file.getAbsolutePath(); if (newPath.startsWith(basePath)) { newPath = newPath.substring(basePath.length()); } vector.add(newPath); if (file.isDirectory()) { listFiles(basePath, newPath, vector); } } } public final static String getFileNameWithoutExtension(File fileName) { int pos = fileName.getName().lastIndexOf('.'); if (0 < pos && pos <= fileName.getName().length() - 2 ) { return fileName.getName().substring(0, pos); } return fileName.getName(); } public void handleAddLibrary(Editor editor) { JFileChooser fileChooser = new JFileChooser(System.getProperty("user.home")); fileChooser.setDialogTitle(_("Select a zip file or a folder containing the library you'd like to add")); fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); fileChooser.setFileFilter(new FileNameExtensionFilter(_("ZIP files or folders"), "zip")); Dimension preferredSize = fileChooser.getPreferredSize(); fileChooser.setPreferredSize(new Dimension(preferredSize.width + 200, preferredSize.height + 200)); int returnVal = fileChooser.showOpenDialog(editor); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } File sourceFile = fileChooser.getSelectedFile(); File tmpFolder = null; try { // unpack ZIP if (!sourceFile.isDirectory()) { try { tmpFolder = FileUtils.createTempFolder(); ZipDeflater zipDeflater = new ZipDeflater(sourceFile, tmpFolder); zipDeflater.deflate(); File[] foldersInTmpFolder = tmpFolder.listFiles(new OnlyDirs()); if (foldersInTmpFolder.length != 1) { throw new IOException(_("Zip doesn't contain a library")); } sourceFile = foldersInTmpFolder[0]; } catch (IOException e) { editor.statusError(e); return; } } // is there a valid library? File libFolder = sourceFile; String libName = libFolder.getName(); if (!Sketch.isSanitaryName(libName)) { String mess = I18n.format(_("The library \"{0}\" cannot be used.\n" + "Library names must contain only basic letters and numbers.\n" + "(ASCII only and no spaces, and it cannot start with a number)"), libName); editor.statusError(mess); return; } // copy folder File destinationFolder = new File(getSketchbookLibrariesFolder(), sourceFile.getName()); if (!destinationFolder.mkdir()) { editor.statusError(I18n.format(_("A library named {0} already exists"), sourceFile.getName())); return; } try { FileUtils.copy(sourceFile, destinationFolder); } catch (IOException e) { editor.statusError(e); return; } editor.statusNotice(_("Library added to your libraries. Check \"Import library\" menu")); } finally { // delete zip created temp folder, if exists FileUtils.recursiveDelete(tmpFolder); } } }
app/src/processing/app/Base.java
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Processing project - http://processing.org Copyright (c) 2004-10 Ben Fry and Casey Reas Copyright (c) 2001-04 Massachusetts Institute of Technology This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package processing.app; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import java.util.List; import javax.swing.*; import processing.app.debug.TargetPackage; import processing.app.debug.TargetPlatform; import processing.app.helpers.FileUtils; import processing.app.helpers.Maps; import processing.app.helpers.PreferencesMap; import processing.app.helpers.filefilters.OnlyDirs; import processing.app.helpers.filefilters.OnlyFilesWithExtension; import processing.app.javax.swing.filechooser.FileNameExtensionFilter;import processing.app.tools.MapWithSubkeys; import processing.app.tools.ZipDeflater; import processing.core.*; import static processing.app.I18n._; /** * The base class for the main processing application. * Primary role of this class is for platform identification and * general interaction with the system (launching URLs, loading * files and images, etc) that comes from that. */ public class Base { public static final int REVISION = 152; /** This might be replaced by main() if there's a lib/version.txt file. */ static String VERSION_NAME = "0152"; /** Set true if this a proper release rather than a numbered revision. */ static public boolean RELEASE = false; static Map<Integer, String> platformNames = new HashMap<Integer, String>(); static { platformNames.put(PConstants.WINDOWS, "windows"); platformNames.put(PConstants.MACOSX, "macosx"); platformNames.put(PConstants.LINUX, "linux"); } static HashMap<String, Integer> platformIndices = new HashMap<String, Integer>(); static { platformIndices.put("windows", PConstants.WINDOWS); platformIndices.put("macosx", PConstants.MACOSX); platformIndices.put("linux", PConstants.LINUX); } static Platform platform; static private boolean commandLine; // A single instance of the preferences window Preferences preferencesFrame; // set to true after the first time the menu is built. // so that the errors while building don't show up again. boolean builtOnce; static File buildFolder; // these are static because they're used by Sketch static private File examplesFolder; static private File toolsFolder; static private List<File> librariesFolders; // maps library name to their library folder static private Map<String, File> libraries; // maps #included files to their library folder static Map<String, File> importToLibraryTable; // classpath for all known libraries for p5 // (both those in the p5/libs folder and those with lib subfolders // found in the sketchbook) static public String librariesClassPath; static public Map<String, TargetPackage> packages; // Location for untitled items static File untitledFolder; // p5 icon for the window // static Image icon; // int editorCount; List<Editor> editors = Collections.synchronizedList(new ArrayList<Editor>()); Editor activeEditor; static File portableFolder = null; static final String portableSketchbookFolder = "sketchbook"; static public void main(String args[]) throws Exception { initPlatform(); // Portable folder portableFolder = getContentFile("portable"); if (!portableFolder.exists()) portableFolder = null; // run static initialization that grabs all the prefs Preferences.init(null); try { File versionFile = getContentFile("lib/version.txt"); if (versionFile.exists()) { String version = PApplet.loadStrings(versionFile)[0]; if (!version.equals(VERSION_NAME)) { VERSION_NAME = version; RELEASE = true; } } } catch (Exception e) { e.printStackTrace(); } // if (System.getProperty("mrj.version") != null) { // //String jv = System.getProperty("java.version"); // String ov = System.getProperty("os.version"); // if (ov.startsWith("10.5")) { // System.setProperty("apple.laf.useScreenMenuBar", "true"); // } // } /* commandLine = false; if (args.length >= 2) { if (args[0].startsWith("--")) { commandLine = true; } } if (PApplet.javaVersion < 1.5f) { //System.err.println("no way man"); Base.showError("Need to install Java 1.5", "This version of Processing requires \n" + "Java 1.5 or later to run properly.\n" + "Please visit java.com to upgrade.", null); } */ // // Set the look and feel before opening the window // try { // platform.setLookAndFeel(); // } catch (Exception e) { // System.err.println("Non-fatal error while setting the Look & Feel."); // System.err.println("The error message follows, however Processing should run fine."); // System.err.println(e.getMessage()); // //e.printStackTrace(); // } // Use native popups so they don't look so crappy on osx JPopupMenu.setDefaultLightWeightPopupEnabled(false); // Don't put anything above this line that might make GUI, // because the platform has to be inited properly first. // Make sure a full JDK is installed //initRequirements(); // setup the theme coloring fun Theme.init(); // Set the look and feel before opening the window try { platform.setLookAndFeel(); } catch (Exception e) { String mess = e.getMessage(); if (mess.indexOf("ch.randelshofer.quaqua.QuaquaLookAndFeel") == -1) { System.err.println(_("Non-fatal error while setting the Look & Feel.")); System.err.println(_("The error message follows, however Arduino should run fine.")); System.err.println(mess); } } // Create a location for untitled sketches untitledFolder = createTempFolder("untitled"); untitledFolder.deleteOnExit(); new Base(args); } static protected void setCommandLine() { commandLine = true; } static protected boolean isCommandLine() { return commandLine; } static protected void initPlatform() { try { Class<?> platformClass = Class.forName("processing.app.Platform"); if (Base.isMacOS()) { platformClass = Class.forName("processing.app.macosx.Platform"); } else if (Base.isWindows()) { platformClass = Class.forName("processing.app.windows.Platform"); } else if (Base.isLinux()) { platformClass = Class.forName("processing.app.linux.Platform"); } platform = (Platform) platformClass.newInstance(); } catch (Exception e) { Base.showError(_("Problem Setting the Platform"), _("An unknown error occurred while trying to load\n" + "platform-specific code for your machine."), e); } } static protected void initRequirements() { try { Class.forName("com.sun.jdi.VirtualMachine"); } catch (ClassNotFoundException cnfe) { Base.showPlatforms(); Base.showError(_("Please install JDK 1.5 or later"), _("Arduino requires a full JDK (not just a JRE)\n" + "to run. Please install JDK 1.5 or later.\n" + "More information can be found in the reference."), cnfe); } } public Base(String[] args) throws Exception { platform.init(this); // Get the sketchbook path, and make sure it's set properly String sketchbookPath = Preferences.get("sketchbook.path"); // If a value is at least set, first check to see if the folder exists. // If it doesn't, warn the user that the sketchbook folder is being reset. if (sketchbookPath != null) { File sketchbookFolder; if (portableFolder != null) sketchbookFolder = new File(portableFolder, sketchbookPath); else sketchbookFolder = new File(sketchbookPath); if (!sketchbookFolder.exists()) { Base.showWarning(_("Sketchbook folder disappeared"), _("The sketchbook folder no longer exists.\n" + "Arduino will switch to the default sketchbook\n" + "location, and create a new sketchbook folder if\n" + "necessary. Arduino will then stop talking about\n" + "himself in the third person."), null); sketchbookPath = null; } } // If no path is set, get the default sketchbook folder for this platform if (sketchbookPath == null) { File defaultFolder = getDefaultSketchbookFolder(); if (portableFolder != null) Preferences.set("sketchbook.path", portableSketchbookFolder); else Preferences.set("sketchbook.path", defaultFolder.getAbsolutePath()); if (!defaultFolder.exists()) { defaultFolder.mkdirs(); } } packages = new HashMap<String, TargetPackage>(); loadHardware(getHardwareFolder()); loadHardware(getSketchbookHardwareFolder()); // Setup board-dependent variables. onBoardOrPortChange(); boolean opened = false; boolean doUpload = false; boolean doVerify = false; boolean doVerbose = false; String selectBoard = null; String selectPort = null; // Check if any files were passed in on the command line for (int i = 0; i < args.length; i++) { if (args[i].equals("--upload")) { doUpload = true; continue; } if (args[i].equals("--verify")) { doVerify = true; continue; } if (args[i].equals("--verbose") || args[i].equals("-v")) { doVerbose = true; continue; } if (args[i].equals("--board")) { i++; if (i < args.length) selectBoard = args[i]; continue; } if (args[i].equals("--port")) { i++; if (i < args.length) selectPort = args[i]; continue; } String path = args[i]; // Fix a problem with systems that use a non-ASCII languages. Paths are // being passed in with 8.3 syntax, which makes the sketch loader code // unhappy, since the sketch folder naming doesn't match up correctly. // http://dev.processing.org/bugs/show_bug.cgi?id=1089 if (isWindows()) { try { File file = new File(args[i]); path = file.getCanonicalPath(); } catch (IOException e) { e.printStackTrace(); } } if (handleOpen(path) != null) { opened = true; } } if (doUpload || doVerify) { if (!opened) { System.out.println(_("Can't open source sketch!")); System.exit(2); } // Set verbosity for command line build Preferences.set("build.verbose", "" + doVerbose); Preferences.set("upload.verbose", "" + doVerbose); Editor editor = editors.get(0); // Wait until editor is initialized while (!editor.status.isInitialized()) Thread.sleep(10); // Do board selection if requested if (selectBoard != null) selectBoard(selectBoard, editor); if (doUpload) { // Build and upload if (selectPort != null) editor.selectSerialPort(selectPort); editor.exportHandler.run(); } else { // Build only editor.runHandler.run(); } // Error during build or upload int res = editor.status.mode; if (res == EditorStatus.ERR) System.exit(1); // No errors exit gracefully System.exit(0); } // Check if there were previously opened sketches to be restored if (restoreSketches()) opened = true; // Create a new empty window (will be replaced with any files to be opened) if (!opened) { handleNew(); } // Check for updates if (Preferences.getBoolean("update.check")) { new UpdateCheck(this); } } /** * Post-constructor setup for the editor area. Loads the last * sketch that was used (if any), and restores other Editor settings. * The complement to "storePreferences", this is called when the * application is first launched. */ protected boolean restoreSketches() { // figure out window placement Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); boolean windowPositionValid = true; if (Preferences.get("last.screen.height") != null) { // if screen size has changed, the window coordinates no longer // make sense, so don't use them unless they're identical int screenW = Preferences.getInteger("last.screen.width"); int screenH = Preferences.getInteger("last.screen.height"); if ((screen.width != screenW) || (screen.height != screenH)) { windowPositionValid = false; } /* int windowX = Preferences.getInteger("last.window.x"); int windowY = Preferences.getInteger("last.window.y"); if ((windowX < 0) || (windowY < 0) || (windowX > screenW) || (windowY > screenH)) { windowPositionValid = false; } */ } else { windowPositionValid = false; } // Iterate through all sketches that were open last time p5 was running. // If !windowPositionValid, then ignore the coordinates found for each. // Save the sketch path and window placement for each open sketch int count = Preferences.getInteger("last.sketch.count"); int opened = 0; for (int i = 0; i < count; i++) { String path = Preferences.get("last.sketch" + i + ".path"); if (portableFolder != null) { File absolute = new File(portableFolder, path); try { path = absolute.getCanonicalPath(); } catch (IOException e) { // path unchanged. } } int[] location; if (windowPositionValid) { String locationStr = Preferences.get("last.sketch" + i + ".location"); location = PApplet.parseInt(PApplet.split(locationStr, ',')); } else { location = nextEditorLocation(); } // If file did not exist, null will be returned for the Editor if (handleOpen(path, location) != null) { opened++; } } return (opened > 0); } /** * Store list of sketches that are currently open. * Called when the application is quitting and documents are still open. */ protected void storeSketches() { // Save the width and height of the screen Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); Preferences.setInteger("last.screen.width", screen.width); Preferences.setInteger("last.screen.height", screen.height); String untitledPath = untitledFolder.getAbsolutePath(); // Save the sketch path and window placement for each open sketch int index = 0; for (Editor editor : editors) { String path = editor.getSketch().getMainFilePath(); // In case of a crash, save untitled sketches if they contain changes. // (Added this for release 0158, may not be a good idea.) if (path.startsWith(untitledPath) && !editor.getSketch().isModified()) { continue; } if (portableFolder != null) { path = FileUtils.relativePath(portableFolder.toString(), path); if (path == null) continue; } Preferences.set("last.sketch" + index + ".path", path); int[] location = editor.getPlacement(); String locationStr = PApplet.join(PApplet.str(location), ","); Preferences.set("last.sketch" + index + ".location", locationStr); index++; } Preferences.setInteger("last.sketch.count", index); } // If a sketch is untitled on quit, may need to store the new name // rather than the location from the temp folder. protected void storeSketchPath(Editor editor, int index) { String path = editor.getSketch().getMainFilePath(); String untitledPath = untitledFolder.getAbsolutePath(); if (path.startsWith(untitledPath)) { path = ""; } else if (portableFolder != null) { path = FileUtils.relativePath(portableFolder.toString(), path); if (path == null) path = ""; } Preferences.set("last.sketch" + index + ".path", path); } /* public void storeSketch(Editor editor) { int index = -1; for (int i = 0; i < editorCount; i++) { if (editors[i] == editor) { index = i; break; } } if (index == -1) { System.err.println("Problem storing sketch " + editor.sketch.name); } else { String path = editor.sketch.getMainFilePath(); Preferences.set("last.sketch" + index + ".path", path); } } */ // ................................................................. // Because of variations in native windowing systems, no guarantees about // changes to the focused and active Windows can be made. Developers must // never assume that this Window is the focused or active Window until this // Window receives a WINDOW_GAINED_FOCUS or WINDOW_ACTIVATED event. protected void handleActivated(Editor whichEditor) { activeEditor = whichEditor; // set the current window to be the console that's getting output EditorConsole.setEditor(activeEditor); } protected int[] nextEditorLocation() { Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); int defaultWidth = Preferences.getInteger("editor.window.width.default"); int defaultHeight = Preferences.getInteger("editor.window.height.default"); if (activeEditor == null) { // If no current active editor, use default placement return new int[] { (screen.width - defaultWidth) / 2, (screen.height - defaultHeight) / 2, defaultWidth, defaultHeight, 0 }; } else { // With a currently active editor, open the new window // using the same dimensions, but offset slightly. synchronized (editors) { final int OVER = 50; // In release 0160, don't //location = activeEditor.getPlacement(); Editor lastOpened = editors.get(editors.size() - 1); int[] location = lastOpened.getPlacement(); // Just in case the bounds for that window are bad location[0] += OVER; location[1] += OVER; if (location[0] == OVER || location[2] == OVER || location[0] + location[2] > screen.width || location[1] + location[3] > screen.height) { // Warp the next window to a randomish location on screen. return new int[] { (int) (Math.random() * (screen.width - defaultWidth)), (int) (Math.random() * (screen.height - defaultHeight)), defaultWidth, defaultHeight, 0 }; } return location; } } } // ................................................................. boolean breakTime = false; String[] months = { "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" }; /** * Handle creating a sketch folder, return its base .pde file * or null if the operation was canceled. * @param shift whether shift is pressed, which will invert prompt setting * @param noPrompt disable prompt, no matter the setting */ protected String createNewUntitled() throws IOException { File newbieDir = null; String newbieName = null; // In 0126, untitled sketches will begin in the temp folder, // and then moved to a new location because Save will default to Save As. File sketchbookDir = getSketchbookFolder(); File newbieParentDir = untitledFolder; // Use a generic name like sketch_031008a, the date plus a char int index = 0; //SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd"); //SimpleDateFormat formatter = new SimpleDateFormat("MMMdd"); //String purty = formatter.format(new Date()).toLowerCase(); Calendar cal = Calendar.getInstance(); int day = cal.get(Calendar.DAY_OF_MONTH); // 1..31 int month = cal.get(Calendar.MONTH); // 0..11 String purty = months[month] + PApplet.nf(day, 2); do { if (index == 26) { // In 0159, avoid running past z by sending people outdoors. if (!breakTime) { Base.showWarning(_("Time for a Break"), _("You've reached the limit for auto naming of new sketches\n" + "for the day. How about going for a walk instead?"), null); breakTime = true; } else { Base.showWarning(_("Sunshine"), _("No really, time for some fresh air for you."), null); } return null; } newbieName = "sketch_" + purty + ((char) ('a' + index)); newbieDir = new File(newbieParentDir, newbieName); index++; // Make sure it's not in the temp folder *and* it's not in the sketchbook } while (newbieDir.exists() || new File(sketchbookDir, newbieName).exists()); // Make the directory for the new sketch newbieDir.mkdirs(); // Make an empty pde file File newbieFile = new File(newbieDir, newbieName + ".ino"); if (!newbieFile.createNewFile()) { throw new IOException(); } FileUtils.copyFile(new File(getContentFile("examples"), "01.Basics" + File.separator + "BareMinimum" + File.separator + "BareMinimum.ino"), newbieFile); return newbieFile.getAbsolutePath(); } /** * Create a new untitled document in a new sketch window. */ public void handleNew() { try { String path = createNewUntitled(); if (path != null) { Editor editor = handleOpen(path); editor.untitled = true; } } catch (IOException e) { if (activeEditor != null) { activeEditor.statusError(e); } } } /** * Replace the sketch in the current window with a new untitled document. */ public void handleNewReplace() { if (!activeEditor.checkModified()) { return; // sketch was modified, and user canceled } // Close the running window, avoid window boogers with multiple sketches activeEditor.internalCloseRunner(); // Actually replace things handleNewReplaceImpl(); } protected void handleNewReplaceImpl() { try { String path = createNewUntitled(); if (path != null) { activeEditor.handleOpenInternal(path); activeEditor.untitled = true; } // return true; } catch (IOException e) { activeEditor.statusError(e); // return false; } } /** * Open a sketch, replacing the sketch in the current window. * @param path Location of the primary pde file for the sketch. */ public void handleOpenReplace(String path) { if (!activeEditor.checkModified()) { return; // sketch was modified, and user canceled } // Close the running window, avoid window boogers with multiple sketches activeEditor.internalCloseRunner(); boolean loaded = activeEditor.handleOpenInternal(path); if (!loaded) { // replace the document without checking if that's ok handleNewReplaceImpl(); } } /** * Prompt for a sketch to open, and open it in a new window. */ public void handleOpenPrompt() { // get the frontmost window frame for placing file dialog FileDialog fd = new FileDialog(activeEditor, _("Open an Arduino sketch..."), FileDialog.LOAD); // This was annoying people, so disabled it in 0125. //fd.setDirectory(Preferences.get("sketchbook.path")); //fd.setDirectory(getSketchbookPath()); // Only show .pde files as eligible bachelors fd.setFilenameFilter(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".ino") || name.toLowerCase().endsWith(".pde"); } }); fd.setVisible(true); String directory = fd.getDirectory(); String filename = fd.getFile(); // User canceled selection if (filename == null) return; File inputFile = new File(directory, filename); handleOpen(inputFile.getAbsolutePath()); } /** * Open a sketch in a new window. * @param path Path to the pde file for the sketch in question * @return the Editor object, so that properties (like 'untitled') * can be set by the caller */ public Editor handleOpen(String path) { return handleOpen(path, nextEditorLocation()); } protected Editor handleOpen(String path, int[] location) { // System.err.println("entering handleOpen " + path); File file = new File(path); if (!file.exists()) return null; // System.err.println(" editors: " + editors); // Cycle through open windows to make sure that it's not already open. for (Editor editor : editors) { if (editor.getSketch().getMainFilePath().equals(path)) { editor.toFront(); // System.err.println(" handleOpen: already opened"); return editor; } } // If the active editor window is an untitled, and un-modified document, // just replace it with the file that's being opened. // if (activeEditor != null) { // Sketch activeSketch = activeEditor.sketch; // if (activeSketch.isUntitled() && !activeSketch.isModified()) { // // if it's an untitled, unmodified document, it can be replaced. // // except in cases where a second blank window is being opened. // if (!path.startsWith(untitledFolder.getAbsolutePath())) { // activeEditor.handleOpenUnchecked(path, 0, 0, 0, 0); // return activeEditor; // } // } // } // System.err.println(" creating new editor"); Editor editor = new Editor(this, path, location); // Editor editor = null; // try { // editor = new Editor(this, path, location); // } catch (Exception e) { // e.printStackTrace(); // System.err.flush(); // System.out.flush(); // System.exit(1); // } // System.err.println(" done creating new editor"); // EditorConsole.systemErr.println(" done creating new editor"); // Make sure that the sketch actually loaded if (editor.getSketch() == null) { // System.err.println("sketch was null, getting out of handleOpen"); return null; // Just walk away quietly } // if (editors == null) { // editors = new Editor[5]; // } // if (editorCount == editors.length) { // editors = (Editor[]) PApplet.expand(editors); // } // editors[editorCount++] = editor; editors.add(editor); // if (markedForClose != null) { // Point p = markedForClose.getLocation(); // handleClose(markedForClose, false); // // open the new window in // editor.setLocation(p); // } // now that we're ready, show the window // (don't do earlier, cuz we might move it based on a window being closed) editor.setVisible(true); // System.err.println("exiting handleOpen"); return editor; } /** * Close a sketch as specified by its editor window. * @param editor Editor object of the sketch to be closed. * @return true if succeeded in closing, false if canceled. */ public boolean handleClose(Editor editor) { // Check if modified // boolean immediate = editors.size() == 1; if (!editor.checkModified()) { return false; } // Close the running window, avoid window boogers with multiple sketches editor.internalCloseRunner(); if (editors.size() == 1) { // For 0158, when closing the last window /and/ it was already an // untitled sketch, just give up and let the user quit. // if (Preferences.getBoolean("sketchbook.closing_last_window_quits") || // (editor.untitled && !editor.getSketch().isModified())) { if (Base.isMacOS()) { Object[] options = { "OK", "Cancel" }; String prompt = _("<html> " + "<head> <style type=\"text/css\">"+ "b { font: 13pt \"Lucida Grande\" }"+ "p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+ "</style> </head>" + "<b>Are you sure you want to Quit?</b>" + "<p>Closing the last open sketch will quit Arduino."); int result = JOptionPane.showOptionDialog(editor, prompt, _("Quit"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == JOptionPane.NO_OPTION || result == JOptionPane.CLOSED_OPTION) { return false; } } // This will store the sketch count as zero editors.remove(editor); Editor.serialMonitor.closeSerialPort(); storeSketches(); // Save out the current prefs state Preferences.save(); // Since this wasn't an actual Quit event, call System.exit() System.exit(0); } else { // More than one editor window open, // proceed with closing the current window. editor.setVisible(false); editor.dispose(); // for (int i = 0; i < editorCount; i++) { // if (editor == editors[i]) { // for (int j = i; j < editorCount-1; j++) { // editors[j] = editors[j+1]; // } // editorCount--; // // Set to null so that garbage collection occurs // editors[editorCount] = null; // } // } editors.remove(editor); } return true; } /** * Handler for File &rarr; Quit. * @return false if canceled, true otherwise. */ public boolean handleQuit() { // If quit is canceled, this will be replaced anyway // by a later handleQuit() that is not canceled. storeSketches(); Editor.serialMonitor.closeSerialPort(); if (handleQuitEach()) { // make sure running sketches close before quitting for (Editor editor : editors) { editor.internalCloseRunner(); } // Save out the current prefs state Preferences.save(); if (!Base.isMacOS()) { // If this was fired from the menu or an AppleEvent (the Finder), // then Mac OS X will send the terminate signal itself. System.exit(0); } return true; } return false; } /** * Attempt to close each open sketch in preparation for quitting. * @return false if canceled along the way */ protected boolean handleQuitEach() { int index = 0; for (Editor editor : editors) { if (editor.checkModified()) { // Update to the new/final sketch path for this fella storeSketchPath(editor, index); index++; } else { return false; } } return true; } // ................................................................. /** * Asynchronous version of menu rebuild to be used on save and rename * to prevent the interface from locking up until the menus are done. */ protected void rebuildSketchbookMenus() { //System.out.println("async enter"); //new Exception().printStackTrace(); SwingUtilities.invokeLater(new Runnable() { public void run() { //System.out.println("starting rebuild"); rebuildSketchbookMenu(Editor.sketchbookMenu); rebuildToolbarMenu(Editor.toolbarMenu); //System.out.println("done with rebuild"); } }); //System.out.println("async exit"); } protected void rebuildToolbarMenu(JMenu menu) { JMenuItem item; menu.removeAll(); // Add the single "Open" item item = Editor.newJMenuItem(_("Open..."), 'O'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleOpenPrompt(); } }); menu.add(item); menu.addSeparator(); // Add a list of all sketches and subfolders try { boolean sketches = addSketches(menu, getSketchbookFolder(), true); if (sketches) menu.addSeparator(); } catch (IOException e) { e.printStackTrace(); } // Add each of the subfolders of examples directly to the menu try { boolean found = addSketches(menu, examplesFolder, true); if (found) menu.addSeparator(); } catch (IOException e) { e.printStackTrace(); } } protected void rebuildSketchbookMenu(JMenu menu) { //System.out.println("rebuilding sketchbook menu"); //new Exception().printStackTrace(); try { menu.removeAll(); addSketches(menu, getSketchbookFolder(), false); //addSketches(menu, getSketchbookFolder()); } catch (IOException e) { e.printStackTrace(); } } public Map<String, File> getIDELibs() { if (libraries == null) return new HashMap<String, File>(); Map<String, File> ideLibs = new HashMap<String, File>(libraries); for (String lib : libraries.keySet()) { if (FileUtils.isSubDirectory(getSketchbookFolder(), libraries.get(lib))) ideLibs.remove(lib); } return ideLibs; } public Map<String, File> getUserLibs() { if (libraries == null) return new HashMap<String, File>(); Map<String, File> userLibs = new HashMap<String, File>(libraries); for (String lib : libraries.keySet()) { if (!FileUtils.isSubDirectory(getSketchbookFolder(), libraries.get(lib))) userLibs.remove(lib); } return userLibs; } public void rebuildImportMenu(JMenu importMenu, final Editor editor) { importMenu.removeAll(); JMenuItem addLibraryMenuItem = new JMenuItem(_("Add Library...")); addLibraryMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.this.handleAddLibrary(editor); Base.this.onBoardOrPortChange(); Base.this.rebuildImportMenu(Editor.importMenu, editor); Base.this.rebuildExamplesMenu(Editor.examplesMenu); } }); importMenu.add(addLibraryMenuItem); // Split between user supplied libraries and IDE libraries TargetPlatform targetPlatform = getTargetPlatform(); if (targetPlatform != null) { Map<String, File> ideLibs = getIDELibs(); Map<String, File> userLibs = getUserLibs(); try { // Find the current target. Get the platform, and then select the // correct name and core path. PreferencesMap prefs = targetPlatform.getPreferences(); String targetname = prefs.get("name"); if (false) { // Hack to extract these words by gettext tool. // These phrases are actually defined in the "platform.txt". String notused = _("Arduino AVR Boards"); notused = _("Arduino ARM (32-bits) Boards"); } JMenuItem platformItem = new JMenuItem(_(targetname)); platformItem.setEnabled(false); importMenu.add(platformItem); if (ideLibs.size() > 0) { importMenu.addSeparator(); addLibraries(importMenu, ideLibs); } if (userLibs.size() > 0) { importMenu.addSeparator(); addLibraries(importMenu, userLibs); } } catch (IOException e) { e.printStackTrace(); } } } public void rebuildExamplesMenu(JMenu menu) { try { menu.removeAll(); // Add examples from distribution "example" folder boolean found = addSketches(menu, examplesFolder, false); if (found) menu.addSeparator(); // Add examples from libraries Map<String, File> ideLibs = getIDELibs(); List<String> names = new ArrayList<String>(ideLibs.keySet()); Collections.sort(names, String.CASE_INSENSITIVE_ORDER); for (String name : names) { File folder = ideLibs.get(name); addSketchesSubmenu(menu, name, folder, false); // Allows "fat" libraries to have examples in the root folder if (folder.getName().equals(Base.getTargetPlatform().getName())) addSketchesSubmenu(menu, name, folder.getParentFile(), false); } Map<String, File> userLibs = getUserLibs(); if (userLibs.size()>0) { menu.addSeparator(); names = new ArrayList<String>(userLibs.keySet()); Collections.sort(names, String.CASE_INSENSITIVE_ORDER); for (String name : names) { File folder = userLibs.get(name); addSketchesSubmenu(menu, name, folder, false); // Allows "fat" libraries to have examples in the root folder if (folder.getName().equals(Base.getTargetPlatform().getName())) addSketchesSubmenu(menu, name, folder.getParentFile(), false); } } } catch (IOException e) { e.printStackTrace(); } } public Map<String, File> scanLibraries(List<File> folders) { Map<String, File> res = new HashMap<String, File>(); for (File folder : folders) res.putAll(scanLibraries(folder)); return res; } public Map<String, File> scanLibraries(File folder) { Map<String, File> res = new HashMap<String, File>(); String list[] = folder.list(new OnlyDirs()); // if a bad folder or something like that, this might come back null if (list == null) return res; for (String libName : list) { File subfolder = new File(folder, libName); if (!Sketch.isSanitaryName(libName)) { String mess = I18n.format(_("The library \"{0}\" cannot be used.\n" + "Library names must contain only basic letters and numbers.\n" + "(ASCII only and no spaces, and it cannot start with a number)"), libName); Base.showMessage(_("Ignoring bad library name"), mess); continue; } subfolder = scanFatLibrary(subfolder); // (also replace previously found libs with the same name) if (subfolder != null) res.put(libName, subfolder); } return res; } /** * Scans inside a "FAT" (multi-platform) library folder to see if it contains * a version suitable for the actual selected architecture. If a suitable * version is found the folder containing that version is returned, otherwise * <b>null</b> is returned.<br /> * <br /> * If a non-"FAT" library is detected, we assume that the library is suitable * for the current architecture and the libFolder parameter is returned.<br /> * * @param libFolder * @return */ public File scanFatLibrary(File libFolder) { // A library is considered "fat" if it contains a file called // "library.properties" File libraryPropFile = new File(libFolder, "library.properties"); if (!libraryPropFile.exists() || !libraryPropFile.isFile()) return libFolder; // Search for a subfolder for actual architecture, return null if not found File archSubfolder = new File(libFolder, Base.getTargetPlatform().getName()); if (!archSubfolder.exists() || !archSubfolder.isDirectory()) return null; return archSubfolder; } public void onBoardOrPortChange() { TargetPlatform targetPlatform = getTargetPlatform(); if (targetPlatform == null) return; // Calculate paths for libraries and examples examplesFolder = getContentFile("examples"); toolsFolder = getContentFile("tools"); File platformFolder = targetPlatform.getFolder(); librariesFolders = new ArrayList<File>(); librariesFolders.add(getContentFile("libraries")); librariesFolders.add(new File(platformFolder.getParentFile(), "libraries")); librariesFolders.add(new File(platformFolder, "libraries")); librariesFolders.add(getSketchbookLibrariesFolder()); // Scan for libraries in each library folder. // Libraries located in the latest folders on the list can override // other libraries with the same name. libraries = scanLibraries(librariesFolders); // Populate importToLibraryTable importToLibraryTable = new HashMap<String, File>(); for (File subfolder : libraries.values()) { try { String packages[] = headerListFromIncludePath(subfolder); for (String pkg : packages) { importToLibraryTable.put(pkg, subfolder); } } catch (IOException e) { showWarning(_("Error"), I18n.format("Unable to list header files in {0}", subfolder), e); } } // Update editors status bar for (Editor editor : editors) editor.onBoardOrPortChange(); } public void rebuildBoardsMenu(JMenu toolsMenu, final Editor editor) { JMenu boardsMenu = makeOrGetBoardMenu(toolsMenu, _("Board")); String selPackage = Preferences.get("target_package"); String selPlatform = Preferences.get("target_platform"); String selBoard = Preferences.get("board"); boolean first = true; List<JMenuItem> menuItemsToClickAfterStartup = new LinkedList<JMenuItem>(); ButtonGroup boardsButtonGroup = new ButtonGroup(); Map<String, ButtonGroup> buttonGroupsMap = new HashMap<String, ButtonGroup>(); JMenu currentMenu = null; // Cycle through all packages for (TargetPackage targetPackage : packages.values()) { String packageName = targetPackage.getName(); // For every package cycle through all platform for (TargetPlatform targetPlatform : targetPackage.platforms()) { String platformName = targetPlatform.getName(); Map<String, PreferencesMap> boards = targetPlatform.getBoards(); if (targetPlatform.getPreferences().get("name") == null || targetPlatform.getBoards().isEmpty()) { continue; } /* // Add a title for each group of boards if (!first) { boardsMenu.add(new JSeparator()); } first = false; */ //JMenuItem separator = new JMenuItem(_(targetPlatform.getPreferences().get("name"))); currentMenu = new JMenu(_(targetPlatform.getPreferences().get("name"))); //separator.setEnabled(false); boardsMenu.add(currentMenu); // For every platform cycle through all boards for (final String boardID : targetPlatform.getBoards().keySet()) { // Setup a menu item for the current board String boardName = boards.get(boardID).get("name"); @SuppressWarnings("serial") Action action = new AbstractAction(boardName) { public void actionPerformed(ActionEvent actionevent) { selectBoard((String) getValue("b"), editor); } }; action.putValue("b", packageName + ":" + platformName + ":" + boardID); JRadioButtonMenuItem item = new JRadioButtonMenuItem(action); currentMenu.add(item); boardsButtonGroup.add(item); if (selBoard.equals(boardID) && selPackage.equals(packageName) && selPlatform.equals(platformName)) { menuItemsToClickAfterStartup.add(item); } if (targetPlatform.getCustomMenus() != null) { List<String> customMenuIDs = new LinkedList<String>(targetPlatform.getCustomMenus().getKeys()); for (int i = 0; i < customMenuIDs.size(); i++) { final String customMenuID = customMenuIDs.get(i); JMenu menu = makeOrGetBoardMenu(toolsMenu, _(targetPlatform.getCustomMenus().getValueOf(customMenuID))); MapWithSubkeys customMenu = targetPlatform.getCustomMenus().get(customMenuID); if (customMenu.getKeys().contains(boardID)) { MapWithSubkeys boardCustomMenu = customMenu.get(boardID); final int currentIndex = i + 1 + 1; //plus 1 to skip the first board menu, plus 1 to keep the custom menu next to this one for (final String customMenuOption : boardCustomMenu.getKeys()) { @SuppressWarnings("serial") Action subAction = new AbstractAction(_(boardCustomMenu.getValueOf(customMenuOption))) { public void actionPerformed(ActionEvent e) { Preferences.set("target_package", (String) getValue("package")); Preferences.set("target_platform", (String) getValue("platform")); Preferences.set("board", (String) getValue("board")); Preferences.set("custom_" + customMenuID, boardID + "_" + (String) getValue("custom_menu_option")); filterVisibilityOfSubsequentBoardMenus((String) getValue("board"), currentIndex); onBoardOrPortChange(); Sketch.buildSettingChanged(); rebuildImportMenu(Editor.importMenu, editor); rebuildExamplesMenu(Editor.examplesMenu); } }; subAction.putValue("board", boardID); subAction.putValue("custom_menu_option", customMenuOption); subAction.putValue("package", packageName); subAction.putValue("platform", platformName); if (!buttonGroupsMap.containsKey(customMenuID)) { buttonGroupsMap.put(customMenuID, new ButtonGroup()); } item = new JRadioButtonMenuItem(subAction); menu.add(item); buttonGroupsMap.get(customMenuID).add(item); String selectedCustomMenuEntry = Preferences.get("custom_" + customMenuID); if (selBoard.equals(boardID) && (boardID + "_" + customMenuOption).equals(selectedCustomMenuEntry)) { menuItemsToClickAfterStartup.add(item); } } } } } } } } if (menuItemsToClickAfterStartup.isEmpty()) { menuItemsToClickAfterStartup.add(selectFirstEnabledMenuItem(boardsMenu)); } for (JMenuItem menuItemToClick : menuItemsToClickAfterStartup) { menuItemToClick.setSelected(true); menuItemToClick.getAction().actionPerformed(new ActionEvent(this, -1, "")); } } private static void filterVisibilityOfSubsequentBoardMenus(String boardID, int fromIndex) { for (int i = fromIndex; i < Editor.boardsMenus.size(); i++) { JMenu menu = Editor.boardsMenus.get(i); for (int m = 0; m < menu.getItemCount(); m++) { JMenuItem menuItem = menu.getItem(m); menuItem.setVisible(menuItem.getAction().getValue("board").equals(boardID)); } menu.setEnabled(ifThereAreVisibleItemsOn(menu)); if (menu.isEnabled()) { JMenuItem visibleSelectedOrFirstMenuItem = selectVisibleSelectedOrFirstMenuItem(menu); if (!visibleSelectedOrFirstMenuItem.isSelected()) { visibleSelectedOrFirstMenuItem.setSelected(true); visibleSelectedOrFirstMenuItem.getAction().actionPerformed(null); } } } } private static boolean ifThereAreVisibleItemsOn(JMenu menu) { for (int i = 0; i < menu.getItemCount(); i++) { if (menu.getItem(i).isVisible()) { return true; } } return false; } private JMenu makeOrGetBoardMenu(JMenu toolsMenu, String label) { for (JMenu menu : Editor.boardsMenus) { if (label.equals(menu.getText())) { return menu; } } JMenu menu = new JMenu(label); Editor.boardsMenus.add(menu); toolsMenu.add(menu); return menu; } private static JMenuItem selectVisibleSelectedOrFirstMenuItem(JMenu menu) { JMenuItem firstVisible = null; for (int i = 0; i < menu.getItemCount(); i++) { JMenuItem item = menu.getItem(i); if (item != null && item.isVisible()) { if (item.isSelected()) { return item; } if (firstVisible == null) { firstVisible = item; } } } if (firstVisible != null) { return firstVisible; } throw new IllegalStateException("Menu has no enabled items"); } private static JMenuItem selectFirstEnabledMenuItem(JMenu menu) { for (int i = 0; i < menu.getItemCount(); i++) { JMenuItem item = menu.getItem(i); if (item != null && item.isEnabled()) { return item; } } throw new IllegalStateException("Menu has no enabled items"); } private void selectBoard(String selectBoard, Editor editor) { String[] split = selectBoard.split(":"); Preferences.set("target_package", split[0]); Preferences.set("target_platform", split[1]); Preferences.set("board", split[2]); filterVisibilityOfSubsequentBoardMenus(split[2], 1); onBoardOrPortChange(); Sketch.buildSettingChanged(); rebuildImportMenu(Editor.importMenu, editor); rebuildExamplesMenu(Editor.examplesMenu); } public void rebuildProgrammerMenu(JMenu menu) { menu.removeAll(); ButtonGroup group = new ButtonGroup(); for (TargetPackage targetPackage : packages.values()) { for (TargetPlatform targetPlatform : targetPackage.platforms()) { for (String programmer : targetPlatform.getProgrammers().keySet()) { String id = targetPackage.getName() + ":" + programmer; @SuppressWarnings("serial") AbstractAction action = new AbstractAction(targetPlatform .getProgrammer(programmer).get("name")) { public void actionPerformed(ActionEvent actionevent) { Preferences.set("programmer", "" + getValue("id")); } }; action.putValue("id", id); JMenuItem item = new JRadioButtonMenuItem(action); if (Preferences.get("programmer").equals(id)) item.setSelected(true); group.add(item); menu.add(item); } } } } /** * Scan a folder recursively, and add any sketches found to the menu * specified. Set the openReplaces parameter to true when opening the sketch * should replace the sketch in the current window, or false when the * sketch should open in a new window. */ protected boolean addSketches(JMenu menu, File folder, final boolean replaceExisting) throws IOException { if (folder == null) return false; // skip .DS_Store files, etc (this shouldn't actually be necessary) if (!folder.isDirectory()) return false; String[] list = folder.list(); // If a bad folder or unreadable or whatever, this will come back null if (list == null) return false; // Alphabetize list, since it's not always alpha order Arrays.sort(list, String.CASE_INSENSITIVE_ORDER); boolean ifound = false; for (String name : list) { if ((name.charAt(0) == '.') || name.equals("CVS")) continue; File subfolder = new File(folder, name); if (!subfolder.isDirectory()) continue; if (addSketchesSubmenu(menu, name, subfolder, replaceExisting)) ifound = true; } return ifound; // actually ignored, but.. } private boolean addSketchesSubmenu(JMenu menu, String name, File folder, final boolean replaceExisting) throws IOException { ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent e) { String path = e.getActionCommand(); if (new File(path).exists()) { boolean replace = replaceExisting; if ((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0) { replace = !replace; } if (replace) { handleOpenReplace(path); } else { handleOpen(path); } } else { showWarning(_("Sketch Does Not Exist"), _("The selected sketch no longer exists.\n" + "You may need to restart Arduino to update\n" + "the sketchbook menu."), null); } } }; File entry = new File(folder, name + ".ino"); if (!entry.exists() && (new File(folder, name + ".pde")).exists()) entry = new File(folder, name + ".pde"); // if a .pde file of the same prefix as the folder exists.. if (entry.exists()) { if (!Sketch.isSanitaryName(name)) { if (!builtOnce) { String complaining = I18n .format( _("The sketch \"{0}\" cannot be used.\n" + "Sketch names must contain only basic letters and numbers\n" + "(ASCII-only with no spaces, " + "and it cannot start with a number).\n" + "To get rid of this message, remove the sketch from\n" + "{1}"), name, entry.getAbsolutePath()); Base.showMessage(_("Ignoring sketch with bad name"), complaining); } return false; } JMenuItem item = new JMenuItem(name); item.addActionListener(listener); item.setActionCommand(entry.getAbsolutePath()); menu.add(item); return true; } // don't create an extra menu level for a folder named "examples" if (folder.getName().equals("examples")) return addSketches(menu, folder, replaceExisting); // not a sketch folder, but maybe a subfolder containing sketches JMenu submenu = new JMenu(name); boolean found = addSketches(submenu, folder, replaceExisting); if (found) menu.add(submenu); return found; } protected void addLibraries(JMenu menu, Map<String, File> libs) throws IOException { List<String> list = new ArrayList<String>(libs.keySet()); Collections.sort(list, String.CASE_INSENSITIVE_ORDER); ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent event) { String jarPath = event.getActionCommand(); try { activeEditor.getSketch().importLibrary(jarPath); } catch (IOException e) { showWarning(_("Error"), I18n.format("Unable to list header files in {0}", jarPath), e); } } }; for (String name : list) { File folder = libs.get(name); // Add new element at the bottom JMenuItem item = new JMenuItem(name); item.addActionListener(listener); item.setActionCommand(folder.getAbsolutePath()); menu.add(item); // XXX: DAM: should recurse here so that library folders can be nested } } /** * Given a folder, return a list of the header files in that folder (but not * the header files in its sub-folders, as those should be included from * within the header files at the top-level). */ static public String[] headerListFromIncludePath(File path) throws IOException { String[] list = path.list(new OnlyFilesWithExtension(".h")); if (list == null) { throw new IOException(); } return list; } protected void loadHardware(File folder) { if (!folder.isDirectory()) return; String list[] = folder.list(new OnlyDirs()); // if a bad folder or something like that, this might come back null if (list == null) return; // alphabetize list, since it's not always alpha order // replaced hella slow bubble sort with this feller for 0093 Arrays.sort(list, String.CASE_INSENSITIVE_ORDER); for (String target : list) { // Skip reserved 'tools' folder. if (target.equals("tools")) continue; File subfolder = new File(folder, target); packages.put(target, new TargetPackage(target, subfolder)); } } // ................................................................. /** * Show the About box. */ @SuppressWarnings("serial") public void handleAbout() { final Image image = Base.getLibImage("about.jpg", activeEditor); final Window window = new Window(activeEditor) { public void paint(Graphics g) { g.drawImage(image, 0, 0, null); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); g.setFont(new Font("SansSerif", Font.PLAIN, 11)); g.setColor(Color.white); g.drawString(Base.VERSION_NAME, 50, 30); } }; window.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { window.dispose(); } }); int w = image.getWidth(activeEditor); int h = image.getHeight(activeEditor); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); window.setBounds((screen.width-w)/2, (screen.height-h)/2, w, h); window.setVisible(true); } /** * Show the Preferences window. */ public void handlePrefs() { if (preferencesFrame == null) preferencesFrame = new Preferences(); preferencesFrame.showFrame(activeEditor); } // ................................................................... /** * Get list of platform constants. */ // static public int[] getPlatforms() { // return platforms; // } // static public int getPlatform() { // String osname = System.getProperty("os.name"); // // if (osname.indexOf("Mac") != -1) { // return PConstants.MACOSX; // // } else if (osname.indexOf("Windows") != -1) { // return PConstants.WINDOWS; // // } else if (osname.equals("Linux")) { // true for the ibm vm // return PConstants.LINUX; // // } else { // return PConstants.OTHER; // } // } static public Platform getPlatform() { return platform; } static public String getPlatformName() { String osname = System.getProperty("os.name"); if (osname.indexOf("Mac") != -1) { return "macosx"; } else if (osname.indexOf("Windows") != -1) { return "windows"; } else if (osname.equals("Linux")) { // true for the ibm vm return "linux"; } else { return "other"; } } /** * Map a platform constant to its name. * @param which PConstants.WINDOWS, PConstants.MACOSX, PConstants.LINUX * @return one of "windows", "macosx", or "linux" */ static public String getPlatformName(int which) { return platformNames.get(which); } static public int getPlatformIndex(String what) { Integer entry = platformIndices.get(what); return (entry == null) ? -1 : entry.intValue(); } // These were changed to no longer rely on PApplet and PConstants because // of conflicts that could happen with older versions of core.jar, where // the MACOSX constant would instead read as the LINUX constant. /** * returns true if Processing is running on a Mac OS X machine. */ static public boolean isMacOS() { //return PApplet.platform == PConstants.MACOSX; return System.getProperty("os.name").indexOf("Mac") != -1; } /** * returns true if running on windows. */ static public boolean isWindows() { //return PApplet.platform == PConstants.WINDOWS; return System.getProperty("os.name").indexOf("Windows") != -1; } /** * true if running on linux. */ static public boolean isLinux() { //return PApplet.platform == PConstants.LINUX; return System.getProperty("os.name").indexOf("Linux") != -1; } // ................................................................. static public File getSettingsFolder() { if (portableFolder != null) return portableFolder; File settingsFolder = null; String preferencesPath = Preferences.get("settings.path"); if (preferencesPath != null) { settingsFolder = new File(preferencesPath); } else { try { settingsFolder = platform.getSettingsFolder(); } catch (Exception e) { showError(_("Problem getting data folder"), _("Error getting the Arduino data folder."), e); } } // create the folder if it doesn't exist already if (!settingsFolder.exists()) { if (!settingsFolder.mkdirs()) { showError(_("Settings issues"), _("Arduino cannot run because it could not\n" + "create a folder to store your settings."), null); } } return settingsFolder; } /** * Convenience method to get a File object for the specified filename inside * the settings folder. * For now, only used by Preferences to get the preferences.txt file. * @param filename A file inside the settings folder. * @return filename wrapped as a File object inside the settings folder */ static public File getSettingsFile(String filename) { return new File(getSettingsFolder(), filename); } static public File getBuildFolder() { if (buildFolder == null) { String buildPath = Preferences.get("build.path"); if (buildPath != null) { buildFolder = new File(buildPath); } else { //File folder = new File(getTempFolder(), "build"); //if (!folder.exists()) folder.mkdirs(); buildFolder = createTempFolder("build"); buildFolder.deleteOnExit(); } } return buildFolder; } /** * Get the path to the platform's temporary folder, by creating * a temporary temporary file and getting its parent folder. * <br/> * Modified for revision 0094 to actually make the folder randomized * to avoid conflicts in multi-user environments. (Bug 177) */ static public File createTempFolder(String name) { try { File folder = File.createTempFile(name, null); //String tempPath = ignored.getParent(); //return new File(tempPath); folder.delete(); folder.mkdirs(); return folder; } catch (Exception e) { e.printStackTrace(); } return null; } static public Map<String, File> getLibraries() { return libraries; } static public String getExamplesPath() { return examplesFolder.getAbsolutePath(); } static public List<File> getLibrariesPath() { return librariesFolders; } static public File getToolsFolder() { return toolsFolder; } static public String getToolsPath() { return toolsFolder.getAbsolutePath(); } static public File getHardwareFolder() { // calculate on the fly because it's needed by Preferences.init() to find // the boards.txt and programmers.txt preferences files (which happens // before the other folders / paths get cached). return getContentFile("hardware"); } //Get the core libraries static public File getCoreLibraries(String path) { return getContentFile(path); } static public String getHardwarePath() { return getHardwareFolder().getAbsolutePath(); } static public String getAvrBasePath() { String path = getHardwarePath() + File.separator + "tools" + File.separator + "avr" + File.separator + "bin" + File.separator; if (Base.isLinux() && !(new File(path)).exists()) { return ""; // use distribution provided avr tools if bundled tools missing } return path; } /** * Returns the currently selected TargetPlatform. * * @return */ static public TargetPlatform getTargetPlatform() { String packageName = Preferences.get("target_package"); String platformName = Preferences.get("target_platform"); return getTargetPlatform(packageName, platformName); } /** * Returns a specific TargetPlatform searching Package/Platform * * @param packageName * @param platformName * @return */ static public TargetPlatform getTargetPlatform(String packageName, String platformName) { TargetPackage p = packages.get(packageName); if (p == null) return null; return p.get(platformName); } static public TargetPlatform getCurrentTargetPlatformFromPackage(String pack) { return getTargetPlatform(pack, Preferences.get("target_platform")); } static public Map<String, String> getBoardPreferences() { TargetPlatform target = getTargetPlatform(); String board = Preferences.get("board"); Map<String, String> boardPreferences = Maps.merge(target.getBoards().get(board), new LinkedHashMap<String, String>()); if (target.getCustomMenus() != null) { for (String customMenuID : target.getCustomMenus().getKeys()) { MapWithSubkeys boardCustomMenu = target.getCustomMenus().get(customMenuID).get(board); String selectedCustomMenuEntry = Preferences.get("custom_" + customMenuID); if (boardCustomMenu != null && selectedCustomMenuEntry != null && selectedCustomMenuEntry.startsWith(board)) { String menuEntryId = selectedCustomMenuEntry.substring(selectedCustomMenuEntry.indexOf("_") + 1); Maps.merge(boardCustomMenu.get(menuEntryId).getValues(), boardPreferences); boardPreferences.put("name", boardPreferences.get("name") + ", " + boardCustomMenu.getValueOf(menuEntryId)); } } } return boardPreferences; } static public File getPortableFolder() { return portableFolder; } static public String getPortableSketchbookFolder() { return portableSketchbookFolder; } static public File getSketchbookFolder() { if (portableFolder != null) return new File(portableFolder, Preferences.get("sketchbook.path")); return new File(Preferences.get("sketchbook.path")); } static public File getSketchbookLibrariesFolder() { File libdir = new File(getSketchbookFolder(), "libraries"); if (!libdir.exists()) { try { libdir.mkdirs(); File readme = new File(libdir, "readme.txt"); FileWriter freadme = new FileWriter(readme); freadme.write(_("For information on installing libraries, see: " + "http://arduino.cc/en/Guide/Libraries\n")); freadme.close(); } catch (Exception e) { } } return libdir; } static public String getSketchbookLibrariesPath() { return getSketchbookLibrariesFolder().getAbsolutePath(); } static public File getSketchbookHardwareFolder() { return new File(getSketchbookFolder(), "hardware"); } protected File getDefaultSketchbookFolder() { if (portableFolder != null) return new File(portableFolder, portableSketchbookFolder); File sketchbookFolder = null; try { sketchbookFolder = platform.getDefaultSketchbookFolder(); } catch (Exception e) { } if (sketchbookFolder == null) { sketchbookFolder = promptSketchbookLocation(); } // create the folder if it doesn't exist already boolean result = true; if (!sketchbookFolder.exists()) { result = sketchbookFolder.mkdirs(); } if (!result) { showError(_("You forgot your sketchbook"), _("Arduino cannot run because it could not\n" + "create a folder to store your sketchbook."), null); } return sketchbookFolder; } /** * Check for a new sketchbook location. */ static protected File promptSketchbookLocation() { File folder = null; folder = new File(System.getProperty("user.home"), "sketchbook"); if (!folder.exists()) { folder.mkdirs(); return folder; } String prompt = _("Select (or create new) folder for sketches..."); folder = Base.selectFolder(prompt, null, null); if (folder == null) { System.exit(0); } return folder; } // ................................................................. /** * Implements the cross-platform headache of opening URLs * TODO This code should be replaced by PApplet.link(), * however that's not a static method (because it requires * an AppletContext when used as an applet), so it's mildly * trickier than just removing this method. */ static public void openURL(String url) { try { platform.openURL(url); } catch (Exception e) { showWarning(_("Problem Opening URL"), I18n.format(_("Could not open the URL\n{0}"), url), e); } } /** * Used to determine whether to disable the "Show Sketch Folder" option. * @return true If a means of opening a folder is known to be available. */ static protected boolean openFolderAvailable() { return platform.openFolderAvailable(); } /** * Implements the other cross-platform headache of opening * a folder in the machine's native file browser. */ static public void openFolder(File file) { try { platform.openFolder(file); } catch (Exception e) { showWarning(_("Problem Opening Folder"), I18n.format(_("Could not open the folder\n{0}"), file.getAbsolutePath()), e); } } // ................................................................. /** * Prompt for a fodler and return it as a File object (or null). * Implementation for choosing directories that handles both the * Mac OS X hack to allow the native AWT file dialog, or uses * the JFileChooser on other platforms. Mac AWT trick obtained from * <A HREF="http://lists.apple.com/archives/java-dev/2003/Jul/msg00243.html">this post</A> * on the OS X Java dev archive which explains the cryptic note in * Apple's Java 1.4 release docs about the special System property. */ static public File selectFolder(String prompt, File folder, Frame frame) { if (Base.isMacOS()) { if (frame == null) frame = new Frame(); //.pack(); FileDialog fd = new FileDialog(frame, prompt, FileDialog.LOAD); if (folder != null) { fd.setDirectory(folder.getParent()); //fd.setFile(folder.getName()); } System.setProperty("apple.awt.fileDialogForDirectories", "true"); fd.setVisible(true); System.setProperty("apple.awt.fileDialogForDirectories", "false"); if (fd.getFile() == null) { return null; } return new File(fd.getDirectory(), fd.getFile()); } else { JFileChooser fc = new JFileChooser(); fc.setDialogTitle(prompt); if (folder != null) { fc.setSelectedFile(folder); } fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int returned = fc.showOpenDialog(new JDialog()); if (returned == JFileChooser.APPROVE_OPTION) { return fc.getSelectedFile(); } } return null; } // ................................................................. /** * Give this Frame a Processing icon. */ static public void setIcon(Frame frame) { // don't use the low-res icon on Mac OS X; the window should // already have the right icon from the .app file. if (Base.isMacOS()) return; Image image = Toolkit.getDefaultToolkit().createImage(PApplet.ICON_IMAGE); frame.setIconImage(image); } // someone needs to be slapped //static KeyStroke closeWindowKeyStroke; /** * Return true if the key event was a Ctrl-W or an ESC, * both indicators to close the window. * Use as part of a keyPressed() event handler for frames. */ /* static public boolean isCloseWindowEvent(KeyEvent e) { if (closeWindowKeyStroke == null) { int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); closeWindowKeyStroke = KeyStroke.getKeyStroke('W', modifiers); } return ((e.getKeyCode() == KeyEvent.VK_ESCAPE) || KeyStroke.getKeyStrokeForEvent(e).equals(closeWindowKeyStroke)); } */ /** * Registers key events for a Ctrl-W and ESC with an ActionListener * that will take care of disposing the window. */ static public void registerWindowCloseKeys(JRootPane root, ActionListener disposer) { KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); root.registerKeyboardAction(disposer, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW); int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); stroke = KeyStroke.getKeyStroke('W', modifiers); root.registerKeyboardAction(disposer, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW); } // ................................................................. static public void showReference(String filename) { File referenceFolder = Base.getContentFile("reference"); File referenceFile = new File(referenceFolder, filename); openURL(referenceFile.getAbsolutePath()); } static public void showGettingStarted() { if (Base.isMacOS()) { Base.showReference(_("Guide_MacOSX.html")); } else if (Base.isWindows()) { Base.showReference(_("Guide_Windows.html")); } else { Base.openURL(_("http://www.arduino.cc/playground/Learning/Linux")); } } static public void showReference() { showReference(_("index.html")); } static public void showEnvironment() { showReference(_("Guide_Environment.html")); } static public void showPlatforms() { showReference(_("environment") + File.separator + _("platforms.html")); } static public void showTroubleshooting() { showReference(_("Guide_Troubleshooting.html")); } static public void showFAQ() { showReference(_("FAQ.html")); } // ................................................................. /** * "No cookie for you" type messages. Nothing fatal or all that * much of a bummer, but something to notify the user about. */ static public void showMessage(String title, String message) { if (title == null) title = _("Message"); if (commandLine) { System.out.println(title + ": " + message); } else { JOptionPane.showMessageDialog(new Frame(), message, title, JOptionPane.INFORMATION_MESSAGE); } } /** * Non-fatal error message with optional stack trace side dish. */ static public void showWarning(String title, String message, Exception e) { if (title == null) title = _("Warning"); if (commandLine) { System.out.println(title + ": " + message); } else { JOptionPane.showMessageDialog(new Frame(), message, title, JOptionPane.WARNING_MESSAGE); } if (e != null) e.printStackTrace(); } /** * Show an error message that's actually fatal to the program. * This is an error that can't be recovered. Use showWarning() * for errors that allow P5 to continue running. */ static public void showError(String title, String message, Throwable e) { if (title == null) title = _("Error"); if (commandLine) { System.err.println(title + ": " + message); } else { JOptionPane.showMessageDialog(new Frame(), message, title, JOptionPane.ERROR_MESSAGE); } if (e != null) e.printStackTrace(); System.exit(1); } // ................................................................... // incomplete static public int showYesNoCancelQuestion(Editor editor, String title, String primary, String secondary) { if (!Base.isMacOS()) { int result = JOptionPane.showConfirmDialog(null, primary + "\n" + secondary, title, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); return result; // if (result == JOptionPane.YES_OPTION) { // // } else if (result == JOptionPane.NO_OPTION) { // return true; // ok to continue // // } else if (result == JOptionPane.CANCEL_OPTION) { // return false; // // } else { // throw new IllegalStateException(); // } } else { // Pane formatting adapted from the Quaqua guide // http://www.randelshofer.ch/quaqua/guide/joptionpane.html JOptionPane pane = new JOptionPane("<html> " + "<head> <style type=\"text/css\">"+ "b { font: 13pt \"Lucida Grande\" }"+ "p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+ "</style> </head>" + "<b>Do you want to save changes to this sketch<BR>" + " before closing?</b>" + "<p>If you don't save, your changes will be lost.", JOptionPane.QUESTION_MESSAGE); String[] options = new String[] { "Save", "Cancel", "Don't Save" }; pane.setOptions(options); // highlight the safest option ala apple hig pane.setInitialValue(options[0]); // on macosx, setting the destructive property places this option // away from the others at the lefthand side pane.putClientProperty("Quaqua.OptionPane.destructiveOption", new Integer(2)); JDialog dialog = pane.createDialog(editor, null); dialog.setVisible(true); Object result = pane.getValue(); if (result == options[0]) { return JOptionPane.YES_OPTION; } else if (result == options[1]) { return JOptionPane.CANCEL_OPTION; } else if (result == options[2]) { return JOptionPane.NO_OPTION; } else { return JOptionPane.CLOSED_OPTION; } } } //if (result == JOptionPane.YES_OPTION) { // // } else if (result == JOptionPane.NO_OPTION) { // return true; // ok to continue // // } else if (result == JOptionPane.CANCEL_OPTION) { // return false; // // } else { // throw new IllegalStateException(); // } static public int showYesNoQuestion(Frame editor, String title, String primary, String secondary) { if (!Base.isMacOS()) { return JOptionPane.showConfirmDialog(editor, "<html><body>" + "<b>" + primary + "</b>" + "<br>" + secondary, title, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); } else { // Pane formatting adapted from the Quaqua guide // http://www.randelshofer.ch/quaqua/guide/joptionpane.html JOptionPane pane = new JOptionPane("<html> " + "<head> <style type=\"text/css\">"+ "b { font: 13pt \"Lucida Grande\" }"+ "p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+ "</style> </head>" + "<b>" + primary + "</b>" + "<p>" + secondary + "</p>", JOptionPane.QUESTION_MESSAGE); String[] options = new String[] { "Yes", "No" }; pane.setOptions(options); // highlight the safest option ala apple hig pane.setInitialValue(options[0]); JDialog dialog = pane.createDialog(editor, null); dialog.setVisible(true); Object result = pane.getValue(); if (result == options[0]) { return JOptionPane.YES_OPTION; } else if (result == options[1]) { return JOptionPane.NO_OPTION; } else { return JOptionPane.CLOSED_OPTION; } } } /** * Retrieve a path to something in the Processing folder. Eventually this * may refer to the Contents subfolder of Processing.app, if we bundle things * up as a single .app file with no additional folders. */ // static public String getContentsPath(String filename) { // String basePath = System.getProperty("user.dir"); // /* // // do this later, when moving to .app package // if (PApplet.platform == PConstants.MACOSX) { // basePath = System.getProperty("processing.contents"); // } // */ // return basePath + File.separator + filename; // } /** * Get a path for something in the Processing lib folder. */ /* static public String getLibContentsPath(String filename) { String libPath = getContentsPath("lib/" + filename); File libDir = new File(libPath); if (libDir.exists()) { return libPath; } // was looking into making this run from Eclipse, but still too much mess // libPath = getContents("build/shared/lib/" + what); // libDir = new File(libPath); // if (libDir.exists()) { // return libPath; // } return null; } */ static public File getContentFile(String name) { String path = System.getProperty("user.dir"); // Get a path to somewhere inside the .app folder if (Base.isMacOS()) { // <key>javaroot</key> // <string>$JAVAROOT</string> String javaroot = System.getProperty("javaroot"); if (javaroot != null) { path = javaroot; } } File working = new File(path); return new File(working, name); } /** * Get an image associated with the current color theme. */ static public Image getThemeImage(String name, Component who) { return getLibImage("theme/" + name, who); } /** * Return an Image object from inside the Processing lib folder. */ static public Image getLibImage(String name, Component who) { Image image = null; Toolkit tk = Toolkit.getDefaultToolkit(); File imageLocation = new File(getContentFile("lib"), name); image = tk.getImage(imageLocation.getAbsolutePath()); MediaTracker tracker = new MediaTracker(who); tracker.addImage(image, 0); try { tracker.waitForAll(); } catch (InterruptedException e) { } return image; } /** * Return an InputStream for a file inside the Processing lib folder. */ static public InputStream getLibStream(String filename) throws IOException { return new FileInputStream(new File(getContentFile("lib"), filename)); } // ................................................................... /** * Get the number of lines in a file by counting the number of newline * characters inside a String (and adding 1). */ static public int countLines(String what) { int count = 1; for (char c : what.toCharArray()) { if (c == '\n') count++; } return count; } /** * Same as PApplet.loadBytes(), however never does gzip decoding. */ static public byte[] loadBytesRaw(File file) throws IOException { int size = (int) file.length(); FileInputStream input = new FileInputStream(file); byte buffer[] = new byte[size]; int offset = 0; int bytesRead; while ((bytesRead = input.read(buffer, offset, size-offset)) != -1) { offset += bytesRead; if (bytesRead == 0) break; } input.close(); // weren't properly being closed input = null; return buffer; } /** * Read from a file with a bunch of attribute/value pairs * that are separated by = and ignore comments with #. */ static public HashMap<String,String> readSettings(File inputFile) { HashMap<String,String> outgoing = new HashMap<String,String>(); if (!inputFile.exists()) return outgoing; // return empty hash String lines[] = PApplet.loadStrings(inputFile); for (int i = 0; i < lines.length; i++) { int hash = lines[i].indexOf('#'); String line = (hash == -1) ? lines[i].trim() : lines[i].substring(0, hash).trim(); if (line.length() == 0) continue; int equals = line.indexOf('='); if (equals == -1) { System.err.println("ignoring illegal line in " + inputFile); System.err.println(" " + line); continue; } String attr = line.substring(0, equals).trim(); String valu = line.substring(equals + 1).trim(); outgoing.put(attr, valu); } return outgoing; } static public void copyFile(File sourceFile, File targetFile) throws IOException { InputStream from = new BufferedInputStream(new FileInputStream(sourceFile)); OutputStream to = new BufferedOutputStream(new FileOutputStream(targetFile)); byte[] buffer = new byte[16 * 1024]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) { to.write(buffer, 0, bytesRead); } to.flush(); from.close(); // ?? from = null; to.close(); // ?? to = null; targetFile.setLastModified(sourceFile.lastModified()); } /** * Grab the contents of a file as a string. */ static public String loadFile(File file) throws IOException { String[] contents = PApplet.loadStrings(file); if (contents == null) return null; return PApplet.join(contents, "\n"); } /** * Spew the contents of a String object out to a file. */ static public void saveFile(String str, File file) throws IOException { File temp = File.createTempFile(file.getName(), null, file.getParentFile()); PApplet.saveStrings(temp, new String[] { str }); if (file.exists()) { boolean result = file.delete(); if (!result) { throw new IOException( I18n.format( _("Could not remove old version of {0}"), file.getAbsolutePath() ) ); } } boolean result = temp.renameTo(file); if (!result) { throw new IOException( I18n.format( _("Could not replace {0}"), file.getAbsolutePath() ) ); } } /** * Copy a folder from one place to another. This ignores all dot files and * folders found in the source directory, to avoid copying silly .DS_Store * files and potentially troublesome .svn folders. */ static public void copyDir(File sourceDir, File targetDir) throws IOException { targetDir.mkdirs(); String files[] = sourceDir.list(); for (int i = 0; i < files.length; i++) { // Ignore dot files (.DS_Store), dot folders (.svn) while copying if (files[i].charAt(0) == '.') continue; //if (files[i].equals(".") || files[i].equals("..")) continue; File source = new File(sourceDir, files[i]); File target = new File(targetDir, files[i]); if (source.isDirectory()) { //target.mkdirs(); copyDir(source, target); target.setLastModified(source.lastModified()); } else { copyFile(source, target); } } } /** * Remove all files in a directory and the directory itself. */ static public void removeDir(File dir) { if (dir.exists()) { removeDescendants(dir); if (!dir.delete()) { System.err.println(I18n.format(_("Could not delete {0}"), dir)); } } } /** * Recursively remove all files within a directory, * used with removeDir(), or when the contents of a dir * should be removed, but not the directory itself. * (i.e. when cleaning temp files from lib/build) */ static public void removeDescendants(File dir) { if (!dir.exists()) return; String files[] = dir.list(); for (int i = 0; i < files.length; i++) { if (files[i].equals(".") || files[i].equals("..")) continue; File dead = new File(dir, files[i]); if (!dead.isDirectory()) { if (!Preferences.getBoolean("compiler.save_build_files")) { if (!dead.delete()) { // temporarily disabled System.err.println(I18n.format(_("Could not delete {0}"), dead)); } } } else { removeDir(dead); //dead.delete(); } } } /** * Calculate the size of the contents of a folder. * Used to determine whether sketches are empty or not. * Note that the function calls itself recursively. */ static public int calcFolderSize(File folder) { int size = 0; String files[] = folder.list(); // null if folder doesn't exist, happens when deleting sketch if (files == null) return -1; for (int i = 0; i < files.length; i++) { if (files[i].equals(".") || (files[i].equals("..")) || files[i].equals(".DS_Store")) continue; File fella = new File(folder, files[i]); if (fella.isDirectory()) { size += calcFolderSize(fella); } else { size += (int) fella.length(); } } return size; } /** * Recursively creates a list of all files within the specified folder, * and returns a list of their relative paths. * Ignores any files/folders prefixed with a dot. */ static public String[] listFiles(String path, boolean relative) { return listFiles(new File(path), relative); } static public String[] listFiles(File folder, boolean relative) { String path = folder.getAbsolutePath(); Vector<String> vector = new Vector<String>(); listFiles(relative ? (path + File.separator) : "", path, vector); String outgoing[] = new String[vector.size()]; vector.copyInto(outgoing); return outgoing; } static protected void listFiles(String basePath, String path, Vector<String> vector) { File folder = new File(path); String list[] = folder.list(); if (list == null) return; for (int i = 0; i < list.length; i++) { if (list[i].charAt(0) == '.') continue; File file = new File(path, list[i]); String newPath = file.getAbsolutePath(); if (newPath.startsWith(basePath)) { newPath = newPath.substring(basePath.length()); } vector.add(newPath); if (file.isDirectory()) { listFiles(basePath, newPath, vector); } } } public final static String getFileNameWithoutExtension(File fileName) { int pos = fileName.getName().lastIndexOf('.'); if (0 < pos && pos <= fileName.getName().length() - 2 ) { return fileName.getName().substring(0, pos); } return fileName.getName(); } public void handleAddLibrary(Editor editor) { JFileChooser fileChooser = new JFileChooser(System.getProperty("user.home")); fileChooser.setDialogTitle(_("Select a zip file or a folder containing the library you'd like to add")); fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); fileChooser.setFileFilter(new FileNameExtensionFilter(_("ZIP files or folders"), "zip")); Dimension preferredSize = fileChooser.getPreferredSize(); fileChooser.setPreferredSize(new Dimension(preferredSize.width + 200, preferredSize.height + 200)); int returnVal = fileChooser.showOpenDialog(editor); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } File sourceFile = fileChooser.getSelectedFile(); File tmpFolder = null; try { // unpack ZIP if (!sourceFile.isDirectory()) { try { tmpFolder = FileUtils.createTempFolder(); ZipDeflater zipDeflater = new ZipDeflater(sourceFile, tmpFolder); zipDeflater.deflate(); File[] foldersInTmpFolder = tmpFolder.listFiles(new OnlyDirs()); if (foldersInTmpFolder.length != 1) { throw new IOException(_("Zip doesn't contain a library")); } sourceFile = foldersInTmpFolder[0]; } catch (IOException e) { editor.statusError(e); return; } } // is there a valid library? File libFolder = sourceFile; String libName = libFolder.getName(); if (!Sketch.isSanitaryName(libName)) { String mess = I18n.format(_("The library \"{0}\" cannot be used.\n" + "Library names must contain only basic letters and numbers.\n" + "(ASCII only and no spaces, and it cannot start with a number)"), libName); editor.statusError(mess); return; } // copy folder File destinationFolder = new File(getSketchbookLibrariesFolder(), sourceFile.getName()); if (!destinationFolder.mkdir()) { editor.statusError(I18n.format(_("A library named {0} already exists"), sourceFile.getName())); return; } try { FileUtils.copy(sourceFile, destinationFolder); } catch (IOException e) { editor.statusError(e); return; } editor.statusNotice(_("Library added to your libraries. Check \"Import library\" menu")); } finally { // delete zip created temp folder, if exists FileUtils.recursiveDelete(tmpFolder); } } }
Boards: fall back to uno board if an invalid board is in preferences
app/src/processing/app/Base.java
Boards: fall back to uno board if an invalid board is in preferences
Java
lgpl-2.1
7ef8371924871d8909e1691a2cf2eed4b7bc4ba6
0
gallardo/opencms-core,alkacon/opencms-core,alkacon/opencms-core,gallardo/opencms-core,gallardo/opencms-core,alkacon/opencms-core,gallardo/opencms-core,alkacon/opencms-core
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.webdav.jackrabbit; import org.opencms.file.CmsResource; import org.opencms.file.CmsVfsResourceNotFoundException; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.repository.CmsPropertyName; import org.opencms.repository.I_CmsRepositoryItem; import org.opencms.repository.I_CmsRepositorySession; import org.opencms.security.CmsPermissionViolationException; import org.opencms.util.CmsFileUtil; import org.opencms.util.CmsStringUtil; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.TreeSet; import java.util.stream.Collectors; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.jackrabbit.webdav.DavCompliance; import org.apache.jackrabbit.webdav.DavException; import org.apache.jackrabbit.webdav.DavMethods; import org.apache.jackrabbit.webdav.DavResource; import org.apache.jackrabbit.webdav.DavResourceFactory; import org.apache.jackrabbit.webdav.DavResourceIterator; import org.apache.jackrabbit.webdav.DavResourceIteratorImpl; import org.apache.jackrabbit.webdav.DavResourceLocator; import org.apache.jackrabbit.webdav.DavServletResponse; import org.apache.jackrabbit.webdav.DavSession; import org.apache.jackrabbit.webdav.MultiStatusResponse; import org.apache.jackrabbit.webdav.io.InputContext; import org.apache.jackrabbit.webdav.io.OutputContext; import org.apache.jackrabbit.webdav.lock.ActiveLock; import org.apache.jackrabbit.webdav.lock.LockInfo; import org.apache.jackrabbit.webdav.lock.LockManager; import org.apache.jackrabbit.webdav.lock.Scope; import org.apache.jackrabbit.webdav.lock.Type; import org.apache.jackrabbit.webdav.property.DavProperty; import org.apache.jackrabbit.webdav.property.DavPropertyName; import org.apache.jackrabbit.webdav.property.DavPropertySet; import org.apache.jackrabbit.webdav.property.DefaultDavProperty; import org.apache.jackrabbit.webdav.property.PropEntry; import org.apache.jackrabbit.webdav.property.ResourceType; import org.apache.jackrabbit.webdav.xml.Namespace; /** * Represents a resource in the WebDav repository (may not actually correspond to an actual OpenCms resource, since * DavResource are also created for the target locations for move/copy operations, before any of the moving / copying happens. */ public class CmsDavResource implements DavResource { /** Logger instance for this class. **/ private static final Log LOG = CmsLog.getLog(CmsDavResource.class); /** The resource factory that produced this resource. */ private CmsDavResourceFactory m_factory; /** The resource locator for this resource. */ private DavResourceLocator m_locator; /** The Webdav session object. */ private CmsDavSession m_session; /** Lazily initialized repository item - null means not initialized, Optional.empty means tried to load resource, but it was not found. */ private Optional<I_CmsRepositoryItem> m_item; /** The lock manager. */ private LockManager m_lockManager; /** * Creates a new instance. * * @param loc the locator for this resource * @param factory the factory that produced this resource * @param session the Webdav session * @param lockManager the lock manager */ public CmsDavResource( DavResourceLocator loc, CmsDavResourceFactory factory, CmsDavSession session, LockManager lockManager) { m_factory = factory; m_locator = loc; m_session = session; m_lockManager = lockManager; } /** * @see org.apache.jackrabbit.webdav.DavResource#addLockManager(org.apache.jackrabbit.webdav.lock.LockManager) */ public void addLockManager(LockManager lockmgr) { m_lockManager = lockmgr; } /** * @see org.apache.jackrabbit.webdav.DavResource#addMember(org.apache.jackrabbit.webdav.DavResource, org.apache.jackrabbit.webdav.io.InputContext) */ public void addMember(DavResource dres, InputContext inputContext) throws DavException { I_CmsRepositorySession session = getRepositorySession(); String childPath = ((CmsDavResource)dres).getCmsPath(); String method = ((CmsDavInputContext)inputContext).getMethod(); InputStream stream = inputContext.getInputStream(); if (method.equals(DavMethods.METHOD_MKCOL) && (stream != null)) { throw new DavException(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); } if (dres.exists() && isLocked(dres)) { throw new DavException(DavServletResponse.SC_LOCKED); } try { if (stream != null) { session.save(childPath, stream, true); } else { session.create(childPath); } } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); throw new DavException(CmsDavUtil.getStatusForException(e), e); } catch (Exception e) { throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } /** * @see org.apache.jackrabbit.webdav.DavResource#alterProperties(java.util.List) */ public MultiStatusResponse alterProperties(List<? extends PropEntry> changeList) throws DavException { if (exists() && isLocked(this)) { throw new DavException(DavServletResponse.SC_LOCKED); } MultiStatusResponse res = new MultiStatusResponse(getHref(), null); Map<CmsPropertyName, String> propMap = new HashMap<>(); for (PropEntry entry : changeList) { if (entry instanceof DefaultDavProperty<?>) { DefaultDavProperty<String> prop = (DefaultDavProperty<String>)entry; CmsPropertyName cmsPropName = new CmsPropertyName( prop.getName().getNamespace().getURI(), prop.getName().getName()); propMap.put(cmsPropName, prop.getValue()); } else if (entry instanceof DavPropertyName) { CmsPropertyName cmsPropName = new CmsPropertyName( ((DavPropertyName)entry).getNamespace().getURI(), ((DavPropertyName)entry).getName()); propMap.put(cmsPropName, ""); } } int status = HttpServletResponse.SC_OK; try { getRepositorySession().updateProperties(getCmsPath(), propMap); } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); if (e instanceof CmsPermissionViolationException) { status = HttpServletResponse.SC_FORBIDDEN; } } for (PropEntry entry : changeList) { if (entry instanceof DavPropertyName) { res.add((DavPropertyName)entry, status); } else if (entry instanceof DefaultDavProperty<?>) { res.add((DavProperty)entry, status); } else { res.add((DavPropertyName)entry, HttpServletResponse.SC_FORBIDDEN); } } return res; } /** * @see org.apache.jackrabbit.webdav.DavResource#copy(org.apache.jackrabbit.webdav.DavResource, boolean) */ public void copy(DavResource dres, boolean shallow) throws DavException { CmsDavResource other = (CmsDavResource)dres; boolean targetParentExists = false; try { targetParentExists = dres.getCollection().exists(); } catch (Exception e) { LOG.warn(e.getLocalizedMessage(), e); } if (!targetParentExists) { throw new DavException(HttpServletResponse.SC_CONFLICT); } try { getRepositorySession().copy(getCmsPath(), other.getCmsPath(), true, shallow); } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); throw new DavException(CmsDavUtil.getStatusForException(e)); } } /** * Deletes the resource. * * @throws DavException if an error occurs */ public void delete() throws DavException { if (!exists()) { throw new DavException(HttpServletResponse.SC_NOT_FOUND); } try { getRepositorySession().delete(getCmsPath()); } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); throw new DavException(CmsDavUtil.getStatusForException(e), e); } } /** * @see org.apache.jackrabbit.webdav.DavResource#exists() */ public boolean exists() { return getItem() != null; } /** * @see org.apache.jackrabbit.webdav.DavResource#getCollection() */ public DavResource getCollection() { DavResourceLocator locator = m_locator.getFactory().createResourceLocator( m_locator.getPrefix(), m_locator.getWorkspacePath(), CmsResource.getParentFolder(m_locator.getResourcePath())); try { return m_factory.createResource(locator, m_session); } catch (DavException e) { return null; } } /** * @see org.apache.jackrabbit.webdav.DavResource#getComplianceClass() */ public String getComplianceClass() { return DavCompliance.concatComplianceClasses(new String[] {DavCompliance._1_, DavCompliance._2_}); } /** * @see org.apache.jackrabbit.webdav.DavResource#getDisplayName() */ public String getDisplayName() { String result = CmsResource.getName(getCmsPath()); result = result.replace("/", ""); return result; } /** * @see org.apache.jackrabbit.webdav.DavResource#getFactory() */ public DavResourceFactory getFactory() { return m_factory; } /** * @see org.apache.jackrabbit.webdav.DavResource#getHref() */ public String getHref() { String href = m_locator.getHref(true); String result = CmsFileUtil.removeTrailingSeparator(href); return result; } /** * @see org.apache.jackrabbit.webdav.DavResource#getLocator() */ public DavResourceLocator getLocator() { return m_locator; } /** * @see org.apache.jackrabbit.webdav.DavResource#getLock(org.apache.jackrabbit.webdav.lock.Type, org.apache.jackrabbit.webdav.lock.Scope) */ public ActiveLock getLock(Type type, Scope scope) { return m_lockManager.getLock(type, scope, this); } /** * @see org.apache.jackrabbit.webdav.DavResource#getLocks() */ public ActiveLock[] getLocks() { ActiveLock writeLock = getLock(Type.WRITE, Scope.EXCLUSIVE); return (writeLock != null) ? new ActiveLock[] {writeLock} : new ActiveLock[0]; } /** * @see org.apache.jackrabbit.webdav.DavResource#getMembers() */ public DavResourceIterator getMembers() { I_CmsRepositorySession session = getRepositorySession(); try { List<I_CmsRepositoryItem> children = session.list(getCmsPath()); List<DavResource> childDavRes = children.stream().map(child -> { String childPath = CmsStringUtil.joinPaths(m_locator.getWorkspacePath(), child.getName()); DavResourceLocator childLocator = m_locator.getFactory().createResourceLocator( m_locator.getPrefix(), m_locator.getWorkspacePath(), childPath); return new CmsDavResource(childLocator, m_factory, m_session, m_lockManager); }).collect(Collectors.toList()); return new DavResourceIteratorImpl(childDavRes); } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); return null; } } /** * @see org.apache.jackrabbit.webdav.DavResource#getModificationTime() */ public long getModificationTime() { I_CmsRepositoryItem item = getItem(); return item.getLastModifiedDate(); } /** * @see org.apache.jackrabbit.webdav.DavResource#getProperties() */ public DavPropertySet getProperties() { DavPropertySet result = new DavPropertySet(); ResourceType typeProp = new ResourceType( isCollection() ? ResourceType.COLLECTION : ResourceType.DEFAULT_RESOURCE); result.add(typeProp); result.add( new DefaultDavProperty<String>( DavPropertyName.GETLASTMODIFIED, CmsDavUtil.DATE_FORMAT.format(new Date(getItem().getLastModifiedDate())))); result.add(new DefaultDavProperty<String>(DavPropertyName.DISPLAYNAME, "" + getItem().getName())); if (!isCollection()) { result.add( new DefaultDavProperty<String>(DavPropertyName.GETCONTENTLENGTH, "" + getItem().getContentLength())); result.add(new DefaultDavProperty<String>(DavPropertyName.GETETAG, getETag())); } try { Map<CmsPropertyName, String> cmsProps = getRepositorySession().getProperties(getCmsPath()); for (Map.Entry<CmsPropertyName, String> entry : cmsProps.entrySet()) { CmsPropertyName propName = entry.getKey(); DavPropertyName name = DavPropertyName.create( propName.getName(), Namespace.getNamespace(propName.getNamespace())); result.add(new DefaultDavProperty<String>(name, entry.getValue())); } } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); } return result; } /** * @see org.apache.jackrabbit.webdav.DavResource#getProperty(org.apache.jackrabbit.webdav.property.DavPropertyName) */ public DavProperty<?> getProperty(DavPropertyName name) { return getProperties().get(name); } /** * @see org.apache.jackrabbit.webdav.DavResource#getPropertyNames() */ public DavPropertyName[] getPropertyNames() { return getProperties().getPropertyNames(); } /** * @see org.apache.jackrabbit.webdav.DavResource#getResourcePath() */ public String getResourcePath() { return m_locator.getResourcePath(); } /** * @see org.apache.jackrabbit.webdav.DavResource#getSession() */ public DavSession getSession() { return m_session; } /** * @see org.apache.jackrabbit.webdav.DavResource#getSupportedMethods() */ public String getSupportedMethods() { TreeSet<String> methods = new TreeSet<>(); I_CmsRepositoryItem item = getItem(); if (item == null) { methods.addAll(Arrays.asList(DavMethods.METHOD_OPTIONS, DavMethods.METHOD_PUT, DavMethods.METHOD_MKCOL)); methods.add(DavMethods.METHOD_LOCK); } else { methods.addAll( Arrays.asList( DavMethods.METHOD_OPTIONS, DavMethods.METHOD_HEAD, DavMethods.METHOD_POST, DavMethods.METHOD_DELETE)); methods.add(DavMethods.METHOD_PROPFIND); methods.add(DavMethods.METHOD_PROPPATCH); Arrays.asList(DavMethods.METHOD_COPY, DavMethods.METHOD_MOVE); if (!item.isCollection()) { methods.add(DavMethods.METHOD_PUT); } } return CmsStringUtil.listAsString(new ArrayList<>(methods), ", "); } /** * @see org.apache.jackrabbit.webdav.DavResource#hasLock(org.apache.jackrabbit.webdav.lock.Type, org.apache.jackrabbit.webdav.lock.Scope) */ public boolean hasLock(Type type, Scope scope) { return m_lockManager.getLock(type, scope, this) != null; } /** * @see org.apache.jackrabbit.webdav.DavResource#isCollection() */ public boolean isCollection() { I_CmsRepositoryItem item = getItem(); return (item != null) && item.isCollection(); } /** * @see org.apache.jackrabbit.webdav.DavResource#isLockable(org.apache.jackrabbit.webdav.lock.Type, org.apache.jackrabbit.webdav.lock.Scope) */ public boolean isLockable(Type type, Scope scope) { // TODO Auto-generated method stub return false; } /** * @see org.apache.jackrabbit.webdav.DavResource#lock(org.apache.jackrabbit.webdav.lock.LockInfo) */ public ActiveLock lock(LockInfo reqLockInfo) throws DavException { return m_lockManager.createLock(reqLockInfo, this); } /** * @see org.apache.jackrabbit.webdav.DavResource#move(org.apache.jackrabbit.webdav.DavResource) */ public void move(DavResource destination) throws DavException { CmsDavResource other = (CmsDavResource)destination; if (isLocked(this)) { throw new DavException(DavServletResponse.SC_LOCKED); } try { getRepositorySession().move(getCmsPath(), other.getCmsPath(), true); } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); throw new DavException(CmsDavUtil.getStatusForException(e)); } } /** * @see org.apache.jackrabbit.webdav.DavResource#refreshLock(org.apache.jackrabbit.webdav.lock.LockInfo, java.lang.String) */ public ActiveLock refreshLock(LockInfo reqLockInfo, String lockToken) throws DavException { return m_lockManager.refreshLock(reqLockInfo, lockToken, this); } /** * @see org.apache.jackrabbit.webdav.DavResource#removeMember(org.apache.jackrabbit.webdav.DavResource) */ public void removeMember(DavResource member) throws DavException { if (isLocked(this) || isLocked(member)) { throw new DavException(DavServletResponse.SC_LOCKED); } ((CmsDavResource)member).delete(); } /** * @see org.apache.jackrabbit.webdav.DavResource#removeProperty(org.apache.jackrabbit.webdav.property.DavPropertyName) */ public void removeProperty(DavPropertyName propertyName) throws DavException { if (exists() && isLocked(this)) { throw new DavException(DavServletResponse.SC_LOCKED); } I_CmsRepositorySession session = getRepositorySession(); Map<CmsPropertyName, String> props = new HashMap<>(); CmsPropertyName key = new CmsPropertyName(propertyName.getNamespace().getURI(), propertyName.getName()); props.put(key, ""); try { session.updateProperties(getCmsPath(), props); } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); throw new DavException(500); } } /** * @see org.apache.jackrabbit.webdav.DavResource#setProperty(org.apache.jackrabbit.webdav.property.DavProperty) */ public void setProperty(DavProperty<?> property) throws DavException { if (exists() && isLocked(this)) { throw new DavException(DavServletResponse.SC_LOCKED); } if (!(property instanceof DefaultDavProperty)) { throw new DavException(HttpServletResponse.SC_FORBIDDEN); } I_CmsRepositorySession session = getRepositorySession(); Map<CmsPropertyName, String> props = new HashMap<>(); DavPropertyName propertyName = property.getName(); String newValue = ((DefaultDavProperty<String>)property).getValue(); if (newValue == null) { newValue = ""; } CmsPropertyName key = new CmsPropertyName(propertyName.getNamespace().getURI(), propertyName.getName()); props.put(key, newValue); try { session.updateProperties(getCmsPath(), props); } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); throw new DavException(500); } } /** * @see org.apache.jackrabbit.webdav.DavResource#spool(org.apache.jackrabbit.webdav.io.OutputContext) */ public void spool(OutputContext outputContext) throws IOException { I_CmsRepositoryItem item = getItem(); outputContext.setContentType(item.getMimeType()); outputContext.setContentLength(item.getContentLength()); outputContext.setModificationTime(item.getLastModifiedDate()); outputContext.setETag(getETag()); OutputStream out = outputContext.getOutputStream(); if (out != null) { out.write(item.getContent()); } } /** * @see org.apache.jackrabbit.webdav.DavResource#unlock(java.lang.String) */ public void unlock(String lockToken) throws DavException { m_lockManager.releaseLock(lockToken, this); } /** * Gets the OpenCms path corresponding to this resource's locator. * * @return the OpenCms path */ private String getCmsPath() { String path = m_locator.getResourcePath(); String workspace = m_locator.getWorkspacePath(); Optional<String> remainingPath = CmsStringUtil.removePrefixPath(workspace, path); return remainingPath.orElse(null); } /** * Computes the ETag for the item (the item must be not null). * * @return the ETag for the repository item */ private String getETag() { return "\"" + getItem().getContentLength() + "-" + getItem().getLastModifiedDate() + "\""; } /** * Tries to load the appropriate repository item for this resource. * * @return the repository item, or null if none was found */ private I_CmsRepositoryItem getItem() { if (m_item == null) { try { I_CmsRepositoryItem item = getRepositorySession().getItem(getCmsPath()); m_item = Optional.of(item); } catch (Exception e) { if (!(e instanceof CmsVfsResourceNotFoundException)) { LOG.error(e.getLocalizedMessage(), e); } else { LOG.info(e.getLocalizedMessage(), e); } m_item = Optional.empty(); } } return m_item.orElse(null); } /** * Gets the OpenCms repository session for which this resource was created. * * @return the OpenCms repository session */ private I_CmsRepositorySession getRepositorySession() { return m_session.getRepositorySession(); } /** * Return true if this resource cannot be modified due to a write lock * that is not owned by the current session. * * @param res the resource to check * * @return true if this resource cannot be modified due to a write lock */ private boolean isLocked(DavResource res) { ActiveLock lock = res.getLock(Type.WRITE, Scope.EXCLUSIVE); if (lock == null) { return false; } else { for (String sLockToken : m_session.getLockTokens()) { if (sLockToken.equals(lock.getToken())) { return false; } } return true; } } }
src/org/opencms/webdav/jackrabbit/CmsDavResource.java
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.webdav.jackrabbit; import org.opencms.file.CmsResource; import org.opencms.file.CmsVfsResourceNotFoundException; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.repository.CmsPropertyName; import org.opencms.repository.I_CmsRepositoryItem; import org.opencms.repository.I_CmsRepositorySession; import org.opencms.security.CmsPermissionViolationException; import org.opencms.util.CmsFileUtil; import org.opencms.util.CmsStringUtil; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.TreeSet; import java.util.stream.Collectors; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.jackrabbit.webdav.DavCompliance; import org.apache.jackrabbit.webdav.DavException; import org.apache.jackrabbit.webdav.DavMethods; import org.apache.jackrabbit.webdav.DavResource; import org.apache.jackrabbit.webdav.DavResourceFactory; import org.apache.jackrabbit.webdav.DavResourceIterator; import org.apache.jackrabbit.webdav.DavResourceIteratorImpl; import org.apache.jackrabbit.webdav.DavResourceLocator; import org.apache.jackrabbit.webdav.DavServletResponse; import org.apache.jackrabbit.webdav.DavSession; import org.apache.jackrabbit.webdav.MultiStatusResponse; import org.apache.jackrabbit.webdav.io.InputContext; import org.apache.jackrabbit.webdav.io.OutputContext; import org.apache.jackrabbit.webdav.lock.ActiveLock; import org.apache.jackrabbit.webdav.lock.LockInfo; import org.apache.jackrabbit.webdav.lock.LockManager; import org.apache.jackrabbit.webdav.lock.Scope; import org.apache.jackrabbit.webdav.lock.Type; import org.apache.jackrabbit.webdav.property.DavProperty; import org.apache.jackrabbit.webdav.property.DavPropertyName; import org.apache.jackrabbit.webdav.property.DavPropertySet; import org.apache.jackrabbit.webdav.property.DefaultDavProperty; import org.apache.jackrabbit.webdav.property.PropEntry; import org.apache.jackrabbit.webdav.property.ResourceType; import org.apache.jackrabbit.webdav.xml.Namespace; /** * Represents a resource in the WebDav repository (may not actually correspond to an actual OpenCms resource, since * DavResource are also created for the target locations for move/copy operations, before any of the moving / copying happens. */ public class CmsDavResource implements DavResource { /** Logger instance for this class. **/ private static final Log LOG = CmsLog.getLog(CmsDavResource.class); /** Default namespace for OpenCms properties. */ Namespace PROP_NAMESPACE = Namespace.getNamespace("prop", "http://opencms.org/ns/prop"); /** The resource factory that produced this resource. */ private CmsDavResourceFactory m_factory; /** The resource locator for this resource. */ private DavResourceLocator m_locator; /** The Webdav session object. */ private CmsDavSession m_session; /** Lazily initialized repository item - null means not initialized, Optional.empty means tried to load resource, but it was not found. */ private Optional<I_CmsRepositoryItem> m_item; /** The lock manager. */ private LockManager m_lockManager; /** * Creates a new instance. * * @param loc the locator for this resource * @param factory the factory that produced this resource * @param session the Webdav session * @param lockManager the lock manager */ public CmsDavResource( DavResourceLocator loc, CmsDavResourceFactory factory, CmsDavSession session, LockManager lockManager) { m_factory = factory; m_locator = loc; m_session = session; m_lockManager = lockManager; } /** * @see org.apache.jackrabbit.webdav.DavResource#addLockManager(org.apache.jackrabbit.webdav.lock.LockManager) */ public void addLockManager(LockManager lockmgr) { m_lockManager = lockmgr; } /** * @see org.apache.jackrabbit.webdav.DavResource#addMember(org.apache.jackrabbit.webdav.DavResource, org.apache.jackrabbit.webdav.io.InputContext) */ public void addMember(DavResource dres, InputContext inputContext) throws DavException { I_CmsRepositorySession session = getRepositorySession(); String childPath = ((CmsDavResource)dres).getCmsPath(); String method = ((CmsDavInputContext)inputContext).getMethod(); InputStream stream = inputContext.getInputStream(); if (method.equals(DavMethods.METHOD_MKCOL) && (stream != null)) { throw new DavException(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); } if (dres.exists() && isLocked(dres)) { throw new DavException(DavServletResponse.SC_LOCKED); } try { if (stream != null) { session.save(childPath, stream, true); } else { session.create(childPath); } } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); throw new DavException(CmsDavUtil.getStatusForException(e), e); } catch (Exception e) { throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } /** * @see org.apache.jackrabbit.webdav.DavResource#alterProperties(java.util.List) */ public MultiStatusResponse alterProperties(List<? extends PropEntry> changeList) throws DavException { if (exists() && isLocked(this)) { throw new DavException(DavServletResponse.SC_LOCKED); } MultiStatusResponse res = new MultiStatusResponse(getHref(), null); Map<CmsPropertyName, String> propMap = new HashMap<>(); for (PropEntry entry : changeList) { if (entry instanceof DefaultDavProperty<?>) { DefaultDavProperty<String> prop = (DefaultDavProperty<String>)entry; CmsPropertyName cmsPropName = new CmsPropertyName( prop.getName().getNamespace().getURI(), prop.getName().getName()); propMap.put(cmsPropName, prop.getValue()); } else if (entry instanceof DavPropertyName) { CmsPropertyName cmsPropName = new CmsPropertyName( ((DavPropertyName)entry).getNamespace().getURI(), ((DavPropertyName)entry).getName()); propMap.put(cmsPropName, ""); } } int status = HttpServletResponse.SC_OK; try { getRepositorySession().updateProperties(getCmsPath(), propMap); } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); if (e instanceof CmsPermissionViolationException) { status = HttpServletResponse.SC_FORBIDDEN; } } for (PropEntry entry : changeList) { if (entry instanceof DavPropertyName) { res.add((DavPropertyName)entry, status); } else if (entry instanceof DefaultDavProperty<?>) { res.add((DavProperty)entry, status); } else { res.add((DavPropertyName)entry, HttpServletResponse.SC_FORBIDDEN); } } return res; } /** * @see org.apache.jackrabbit.webdav.DavResource#copy(org.apache.jackrabbit.webdav.DavResource, boolean) */ public void copy(DavResource dres, boolean shallow) throws DavException { CmsDavResource other = (CmsDavResource)dres; boolean targetParentExists = false; try { targetParentExists = dres.getCollection().exists(); } catch (Exception e) { LOG.warn(e.getLocalizedMessage(), e); } if (!targetParentExists) { throw new DavException(HttpServletResponse.SC_CONFLICT); } try { getRepositorySession().copy(getCmsPath(), other.getCmsPath(), true, shallow); } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); throw new DavException(CmsDavUtil.getStatusForException(e)); } } /** * Deletes the resource. * * @throws DavException if an error occurs */ public void delete() throws DavException { if (!exists()) { throw new DavException(HttpServletResponse.SC_NOT_FOUND); } try { getRepositorySession().delete(getCmsPath()); } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); throw new DavException(CmsDavUtil.getStatusForException(e), e); } } /** * @see org.apache.jackrabbit.webdav.DavResource#exists() */ public boolean exists() { return getItem() != null; } /** * @see org.apache.jackrabbit.webdav.DavResource#getCollection() */ public DavResource getCollection() { DavResourceLocator locator = m_locator.getFactory().createResourceLocator( m_locator.getPrefix(), m_locator.getWorkspacePath(), CmsResource.getParentFolder(m_locator.getResourcePath())); try { return m_factory.createResource(locator, m_session); } catch (DavException e) { return null; } } /** * @see org.apache.jackrabbit.webdav.DavResource#getComplianceClass() */ public String getComplianceClass() { return DavCompliance.concatComplianceClasses(new String[] {DavCompliance._1_, DavCompliance._2_}); } /** * @see org.apache.jackrabbit.webdav.DavResource#getDisplayName() */ public String getDisplayName() { String result = CmsResource.getName(getCmsPath()); result = result.replace("/", ""); return result; } /** * @see org.apache.jackrabbit.webdav.DavResource#getFactory() */ public DavResourceFactory getFactory() { return m_factory; } /** * @see org.apache.jackrabbit.webdav.DavResource#getHref() */ public String getHref() { String href = m_locator.getHref(true); String result = CmsFileUtil.removeTrailingSeparator(href); return result; } /** * @see org.apache.jackrabbit.webdav.DavResource#getLocator() */ public DavResourceLocator getLocator() { return m_locator; } /** * @see org.apache.jackrabbit.webdav.DavResource#getLock(org.apache.jackrabbit.webdav.lock.Type, org.apache.jackrabbit.webdav.lock.Scope) */ public ActiveLock getLock(Type type, Scope scope) { return m_lockManager.getLock(type, scope, this); } /** * @see org.apache.jackrabbit.webdav.DavResource#getLocks() */ public ActiveLock[] getLocks() { ActiveLock writeLock = getLock(Type.WRITE, Scope.EXCLUSIVE); return (writeLock != null) ? new ActiveLock[] {writeLock} : new ActiveLock[0]; } /** * @see org.apache.jackrabbit.webdav.DavResource#getMembers() */ public DavResourceIterator getMembers() { I_CmsRepositorySession session = getRepositorySession(); try { List<I_CmsRepositoryItem> children = session.list(getCmsPath()); List<DavResource> childDavRes = children.stream().map(child -> { String childPath = CmsStringUtil.joinPaths(m_locator.getWorkspacePath(), child.getName()); DavResourceLocator childLocator = m_locator.getFactory().createResourceLocator( m_locator.getPrefix(), m_locator.getWorkspacePath(), childPath); return new CmsDavResource(childLocator, m_factory, m_session, m_lockManager); }).collect(Collectors.toList()); return new DavResourceIteratorImpl(childDavRes); } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); return null; } } /** * @see org.apache.jackrabbit.webdav.DavResource#getModificationTime() */ public long getModificationTime() { I_CmsRepositoryItem item = getItem(); return item.getLastModifiedDate(); } /** * @see org.apache.jackrabbit.webdav.DavResource#getProperties() */ public DavPropertySet getProperties() { DavPropertySet result = new DavPropertySet(); ResourceType typeProp = new ResourceType( isCollection() ? ResourceType.COLLECTION : ResourceType.DEFAULT_RESOURCE); result.add(typeProp); result.add( new DefaultDavProperty<String>( DavPropertyName.GETLASTMODIFIED, CmsDavUtil.DATE_FORMAT.format(new Date(getItem().getLastModifiedDate())))); result.add(new DefaultDavProperty<String>(DavPropertyName.DISPLAYNAME, "" + getItem().getName())); if (!isCollection()) { result.add( new DefaultDavProperty<String>(DavPropertyName.GETCONTENTLENGTH, "" + getItem().getContentLength())); result.add(new DefaultDavProperty<String>(DavPropertyName.GETETAG, getETag())); } try { Map<CmsPropertyName, String> cmsProps = getRepositorySession().getProperties(getCmsPath()); for (Map.Entry<CmsPropertyName, String> entry : cmsProps.entrySet()) { CmsPropertyName propName = entry.getKey(); DavPropertyName name = DavPropertyName.create( propName.getName(), Namespace.getNamespace(propName.getNamespace())); result.add(new DefaultDavProperty<String>(name, entry.getValue())); } } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); } return result; } /** * @see org.apache.jackrabbit.webdav.DavResource#getProperty(org.apache.jackrabbit.webdav.property.DavPropertyName) */ public DavProperty<?> getProperty(DavPropertyName name) { return getProperties().get(name); } /** * @see org.apache.jackrabbit.webdav.DavResource#getPropertyNames() */ public DavPropertyName[] getPropertyNames() { return getProperties().getPropertyNames(); } /** * @see org.apache.jackrabbit.webdav.DavResource#getResourcePath() */ public String getResourcePath() { return m_locator.getResourcePath(); } /** * @see org.apache.jackrabbit.webdav.DavResource#getSession() */ public DavSession getSession() { return m_session; } /** * @see org.apache.jackrabbit.webdav.DavResource#getSupportedMethods() */ public String getSupportedMethods() { TreeSet<String> methods = new TreeSet<>(); I_CmsRepositoryItem item = getItem(); if (item == null) { methods.addAll(Arrays.asList(DavMethods.METHOD_OPTIONS, DavMethods.METHOD_PUT, DavMethods.METHOD_MKCOL)); methods.add(DavMethods.METHOD_LOCK); } else { methods.addAll( Arrays.asList( DavMethods.METHOD_OPTIONS, DavMethods.METHOD_HEAD, DavMethods.METHOD_POST, DavMethods.METHOD_DELETE)); methods.add(DavMethods.METHOD_PROPFIND); methods.add(DavMethods.METHOD_PROPPATCH); Arrays.asList(DavMethods.METHOD_COPY, DavMethods.METHOD_MOVE); if (!item.isCollection()) { methods.add(DavMethods.METHOD_PUT); } } return CmsStringUtil.listAsString(new ArrayList<>(methods), ", "); } /** * @see org.apache.jackrabbit.webdav.DavResource#hasLock(org.apache.jackrabbit.webdav.lock.Type, org.apache.jackrabbit.webdav.lock.Scope) */ public boolean hasLock(Type type, Scope scope) { return m_lockManager.getLock(type, scope, this) != null; } /** * @see org.apache.jackrabbit.webdav.DavResource#isCollection() */ public boolean isCollection() { I_CmsRepositoryItem item = getItem(); return (item != null) && item.isCollection(); } /** * @see org.apache.jackrabbit.webdav.DavResource#isLockable(org.apache.jackrabbit.webdav.lock.Type, org.apache.jackrabbit.webdav.lock.Scope) */ public boolean isLockable(Type type, Scope scope) { // TODO Auto-generated method stub return false; } /** * @see org.apache.jackrabbit.webdav.DavResource#lock(org.apache.jackrabbit.webdav.lock.LockInfo) */ public ActiveLock lock(LockInfo reqLockInfo) throws DavException { return m_lockManager.createLock(reqLockInfo, this); } /** * @see org.apache.jackrabbit.webdav.DavResource#move(org.apache.jackrabbit.webdav.DavResource) */ public void move(DavResource destination) throws DavException { CmsDavResource other = (CmsDavResource)destination; if (isLocked(this)) { throw new DavException(DavServletResponse.SC_LOCKED); } try { getRepositorySession().move(getCmsPath(), other.getCmsPath(), true); } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); throw new DavException(CmsDavUtil.getStatusForException(e)); } } /** * @see org.apache.jackrabbit.webdav.DavResource#refreshLock(org.apache.jackrabbit.webdav.lock.LockInfo, java.lang.String) */ public ActiveLock refreshLock(LockInfo reqLockInfo, String lockToken) throws DavException { return m_lockManager.refreshLock(reqLockInfo, lockToken, this); } /** * @see org.apache.jackrabbit.webdav.DavResource#removeMember(org.apache.jackrabbit.webdav.DavResource) */ public void removeMember(DavResource member) throws DavException { if (isLocked(this) || isLocked(member)) { throw new DavException(DavServletResponse.SC_LOCKED); } ((CmsDavResource)member).delete(); } /** * @see org.apache.jackrabbit.webdav.DavResource#removeProperty(org.apache.jackrabbit.webdav.property.DavPropertyName) */ public void removeProperty(DavPropertyName propertyName) throws DavException { if (exists() && isLocked(this)) { throw new DavException(DavServletResponse.SC_LOCKED); } I_CmsRepositorySession session = getRepositorySession(); Map<CmsPropertyName, String> props = new HashMap<>(); CmsPropertyName key = new CmsPropertyName(propertyName.getNamespace().getURI(), propertyName.getName()); props.put(key, ""); try { session.updateProperties(getCmsPath(), props); } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); throw new DavException(500); } } /** * @see org.apache.jackrabbit.webdav.DavResource#setProperty(org.apache.jackrabbit.webdav.property.DavProperty) */ public void setProperty(DavProperty<?> property) throws DavException { if (exists() && isLocked(this)) { throw new DavException(DavServletResponse.SC_LOCKED); } if (!(property instanceof DefaultDavProperty)) { throw new DavException(HttpServletResponse.SC_FORBIDDEN); } I_CmsRepositorySession session = getRepositorySession(); Map<CmsPropertyName, String> props = new HashMap<>(); DavPropertyName propertyName = property.getName(); String newValue = ((DefaultDavProperty<String>)property).getValue(); if (newValue == null) { newValue = ""; } CmsPropertyName key = new CmsPropertyName(propertyName.getNamespace().getURI(), propertyName.getName()); props.put(key, newValue); try { session.updateProperties(getCmsPath(), props); } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); throw new DavException(500); } } /** * @see org.apache.jackrabbit.webdav.DavResource#spool(org.apache.jackrabbit.webdav.io.OutputContext) */ public void spool(OutputContext outputContext) throws IOException { I_CmsRepositoryItem item = getItem(); outputContext.setContentType(item.getMimeType()); outputContext.setContentLength(item.getContentLength()); outputContext.setModificationTime(item.getLastModifiedDate()); outputContext.setETag(getETag()); OutputStream out = outputContext.getOutputStream(); if (out != null) { out.write(item.getContent()); } } /** * @see org.apache.jackrabbit.webdav.DavResource#unlock(java.lang.String) */ public void unlock(String lockToken) throws DavException { m_lockManager.releaseLock(lockToken, this); } /** * Gets the OpenCms path corresponding to this resource's locator. * * @return the OpenCms path */ private String getCmsPath() { String path = m_locator.getResourcePath(); String workspace = m_locator.getWorkspacePath(); Optional<String> remainingPath = CmsStringUtil.removePrefixPath(workspace, path); return remainingPath.orElse(null); } /** * Computes the ETag for the item (the item must be not null). * * @return the ETag for the repository item */ private String getETag() { return "\"" + getItem().getContentLength() + "-" + getItem().getLastModifiedDate() + "\""; } /** * Tries to load the appropriate repository item for this resource. * * @return the repository item, or null if none was found */ private I_CmsRepositoryItem getItem() { if (m_item == null) { try { I_CmsRepositoryItem item = getRepositorySession().getItem(getCmsPath()); m_item = Optional.of(item); } catch (Exception e) { if (!(e instanceof CmsVfsResourceNotFoundException)) { LOG.error(e.getLocalizedMessage(), e); } else { LOG.info(e.getLocalizedMessage(), e); } m_item = Optional.empty(); } } return m_item.orElse(null); } /** * Gets the OpenCms repository session for which this resource was created. * * @return the OpenCms repository session */ private I_CmsRepositorySession getRepositorySession() { return m_session.getRepositorySession(); } /** * Return true if this resource cannot be modified due to a write lock * that is not owned by the current session. * * @param res the resource to check * * @return true if this resource cannot be modified due to a write lock */ private boolean isLocked(DavResource res) { ActiveLock lock = res.getLock(Type.WRITE, Scope.EXCLUSIVE); if (lock == null) { return false; } else { for (String sLockToken : m_session.getLockTokens()) { if (sLockToken.equals(lock.getToken())) { return false; } } return true; } } }
Removed unused constant.
src/org/opencms/webdav/jackrabbit/CmsDavResource.java
Removed unused constant.