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
c3639173caecde46a6537f3737b158c51e1f7eb0
0
belaban/JGroups,belaban/JGroups,TarantulaTechnology/JGroups,TarantulaTechnology/JGroups,pruivo/JGroups,rvansa/JGroups,kedzie/JGroups,vjuranek/JGroups,ligzy/JGroups,slaskawi/JGroups,dimbleby/JGroups,dimbleby/JGroups,danberindei/JGroups,pferraro/JGroups,Sanne/JGroups,pruivo/JGroups,pferraro/JGroups,pferraro/JGroups,belaban/JGroups,rpelisse/JGroups,TarantulaTechnology/JGroups,rhusar/JGroups,rhusar/JGroups,deepnarsay/JGroups,ligzy/JGroups,ligzy/JGroups,rpelisse/JGroups,vjuranek/JGroups,ibrahimshbat/JGroups,ibrahimshbat/JGroups,deepnarsay/JGroups,deepnarsay/JGroups,kedzie/JGroups,danberindei/JGroups,pruivo/JGroups,dimbleby/JGroups,ibrahimshbat/JGroups,kedzie/JGroups,rvansa/JGroups,ibrahimshbat/JGroups,tristantarrant/JGroups,tristantarrant/JGroups,danberindei/JGroups,rhusar/JGroups,rpelisse/JGroups,slaskawi/JGroups,Sanne/JGroups,vjuranek/JGroups,Sanne/JGroups,slaskawi/JGroups
package org.jgroups.protocols; import org.jgroups.Address; import org.jgroups.Event; import org.jgroups.Message; import org.jgroups.stack.IpAddress; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Loopback transport shared by all channels within the same VM. Property for testing is that no messages are lost. Allows * us to test various protocols (with ProtocolTester) at maximum speed. * @author Bela Ban * @version $Id: SHARED_LOOPBACK.java,v 1.5 2008/04/04 10:23:36 belaban Exp $ */ public class SHARED_LOOPBACK extends TP { private static int next_port=10000; /** Map of cluster names and address-protocol mappings. Used for routing messages to all or single members */ private static final Map<String,Map<Address,SHARED_LOOPBACK>> routing_table=new ConcurrentHashMap<String,Map<Address,SHARED_LOOPBACK>>(); public SHARED_LOOPBACK() { } public String toString() { return "SHARED_LOOPBACK(local address: " + local_addr + ')'; } public void sendToAllMembers(byte[] data, int offset, int length) throws Exception { Map<Address,SHARED_LOOPBACK> dests=routing_table.get(channel_name); if(dests == null) { if(log.isWarnEnabled()) log.warn("no destination found for " + channel_name); return; } for(Map.Entry<Address,SHARED_LOOPBACK> entry: dests.entrySet()) { Address dest=entry.getKey(); SHARED_LOOPBACK target=entry.getValue(); try { target.receive(dest, local_addr, data, offset, length); } catch(Throwable t) { log.error("failed sending message to " + dest, t); } } } public void sendToSingleMember(Address dest, byte[] data, int offset, int length) throws Exception { Map<Address,SHARED_LOOPBACK> dests=routing_table.get(channel_name); if(dests == null) { if(log.isWarnEnabled()) log.warn("no destination found for " + channel_name); return; } SHARED_LOOPBACK target=dests.get(dest); if(target == null) { if(log.isWarnEnabled()) log.warn("destination address " + dest + " not found"); return; } target.receive(dest, local_addr, data, offset, length); } public String getInfo() { return toString(); } public void postUnmarshalling(Message msg, Address dest, Address src, boolean multicast) { msg.setDest(dest); } public void postUnmarshallingList(Message msg, Address dest, boolean multicast) { msg.setDest(dest); } /*------------------------------ Protocol interface ------------------------------ */ public String getName() { return "SHARED_LOOPBACK"; } // public boolean setProperties(Properties props) { // super.setProperties(props); // if(!props.isEmpty()) { // log.error("the following properties are not recognized: " + props); // return false; // } // return true; // } public void init() throws Exception { local_addr=new IpAddress("127.0.0.1", next_port++); super.init(); } public void start() throws Exception { super.start(); } public void stop() { super.stop(); } public Object down(Event evt) { Object retval=super.down(evt); switch(evt.getType()) { case Event.CONNECT: case Event.CONNECT_WITH_STATE_TRANSFER: register(channel_name, local_addr, this); break; case Event.DISCONNECT: unregister(channel_name, local_addr); break; } return retval; } private void register(String channel_name, Address local_addr, SHARED_LOOPBACK shared_loopback) { Map<Address,SHARED_LOOPBACK> map=routing_table.get(channel_name); if(map == null) { map=new ConcurrentHashMap<Address,SHARED_LOOPBACK>(); routing_table.put(channel_name, map); } map.put(local_addr, shared_loopback); } private void unregister(String channel_name, Address local_addr) { Map<Address,SHARED_LOOPBACK> map=routing_table.get(channel_name); if(map != null) { map.remove(local_addr); if(map.isEmpty()) { routing_table.remove(channel_name); } } } }
src/org/jgroups/protocols/SHARED_LOOPBACK.java
package org.jgroups.protocols; import org.jgroups.Address; import org.jgroups.Event; import org.jgroups.Message; import org.jgroups.stack.IpAddress; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Loopback transport shared by all channels within the same VM. Property for testing is that no messages are lost. Allows * us to test various protocols (with ProtocolTester) at maximum speed. * @author Bela Ban * @version $Id: SHARED_LOOPBACK.java,v 1.4 2007/08/14 08:15:49 belaban Exp $ */ public class SHARED_LOOPBACK extends TP { private static int next_port=10000; /** Map of cluster names and address-protocol mappings. Used for routing messages to all or single members */ private static final Map<String,Map<Address,SHARED_LOOPBACK>> routing_table=new ConcurrentHashMap<String,Map<Address,SHARED_LOOPBACK>>(); public SHARED_LOOPBACK() { } public String toString() { return "SHARED_LOOPBACK(local address: " + local_addr + ')'; } public void sendToAllMembers(byte[] data, int offset, int length) throws Exception { Map<Address,SHARED_LOOPBACK> dests=routing_table.get(channel_name); if(dests == null) { if(log.isWarnEnabled()) log.warn("no destination found for " + channel_name); return; } for(Map.Entry<Address,SHARED_LOOPBACK> entry: dests.entrySet()) { Address dest=entry.getKey(); SHARED_LOOPBACK target=entry.getValue(); try { target.receive(dest, local_addr, data, offset, length); } catch(Throwable t) { log.error("failed sending message to " + dest, t); } } } public void sendToSingleMember(Address dest, byte[] data, int offset, int length) throws Exception { Map<Address,SHARED_LOOPBACK> dests=routing_table.get(channel_name); if(dests == null) { if(log.isWarnEnabled()) log.warn("no destination found for " + channel_name); return; } SHARED_LOOPBACK target=dests.get(dest); if(target == null) { if(log.isWarnEnabled()) log.warn("destination address " + dest + " not found"); return; } target.receive(dest, local_addr, data, offset, length); } public String getInfo() { return toString(); } public void postUnmarshalling(Message msg, Address dest, Address src, boolean multicast) { } public void postUnmarshallingList(Message msg, Address dest, boolean multicast) { } /*------------------------------ Protocol interface ------------------------------ */ public String getName() { return "SHARED_LOOPBACK"; } // public boolean setProperties(Properties props) { // super.setProperties(props); // if(!props.isEmpty()) { // log.error("the following properties are not recognized: " + props); // return false; // } // return true; // } public void init() throws Exception { local_addr=new IpAddress("127.0.0.1", next_port++); super.init(); } public void start() throws Exception { super.start(); } public void stop() { super.stop(); } public Object down(Event evt) { Object retval=super.down(evt); switch(evt.getType()) { case Event.CONNECT: case Event.CONNECT_WITH_STATE_TRANSFER: register(channel_name, local_addr, this); break; case Event.DISCONNECT: unregister(channel_name, local_addr); break; } return retval; } private void register(String channel_name, Address local_addr, SHARED_LOOPBACK shared_loopback) { Map<Address,SHARED_LOOPBACK> map=routing_table.get(channel_name); if(map == null) { map=new ConcurrentHashMap<Address,SHARED_LOOPBACK>(); routing_table.put(channel_name, map); } map.put(local_addr, shared_loopback); } private void unregister(String channel_name, Address local_addr) { Map<Address,SHARED_LOOPBACK> map=routing_table.get(channel_name); if(map != null) { map.remove(local_addr); if(map.isEmpty()) { routing_table.remove(channel_name); } } } }
settig destination now in postXXX() callbacks
src/org/jgroups/protocols/SHARED_LOOPBACK.java
settig destination now in postXXX() callbacks
Java
apache-2.0
6372cec29780124daffba920fa0234908875ca78
0
danc86/jena-core,danc86/jena-core
/***************************************************************************** * File Test_schemagen.java * Original author Ian Dickinson, HP Labs Bristol * Author email [email protected] * Package Jena 2 * Web http://sourceforge.net/projects/jena/ * Created 8 Sep 2006 * Filename $RCSfile: Test_schemagen.java,v $ * Revision $Revision: 1.9 $ * Release status $State: Exp $ * * Last modified on $Date: 2010-07-26 10:01:23 $ * by $Author: ian_dickinson $ * * (c) Copyright 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP * [See end of file] *****************************************************************************/ // Package /////////////// package jena.test; // Imports /////////////// import java.io.*; import java.lang.reflect.Method; import java.util.*; import java.util.regex.Pattern; import jena.schemagen; import jena.schemagen.SchemagenOptionsImpl; import junit.framework.TestCase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hp.hpl.jena.rdf.model.*; import com.hp.hpl.jena.util.FileUtils; /** * <p> * Unit tests for schemagen * </p> * * @author Ian Dickinson, HP Labs * (<a href="mailto:[email protected]" >email</a>) * @version CVS $Id: Test_schemagen.java,v 1.9 2010-07-26 10:01:23 ian_dickinson Exp $ */ public class Test_schemagen extends TestCase { // Constants ////////////////////////////////// String PREFIX = "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n" + "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n" + "@prefix owl: <http://www.w3.org/2002/07/owl#> .\n" + "@prefix ex: <http://example.com/sg#> .\n"; // Static variables ////////////////////////////////// private static Logger log = LoggerFactory.getLogger( Test_schemagen.class ); // Instance variables ////////////////////////////////// // Constructors ////////////////////////////////// // External signature methods ////////////////////////////////// /** This test used to fail with an abort, but we now guess the NS based on prevalence */ public void testNoBaseURI0() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ."; testSchemagenOutput( SOURCE, null, new String[] {}, new String[] {".*public static final Resource A =.*"}, new String[] {} ); } public void testClass0() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl"}, new String[] {".*public static final Resource A.*"}, new String[] {} ); } public void testClass1() throws Exception { String SOURCE = PREFIX + "ex:A a rdfs:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl"}, new String[] {}, new String[] {".*public static final Resource A.*"} ); } public void testClass2() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs"}, new String[] {}, new String[] {".*public static final Resource A.*"} ); } public void testClass3() throws Exception { String SOURCE = PREFIX + "ex:A a rdfs:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs"}, new String[] {".*public static final Resource A.*"}, new String[] {} ); } public void testProperty0() throws Exception { String SOURCE = PREFIX + "ex:p a owl:ObjectProperty ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl"}, new String[] {".*public static final Property p.*"}, new String[] {} ); } public void testProperty1() throws Exception { String SOURCE = PREFIX + "ex:p a rdf:Property ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl"}, // in OWL mode we permit rdf:properties new String[] {".*public static final Property p.*"}, new String[] {} ); } public void testProperty2() throws Exception { String SOURCE = PREFIX + "ex:p a owl:ObjectProperty ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs"}, new String[] {}, new String[] {".*public static final Property p.*"} ); } public void testProperty3() throws Exception { String SOURCE = PREFIX + "ex:p a rdf:Property ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs"}, new String[] {".*public static final Property p.*"}, new String[] {} ); } public void testInstance0() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class . ex:i a ex:A ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl"}, new String[] {".*public static final Resource i.*"}, new String[] {} ); } public void testInstance1() throws Exception { String SOURCE = PREFIX + "ex:A a rdfs:Class . ex:i a ex:A ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl"}, new String[] {".*public static final Resource i.*"}, new String[] {} ); } /* TODO this test fails, because the isInstance check in schemagen is quite weak. * Consider whether to fix the test or the code... * public void testInstance2() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class . ex:i a ex:A ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs"}, new String[] {}, new String[] {".*public static final Resource i.*"} ); } */ public void testInstance3() throws Exception { String SOURCE = PREFIX + "ex:A a rdfs:Class . ex:i a ex:A ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs"}, new String[] {".*public static final Resource i.*"}, new String[] {} ); } /** Bug report by Brian: instance is in the namespace, but the class itself is not */ public void testInstance4() throws Exception { String SOURCE = PREFIX + "@prefix ex2: <http://example.org/otherNS#>. ex2:A a rdfs:Class . ex:i a ex2:A ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs"}, new String[] {".*public static final Resource i.*"}, new String[] {} ); } /** Bug report by Brian: instances not being recognised */ public void testInstance5() throws Exception { String SOURCE = "@prefix : <http://ontology.earthster.org/eco/impact#> .\n" + "@prefix core: <http://ontology.earthster.org/eco/core#> .\n" + "@prefix ecoinvent: <http://ontology.earthster.org/eco/ecoinvent#> .\n" + "@prefix owl: <http://www.w3.org/2002/07/owl#> .\n" + "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n" + "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n" + "@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n" + "\n" + "<http://ontology.earthster.org/eco/impact>\n" + " rdf:type owl:Ontology ;\n" + " owl:imports <http://ontology.earthster.org/eco/ecoinvent> , <http://ontology.earthster.org/eco/core> ;\n" + " owl:versionInfo \"Created with TopBraid Composer\"^^xsd:string .\n" + "\n" + ":CD-CML2001-AbioticDepletion\n" + " rdf:type core:ImpactAssessmentMethodCategoryDescription ;\n" + " rdfs:label \"abiotic resource depletion\"^^xsd:string ;\n" + " core:hasImpactCategory\n" + " :abioticDepletion ."; testSchemagenOutput( SOURCE, null, new String[] {"--owl", "--inference"}, new String[] {".*public static final Resource CD_CML2001_AbioticDepletion.*"}, new String[] {".*valtype.*"} ); } /** Bug report by Richard Cyganiak */ public void testRC0() throws Exception { String SOURCE = PREFIX + "ex:class a owl:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl"}, new String[] {}, new String[] {".*public static final Resource class .*"} ); } public void testComment0() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ; rdfs:comment \"commentcomment\" ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl"}, new String[] {" */\\*\\* <p>commentcomment</p> \\*/ *"}, new String[] {} ); } public void testComment1() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ; rdfs:comment \"commentcomment\" ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl", "--nocomments"}, new String[] {}, new String[] {" */\\*\\* <p>commentcomment</p> \\*/ *"} ); } public void testComment2() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ; rdfs:comment \"commentcomment\" ."; // we don't want the input fixed to be http://example.com/sg SchemaGenAux sga = new SchemaGenAux() { @Override protected void go( String[] args ) { go( new SchemagenOptionsImpl( args ) ); } }; testSchemagenOutput( SOURCE, sga, new String[] {"-a", "http://example.com/sg#", "--owl", "-i", "file:\\\\C:\\Users\\fubar/vocabs/test.ttl"}, new String[] {".*Vocabulary definitions from file:\\\\\\\\C:\\\\Users\\\\fubar/vocabs/test.ttl.*"}, new String[] {} ); } public void testComment3() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ; rdfs:comment \"commentcomment\" ."; // we don't want the input fixed to be http://example.com/sg SchemaGenAux sga = new SchemaGenAux() { @Override protected void go( String[] args ) { go( new SchemagenOptionsImpl( args ) ); } }; testSchemagenOutput( SOURCE, sga, new String[] {"-a", "http://example.com/sg#", "--owl", "-i", "C:\\Users\\fubar/vocabs/test.ttl"}, new String[] {".*Vocabulary definitions from C:\\\\Users\\\\fubar/vocabs/test.ttl.*"}, new String[] {} ); } public void testOntClass0() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl", "--ontology"}, new String[] {".*public static final OntClass A.*"}, new String[] {} ); } public void testOntClass1() throws Exception { String SOURCE = PREFIX + "ex:A a rdfs:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl", "--ontology"}, new String[] {}, new String[] {".*public static final OntClass A.*"} ); } public void testOntClass2() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs", "--ontology"}, new String[] {}, new String[] {".*public static final OntClass A.*"} ); } public void testOntClass3() throws Exception { String SOURCE = PREFIX + "ex:A a rdfs:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs", "--ontology"}, new String[] {".*public static final OntClass A.*"}, new String[] {} ); } public void testOntProperty0() throws Exception { String SOURCE = PREFIX + "ex:p a owl:ObjectProperty ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl", "--ontology"}, new String[] {".*public static final ObjectProperty p.*"}, new String[] {} ); } public void testOntProperty1() throws Exception { String SOURCE = PREFIX + "ex:p a rdf:Property ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl", "--ontology"}, // in OWL mode we permit rdf:properties new String[] {".*public static final OntProperty p.*"}, new String[] {} ); } public void testOntProperty2() throws Exception { String SOURCE = PREFIX + "ex:p a owl:ObjectProperty ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs", "--ontology"}, new String[] {}, new String[] {".*public static final ObjectProperty p.*"} ); } public void testOntProperty3() throws Exception { String SOURCE = PREFIX + "ex:p a rdf:Property ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs", "--ontology"}, new String[] {".*public static final OntProperty p.*"}, new String[] {} ); } public void testHeader() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--ontology", "--header", "/* header */\n%package%\n%imports%\n"}, new String[] {"/\\* header \\*/"}, new String[] {} ); } public void testFooter() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--ontology", "--footer", "/* footer */"}, new String[] {"/\\* footer \\*/"}, new String[] {} ); } public void testPackage() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--ontology", "--package", "test.test"}, new String[] {"package test.test;\\s*"}, new String[] {} ); } public void testClassname() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ."; SchemaGenAux fixture = new SchemaGenAux() { @Override protected void go( String[] args ) { SchemagenOptionsFixture sgf = new SchemagenOptionsFixture( args ) { @Override public Resource getInputOption() { return ResourceFactory.createResource( "http://example.org/soggy" ); } }; go( sgf ); } }; testSchemagenOutput( SOURCE, fixture, new String[] {"-a", "http://example.com/soggy#", "--ontology", "--package", "test.test", "-n", "Sg"}, new String[] {}, new String[] {} ); } public void testClassdec() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--ontology", "--classdec", "\n implements java.lang.Cloneable\n"}, new String[] {"\\s*implements java.lang.Cloneable\\s*"}, new String[] {} ); } public void testDeclarations() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--ontology", "--declarations", "protected String m_gnole = \"Fungle\";;\n"}, new String[] {".*Fungle.*"}, new String[] {} ); } public void testNoClasses() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--ontology", "--noclasses"}, new String[] {}, new String[] {".*OntClass A.*"} ); } public void testNoProperties() throws Exception { String SOURCE = PREFIX + "ex:p a owl:ObjectProperty ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl", "--ontology", "--noproperties"}, new String[] {}, new String[] {".*Property p.*"} ); } public void testNoIndividuals() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class . ex:i a ex:A ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl", "--noindividuals"}, new String[] {".*Resource A.*"}, new String[] {".*Resource i.*"} ); } public void testNoHeader() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class . ex:i a ex:A ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl", "--noheader"}, new String[] {}, new String[] {"/\\*\\*.*"} ); } public void testUCNames() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class . ex:i a ex:A ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl", "--uppercase"}, new String[] {".*Resource A.*",".*Resource I.*"}, new String[] {} ); } public void testInference0() throws Exception { String SOURCE = PREFIX + "ex:p rdfs:domain ex:A ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl"}, new String[] {}, new String[] {".*Resource A.*",".*Property p.*"} ); } public void testInference1() throws Exception { String SOURCE = PREFIX + "ex:p rdfs:domain ex:A ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl", "--inference"}, new String[] {".*Resource A.*",".*Property p.*"}, new String[] {} ); } public void testInference2() throws Exception { String SOURCE = PREFIX + "ex:p rdfs:domain ex:A ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs", "--inference"}, new String[] {".*Resource A.*",".*Property p.*"}, new String[] {} ); } public void testStrictIndividuals0() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class . ex:i a ex:A . <http://example.com/different#j> a ex:A ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs"}, new String[] {".*Resource i.*",".*Resource j.*"}, new String[] {} ); } public void testStrictIndividuals1() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class . ex:i a ex:A . <http://example.com/different#j> a ex:A ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs", "--strictIndividuals"}, new String[] {".*Resource i.*"}, new String[] {".*Resource j.*"} ); } public void testLineEnd0() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class . ex:i a ex:A . ex:p a rdf:Property ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs", "--strictIndividuals"}, new String[] {}, new String[] {".*\r.*"} ); } public void testLineEnd1() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class . ex:i a ex:A . ex:p a rdf:Property ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs", "--dos"}, new String[] {".*\\r"}, new String[] {".*[^\r]"} ); } public void testIncludeSource0() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class . ex:i a ex:A . ex:p a owl:ObjectProperty ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl", "--includeSource"}, new String[] {".*private static final String SOURCE.*", ".*ex:A *(a|rdf:type) *owl:Class.*"} , new String[] {} ); } public void testIncludeSource1() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ; rdfs:comment \"comment\"."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl", "--includeSource"}, new String[] {".*\\\\\"comment\\\\\".*\""}, new String[] {} ); } public void testIncludeSource2() throws Exception { // had a report of the following not compiling .... String SOURCE = PREFIX + "@prefix skos: <http://www.w3.org/2004/02/skos/core#>.\n" + " <http://purl.org/dc/elements/1.1/relation> skos:note \"\"\"A second property with the same name as this property has been declared in the dcterms: namespace (http://purl.org/dc/terms/). See the Introduction to the document \"DCMI Metadata Terms\" (http://dublincore.org/documents/dcmi-terms/) for an explanation.\"\"\"."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl", "--includeSource"}, new String[] {}, new String[] {} ); } // Internal implementation methods ////////////////////////////////// /** * Test the output from schemagen by saving the output to a string, * then ensuring that every positive regex matches at least one line, and * every negative regex matches at most no lines. Also checks that * compiling the file does not cause any errors. * * @param source String defining the model, using N3 * @param sg The schemagen object to test, or null for a default * @param args list of args to pass to SG * @param posPatterns array of regexps that must match at least once in the output * @param negPatterns arrays of regexps that must not match the output * @return The string defining the java class */ protected String testSchemagenOutput( String source, SchemaGenAux sg, String[] args, String[] posPatterns, String[] negPatterns ) throws Exception { sg = (sg == null) ? new SchemaGenAux() : sg; Model m = ModelFactory.createDefaultModel(); m.read( new StringReader( source ), "http://example.com/sg#", "N3" ); sg.setSource( m ); ByteArrayOutputStream buf = new ByteArrayOutputStream(); sg.setOutput( new PrintStream( buf ) ); // run schemagen sg.testGo( args ); // now run the test pattern over the lines in the file String result = buf.toString(); // if (log.isDebugEnabled()) { // log.debug( result ); // } StringTokenizer tokens = new StringTokenizer( result, "\n" ); boolean[] foundPos = new boolean[posPatterns.length]; // look for any line that matches the patterns while (tokens.hasMoreTokens()) { String line = tokens.nextToken(); // try each positive pattern for (int i = 0; i < posPatterns.length; i++) { Pattern pat = Pattern.compile( posPatterns[i] ); foundPos[i] |= pat.matcher( line ).matches(); } // try each negative pattern for (int i = 0; i < negPatterns.length; i++) { Pattern pat = Pattern.compile( negPatterns[i] ); assertFalse( "negative match pattern ||" + negPatterns[i] + "|| matched on line: " + line, pat.matcher( line ).matches() ); } } for (int i = 0; i < posPatterns.length; i++) { String msg = "Expecting a positive match to pattern: ||" + posPatterns[i] + "||"; assertTrue( msg + " in:\n" + result, foundPos[i] ); } // check that the file compiles with javac testCompile( result, "Sg" ); return result; } /** * Test the compilability of the generated output string by saving it to a * class file, and invoking javac on that file. * @param source * @param className * @throws Exception */ protected void testCompile( String source, String defaultClassName ) throws Exception { String className = defaultClassName; // ensure we use the right class name for the temp file // should do this with a regex, but java Pattern & Matcher is borked String key = "public class "; int i = source.indexOf( key ); if (i > 0) { i += key.length(); className = source.substring( i, source.indexOf( " ", i ) ); } // first write the source file to a temp dir File tmpDir = FileUtils.getScratchDirectory( "schemagen" ); File srcFile = new File( tmpDir, className + ".java" ); FileWriter out = new FileWriter( srcFile ); out.write( source ); out.close(); // now get ready to invoke javac using the new javax.tools package try { Class<?> tp = Class.forName( "javax.tools.ToolProvider" ); // static method to get the Java compiler tool Method gsjc = tp.getMethod( "getSystemJavaCompiler" ); Object sjc = gsjc.invoke( null ); // get the run method for the Java compiler tool Class<?> jc = Class.forName( "javax.tools.JavaCompiler" ); Method jcRun = jc.getMethod( "run", new Class[] {InputStream.class, OutputStream.class, OutputStream.class, String[].class} ); // build the args list for javac String[] args = new String[] {"-classpath", getClassPath( tmpDir ), "-d", tmpDir.getPath(), srcFile.getPath()}; int success = (Integer) jcRun.invoke( sjc, null, null, null, args ); assertEquals( "Errors reported from compilation of schemagen output", 0, success ); } catch (ClassNotFoundException nf) { log.debug( "javax.tools not found (no tools.jar on classpath?). schemagen compilation test skipped." ); } catch (Exception e) { log.debug( e.getMessage(), e ); fail( e.getMessage() ); } // clean up List<File> toClean = new ArrayList<File>(); toClean.add( tmpDir ); while (!toClean.isEmpty()) { File f = toClean.remove( 0 ); f.deleteOnExit(); if (f.isDirectory()) { for (File g: f.listFiles()) {toClean.add( g );} } } } /** * Return the classpath we can use to compile the sg output files * @param tmpDir * @return */ protected String getClassPath( File tmpDir ) { Properties pp = System.getProperties(); // if we're running under maven, use Special Secret Knowledge to identify the class path // otherwise, default to the CP that Java thinks it's using return pp.getProperty( "surefire.test.class.path", pp.getProperty( "java.class.path" ) ); } //============================================================================== // Inner class definitions //============================================================================== /** * An extension to standard schemagen to create a test fixture; we override the * input and output methods. */ static class SchemaGenAux extends schemagen { protected PrintStream m_auxOutput; protected Model m_auxSource; public void setOutput( PrintStream out ) { m_auxOutput = out; } public void setSource( Model m ) { m_auxSource = m; } // override the behaviours from schemagen @Override protected void selectInput() { m_source.add( m_auxSource ); m_source.setNsPrefixes( m_auxSource ); } @Override protected void selectOutput() { // call super to allow option processing super.selectOutput(); // then override the result m_output = m_auxOutput; } public void testGo( String[] args ) { go( args ); } @Override protected void go( String[] args ) { go( new SchemagenOptionsFixture( args ) ); } @Override protected void abort( String msg, Exception e ) { throw new RuntimeException( msg, e ); } } static class SchemagenOptionsFixture extends SchemagenOptionsImpl { public SchemagenOptionsFixture( String[] args ) { super( args ); } @Override public Resource getInputOption() { return ResourceFactory.createResource( "http://example.org/sg" ); } } } /* * (c) Copyright 2003, 2004, 2005, 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */
src/test/java/jena/test/Test_schemagen.java
/***************************************************************************** * File Test_schemagen.java * Original author Ian Dickinson, HP Labs Bristol * Author email [email protected] * Package Jena 2 * Web http://sourceforge.net/projects/jena/ * Created 8 Sep 2006 * Filename $RCSfile: Test_schemagen.java,v $ * Revision $Revision: 1.8 $ * Release status $State: Exp $ * * Last modified on $Date: 2010-07-23 16:22:34 $ * by $Author: ian_dickinson $ * * (c) Copyright 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP * [See end of file] *****************************************************************************/ // Package /////////////// package jena.test; // Imports /////////////// import java.io.*; import java.lang.reflect.Method; import java.util.*; import java.util.regex.Pattern; import jena.schemagen; import jena.schemagen.SchemagenOptionsImpl; import junit.framework.TestCase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hp.hpl.jena.rdf.model.*; import com.hp.hpl.jena.util.FileUtils; /** * <p> * Unit tests for schemagen * </p> * * @author Ian Dickinson, HP Labs * (<a href="mailto:[email protected]" >email</a>) * @version CVS $Id: Test_schemagen.java,v 1.8 2010-07-23 16:22:34 ian_dickinson Exp $ */ public class Test_schemagen extends TestCase { // Constants ////////////////////////////////// String PREFIX = "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n" + "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n" + "@prefix owl: <http://www.w3.org/2002/07/owl#> .\n" + "@prefix ex: <http://example.com/sg#> .\n"; // Static variables ////////////////////////////////// private static Logger log = LoggerFactory.getLogger( Test_schemagen.class ); // Instance variables ////////////////////////////////// // Constructors ////////////////////////////////// // External signature methods ////////////////////////////////// /** This test used to fail with an abort, but we now guess the NS based on prevalence */ public void testNoBaseURI0() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ."; testSchemagenOutput( SOURCE, null, new String[] {}, new String[] {".*public static final Resource A =.*"}, new String[] {} ); } public void testClass0() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl"}, new String[] {".*public static final Resource A.*"}, new String[] {} ); } public void testClass1() throws Exception { String SOURCE = PREFIX + "ex:A a rdfs:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl"}, new String[] {}, new String[] {".*public static final Resource A.*"} ); } public void testClass2() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs"}, new String[] {}, new String[] {".*public static final Resource A.*"} ); } public void testClass3() throws Exception { String SOURCE = PREFIX + "ex:A a rdfs:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs"}, new String[] {".*public static final Resource A.*"}, new String[] {} ); } public void testProperty0() throws Exception { String SOURCE = PREFIX + "ex:p a owl:ObjectProperty ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl"}, new String[] {".*public static final Property p.*"}, new String[] {} ); } public void testProperty1() throws Exception { String SOURCE = PREFIX + "ex:p a rdf:Property ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl"}, // in OWL mode we permit rdf:properties new String[] {".*public static final Property p.*"}, new String[] {} ); } public void testProperty2() throws Exception { String SOURCE = PREFIX + "ex:p a owl:ObjectProperty ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs"}, new String[] {}, new String[] {".*public static final Property p.*"} ); } public void testProperty3() throws Exception { String SOURCE = PREFIX + "ex:p a rdf:Property ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs"}, new String[] {".*public static final Property p.*"}, new String[] {} ); } public void testInstance0() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class . ex:i a ex:A ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl"}, new String[] {".*public static final Resource i.*"}, new String[] {} ); } public void testInstance1() throws Exception { String SOURCE = PREFIX + "ex:A a rdfs:Class . ex:i a ex:A ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl"}, new String[] {".*public static final Resource i.*"}, new String[] {} ); } /* TODO this test fails, because the isInstance check in schemagen is quite weak. * Consider whether to fix the test or the code... * public void testInstance2() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class . ex:i a ex:A ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs"}, new String[] {}, new String[] {".*public static final Resource i.*"} ); } */ public void testInstance3() throws Exception { String SOURCE = PREFIX + "ex:A a rdfs:Class . ex:i a ex:A ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs"}, new String[] {".*public static final Resource i.*"}, new String[] {} ); } /** Bug report by Brian: instance is in the namespace, but the class itself is not */ public void testInstance4() throws Exception { String SOURCE = PREFIX + "@prefix ex2: <http://example.org/otherNS#>. ex2:A a rdfs:Class . ex:i a ex2:A ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs"}, new String[] {".*public static final Resource i.*"}, new String[] {} ); } /** Bug report by Brian: instances not being recognised */ public void testInstance5() throws Exception { String SOURCE = "@prefix : <http://ontology.earthster.org/eco/impact#> .\n" + "@prefix core: <http://ontology.earthster.org/eco/core#> .\n" + "@prefix ecoinvent: <http://ontology.earthster.org/eco/ecoinvent#> .\n" + "@prefix owl: <http://www.w3.org/2002/07/owl#> .\n" + "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n" + "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n" + "@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n" + "\n" + "<http://ontology.earthster.org/eco/impact>\n" + " rdf:type owl:Ontology ;\n" + " owl:imports <http://ontology.earthster.org/eco/ecoinvent> , <http://ontology.earthster.org/eco/core> ;\n" + " owl:versionInfo \"Created with TopBraid Composer\"^^xsd:string .\n" + "\n" + ":CD-CML2001-AbioticDepletion\n" + " rdf:type core:ImpactAssessmentMethodCategoryDescription ;\n" + " rdfs:label \"abiotic resource depletion\"^^xsd:string ;\n" + " core:hasImpactCategory\n" + " :abioticDepletion ."; testSchemagenOutput( SOURCE, null, new String[] {"--owl", "--inference"}, new String[] {".*public static final Resource CD_CML2001_AbioticDepletion.*"}, new String[] {".*valtype.*"} ); } /** Bug report by Richard Cyganiak */ public void testRC0() throws Exception { String SOURCE = PREFIX + "ex:class a owl:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl"}, new String[] {}, new String[] {".*public static final Resource class .*"} ); } public void testComment0() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ; rdfs:comment \"commentcomment\" ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl"}, new String[] {" */\\*\\* <p>commentcomment</p> \\*/ *"}, new String[] {} ); } public void testComment1() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ; rdfs:comment \"commentcomment\" ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl", "--nocomments"}, new String[] {}, new String[] {" */\\*\\* <p>commentcomment</p> \\*/ *"} ); } public void testComment2() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ; rdfs:comment \"commentcomment\" ."; // we don't want the input fixed to be http://example.com/sg SchemaGenAux sga = new SchemaGenAux() { @Override protected void go( String[] args ) { go( new SchemagenOptionsImpl( args ) ); } }; testSchemagenOutput( SOURCE, sga, new String[] {"-a", "http://example.com/sg#", "--owl", "-i", "file:\\\\C:\\Users\\fubar/vocabs/test.ttl"}, new String[] {".*Vocabulary definitions from file:\\\\\\\\C:\\\\Users\\\\fubar/vocabs/test.ttl.*"}, new String[] {} ); } public void testComment3() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ; rdfs:comment \"commentcomment\" ."; // we don't want the input fixed to be http://example.com/sg SchemaGenAux sga = new SchemaGenAux() { @Override protected void go( String[] args ) { go( new SchemagenOptionsImpl( args ) ); } }; testSchemagenOutput( SOURCE, sga, new String[] {"-a", "http://example.com/sg#", "--owl", "-i", "C:\\Users\\fubar/vocabs/test.ttl"}, new String[] {".*Vocabulary definitions from C:\\\\Users\\\\fubar/vocabs/test.ttl.*"}, new String[] {} ); } public void testOntClass0() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl", "--ontology"}, new String[] {".*public static final OntClass A.*"}, new String[] {} ); } public void testOntClass1() throws Exception { String SOURCE = PREFIX + "ex:A a rdfs:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl", "--ontology"}, new String[] {}, new String[] {".*public static final OntClass A.*"} ); } public void testOntClass2() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs", "--ontology"}, new String[] {}, new String[] {".*public static final OntClass A.*"} ); } public void testOntClass3() throws Exception { String SOURCE = PREFIX + "ex:A a rdfs:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs", "--ontology"}, new String[] {".*public static final OntClass A.*"}, new String[] {} ); } public void testOntProperty0() throws Exception { String SOURCE = PREFIX + "ex:p a owl:ObjectProperty ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl", "--ontology"}, new String[] {".*public static final ObjectProperty p.*"}, new String[] {} ); } public void testOntProperty1() throws Exception { String SOURCE = PREFIX + "ex:p a rdf:Property ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl", "--ontology"}, // in OWL mode we permit rdf:properties new String[] {".*public static final OntProperty p.*"}, new String[] {} ); } public void testOntProperty2() throws Exception { String SOURCE = PREFIX + "ex:p a owl:ObjectProperty ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs", "--ontology"}, new String[] {}, new String[] {".*public static final ObjectProperty p.*"} ); } public void testOntProperty3() throws Exception { String SOURCE = PREFIX + "ex:p a rdf:Property ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs", "--ontology"}, new String[] {".*public static final OntProperty p.*"}, new String[] {} ); } public void testHeader() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--ontology", "--header", "/* header */\n%package%\n%imports%\n"}, new String[] {"/\\* header \\*/"}, new String[] {} ); } public void testFooter() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--ontology", "--footer", "/* footer */"}, new String[] {"/\\* footer \\*/"}, new String[] {} ); } public void testPackage() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--ontology", "--package", "test.test"}, new String[] {"package test.test;\\s*"}, new String[] {} ); } public void testClassname() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ."; SchemaGenAux fixture = new SchemaGenAux() { @Override protected void go( String[] args ) { SchemagenOptionsFixture sgf = new SchemagenOptionsFixture( args ) { @Override public Resource getInputOption() { return ResourceFactory.createResource( "http://example.org/soggy" ); } }; go( sgf ); } }; testSchemagenOutput( SOURCE, fixture, new String[] {"-a", "http://example.com/soggy#", "--ontology", "--package", "test.test", "-n", "Sg"}, new String[] {}, new String[] {} ); } public void testClassdec() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--ontology", "--classdec", "\n implements java.lang.Cloneable\n"}, new String[] {"\\s*implements java.lang.Cloneable\\s*"}, new String[] {} ); } public void testDeclarations() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--ontology", "--declarations", "protected String m_gnole = \"Fungle\";;\n"}, new String[] {".*Fungle.*"}, new String[] {} ); } public void testNoClasses() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--ontology", "--noclasses"}, new String[] {}, new String[] {".*OntClass A.*"} ); } public void testNoProperties() throws Exception { String SOURCE = PREFIX + "ex:p a owl:ObjectProperty ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl", "--ontology", "--noproperties"}, new String[] {}, new String[] {".*Property p.*"} ); } public void testNoIndividuals() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class . ex:i a ex:A ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl", "--noindividuals"}, new String[] {".*Resource A.*"}, new String[] {".*Resource i.*"} ); } public void testNoHeader() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class . ex:i a ex:A ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl", "--noheader"}, new String[] {}, new String[] {"/\\*\\*.*"} ); } public void testUCNames() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class . ex:i a ex:A ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl", "--uppercase"}, new String[] {".*Resource A.*",".*Resource I.*"}, new String[] {} ); } public void testInference0() throws Exception { String SOURCE = PREFIX + "ex:p rdfs:domain ex:A ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl"}, new String[] {}, new String[] {".*Resource A.*",".*Property p.*"} ); } public void testInference1() throws Exception { String SOURCE = PREFIX + "ex:p rdfs:domain ex:A ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl", "--inference"}, new String[] {".*Resource A.*",".*Property p.*"}, new String[] {} ); } public void testInference2() throws Exception { String SOURCE = PREFIX + "ex:p rdfs:domain ex:A ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs", "--inference"}, new String[] {".*Resource A.*",".*Property p.*"}, new String[] {} ); } public void testStrictIndividuals0() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class . ex:i a ex:A . <http://example.com/different#j> a ex:A ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs"}, new String[] {".*Resource i.*",".*Resource j.*"}, new String[] {} ); } public void testStrictIndividuals1() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class . ex:i a ex:A . <http://example.com/different#j> a ex:A ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs", "--strictIndividuals"}, new String[] {".*Resource i.*"}, new String[] {".*Resource j.*"} ); } public void testLineEnd0() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class . ex:i a ex:A . ex:p a rdf:Property ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs", "--strictIndividuals"}, new String[] {}, new String[] {".*\r.*"} ); } public void testLineEnd1() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class . ex:i a ex:A . ex:p a rdf:Property ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--rdfs", "--dos"}, new String[] {".*\\r"}, new String[] {".*[^\r]"} ); } public void testIncludeSource0() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class . ex:i a ex:A . ex:p a owl:ObjectProperty ."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl", "--includeSource"}, new String[] {".*private static final String SOURCE.*", ".*ex:A *(a|rdf:type) *owl:Class.*"} , new String[] {} ); } public void testIncludeSource1() throws Exception { String SOURCE = PREFIX + "ex:A a owl:Class ; rdfs:comment \"comment\"."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl", "--includeSource"}, new String[] {".*\\\\\"comment\\\\\".*\""}, new String[] {} ); } public void testIncludeSource2() throws Exception { // had a report of the following not compiling .... String SOURCE = PREFIX + "@prefix skos: <http://www.w3.org/2004/02/skos/core#>.\n" + " <http://purl.org/dc/elements/1.1/relation> skos:note \"\"\"A second property with the same name as this property has been declared in the dcterms: namespace (http://purl.org/dc/terms/). See the Introduction to the document \"DCMI Metadata Terms\" (http://dublincore.org/documents/dcmi-terms/) for an explanation.\"\"\"."; testSchemagenOutput( SOURCE, null, new String[] {"-a", "http://example.com/sg#", "--owl", "--includeSource"}, new String[] {}, new String[] {} ); } // Internal implementation methods ////////////////////////////////// /** * Test the output from schemagen by saving the output to a string, * then ensuring that every positive regex matches at least one line, and * every negative regex matches at most no lines. Also checks that * compiling the file does not cause any errors. * * @param source String defining the model, using N3 * @param sg The schemagen object to test, or null for a default * @param args list of args to pass to SG * @param posPatterns array of regexps that must match at least once in the output * @param negPatterns arrays of regexps that must not match the output * @return The string defining the java class */ protected String testSchemagenOutput( String source, SchemaGenAux sg, String[] args, String[] posPatterns, String[] negPatterns ) throws Exception { sg = (sg == null) ? new SchemaGenAux() : sg; Model m = ModelFactory.createDefaultModel(); m.read( new StringReader( source ), "http://example.com/sg#", "N3" ); sg.setSource( m ); ByteArrayOutputStream buf = new ByteArrayOutputStream(); sg.setOutput( new PrintStream( buf ) ); // run schemagen sg.testGo( args ); // now run the test pattern over the lines in the file String result = buf.toString(); // if (log.isDebugEnabled()) { // log.debug( result ); // } StringTokenizer tokens = new StringTokenizer( result, "\n" ); boolean[] foundPos = new boolean[posPatterns.length]; // look for any line that matches the patterns while (tokens.hasMoreTokens()) { String line = tokens.nextToken(); // try each positive pattern for (int i = 0; i < posPatterns.length; i++) { Pattern pat = Pattern.compile( posPatterns[i] ); foundPos[i] |= pat.matcher( line ).matches(); } // try each negative pattern for (int i = 0; i < negPatterns.length; i++) { Pattern pat = Pattern.compile( negPatterns[i] ); assertFalse( "negative match pattern ||" + negPatterns[i] + "|| matched on line: " + line, pat.matcher( line ).matches() ); } } for (int i = 0; i < posPatterns.length; i++) { String msg = "Expecting a positive match to pattern: ||" + posPatterns[i] + "||"; assertTrue( msg + " in:\n" + result, foundPos[i] ); } // check that the file compiles with javac testCompile( result, "Sg" ); return result; } /** * Test the compilability of the generated output string by saving it to a * class file, and invoking javac on that file. * @param source * @param className * @throws Exception */ protected void testCompile( String source, String defaultClassName ) throws Exception { String className = defaultClassName; // ensure we use the right class name for the temp file // should do this with a regex, but java Pattern & Matcher is borked String key = "public class "; int i = source.indexOf( key ); if (i > 0) { i += key.length(); className = source.substring( i, source.indexOf( " ", i ) ); } // first write the source file to a temp dir File tmpDir = FileUtils.getScratchDirectory( "schemagen" ); File srcFile = new File( tmpDir, className + ".java" ); FileWriter out = new FileWriter( srcFile ); out.write( source ); out.close(); // now get ready to invoke javac using the new javax.tools package try { Class<?> tp = Class.forName( "javax.tools.ToolProvider" ); // static method to get the Java compiler tool Method gsjc = tp.getMethod( "getSystemJavaCompiler" ); Object sjc = gsjc.invoke( null ); // get the run method for the Java compiler tool Class<?> jc = Class.forName( "javax.tools.JavaCompiler" ); Method jcRun = jc.getMethod( "run", new Class[] {InputStream.class, OutputStream.class, OutputStream.class, String[].class} ); // build the args list for javac String[] args = new String[] {"-classpath", getClassPath( tmpDir ), "-d", tmpDir.getPath(), srcFile.getPath()}; int success = (Integer) jcRun.invoke( sjc, null, null, null, args ); assertEquals( "Errors reported from compilation of schemagen output", 0, success ); } catch (ClassNotFoundException nf) { log.debug( "javax.tools not found (no tools.jar on classpath?). schemagen compilation test skipped." ); } catch (Exception e) { log.debug( e.getMessage(), e ); fail( e.getMessage() ); } // clean up List<File> toClean = new ArrayList<File>(); toClean.add( tmpDir ); while (!toClean.isEmpty()) { File f = toClean.remove( 0 ); f.deleteOnExit(); if (f.isDirectory()) { for (File g: f.listFiles()) {toClean.add( g );} } } } /** * Return the classpath we can use to compile the sg output files * @param tmpDir * @return */ protected String getClassPath( File tmpDir ) { return System.getProperty ("java.class.path"); } //============================================================================== // Inner class definitions //============================================================================== /** * An extension to standard schemagen to create a test fixture; we override the * input and output methods. */ static class SchemaGenAux extends schemagen { protected PrintStream m_auxOutput; protected Model m_auxSource; public void setOutput( PrintStream out ) { m_auxOutput = out; } public void setSource( Model m ) { m_auxSource = m; } // override the behaviours from schemagen @Override protected void selectInput() { m_source.add( m_auxSource ); m_source.setNsPrefixes( m_auxSource ); } @Override protected void selectOutput() { // call super to allow option processing super.selectOutput(); // then override the result m_output = m_auxOutput; } public void testGo( String[] args ) { go( args ); } @Override protected void go( String[] args ) { go( new SchemagenOptionsFixture( args ) ); } @Override protected void abort( String msg, Exception e ) { throw new RuntimeException( msg, e ); } } static class SchemagenOptionsFixture extends SchemagenOptionsImpl { public SchemagenOptionsFixture( String[] args ) { super( args ); } @Override public Resource getInputOption() { return ResourceFactory.createResource( "http://example.org/sg" ); } } } /* * (c) Copyright 2003, 2004, 2005, 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */
Fixed problem with classpath when running tests under maven git-svn-id: 227c23bb629cf7bef445105b977924772e49ae4f@1114018 13f79535-47bb-0310-9956-ffa450edef68
src/test/java/jena/test/Test_schemagen.java
Fixed problem with classpath when running tests under maven
Java
apache-2.0
3676377bea7709d8a258cc939b302bf3c27aeb8c
0
Qurred/RMI-Turn-Based-Game
package client; import java.awt.Dimension; import java.awt.Toolkit; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import nakymat.YleisNakyma; public class Main extends UnicastRemoteObject implements AsiakasRajapinta { private JFrame ikkuna; private Dimension dim = new Dimension(800,450); private YleisNakyma yleis; public static void main(String[] args) throws RemoteException{ Main main = new Main(); } public Main() throws RemoteException{ Data.Alusta(); Data.lisaaNakymat(dim); yleis = (YleisNakyma) Data.nakymat.get(Data.PERUSNAKYMA); ikkuna = new JFrame("RMI-Game"); ikkuna.setSize(dim); ikkuna.setLayout(null); ikkuna.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ikkuna.setVisible(true); ikkuna.setLocationRelativeTo(null); ikkuna.setResizable(false); for(int i = 0; i < Data.nakymat.size(); i++){ ikkuna.add(Data.nakymat.get(i)); } JLabel tausta = new JLabel(); tausta.setBounds(0, 0, dim.width, dim.height); tausta.setIcon(new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/res/tausta.png")))); tausta.setOpaque(false); tausta.setVisible(true); ikkuna.add(tausta); Data.arp = this; } @Override public void vastaanotaViesti(String msg) throws RemoteException { yleis.vastaanotaViesti(msg); } @Override public int ping() throws RemoteException { return 0; } @Override public void vastaanotaTulokset(String[] tulokset) throws RemoteException { yleis.vastaanotaTiedot(tulokset); for(int i = 0; i < tulokset.length; i++){ System.out.println(tulokset[i]); } } }
src/client/Main.java
package client; import java.awt.Dimension; import java.awt.Toolkit; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import nakymat.YleisNakyma; public class Main extends UnicastRemoteObject implements AsiakasRajapinta { private JFrame ikkuna; private Dimension dim = new Dimension(800,450); private YleisNakyma yleis; public static void main(String[] args) throws RemoteException{ Main main = new Main(); } public Main() throws RemoteException{ Data.Alusta(); Data.lisaaNakymat(dim); yleis = (YleisNakyma) Data.nakymat.get(Data.PERUSNAKYMA); ikkuna = new JFrame("RMI-Game"); ikkuna.setSize(dim); ikkuna.setLayout(null); ikkuna.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ikkuna.setVisible(true); ikkuna.setLocationRelativeTo(null); ikkuna.setResizable(false); for(int i = 0; i < Data.nakymat.size(); i++){ ikkuna.add(Data.nakymat.get(i)); } JLabel tausta = new JLabel(); tausta.setBounds(0, 0, dim.width, dim.height); tausta.setIcon(new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/res/tausta.png")))); tausta.setOpaque(false); tausta.setVisible(true); ikkuna.add(tausta); Data.arp = this; } @Override public void vastaanotaViesti(String msg) throws RemoteException { yleis.vastaanotaViesti(msg); } @Override public int ping() throws RemoteException { return 0; } @Override public void vastaanotaTulokset(String[] tulokset) throws RemoteException { for(int i = 0; i < tulokset.length; i++){ System.out.println(tulokset[i]); } } }
lisätty mainiin tulosten tulostus
src/client/Main.java
lisätty mainiin tulosten tulostus
Java
apache-2.0
1b7d03c60cdceac2ad7b035d1c1a02faf07ab0cc
0
malcolmshen/seleniumtestsframework,malcolmshen/seleniumtestsframework,malcolmshen/seleniumtestsframework,tarun3kumar/seleniumtestsframework,SaiVDivya04/Automation-Code-,tarun3kumar/seleniumtestsframework,TestingForum/seleniumtestsframework,TestingForum/seleniumtestsframework,SaiVDivya04/Automation-Code-,SaiVDivya04/Automation-Code-,TestingForum/seleniumtestsframework,tarun3kumar/seleniumtestsframework
/* * Copyright 2015 www.seleniumtests.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.seleniumtests.driver; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Date; import com.seleniumtests.browserfactory.*; import org.openqa.selenium.Platform; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.support.events.WebDriverEventListener; import com.seleniumtests.core.SeleniumTestsContext; import com.seleniumtests.core.SeleniumTestsContextManager; /** * This class provides factory to create webDriver session. */ public class WebUIDriver { private static ThreadLocal<WebDriver> driverSession = new ThreadLocal<WebDriver>(); private static ThreadLocal<WebUIDriver> uxDriverSession = new ThreadLocal<WebUIDriver>(); private String node; private DriverConfig config = new DriverConfig(); private WebDriver driver; private IWebDriverFactory webDriverBuilder; public String getNode() { return node; } public void setNode(final String node) { this.node = node; } public static void cleanUp() { IWebDriverFactory iWebDriverFactory = getWebUIDriver().webDriverBuilder; if (iWebDriverFactory != null) { iWebDriverFactory.cleanUp(); } else { WebDriver driver = driverSession.get(); if (driver != null) { try { driver.quit(); } catch (WebDriverException ex) { ex.printStackTrace(); } driver = null; } } driverSession.remove(); uxDriverSession.remove(); } /** * Returns native WebDriver which can be converted to RemoteWebDriver. * * @return webDriver */ public static WebDriver getNativeWebDriver() { return ((CustomEventFiringWebDriver) getWebDriver(false)).getWebDriver(); } /** * Get EventFiringWebDriver. * * @return webDriver */ public static WebDriver getWebDriver() { return getWebDriver(false); } /** * Returns WebDriver instance Creates a new WebDriver Instance if it is null and isCreate is true. * * @param isCreate create webdriver or not * * @return */ public static WebDriver getWebDriver(final Boolean isCreate) { if (driverSession.get() == null && isCreate) { try { getWebUIDriver().createWebDriver(); } catch (Exception e) { e.printStackTrace(); } } return driverSession.get(); } /** * Returns WebUIDriver instance Creates new WebUIDriver instance if it is null. * * @return */ public static WebUIDriver getWebUIDriver() { if (uxDriverSession.get() == null) { uxDriverSession.set(new WebUIDriver()); } return uxDriverSession.get(); } /** * Lets user set their own driver This can be retrieved as WebUIDriver.getWebDriver(). * * @param driver */ public static void setWebDriver(final WebDriver driver) { if (driver == null) { driverSession.remove(); } else { if (getWebUIDriver() == null) { new WebUIDriver(); } driverSession.set(driver); } } public WebUIDriver() { init(); uxDriverSession.set(this); } public WebUIDriver(final String browser, final String mode) { init(); this.setBrowser(browser); this.setMode(mode); uxDriverSession.set(this); } public WebDriver createRemoteWebDriver(final String browser, final String mode) throws Exception { WebDriver driver = null; config.setBrowser(BrowserType.getBrowserType(browser)); config.setMode(DriverMode.valueOf(mode)); if (config.getMode() == DriverMode.ExistingGrid) { webDriverBuilder = new RemoteDriverFactory(this.config); } else { if (config.getBrowser() == BrowserType.FireFox) { webDriverBuilder = new FirefoxDriverFactory(this.config); } else if (config.getBrowser() == BrowserType.InternetExplore) { webDriverBuilder = new IEDriverFactory(this.config); } else if (config.getBrowser() == BrowserType.Chrome) { webDriverBuilder = new ChromeDriverFactory(this.config); } else if (config.getBrowser() == BrowserType.HtmlUnit) { webDriverBuilder = new HtmlUnitDriverFactory(this.config); } else if (config.getBrowser() == BrowserType.Safari) { webDriverBuilder = new SafariDriverFactory(this.config); } else if (config.getBrowser() == BrowserType.SauceLabs) { webDriverBuilder = new SauceLabsDriverFactory(this.config); } else if (config.getBrowser() == BrowserType.Android) { webDriverBuilder = new AndroidDriverFactory(this.config); } else if (config.getBrowser() == BrowserType.IPhone) { webDriverBuilder = new IPhoneDriverFactory(this.config); } else { throw new RuntimeException("Unsupported browser" + browser); } } synchronized (this.getClass()) { driver = webDriverBuilder.createWebDriver(); } driver = handleListeners(driver); return driver; } protected WebDriver handleListeners(WebDriver driver) { ArrayList<WebDriverEventListener> listeners = config.getWebDriverListeners(); if (listeners != null && listeners.size() > 0) { for (int i = 0; i < config.getWebDriverListeners().size(); i++) { driver = new CustomEventFiringWebDriver(driver).register(listeners.get(i)); } } return driver; } public WebDriver createWebDriver() throws Exception { System.out.println(Thread.currentThread() + ":" + new Date() + ":::Start creating web driver instance: " + this.getBrowser()); driver = createRemoteWebDriver(config.getBrowser().getBrowserType(), config.getMode().name()); System.out.println(Thread.currentThread() + ":" + new Date() + ":::Finish creating web driver instance: " + this.getBrowser()); driverSession.set(driver); return driver; } public String getBrowser() { return config.getBrowser().getBrowserType(); } public String getPlatform() { return config.getWebPlatform().name(); } public String getBrowserVersion() { return config.getBrowserVersion(); } public String getChromeBinPath() { return config.getChromeBinPath(); } public String getChromeDriverPath() { return config.getChromeDriverPath(); } public DriverConfig getConfig() { return config; } public int getExplicitWait() { return config.getExplicitWaitTimeout(); } public String getFfBinPath() { return config.getFirefoxBinPath(); } public String getFfProfilePath() throws URISyntaxException { return config.getFirefoxProfilePath(); } public String getOperaProfilePath() throws URISyntaxException { return config.getOperaProfilePath(); } public void setOperaProfilePath(final String operaProfilePath) { config.setOperaProfilePath(operaProfilePath); } public String getHubUrl() { return config.getHubUrl(); } public String getIEDriverPath() { return config.getIeDriverPath(); } public double getImplicitWait() { return config.getImplicitWaitTimeout(); } public String getMode() { return config.getMode().name(); } public String getOutputDirectory() { return config.getOutputDirectory(); } public String getNtlmAuthTrustedUris() { return config.getNtlmAuthTrustedUris(); } public void setNtlmAuthTrustedUris(final String url) { config.setNtlmAuthTrustedUris(url); } public int getPageLoadTimeout() { return config.getPageLoadTimeout(); } public String getProxyHost() { return config.getProxyHost(); } public void setUserAgentOverride(final String userAgentOverride) { config.setUserAgentOverride(userAgentOverride); } public String getUserAgentOverride() { return config.getUserAgentOverride(); } public IWebDriverFactory getWebDriverBuilder() { return webDriverBuilder; } public int getWebSessionTimeout() { return config.getWebSessionTimeout(); } private void init() { if (SeleniumTestsContextManager.getThreadContext() == null) { return; } String browser = SeleniumTestsContextManager.getThreadContext().getWebRunBrowser(); config.setBrowser(BrowserType.getBrowserType(browser)); String mode = SeleniumTestsContextManager.getThreadContext().getWebRunMode(); config.setMode(DriverMode.valueOf(mode)); String hubUrl = SeleniumTestsContextManager.getThreadContext().getWebDriverGrid(); config.setHubUrl(hubUrl); String ffProfilePath = SeleniumTestsContextManager.getThreadContext().getFirefoxUserProfilePath(); config.setFfProfilePath(ffProfilePath); String operaProfilePath = SeleniumTestsContextManager.getThreadContext().getOperaUserProfilePath(); config.setOperaProfilePath(operaProfilePath); String ffBinPath = SeleniumTestsContextManager.getThreadContext().getFirefoxBinPath(); config.setFfBinPath(ffBinPath); String chromeBinPath = SeleniumTestsContextManager.getThreadContext().getChromeBinPath(); config.setChromeBinPath(chromeBinPath); String chromeDriverPath = SeleniumTestsContextManager.getThreadContext().getChromeDriverPath(); config.setChromeDriverPath(chromeDriverPath); String ieDriverPath = SeleniumTestsContextManager.getThreadContext().getIEDriverPath(); config.setIeDriverPath(ieDriverPath); int webSessionTimeout = SeleniumTestsContextManager.getThreadContext().getWebSessionTimeout(); config.setWebSessionTimeout(webSessionTimeout); double implicitWaitTimeout = SeleniumTestsContextManager.getThreadContext().getImplicitWaitTimeout(); config.setImplicitWaitTimeout(implicitWaitTimeout); int explicitWaitTimeout = SeleniumTestsContextManager.getThreadContext().getExplicitWaitTimeout(); config.setExplicitWaitTimeout(explicitWaitTimeout); config.setPageLoadTimeout(SeleniumTestsContextManager.getThreadContext().getPageLoadTimeout()); String outputDirectory = SeleniumTestsContextManager.getGlobalContext().getOutputDirectory(); config.setOutputDirectory(outputDirectory); if (SeleniumTestsContextManager.getThreadContext().isWebProxyEnabled()) { String proxyHost = SeleniumTestsContextManager.getThreadContext().getWebProxyAddress(); config.setProxyHost(proxyHost); } String browserVersion = SeleniumTestsContextManager.getThreadContext().getWebBrowserVersion(); config.setBrowserVersion(browserVersion); String webPlatform = SeleniumTestsContextManager.getThreadContext().getWebPlatform(); if (webPlatform != null) { config.setWebPlatform(Platform.valueOf(webPlatform)); } if ("false".equalsIgnoreCase( (String) SeleniumTestsContextManager.getThreadContext().getAttribute( SeleniumTestsContext.Set_Assume_Untrusted_Certificate_Issuer))) { config.setSetAssumeUntrustedCertificateIssuer(false); } if ("false".equalsIgnoreCase( (String) SeleniumTestsContextManager.getThreadContext().getAttribute( SeleniumTestsContext.Set_Accept_Untrusted_Certificates))) { config.setSetAcceptUntrustedCertificates(false); } if ("false".equalsIgnoreCase( (String) SeleniumTestsContextManager.getThreadContext().getAttribute( SeleniumTestsContext.ENABLE_JAVASCRIPT))) { config.setEnableJavascript(false); } if (SeleniumTestsContextManager.getThreadContext().getNtlmAuthTrustedUris() != null) { config.setNtlmAuthTrustedUris(SeleniumTestsContextManager.getThreadContext().getNtlmAuthTrustedUris()); } if (SeleniumTestsContextManager.getThreadContext().getBrowserDownloadDir() != null) { config.setBrowserDownloadDir(SeleniumTestsContextManager.getThreadContext().getBrowserDownloadDir()); } if (SeleniumTestsContextManager.getThreadContext().getAddJSErrorCollectorExtension() != null) { config.setAddJSErrorCollectorExtension(Boolean.parseBoolean( SeleniumTestsContextManager.getThreadContext().getAddJSErrorCollectorExtension())); } String ua = null; if (SeleniumTestsContextManager.getThreadContext().getUserAgent() != null) { ua = SeleniumTestsContextManager.getThreadContext().getUserAgent(); } else { ua = null; } config.setUserAgentOverride(ua); String listeners = SeleniumTestsContextManager.getThreadContext().getWebDriverListener(); if (SeleniumTestsContextManager.getThreadContext().getEnableExceptionListener()) { if (listeners != null) { listeners = listeners + ","; } else { listeners = ""; } listeners = listeners + DriverExceptionListener.class.getName(); } if (listeners != null && !listeners.equals("")) { config.setWebDriverListeners(listeners); } else { config.setWebDriverListeners(""); } config.setUseFirefoxDefaultProfile(SeleniumTestsContextManager.getThreadContext().isUseFirefoxDefaultProfile()); String size = SeleniumTestsContextManager.getThreadContext().getBrowserWindowSize(); if (size != null) { int width = -1; int height = -1; try { width = Integer.parseInt(size.split(",")[0].trim()); height = Integer.parseInt(size.split(",")[1].trim()); } catch (Exception ex) { } config.setBrowserWindowWidth(width); config.setBrowserWindowHeight(height); } String appiumServerURL = SeleniumTestsContextManager.getThreadContext().getAppiumServerURL(); config.setAppiumServerURL(appiumServerURL); String automationName = SeleniumTestsContextManager.getThreadContext().getAutomationName(); config.setAutomationName(automationName); String mobilePlatformName = SeleniumTestsContextManager.getThreadContext().getMobilePlatformName(); config.setMobilePlatformName(mobilePlatformName); String mobilePlatformVersion = SeleniumTestsContextManager.getThreadContext().getMobilePlatformVersion(); config.setMobilePlatformVersion(mobilePlatformVersion); String deviceName = SeleniumTestsContextManager.getThreadContext().getDeviceName(); config.setDeviceName(deviceName); String app = SeleniumTestsContextManager.getThreadContext().getApp(); config.setApp(app); String browserName = SeleniumTestsContextManager.getThreadContext().getBrowserName(); config.setBrowserName(browserName); String appPackage = SeleniumTestsContextManager.getThreadContext().getAppPackage(); config.setAppPackage(appPackage); String appActivity = SeleniumTestsContextManager.getThreadContext().getAppActivity(); config.setAppActivity(appActivity); String newCommandTimeOut = SeleniumTestsContextManager.getThreadContext().getNewCommandTimeout(); config.setNewCommandTimeout(newCommandTimeOut); config.setVersion(SeleniumTestsContextManager.getThreadContext().getVersion()); config.setPlatform(SeleniumTestsContextManager.getThreadContext().getPlatform()); config.setSauceLabsURL(SeleniumTestsContextManager.getThreadContext().getSaucelabsURL()); config.setTestType(SeleniumTestsContextManager.getThreadContext().getTestType()); } public static void main(final String[] args) { System.out.println(DriverExceptionListener.class.getName()); } public boolean isSetAcceptUntrustedCertificates() { return config.isSetAcceptUntrustedCertificates(); } public boolean isAddJSErrorCollectorExtension() { return config.isAddJSErrorCollectorExtension(); } public void setAddJSErrorCollectorExtension(final Boolean addJSErrorCollectorExtension) { config.setAddJSErrorCollectorExtension(addJSErrorCollectorExtension); } public boolean isSetAssumeUntrustedCertificateIssuer() { return config.isSetAssumeUntrustedCertificateIssuer(); } public boolean isEnableJavascript() { return config.isEnableJavascript(); } public void setEnableJavascript(final Boolean enableJavascript) { config.setEnableJavascript(enableJavascript); } public void setBrowser(final String browser) { config.setBrowser(BrowserType.getBrowserType(browser)); } public void setBrowserVersion(final String browserVersion) { config.setBrowserVersion(browserVersion); } public void setPlatform(final String platform) { config.setWebPlatform(Platform.valueOf(platform)); } public void setChromeBinPath(final String chromeBinPath) { config.setChromeBinPath(chromeBinPath); } public void setBrowserDownloadDir(final String browserDownloadDir) { config.setBrowserDownloadDir(browserDownloadDir); } public String getBrowserDownloadDir() { return config.getBrowserDownloadDir(); } public void setChromeDriverPath(final String chromeDriverPath) { config.setChromeDriverPath(chromeDriverPath); } public void setConfig(final DriverConfig config) { this.config = config; } public void setExplicitTimeout(final int explicitWaitTimeout) { config.setExplicitWaitTimeout(explicitWaitTimeout); } public void setFfBinPath(final String ffBinPath) { config.setFfBinPath(ffBinPath); } public void setFfProfilePath(final String ffProfilePath) { config.setFfProfilePath(ffProfilePath); } public void setHubUrl(final String hubUrl) { config.setHubUrl(hubUrl); } public void setIEDriverPath(final String ieDriverPath) { config.setIeDriverPath(ieDriverPath); } public void setImplicitlyWaitTimeout(final double implicitTimeout) { config.setImplicitWaitTimeout(implicitTimeout); } public void setMode(final String mode) { config.setMode(DriverMode.valueOf(mode)); } public void setOutputDirectory(final String outputDirectory) { config.setOutputDirectory(outputDirectory); } public void setPageLoadTimeout(final int pageLoadTimeout) { config.setPageLoadTimeout(pageLoadTimeout); } public void setProxyHost(final String proxyHost) { config.setProxyHost(proxyHost); } public void setSetAcceptUntrustedCertificates(final boolean setAcceptUntrustedCertificates) { config.setSetAcceptUntrustedCertificates(setAcceptUntrustedCertificates); } public void setSetAssumeUntrustedCertificateIssuer(final boolean setAssumeUntrustedCertificateIssuer) { config.setSetAssumeUntrustedCertificateIssuer(setAssumeUntrustedCertificateIssuer); } public void setWebDriverBuilder(final IWebDriverFactory builder) { this.webDriverBuilder = builder; } public void setWebSessionTimeout(final int webSessionTimeout) { config.setWebSessionTimeout(webSessionTimeout); } }
src/main/java/com/seleniumtests/driver/WebUIDriver.java
/* * Copyright 2015 www.seleniumtests.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.seleniumtests.driver; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Date; import com.seleniumtests.browserfactory.*; import org.openqa.selenium.Platform; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.support.events.WebDriverEventListener; import com.seleniumtests.core.SeleniumTestsContext; import com.seleniumtests.core.SeleniumTestsContextManager; /** * This class provides factory to create webDriver session. */ public class WebUIDriver { private static ThreadLocal<WebDriver> driverSession = new ThreadLocal<WebDriver>(); private static ThreadLocal<WebUIDriver> uxDriverSession = new ThreadLocal<WebUIDriver>(); private String node; private DriverConfig config = new DriverConfig(); private WebDriver driver; private IWebDriverFactory webDriverBuilder; public String getNode() { return node; } public void setNode(final String node) { this.node = node; } public static void cleanUp() { IWebDriverFactory iWebDriverFactory = getWebUIDriver().webDriverBuilder; if (iWebDriverFactory != null) { iWebDriverFactory.cleanUp(); } else { WebDriver driver = driverSession.get(); if (driver != null) { try { driver.quit(); } catch (WebDriverException ex) { ex.printStackTrace(); } driver = null; } } driverSession.remove(); uxDriverSession.remove(); } /** * Returns native WebDriver which can be converted to RemoteWebDriver. * * @return webDriver */ public static WebDriver getNativeWebDriver() { return ((CustomEventFiringWebDriver) getWebDriver(false)).getWebDriver(); } /** * Get EventFiringWebDriver. * * @return webDriver */ public static WebDriver getWebDriver() { return getWebDriver(false); } /** * Returns WebDriver instance Creates a new WebDriver Instance if it is null and isCreate is true. * * @param isCreate create webdriver or not * * @return */ public static WebDriver getWebDriver(final Boolean isCreate) { if (driverSession.get() == null && isCreate) { try { getWebUIDriver().createWebDriver(); } catch (Exception e) { e.printStackTrace(); } } return driverSession.get(); } /** * Returns WebUIDriver instance Creates new WebUIDriver instance if it is null. * * @return */ public static WebUIDriver getWebUIDriver() { if (uxDriverSession.get() == null) { uxDriverSession.set(new WebUIDriver()); } return uxDriverSession.get(); } /** * Lets user set their own driver This can be retrieved as WebUIDriver.getWebDriver(). * * @param driver */ public static void setWebDriver(final WebDriver driver) { if (driver == null) { driverSession.remove(); } else { if (getWebUIDriver() == null) { new WebUIDriver(); } driverSession.set(driver); } } public WebUIDriver() { init(); uxDriverSession.set(this); } public WebUIDriver(final String browser, final String mode) { init(); this.setBrowser(browser); this.setMode(mode); uxDriverSession.set(this); } public WebDriver createRemoteWebDriver(final String browser, final String mode) throws Exception { WebDriver driver = null; config.setBrowser(BrowserType.getBrowserType(browser)); config.setMode(DriverMode.valueOf(mode)); if (config.getMode() == DriverMode.ExistingGrid) { webDriverBuilder = new RemoteDriverFactory(this.config); } else { if (config.getBrowser() == BrowserType.FireFox) { webDriverBuilder = new FirefoxDriverFactory(this.config); } else if (config.getBrowser() == BrowserType.InternetExplore) { webDriverBuilder = new IEDriverFactory(this.config); } else if (config.getBrowser() == BrowserType.Chrome) { webDriverBuilder = new ChromeDriverFactory(this.config); } else if (config.getBrowser() == BrowserType.HtmlUnit) { webDriverBuilder = new HtmlUnitDriverFactory(this.config); } else if (config.getBrowser() == BrowserType.Safari) { webDriverBuilder = new SafariDriverFactory(this.config); } else if (config.getBrowser() == BrowserType.SauceLabs) { webDriverBuilder = new SauceLabsDriverFactory(this.config); } else if (config.getBrowser() == BrowserType.Android) { webDriverBuilder = new AndroidDriverFactory(this.config); } else if (config.getBrowser() == BrowserType.IPhone) { // webDriverBuilder = new IPhoneDriverFactory(this.config); webDriverBuilder = (IWebDriverFactory) Class.forName( "com.seleniumtests.browserfactory.IPhoneDriverFactory") .getConstructor(DriverConfig.class).newInstance( this.config); } else if (config.getBrowser() == BrowserType.IPad) { // webDriverBuilder = new IPadDriverFactory(this.config); webDriverBuilder = (IWebDriverFactory) Class.forName( "com.seleniumtests.browserfactory.IPadDriverFactory") .getConstructor(DriverConfig.class).newInstance( this.config); } else { throw new RuntimeException("Unsupported browser" + browser); } } synchronized (this.getClass()) { driver = webDriverBuilder.createWebDriver(); } driver = handleListeners(driver); return driver; } protected WebDriver handleListeners(WebDriver driver) { ArrayList<WebDriverEventListener> listeners = config.getWebDriverListeners(); if (listeners != null && listeners.size() > 0) { for (int i = 0; i < config.getWebDriverListeners().size(); i++) { driver = new CustomEventFiringWebDriver(driver).register(listeners.get(i)); } } return driver; } public WebDriver createWebDriver() throws Exception { System.out.println(Thread.currentThread() + ":" + new Date() + ":::Start creating web driver instance: " + this.getBrowser()); driver = createRemoteWebDriver(config.getBrowser().getBrowserType(), config.getMode().name()); System.out.println(Thread.currentThread() + ":" + new Date() + ":::Finish creating web driver instance: " + this.getBrowser()); driverSession.set(driver); return driver; } public String getBrowser() { return config.getBrowser().getBrowserType(); } public String getPlatform() { return config.getWebPlatform().name(); } public String getBrowserVersion() { return config.getBrowserVersion(); } public String getChromeBinPath() { return config.getChromeBinPath(); } public String getChromeDriverPath() { return config.getChromeDriverPath(); } public DriverConfig getConfig() { return config; } public int getExplicitWait() { return config.getExplicitWaitTimeout(); } public String getFfBinPath() { return config.getFirefoxBinPath(); } public String getFfProfilePath() throws URISyntaxException { return config.getFirefoxProfilePath(); } public String getOperaProfilePath() throws URISyntaxException { return config.getOperaProfilePath(); } public void setOperaProfilePath(final String operaProfilePath) { config.setOperaProfilePath(operaProfilePath); } public String getHubUrl() { return config.getHubUrl(); } public String getIEDriverPath() { return config.getIeDriverPath(); } public double getImplicitWait() { return config.getImplicitWaitTimeout(); } public String getMode() { return config.getMode().name(); } public String getOutputDirectory() { return config.getOutputDirectory(); } public String getNtlmAuthTrustedUris() { return config.getNtlmAuthTrustedUris(); } public void setNtlmAuthTrustedUris(final String url) { config.setNtlmAuthTrustedUris(url); } public int getPageLoadTimeout() { return config.getPageLoadTimeout(); } public String getProxyHost() { return config.getProxyHost(); } public void setUserAgentOverride(final String userAgentOverride) { config.setUserAgentOverride(userAgentOverride); } public String getUserAgentOverride() { return config.getUserAgentOverride(); } public IWebDriverFactory getWebDriverBuilder() { return webDriverBuilder; } public int getWebSessionTimeout() { return config.getWebSessionTimeout(); } private void init() { if (SeleniumTestsContextManager.getThreadContext() == null) { return; } String browser = SeleniumTestsContextManager.getThreadContext().getWebRunBrowser(); config.setBrowser(BrowserType.getBrowserType(browser)); String mode = SeleniumTestsContextManager.getThreadContext().getWebRunMode(); config.setMode(DriverMode.valueOf(mode)); String hubUrl = SeleniumTestsContextManager.getThreadContext().getWebDriverGrid(); config.setHubUrl(hubUrl); String ffProfilePath = SeleniumTestsContextManager.getThreadContext().getFirefoxUserProfilePath(); config.setFfProfilePath(ffProfilePath); String operaProfilePath = SeleniumTestsContextManager.getThreadContext().getOperaUserProfilePath(); config.setOperaProfilePath(operaProfilePath); String ffBinPath = SeleniumTestsContextManager.getThreadContext().getFirefoxBinPath(); config.setFfBinPath(ffBinPath); String chromeBinPath = SeleniumTestsContextManager.getThreadContext().getChromeBinPath(); config.setChromeBinPath(chromeBinPath); String chromeDriverPath = SeleniumTestsContextManager.getThreadContext().getChromeDriverPath(); config.setChromeDriverPath(chromeDriverPath); String ieDriverPath = SeleniumTestsContextManager.getThreadContext().getIEDriverPath(); config.setIeDriverPath(ieDriverPath); int webSessionTimeout = SeleniumTestsContextManager.getThreadContext().getWebSessionTimeout(); config.setWebSessionTimeout(webSessionTimeout); double implicitWaitTimeout = SeleniumTestsContextManager.getThreadContext().getImplicitWaitTimeout(); config.setImplicitWaitTimeout(implicitWaitTimeout); int explicitWaitTimeout = SeleniumTestsContextManager.getThreadContext().getExplicitWaitTimeout(); config.setExplicitWaitTimeout(explicitWaitTimeout); config.setPageLoadTimeout(SeleniumTestsContextManager.getThreadContext().getPageLoadTimeout()); String outputDirectory = SeleniumTestsContextManager.getGlobalContext().getOutputDirectory(); config.setOutputDirectory(outputDirectory); if (SeleniumTestsContextManager.getThreadContext().isWebProxyEnabled()) { String proxyHost = SeleniumTestsContextManager.getThreadContext().getWebProxyAddress(); config.setProxyHost(proxyHost); } String browserVersion = SeleniumTestsContextManager.getThreadContext().getWebBrowserVersion(); config.setBrowserVersion(browserVersion); String webPlatform = SeleniumTestsContextManager.getThreadContext().getWebPlatform(); if (webPlatform != null) { config.setWebPlatform(Platform.valueOf(webPlatform)); } if ("false".equalsIgnoreCase( (String) SeleniumTestsContextManager.getThreadContext().getAttribute( SeleniumTestsContext.Set_Assume_Untrusted_Certificate_Issuer))) { config.setSetAssumeUntrustedCertificateIssuer(false); } if ("false".equalsIgnoreCase( (String) SeleniumTestsContextManager.getThreadContext().getAttribute( SeleniumTestsContext.Set_Accept_Untrusted_Certificates))) { config.setSetAcceptUntrustedCertificates(false); } if ("false".equalsIgnoreCase( (String) SeleniumTestsContextManager.getThreadContext().getAttribute( SeleniumTestsContext.ENABLE_JAVASCRIPT))) { config.setEnableJavascript(false); } if (SeleniumTestsContextManager.getThreadContext().getNtlmAuthTrustedUris() != null) { config.setNtlmAuthTrustedUris(SeleniumTestsContextManager.getThreadContext().getNtlmAuthTrustedUris()); } if (SeleniumTestsContextManager.getThreadContext().getBrowserDownloadDir() != null) { config.setBrowserDownloadDir(SeleniumTestsContextManager.getThreadContext().getBrowserDownloadDir()); } if (SeleniumTestsContextManager.getThreadContext().getAddJSErrorCollectorExtension() != null) { config.setAddJSErrorCollectorExtension(Boolean.parseBoolean( SeleniumTestsContextManager.getThreadContext().getAddJSErrorCollectorExtension())); } String ua = null; if (SeleniumTestsContextManager.getThreadContext().getUserAgent() != null) { ua = SeleniumTestsContextManager.getThreadContext().getUserAgent(); } else { ua = null; } config.setUserAgentOverride(ua); String listeners = SeleniumTestsContextManager.getThreadContext().getWebDriverListener(); if (SeleniumTestsContextManager.getThreadContext().getEnableExceptionListener()) { if (listeners != null) { listeners = listeners + ","; } else { listeners = ""; } listeners = listeners + DriverExceptionListener.class.getName(); } if (listeners != null && !listeners.equals("")) { config.setWebDriverListeners(listeners); } else { config.setWebDriverListeners(""); } config.setUseFirefoxDefaultProfile(SeleniumTestsContextManager.getThreadContext().isUseFirefoxDefaultProfile()); String size = SeleniumTestsContextManager.getThreadContext().getBrowserWindowSize(); if (size != null) { int width = -1; int height = -1; try { width = Integer.parseInt(size.split(",")[0].trim()); height = Integer.parseInt(size.split(",")[1].trim()); } catch (Exception ex) { } config.setBrowserWindowWidth(width); config.setBrowserWindowHeight(height); } String appiumServerURL = SeleniumTestsContextManager.getThreadContext().getAppiumServerURL(); config.setAppiumServerURL(appiumServerURL); String automationName = SeleniumTestsContextManager.getThreadContext().getAutomationName(); config.setAutomationName(automationName); String mobilePlatformName = SeleniumTestsContextManager.getThreadContext().getMobilePlatformName(); config.setMobilePlatformName(mobilePlatformName); String mobilePlatformVersion = SeleniumTestsContextManager.getThreadContext().getMobilePlatformVersion(); config.setMobilePlatformVersion(mobilePlatformVersion); String deviceName = SeleniumTestsContextManager.getThreadContext().getDeviceName(); config.setDeviceName(deviceName); String app = SeleniumTestsContextManager.getThreadContext().getApp(); config.setApp(app); String browserName = SeleniumTestsContextManager.getThreadContext().getBrowserName(); config.setBrowserName(browserName); String appPackage = SeleniumTestsContextManager.getThreadContext().getAppPackage(); config.setAppPackage(appPackage); String appActivity = SeleniumTestsContextManager.getThreadContext().getAppActivity(); config.setAppActivity(appActivity); String newCommandTimeOut = SeleniumTestsContextManager.getThreadContext().getNewCommandTimeout(); config.setNewCommandTimeout(newCommandTimeOut); config.setVersion(SeleniumTestsContextManager.getThreadContext().getVersion()); config.setPlatform(SeleniumTestsContextManager.getThreadContext().getPlatform()); config.setSauceLabsURL(SeleniumTestsContextManager.getThreadContext().getSaucelabsURL()); config.setTestType(SeleniumTestsContextManager.getThreadContext().getTestType()); } public static void main(final String[] args) { System.out.println(DriverExceptionListener.class.getName()); } public boolean isSetAcceptUntrustedCertificates() { return config.isSetAcceptUntrustedCertificates(); } public boolean isAddJSErrorCollectorExtension() { return config.isAddJSErrorCollectorExtension(); } public void setAddJSErrorCollectorExtension(final Boolean addJSErrorCollectorExtension) { config.setAddJSErrorCollectorExtension(addJSErrorCollectorExtension); } public boolean isSetAssumeUntrustedCertificateIssuer() { return config.isSetAssumeUntrustedCertificateIssuer(); } public boolean isEnableJavascript() { return config.isEnableJavascript(); } public void setEnableJavascript(final Boolean enableJavascript) { config.setEnableJavascript(enableJavascript); } public void setBrowser(final String browser) { config.setBrowser(BrowserType.getBrowserType(browser)); } public void setBrowserVersion(final String browserVersion) { config.setBrowserVersion(browserVersion); } public void setPlatform(final String platform) { config.setWebPlatform(Platform.valueOf(platform)); } public void setChromeBinPath(final String chromeBinPath) { config.setChromeBinPath(chromeBinPath); } public void setBrowserDownloadDir(final String browserDownloadDir) { config.setBrowserDownloadDir(browserDownloadDir); } public String getBrowserDownloadDir() { return config.getBrowserDownloadDir(); } public void setChromeDriverPath(final String chromeDriverPath) { config.setChromeDriverPath(chromeDriverPath); } public void setConfig(final DriverConfig config) { this.config = config; } public void setExplicitTimeout(final int explicitWaitTimeout) { config.setExplicitWaitTimeout(explicitWaitTimeout); } public void setFfBinPath(final String ffBinPath) { config.setFfBinPath(ffBinPath); } public void setFfProfilePath(final String ffProfilePath) { config.setFfProfilePath(ffProfilePath); } public void setHubUrl(final String hubUrl) { config.setHubUrl(hubUrl); } public void setIEDriverPath(final String ieDriverPath) { config.setIeDriverPath(ieDriverPath); } public void setImplicitlyWaitTimeout(final double implicitTimeout) { config.setImplicitWaitTimeout(implicitTimeout); } public void setMode(final String mode) { config.setMode(DriverMode.valueOf(mode)); } public void setOutputDirectory(final String outputDirectory) { config.setOutputDirectory(outputDirectory); } public void setPageLoadTimeout(final int pageLoadTimeout) { config.setPageLoadTimeout(pageLoadTimeout); } public void setProxyHost(final String proxyHost) { config.setProxyHost(proxyHost); } public void setSetAcceptUntrustedCertificates(final boolean setAcceptUntrustedCertificates) { config.setSetAcceptUntrustedCertificates(setAcceptUntrustedCertificates); } public void setSetAssumeUntrustedCertificateIssuer(final boolean setAssumeUntrustedCertificateIssuer) { config.setSetAssumeUntrustedCertificateIssuer(setAssumeUntrustedCertificateIssuer); } public void setWebDriverBuilder(final IWebDriverFactory builder) { this.webDriverBuilder = builder; } public void setWebSessionTimeout(final int webSessionTimeout) { config.setWebSessionTimeout(webSessionTimeout); } }
remove browser type ipad as iphone suffices for both iphone and ipad
src/main/java/com/seleniumtests/driver/WebUIDriver.java
remove browser type ipad as iphone suffices for both iphone and ipad
Java
apache-2.0
8c705623604212bc733496a36154862a9d33f25c
0
satabin/sablecc,satabin/sablecc,satabin/sablecc,satabin/sablecc,satabin/sablecc,satabin/sablecc
/* This file is part of SableCC ( http://sablecc.org ). * * See the NOTICE file distributed with this work for copyright information. * * 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.sablecc.sablecc.automaton; import static java.math.BigInteger.*; import static org.sablecc.util.UsefulStaticImports.*; import java.math.*; import java.util.*; import org.sablecc.exception.*; import org.sablecc.sablecc.alphabet.*; import org.sablecc.sablecc.alphabet.Bound; import org.sablecc.util.*; /** * An instance of this class represents a finite automaton. */ public final class Automaton { /** * A comparator for rich symbols which can handle epsilon (null) * comparisons. */ private static final Comparator<RichSymbol> richSymbolComparator = new Comparator<RichSymbol>() { // allows comparison of null symbols @Override public int compare( RichSymbol richSymbol1, RichSymbol richSymbol2) { if (richSymbol1 == null) { return richSymbol2 == null ? 0 : -1; } if (richSymbol2 == null) { return 1; } return richSymbol1.compareTo(richSymbol2); } }; private static final Progeny<State> lookaheadProgeny = new Progeny<State>() { @Override protected Set<State> getChildrenNoCache( State sourceState) { Set<State> children = new LinkedHashSet<State>(); for (RichSymbol richSymbol : sourceState.getTransitions().keySet()) { if (!richSymbol.isLookahead()) { continue; } State targetState = sourceState.getSingleTarget(richSymbol); children.add(targetState); } return children; } }; /** * The alphabet of this automaton. */ private final Alphabet alphabet; /** * The states of this automaton. */ private SortedSet<State> states; /** * The start state of this automaton. */ private State startState; /** * The markers of this automaton. */ private SortedSet<Marker> markers; /** * The acceptations of this automaton. */ private SortedSet<Acceptation> acceptations; private Boolean isDeterministic; /** * The stability status of this automaton. */ private boolean isStable; /** * The cached string representation of this automaton. It is * <code>null</code> when not yet computed. */ private String toString; /** * Initializes this automaton. This method must be called at the beginning * of every constructors. */ private void init() { this.states = new TreeSet<State>(); this.startState = new State(this); this.markers = new TreeSet<Marker>(); this.acceptations = new TreeSet<Acceptation>(); this.isStable = false; } /** * Constructs an incomplete automaton. This private constructor returns an * automaton to which new states can be added. The <code>stabilize()</code> * method should be called on this instance before exposing it publicly. */ Automaton( Alphabet alphabet) { init(); this.alphabet = alphabet; } /** * Returns the alphabet of this automaton. */ public Alphabet getAlphabet() { return this.alphabet; } /** * Returns the states of this automaton. */ public SortedSet<State> getStates() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } return this.states; } /** * Returns the start state of this automaton. */ public State getStartState() { return this.startState; } /** * Returns the markers of this automaton. */ public SortedSet<Marker> getMarkers() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } return this.markers; } /** * Returns the markers of this unstable automaton. */ SortedSet<Marker> getUnstableMarkers() { if (this.isStable) { throw new InternalException("this automaton is stable"); } return this.markers; } /** * Returns the acceptations of this automaton. */ public SortedSet<Acceptation> getAcceptations() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } return this.acceptations; } /** * Returns the acceptations of this unstable automaton. */ SortedSet<Acceptation> getUnstableAcceptations() { if (this.isStable) { throw new InternalException("this automaton is stable"); } return this.acceptations; } /** * Returns the string representation of this automaton. */ @Override public String toString() { if (this.toString == null) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } StringBuilder sb = new StringBuilder(); sb.append("Automaton:{"); for (State state : this.states) { sb.append(LINE_SEPARATOR); sb.append(" "); if (state == this.startState) { sb.append("(start)"); } sb.append(state); sb.append(":"); for (Map.Entry<RichSymbol, SortedSet<State>> entry : state .getTransitions().entrySet()) { RichSymbol richSymbol = entry.getKey(); SortedSet<State> targets = entry.getValue(); for (State target : targets) { sb.append(LINE_SEPARATOR); sb.append(" "); sb.append(richSymbol == null ? "EPSILON" : richSymbol .toString()); sb.append(" -> state_"); sb.append(target.getId()); } } } sb.append(LINE_SEPARATOR); sb.append("}"); this.toString = sb.toString(); } return this.toString; } /** * Stabilizes this automaton by stabilizing each of its states. */ void stabilize() { if (this.isStable) { throw new InternalException("this automaton is already stable"); } for (State state : this.states) { state.stabilize(); } this.states = Collections.unmodifiableSortedSet(this.states); this.markers = Collections.unmodifiableSortedSet(this.markers); this.acceptations = Collections .unmodifiableSortedSet(this.acceptations); this.isStable = true; } /** * Returns the next available state ID. This is useful for the construction * of a new state. */ int getNextStateId() { if (this.isStable) { throw new InternalException( "this automaton is stable and may not be modified"); } return this.states.size(); } /** * Adds the provided state to this automaton. */ void addState( State state) { if (this.isStable) { throw new InternalException( "this automaton is stable and may not be modified"); } if (state == null) { throw new InternalException("state may not be null"); } if (state.getId() != this.states.size()) { throw new InternalException("invalid state ID"); } if (!this.states.add(state)) { throw new InternalException("state is already in states"); } } /** * Adds the provided marker to this automaton. */ void addMarker( Marker marker) { if (this.isStable) { throw new InternalException( "this automaton is stable and may not be modified"); } if (marker == null) { throw new InternalException("marker may not be null"); } if (!this.markers.add(marker)) { throw new InternalException("marker is already in markers"); } } /** * Adds the provided state as an accept state of this automaton according to * the provided acceptation. */ void addAcceptation( Acceptation acceptation) { if (this.isStable) { throw new InternalException( "this automaton is stable and may not be modified"); } if (acceptation == null) { throw new InternalException("acceptation may not be null"); } if (acceptation.getMarker() != null && !this.markers.contains(acceptation.getMarker())) { throw new InternalException("acceptation has invalid marker"); } if (!this.acceptations.add(acceptation)) { throw new InternalException( "acceptation is already in acceptations"); } } public boolean isDeterministic() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (this.isDeterministic == null) { outer_loop: for (State state : this.states) { for (Map.Entry<RichSymbol, SortedSet<State>> entry : state .getTransitions().entrySet()) { if (entry.getKey() == null || entry.getValue().size() > 1) { this.isDeterministic = false; break outer_loop; } } } if (this.isDeterministic == null) { this.isDeterministic = true; } } return this.isDeterministic; } public boolean hasMarkers() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } return this.markers.size() > 0; } public boolean hasCustomAcceptations() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } for (Acceptation acceptation : this.acceptations) { if (acceptation != Acceptation.ACCEPT) { return true; } } return false; } public boolean hasEndTransition() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } for (State state : this.states) { if (state.getTransitions().containsKey(RichSymbol.END)) { return true; } } return false; } public Automaton withMergedAlphabet( AlphabetMergeResult alphabetMergeResult) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (alphabetMergeResult == null) { throw new InternalException("alphabetMergeResult may not be null"); } if (hasMarkers()) { throw new InternalException("invalid operation"); } Automaton newAutomaton = new Automaton( alphabetMergeResult.getNewAlphabet()); for (Acceptation acceptation : getAcceptations()) { newAutomaton.addAcceptation(acceptation); } SortedMap<State, State> oldStateToNewStateMap = new TreeMap<State, State>(); SortedMap<State, State> newStateToOldStateMap = new TreeMap<State, State>(); oldStateToNewStateMap .put(getStartState(), newAutomaton.getStartState()); newStateToOldStateMap .put(newAutomaton.getStartState(), getStartState()); for (State oldState : getStates()) { if (oldState.equals(getStartState())) { continue; } State newState = new State(newAutomaton); oldStateToNewStateMap.put(oldState, newState); newStateToOldStateMap.put(newState, oldState); } for (State oldSourceState : getStates()) { State newSourceState = oldStateToNewStateMap.get(oldSourceState); for (Map.Entry<RichSymbol, SortedSet<State>> entry : oldSourceState .getTransitions().entrySet()) { RichSymbol oldRichSymbol = entry.getKey(); SortedSet<State> oldTargetStates = entry.getValue(); for (State oldTargetState : oldTargetStates) { State newTargetState = oldStateToNewStateMap .get(oldTargetState); if (oldRichSymbol == null) { RichSymbol newRichSymbol = null; newSourceState.addTransition(newRichSymbol, newTargetState); } else { for (RichSymbol newRichSymbol : alphabetMergeResult .getNewRichSymbols(oldRichSymbol)) { newSourceState.addTransition(newRichSymbol, newTargetState); } } } } for (Acceptation acceptation : oldSourceState.getAcceptations()) { newSourceState.addAcceptation(acceptation); } } newAutomaton.stabilize(); return newAutomaton; } public Automaton withoutUnreachableStates() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (hasMarkers()) { throw new InternalException("invalid operation"); } SortedSet<State> reachableStates = new TreeSet<State>(); SortedSet<Acceptation> usefulAcceptations = new TreeSet<Acceptation>(); WorkSet<State> workSet = new WorkSet<State>(); workSet.add(getStartState()); Automaton newAutomaton = new Automaton(getAlphabet()); SortedMap<State, State> oldStatetoNewStateMap = new TreeMap<State, State>(); while (workSet.hasNext()) { State reachableState = workSet.next(); reachableStates.add(reachableState); State newState = reachableState == getStartState() ? newAutomaton .getStartState() : new State(newAutomaton); oldStatetoNewStateMap.put(reachableState, newState); for (Acceptation usefulAcceptation : reachableState .getAcceptations()) { usefulAcceptations.add(usefulAcceptation); } for (Map.Entry<RichSymbol, SortedSet<State>> entry : reachableState .getTransitions().entrySet()) { for (State targetState : entry.getValue()) { workSet.add(targetState); } } } for (Acceptation usefulAcceptation : usefulAcceptations) { newAutomaton.addAcceptation(usefulAcceptation); } for (State oldSourceState : reachableStates) { State newSourceState = oldStatetoNewStateMap.get(oldSourceState); for (Map.Entry<RichSymbol, SortedSet<State>> entry : oldSourceState .getTransitions().entrySet()) { SortedSet<State> oldTargetStates = entry.getValue(); for (State oldTargetState : oldTargetStates) { State newTargetState = oldStatetoNewStateMap .get(oldTargetState); newSourceState .addTransition(entry.getKey(), newTargetState); } } for (Acceptation acceptation : oldSourceState.getAcceptations()) { newSourceState.addAcceptation(acceptation); } } newAutomaton.stabilize(); return newAutomaton; } public Automaton accept( Acceptation acceptation) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (hasCustomAcceptations()) { throw new InternalException("invalid operation"); } if (hasMarkers()) { throw new InternalException("invalid operation"); } if (acceptation == null) { throw new InternalException("acceptation may not be null"); } if (acceptation.equals(Acceptation.ACCEPT)) { throw new InternalException("acceptation is invalid"); } Automaton newAutomaton = new Automaton(getAlphabet()); newAutomaton.addAcceptation(acceptation); SortedMap<State, State> oldStatetoNewStateMap = new TreeMap<State, State>(); for (State oldState : getStates()) { State newState = oldState == getStartState() ? newAutomaton .getStartState() : new State(newAutomaton); oldStatetoNewStateMap.put(oldState, newState); if (oldState.isAcceptState()) { newState.addAcceptation(acceptation); } } for (State oldSourceState : getStates()) { State newSourceState = oldStatetoNewStateMap.get(oldSourceState); for (Map.Entry<RichSymbol, SortedSet<State>> entry : oldSourceState .getTransitions().entrySet()) { RichSymbol richSymbol = entry.getKey(); for (State oldTargetState : entry.getValue()) { State newTargetState = oldStatetoNewStateMap .get(oldTargetState); newSourceState.addTransition(richSymbol, newTargetState); } } } newAutomaton.stabilize(); return newAutomaton; } public Automaton deterministic() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } return new DeterministicOperation(this).getNewAutomaton(); } public Automaton minimal() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } return new MinimalOperation(this).getNewAutomaton(); } public Automaton or( Automaton automaton) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (automaton == null) { throw new InternalException("automaton may not be null"); } if (!automaton.isStable) { throw new InternalException("automaton is not yet stable"); } return new OrOperation(this, automaton).getNewAutomaton(); } public Automaton concat( Automaton automaton) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (automaton == null) { throw new InternalException("automaton may not be null"); } if (!automaton.isStable) { throw new InternalException("automaton is not yet stable"); } return new ConcatOperation(this, automaton).getNewAutomaton(); } public Automaton zeroOrOne() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } return or(getEpsilonLookAnyStarEnd()); } public Automaton oneOrMore() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } return new OneOrMoreOperation(this).getNewAutomaton(); } public Automaton oneOrMoreWithSeparator( Automaton automaton) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (automaton == null) { throw new InternalException("automaton may not be null"); } if (!automaton.isStable) { throw new InternalException("automaton is not yet stable"); } return concat(automaton.concat(this).zeroOrMore()); } public Automaton zeroOrMore() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } return oneOrMore().zeroOrOne(); } public Automaton zeroOrMoreWithSeparator( Automaton automaton) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (automaton == null) { throw new InternalException("automaton may not be null"); } if (!automaton.isStable) { throw new InternalException("automaton is not yet stable"); } return oneOrMoreWithSeparator(automaton).zeroOrOne(); } public Automaton nTimes( BigInteger n) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (n.compareTo(ZERO) < 0) { throw new InternalException("n may not be negative"); } if (n.compareTo(ZERO) == 0) { return getEpsilonLookAnyStarEnd(); } Automaton newAutomaton = this; for (BigInteger i = ONE; i.compareTo(n) < 0; i = i.add(ONE)) { newAutomaton = newAutomaton.concat(this); } return newAutomaton; } public Automaton nTimesWithSeparator( Automaton automaton, BigInteger n) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (automaton == null) { throw new InternalException("automaton may not be null"); } if (!automaton.isStable) { throw new InternalException("automaton is not yet stable"); } if (n.compareTo(ZERO) < 0) { throw new InternalException("n may not be negative"); } if (n.compareTo(ZERO) == 0) { return getEpsilonLookAnyStarEnd(); } if (n.compareTo(ONE) == 0) { return this; } return concat(automaton.concat(this).nTimes(n.subtract(ONE))); } public Automaton nOrMore( BigInteger n) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (n.compareTo(ZERO) < 0) { throw new InternalException("n may not be negative"); } return nTimes(n).concat(zeroOrMore()); } public Automaton nOrMoreWithSeparator( Automaton automaton, BigInteger n) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (automaton == null) { throw new InternalException("automaton may not be null"); } if (!automaton.isStable) { throw new InternalException("automaton is not yet stable"); } if (n.compareTo(ZERO) < 0) { throw new InternalException("n may not be negative"); } if (n.compareTo(ZERO) == 0) { return zeroOrMoreWithSeparator(automaton); } if (n.compareTo(ONE) == 0) { return oneOrMoreWithSeparator(automaton); } return concat(automaton.concat(this).nOrMore(n.subtract(ONE))); } public Automaton nToM( BigInteger n, BigInteger m) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (n.compareTo(ZERO) < 0) { throw new InternalException("n may not be negative"); } if (m.compareTo(n) < 0) { throw new InternalException("m may not be smaller than n"); } Automaton tailAutomaton = getEpsilonLookAnyStarEnd(); for (BigInteger i = n; i.compareTo(m) < 0; i = i.add(ONE)) { tailAutomaton = tailAutomaton.concat(this).zeroOrOne(); } return nTimes(n).concat(tailAutomaton); } public Automaton nToMWithSeparator( Automaton automaton, BigInteger n, BigInteger m) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (automaton == null) { throw new InternalException("automaton may not be null"); } if (!automaton.isStable) { throw new InternalException("automaton is not yet stable"); } if (n.compareTo(ZERO) < 0) { throw new InternalException("n may not be negative"); } if (m.compareTo(n) < 0) { throw new InternalException("m may not be smaller than n"); } if (m.compareTo(n) == 0) { return nTimesWithSeparator(automaton, n); } Automaton tailAutomaton = getEpsilonLookAnyStarEnd(); if (n.compareTo(ZERO) == 0) { for (BigInteger i = ONE; i.compareTo(m) < 0; i = i.add(ONE)) { tailAutomaton = tailAutomaton.concat(automaton.concat(this)) .zeroOrOne(); } return concat(tailAutomaton).zeroOrOne(); } for (BigInteger i = n; i.compareTo(m) < 0; i = i.add(ONE)) { tailAutomaton = tailAutomaton.concat(automaton.concat(this)) .zeroOrOne(); } return nTimesWithSeparator(automaton, n).concat(tailAutomaton); } public Automaton look( Automaton automaton) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (automaton == null) { throw new InternalException("automaton may not be null"); } if (!automaton.isStable) { throw new InternalException("automaton is not yet stable"); } return new LookOperation(this, automaton).getNewAutomaton(); } public Automaton lookNot( Automaton automaton) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (automaton == null) { throw new InternalException("automaton may not be null"); } if (!automaton.isStable) { throw new InternalException("automaton is not yet stable"); } Automaton lookAutomaton = getEpsilonLookAnyStarEnd().except( getEpsilonLookAnyStarEnd().look(automaton)); return look(lookAutomaton); } public Automaton except( Automaton automaton) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (automaton == null) { throw new InternalException("automaton may not be null"); } if (!automaton.isStable) { throw new InternalException("automaton is not yet stable"); } Acceptation leftAcceptation = new Acceptation("left"); Acceptation rightAcceptation = new Acceptation("right"); Automaton leftAutomaton = accept(leftAcceptation).minimal(); Automaton rightAutomaton = automaton.accept(rightAcceptation).minimal(); Automaton combinedAutomaton = leftAutomaton.or(rightAutomaton) .minimal(); Automaton newAutomaton = new Automaton(combinedAutomaton.getAlphabet()); newAutomaton.addAcceptation(Acceptation.ACCEPT); SortedMap<State, State> oldStatetoNewStateMap = new TreeMap<State, State>(); for (State oldState : combinedAutomaton.getStates()) { State newState = oldState == combinedAutomaton.getStartState() ? newAutomaton .getStartState() : new State(newAutomaton); oldStatetoNewStateMap.put(oldState, newState); if (oldState.getAcceptations().size() == 1 && oldState.getAcceptations().first() .equals(leftAcceptation)) { newState.addAcceptation(Acceptation.ACCEPT); } } for (State oldSourceState : combinedAutomaton.getStates()) { State newSourceState = oldStatetoNewStateMap.get(oldSourceState); for (Map.Entry<RichSymbol, SortedSet<State>> entry : oldSourceState .getTransitions().entrySet()) { RichSymbol richSymbol = entry.getKey(); for (State oldTargetState : entry.getValue()) { State newTargetState = oldStatetoNewStateMap .get(oldTargetState); newSourceState.addTransition(richSymbol, newTargetState); } } } newAutomaton.stabilize(); return newAutomaton; } public Automaton and( Automaton automaton) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (automaton == null) { throw new InternalException("automaton may not be null"); } if (!automaton.isStable) { throw new InternalException("automaton is not yet stable"); } Acceptation leftAcceptation = new Acceptation("left"); Acceptation rightAcceptation = new Acceptation("right"); Automaton leftAutomaton = accept(leftAcceptation).minimal(); Automaton rightAutomaton = automaton.accept(rightAcceptation).minimal(); Automaton combinedAutomaton = leftAutomaton.or(rightAutomaton) .minimal(); Automaton newAutomaton = new Automaton(combinedAutomaton.getAlphabet()); newAutomaton.addAcceptation(Acceptation.ACCEPT); SortedMap<State, State> oldStatetoNewStateMap = new TreeMap<State, State>(); for (State oldState : combinedAutomaton.getStates()) { State newState = oldState == combinedAutomaton.getStartState() ? newAutomaton .getStartState() : new State(newAutomaton); oldStatetoNewStateMap.put(oldState, newState); if (oldState.getAcceptations().size() == 2) { newState.addAcceptation(Acceptation.ACCEPT); } } for (State oldSourceState : combinedAutomaton.getStates()) { State newSourceState = oldStatetoNewStateMap.get(oldSourceState); for (Map.Entry<RichSymbol, SortedSet<State>> entry : oldSourceState .getTransitions().entrySet()) { RichSymbol richSymbol = entry.getKey(); for (State oldTargetState : entry.getValue()) { State newTargetState = oldStatetoNewStateMap .get(oldTargetState); newSourceState.addTransition(richSymbol, newTargetState); } } } newAutomaton.stabilize(); return newAutomaton; } public Automaton subtract( Automaton automaton) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (automaton == null) { throw new InternalException("automaton may not be null"); } if (!automaton.isStable) { throw new InternalException("automaton is not yet stable"); } return new SubtractOperation(this, automaton).getNewAutomaton(); } public Automaton shortest() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } return new ShortestOperation(this).getNewAutomaton(); } public Automaton longest() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } return new LongestOperation(this).getNewAutomaton(); } public Automaton withMarkers() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } return new WithMarkersOperation(this).getNewAutomaton(); } public static Automaton getEpsilonLookAnyStarEnd() { Symbol any = new Symbol(new Interval(Bound.MIN, Bound.MAX)); Alphabet alphabet = new Alphabet(any); Automaton automaton = new Automaton(alphabet); State start = automaton.startState; State end = new State(automaton); start.addTransition(any.getLookaheadRichSymbol(), start); start.addTransition(RichSymbol.END, end); automaton.addAcceptation(Acceptation.ACCEPT); end.addAcceptation(Acceptation.ACCEPT); automaton.stabilize(); return automaton; } public static Automaton getSymbolLookAnyStarEnd( Symbol symbol) { if (symbol == null) { throw new InternalException("symbol may not be null"); } Symbol any = new Symbol(new Interval(Bound.MIN, Bound.MAX)); Alphabet anyAlphabet = new Alphabet(any); Alphabet symbolAlphabet = new Alphabet(symbol); AlphabetMergeResult alphabetMergeResult = anyAlphabet .mergeWith(symbolAlphabet); Alphabet alphabet = alphabetMergeResult.getNewAlphabet(); Automaton automaton = new Automaton(alphabet); State start = automaton.startState; State middle = new State(automaton); State end = new State(automaton); for (Symbol newSymbol : alphabetMergeResult.getNewSymbols(symbol)) { start.addTransition(newSymbol.getNormalRichSymbol(), middle); } for (Symbol newSymbol : alphabetMergeResult.getNewSymbols(any)) { middle.addTransition(newSymbol.getLookaheadRichSymbol(), middle); } middle.addTransition(RichSymbol.END, end); automaton.addAcceptation(Acceptation.ACCEPT); end.addAcceptation(Acceptation.ACCEPT); automaton.stabilize(); return automaton; } public static Automaton getEpsilonLookEnd() { Alphabet alphabet = new Alphabet(); Automaton automaton = new Automaton(alphabet); State start = automaton.startState; State end = new State(automaton); start.addTransition(RichSymbol.END, end); automaton.addAcceptation(Acceptation.ACCEPT); end.addAcceptation(Acceptation.ACCEPT); automaton.stabilize(); return automaton; } public static Automaton getEmptyAutomaton() { Automaton automaton = new Automaton(new Alphabet()); automaton.stabilize(); return automaton; } /** Collect all states associated with each acceptation. */ public Map<Acceptation, Set<State>> collectAcceptationStates() { Map<Acceptation, Set<State>> result = new HashMap<Acceptation, Set<State>>(); for (State state : getStates()) { for (Acceptation acceptation : state.getAcceptations()) { if (acceptation == Acceptation.ACCEPT) { continue; } Set<State> set = result.get(acceptation); if (set == null) { set = new TreeSet<State>(); result.put(acceptation, set); } set.add(state); } } return result; } /** Find an example of a shortest word for each state of the automaton. */ public Map<State, String> collectShortestWords() { WorkSet<State> todo = new WorkSet<State>(); Map<State, State> prev = new HashMap<State, State>(); Map<State, String> result = new HashMap<State, String>(); Set<State> inlook = new HashSet<State>(); State start = getStartState(); prev.put(start, null); result.put(start, ""); todo.add(start); while (todo.hasNext()) { State s = todo.next(); SortedMap<RichSymbol, SortedSet<State>> map = s.getTransitions(); for (RichSymbol rsym : map.keySet()) { if (rsym == null) { continue; } for (State s2 : map.get(rsym)) { if (result.get(s2) != null) { continue; } Symbol sym = rsym.getSymbol(); prev.put(s2, s); String w = result.get(s); if (sym != null) { if (inlook.contains(s)) { inlook.add(s2); } else if (rsym.isLookahead()) { w += "' Lookahead '"; inlook.add(s2); } w += sym.getExample(); } result.put(s2, w); todo.add(s2); } } } return result; } /** * Returns a comparator for rich symbols which can handle epsilon (null) * comparisons. */ static Comparator<RichSymbol> getRichSymbolComparator() { return Automaton.richSymbolComparator; } void identifyCyclicStatesOnLookaheadTransitions() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (!isDeterministic()) { throw new InternalException("invalid operation"); } ComponentFinder<State> componentFinder = new ComponentFinder<State>( getStates(), lookaheadProgeny); for (State state : getStates()) { State representative = componentFinder.getRepresentative(state); state.setIsCyclic(componentFinder.getReach(representative) .contains(state)); } } /** * Return a new automaton with a new set of acceptation states. Existing * acceptation states are not preserved. Note that: 1) the states of the * result are new objects (the states of newAccepts refers to the one in the * current automaton). 2) the acceptation objects of newAccepts are reused * in the new automaton. * */ public Automaton resetAcceptations( Map<State, Acceptation> newAccepts) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (this.acceptations.size() == 1 && this.acceptations.first() == Acceptation.ACCEPT) { throw new InternalException("invalid operation"); } if (hasMarkers()) { throw new InternalException("invalid operation"); } if (newAccepts == null) { throw new InternalException("newAccepts may not be null"); } Automaton oldAutomaton = this; Automaton newAutomaton = new Automaton(oldAutomaton.getAlphabet()); SortedMap<State, State> oldStatetoNewStateMap = new TreeMap<State, State>(); // Duplicate all states for (State oldState : oldAutomaton.getStates()) { State newState; if (oldState == oldAutomaton.getStartState()) { newState = newAutomaton.getStartState(); } else { newState = new State(newAutomaton); } oldStatetoNewStateMap.put(oldState, newState); } // Duplicate all transitions for (State oldSourceState : oldAutomaton.getStates()) { State newSourceState = oldStatetoNewStateMap.get(oldSourceState); SortedMap<RichSymbol, SortedSet<State>> map = oldSourceState .getTransitions(); for (RichSymbol rsym : map.keySet()) { for (State oldTargetState : map.get(rsym)) { State newTargetState = oldStatetoNewStateMap .get(oldTargetState); newSourceState.addTransition(rsym, newTargetState); } } } // Set new acceptations for (State oldState : oldAutomaton.getStates()) { Acceptation acceptation = newAccepts.get(oldState); if (acceptation == null) { continue; } State newState = oldStatetoNewStateMap.get(oldState); // NOTE: why is Node.addAcceptation so picky? and why // adding an acceptation in an automaton so dirty? if (!newAutomaton.acceptations.contains(acceptation)) { newAutomaton.addAcceptation(acceptation); } newState.addAcceptation(acceptation); } newAutomaton.stabilize(); return newAutomaton; } }
src/org/sablecc/sablecc/automaton/Automaton.java
/* This file is part of SableCC ( http://sablecc.org ). * * See the NOTICE file distributed with this work for copyright information. * * 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.sablecc.sablecc.automaton; import static java.math.BigInteger.*; import static org.sablecc.util.UsefulStaticImports.*; import java.math.*; import java.util.*; import org.sablecc.exception.*; import org.sablecc.sablecc.alphabet.*; import org.sablecc.sablecc.alphabet.Bound; import org.sablecc.util.*; /** * An instance of this class represents a finite automaton. */ public final class Automaton { /** * A comparator for rich symbols which can handle epsilon (null) * comparisons. */ private static final Comparator<RichSymbol> richSymbolComparator = new Comparator<RichSymbol>() { // allows comparison of null symbols @Override public int compare( RichSymbol richSymbol1, RichSymbol richSymbol2) { if (richSymbol1 == null) { return richSymbol2 == null ? 0 : -1; } if (richSymbol2 == null) { return 1; } return richSymbol1.compareTo(richSymbol2); } }; private static final Progeny<State> lookaheadProgeny = new Progeny<State>() { @Override protected Set<State> getChildrenNoCache( State sourceState) { Set<State> children = new LinkedHashSet<State>(); for (RichSymbol richSymbol : sourceState.getTransitions().keySet()) { if (!richSymbol.isLookahead()) { continue; } State targetState = sourceState.getSingleTarget(richSymbol); children.add(targetState); } return children; } }; /** * The alphabet of this automaton. */ private final Alphabet alphabet; /** * The states of this automaton. */ private SortedSet<State> states; /** * The start state of this automaton. */ private State startState; /** * The markers of this automaton. */ private SortedSet<Marker> markers; /** * The acceptations of this automaton. */ private SortedSet<Acceptation> acceptations; private Boolean isDeterministic; /** * The stability status of this automaton. */ private boolean isStable; /** * The cached string representation of this automaton. It is * <code>null</code> when not yet computed. */ private String toString; /** * Initializes this automaton. This method must be called at the beginning * of every constructors. */ private void init() { this.states = new TreeSet<State>(); this.startState = new State(this); this.markers = new TreeSet<Marker>(); this.acceptations = new TreeSet<Acceptation>(); this.isStable = false; } /** * Constructs an incomplete automaton. This private constructor returns an * automaton to which new states can be added. The <code>stabilize()</code> * method should be called on this instance before exposing it publicly. */ Automaton( Alphabet alphabet) { init(); this.alphabet = alphabet; } /** * Returns the alphabet of this automaton. */ public Alphabet getAlphabet() { return this.alphabet; } /** * Returns the states of this automaton. */ public SortedSet<State> getStates() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } return this.states; } /** * Returns the start state of this automaton. */ public State getStartState() { return this.startState; } /** * Returns the markers of this automaton. */ public SortedSet<Marker> getMarkers() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } return this.markers; } /** * Returns the markers of this unstable automaton. */ SortedSet<Marker> getUnstableMarkers() { if (this.isStable) { throw new InternalException("this automaton is stable"); } return this.markers; } /** * Returns the acceptations of this automaton. */ public SortedSet<Acceptation> getAcceptations() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } return this.acceptations; } /** * Returns the acceptations of this unstable automaton. */ SortedSet<Acceptation> getUnstableAcceptations() { if (this.isStable) { throw new InternalException("this automaton is stable"); } return this.acceptations; } /** * Returns the string representation of this automaton. */ @Override public String toString() { if (this.toString == null) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } StringBuilder sb = new StringBuilder(); sb.append("Automaton:{"); for (State state : this.states) { sb.append(LINE_SEPARATOR); sb.append(" "); if (state == this.startState) { sb.append("(start)"); } sb.append(state); sb.append(":"); for (Map.Entry<RichSymbol, SortedSet<State>> entry : state .getTransitions().entrySet()) { RichSymbol richSymbol = entry.getKey(); SortedSet<State> targets = entry.getValue(); for (State target : targets) { sb.append(LINE_SEPARATOR); sb.append(" "); sb.append(richSymbol == null ? "EPSILON" : richSymbol .toString()); sb.append(" -> state_"); sb.append(target.getId()); } } } sb.append(LINE_SEPARATOR); sb.append("}"); this.toString = sb.toString(); } return this.toString; } /** * Stabilizes this automaton by stabilizing each of its states. */ void stabilize() { if (this.isStable) { throw new InternalException("this automaton is already stable"); } for (State state : this.states) { state.stabilize(); } this.states = Collections.unmodifiableSortedSet(this.states); this.markers = Collections.unmodifiableSortedSet(this.markers); this.acceptations = Collections .unmodifiableSortedSet(this.acceptations); this.isStable = true; } /** * Returns the next available state ID. This is useful for the construction * of a new state. */ int getNextStateId() { if (this.isStable) { throw new InternalException( "this automaton is stable and may not be modified"); } return this.states.size(); } /** * Adds the provided state to this automaton. */ void addState( State state) { if (this.isStable) { throw new InternalException( "this automaton is stable and may not be modified"); } if (state == null) { throw new InternalException("state may not be null"); } if (state.getId() != this.states.size()) { throw new InternalException("invalid state ID"); } if (!this.states.add(state)) { throw new InternalException("state is already in states"); } } /** * Adds the provided marker to this automaton. */ void addMarker( Marker marker) { if (this.isStable) { throw new InternalException( "this automaton is stable and may not be modified"); } if (marker == null) { throw new InternalException("marker may not be null"); } if (!this.markers.add(marker)) { throw new InternalException("marker is already in markers"); } } /** * Adds the provided state as an accept state of this automaton according to * the provided acceptation. */ void addAcceptation( Acceptation acceptation) { if (this.isStable) { throw new InternalException( "this automaton is stable and may not be modified"); } if (acceptation == null) { throw new InternalException("acceptation may not be null"); } if (acceptation.getMarker() != null && !this.markers.contains(acceptation.getMarker())) { throw new InternalException("acceptation has invalid marker"); } if (!this.acceptations.add(acceptation)) { throw new InternalException( "acceptation is already in acceptations"); } } public boolean isDeterministic() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (this.isDeterministic == null) { outer_loop: for (State state : this.states) { for (Map.Entry<RichSymbol, SortedSet<State>> entry : state .getTransitions().entrySet()) { if (entry.getKey() == null || entry.getValue().size() > 1) { this.isDeterministic = false; break outer_loop; } } } if (this.isDeterministic == null) { this.isDeterministic = true; } } return this.isDeterministic; } public boolean hasMarkers() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } return this.markers.size() > 0; } public boolean hasCustomAcceptations() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } for (Acceptation acceptation : this.acceptations) { if (acceptation != Acceptation.ACCEPT) { return true; } } return false; } public boolean hasEndTransition() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } for (State state : this.states) { if (state.getTransitions().containsKey(RichSymbol.END)) { return true; } } return false; } public Automaton withMergedAlphabet( AlphabetMergeResult alphabetMergeResult) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (alphabetMergeResult == null) { throw new InternalException("alphabetMergeResult may not be null"); } if (hasMarkers()) { throw new InternalException("invalid operation"); } Automaton newAutomaton = new Automaton( alphabetMergeResult.getNewAlphabet()); for (Acceptation acceptation : getAcceptations()) { newAutomaton.addAcceptation(acceptation); } SortedMap<State, State> oldStateToNewStateMap = new TreeMap<State, State>(); SortedMap<State, State> newStateToOldStateMap = new TreeMap<State, State>(); oldStateToNewStateMap .put(getStartState(), newAutomaton.getStartState()); newStateToOldStateMap .put(newAutomaton.getStartState(), getStartState()); for (State oldState : getStates()) { if (oldState.equals(getStartState())) { continue; } State newState = new State(newAutomaton); oldStateToNewStateMap.put(oldState, newState); newStateToOldStateMap.put(newState, oldState); } for (State oldSourceState : getStates()) { State newSourceState = oldStateToNewStateMap.get(oldSourceState); for (Map.Entry<RichSymbol, SortedSet<State>> entry : oldSourceState .getTransitions().entrySet()) { RichSymbol oldRichSymbol = entry.getKey(); SortedSet<State> oldTargetStates = entry.getValue(); for (State oldTargetState : oldTargetStates) { State newTargetState = oldStateToNewStateMap .get(oldTargetState); if (oldRichSymbol == null) { RichSymbol newRichSymbol = null; newSourceState.addTransition(newRichSymbol, newTargetState); } else { for (RichSymbol newRichSymbol : alphabetMergeResult .getNewRichSymbols(oldRichSymbol)) { newSourceState.addTransition(newRichSymbol, newTargetState); } } } } for (Acceptation acceptation : oldSourceState.getAcceptations()) { newSourceState.addAcceptation(acceptation); } } newAutomaton.stabilize(); return newAutomaton; } public Automaton withoutUnreachableStates() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (hasMarkers()) { throw new InternalException("invalid operation"); } SortedSet<State> reachableStates = new TreeSet<State>(); SortedSet<Acceptation> usefulAcceptations = new TreeSet<Acceptation>(); WorkSet<State> workSet = new WorkSet<State>(); workSet.add(getStartState()); Automaton newAutomaton = new Automaton(getAlphabet()); SortedMap<State, State> oldStatetoNewStateMap = new TreeMap<State, State>(); while (workSet.hasNext()) { State reachableState = workSet.next(); reachableStates.add(reachableState); State newState = reachableState == getStartState() ? newAutomaton .getStartState() : new State(newAutomaton); oldStatetoNewStateMap.put(reachableState, newState); for (Acceptation usefulAcceptation : reachableState .getAcceptations()) { usefulAcceptations.add(usefulAcceptation); } for (Map.Entry<RichSymbol, SortedSet<State>> entry : reachableState .getTransitions().entrySet()) { for (State targetState : entry.getValue()) { workSet.add(targetState); } } } for (Acceptation usefulAcceptation : usefulAcceptations) { newAutomaton.addAcceptation(usefulAcceptation); } for (State oldSourceState : reachableStates) { State newSourceState = oldStatetoNewStateMap.get(oldSourceState); for (Map.Entry<RichSymbol, SortedSet<State>> entry : oldSourceState .getTransitions().entrySet()) { SortedSet<State> oldTargetStates = entry.getValue(); for (State oldTargetState : oldTargetStates) { State newTargetState = oldStatetoNewStateMap .get(oldTargetState); newSourceState .addTransition(entry.getKey(), newTargetState); } } for (Acceptation acceptation : oldSourceState.getAcceptations()) { newSourceState.addAcceptation(acceptation); } } newAutomaton.stabilize(); return newAutomaton; } public Automaton accept( Acceptation acceptation) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (hasCustomAcceptations()) { throw new InternalException("invalid operation"); } if (hasMarkers()) { throw new InternalException("invalid operation"); } if (acceptation == null) { throw new InternalException("acceptation may not be null"); } if (acceptation.equals(Acceptation.ACCEPT)) { throw new InternalException("acceptation is invalid"); } Automaton newAutomaton = new Automaton(getAlphabet()); newAutomaton.addAcceptation(acceptation); SortedMap<State, State> oldStatetoNewStateMap = new TreeMap<State, State>(); for (State oldState : getStates()) { State newState = oldState == getStartState() ? newAutomaton .getStartState() : new State(newAutomaton); oldStatetoNewStateMap.put(oldState, newState); if (oldState.isAcceptState()) { newState.addAcceptation(acceptation); } } for (State oldSourceState : getStates()) { State newSourceState = oldStatetoNewStateMap.get(oldSourceState); for (Map.Entry<RichSymbol, SortedSet<State>> entry : oldSourceState .getTransitions().entrySet()) { RichSymbol richSymbol = entry.getKey(); for (State oldTargetState : entry.getValue()) { State newTargetState = oldStatetoNewStateMap .get(oldTargetState); newSourceState.addTransition(richSymbol, newTargetState); } } } newAutomaton.stabilize(); return newAutomaton; } public Automaton deterministic() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } return new DeterministicOperation(this).getNewAutomaton(); } public Automaton minimal() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } return new MinimalOperation(this).getNewAutomaton(); } public Automaton or( Automaton automaton) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (automaton == null) { throw new InternalException("automaton may not be null"); } if (!automaton.isStable) { throw new InternalException("automaton is not yet stable"); } return new OrOperation(this, automaton).getNewAutomaton(); } public Automaton concat( Automaton automaton) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (automaton == null) { throw new InternalException("automaton may not be null"); } if (!automaton.isStable) { throw new InternalException("automaton is not yet stable"); } return new ConcatOperation(this, automaton).getNewAutomaton(); } public Automaton zeroOrOne() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } return or(getEpsilonLookAnyStarEnd()); } public Automaton oneOrMore() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } return new OneOrMoreOperation(this).getNewAutomaton(); } public Automaton oneOrMoreWithSeparator( Automaton automaton) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (automaton == null) { throw new InternalException("automaton may not be null"); } if (!automaton.isStable) { throw new InternalException("automaton is not yet stable"); } return concat(automaton.concat(this).zeroOrMore()); } public Automaton zeroOrMore() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } return oneOrMore().zeroOrOne(); } public Automaton zeroOrMoreWithSeparator( Automaton automaton) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (automaton == null) { throw new InternalException("automaton may not be null"); } if (!automaton.isStable) { throw new InternalException("automaton is not yet stable"); } return oneOrMoreWithSeparator(automaton).zeroOrOne(); } public Automaton nTimes( BigInteger n) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (n.compareTo(ZERO) < 0) { throw new InternalException("n may not be negative"); } if (n.compareTo(ZERO) == 0) { return getEpsilonLookAnyStarEnd(); } Automaton newAutomaton = this; for (BigInteger i = ONE; i.compareTo(n) < 0; i = i.add(ONE)) { newAutomaton = newAutomaton.concat(this); } return newAutomaton; } public Automaton nTimesWithSeparator( Automaton automaton, BigInteger n) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (automaton == null) { throw new InternalException("automaton may not be null"); } if (!automaton.isStable) { throw new InternalException("automaton is not yet stable"); } if (n.compareTo(ZERO) < 0) { throw new InternalException("n may not be negative"); } if (n.compareTo(ZERO) == 0) { return getEpsilonLookAnyStarEnd(); } if (n.compareTo(ONE) == 0) { return this; } return concat(automaton.concat(this).nTimes(n.subtract(ONE))); } public Automaton nOrMore( BigInteger n) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (n.compareTo(ZERO) < 0) { throw new InternalException("n may not be negative"); } return nTimes(n).concat(zeroOrMore()); } public Automaton nOrMoreWithSeparator( Automaton automaton, BigInteger n) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (automaton == null) { throw new InternalException("automaton may not be null"); } if (!automaton.isStable) { throw new InternalException("automaton is not yet stable"); } if (n.compareTo(ZERO) < 0) { throw new InternalException("n may not be negative"); } if (n.compareTo(ZERO) == 0) { return zeroOrMoreWithSeparator(automaton); } if (n.compareTo(ONE) == 0) { return oneOrMoreWithSeparator(automaton); } return concat(automaton.concat(this).nOrMore(n.subtract(ONE))); } public Automaton nToM( BigInteger n, BigInteger m) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (n.compareTo(ZERO) < 0) { throw new InternalException("n may not be negative"); } if (m.compareTo(n) < 0) { throw new InternalException("m may not be smaller than n"); } Automaton tailAutomaton = getEpsilonLookAnyStarEnd(); for (BigInteger i = n; i.compareTo(m) < 0; i = i.add(ONE)) { tailAutomaton = tailAutomaton.concat(this).zeroOrOne(); } return nTimes(n).concat(tailAutomaton); } public Automaton nToMWithSeparator( Automaton automaton, BigInteger n, BigInteger m) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (automaton == null) { throw new InternalException("automaton may not be null"); } if (!automaton.isStable) { throw new InternalException("automaton is not yet stable"); } if (n.compareTo(ZERO) < 0) { throw new InternalException("n may not be negative"); } if (m.compareTo(n) < 0) { throw new InternalException("m may not be smaller than n"); } if (m.compareTo(n) == 0) { return nTimesWithSeparator(automaton, n); } Automaton tailAutomaton = getEpsilonLookAnyStarEnd(); if (n.compareTo(ZERO) == 0) { for (BigInteger i = ONE; i.compareTo(m) < 0; i = i.add(ONE)) { tailAutomaton = tailAutomaton.concat(automaton.concat(this)) .zeroOrOne(); } return concat(tailAutomaton).zeroOrOne(); } for (BigInteger i = n; i.compareTo(m) < 0; i = i.add(ONE)) { tailAutomaton = tailAutomaton.concat(automaton.concat(this)) .zeroOrOne(); } return nTimesWithSeparator(automaton, n).concat(tailAutomaton); } public Automaton look( Automaton automaton) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (automaton == null) { throw new InternalException("automaton may not be null"); } if (!automaton.isStable) { throw new InternalException("automaton is not yet stable"); } return new LookOperation(this, automaton).getNewAutomaton(); } public Automaton lookNot( Automaton automaton) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (automaton == null) { throw new InternalException("automaton may not be null"); } if (!automaton.isStable) { throw new InternalException("automaton is not yet stable"); } Automaton lookAutomaton = getEpsilonLookAnyStarEnd().except( getEpsilonLookAnyStarEnd().look(automaton)); return look(lookAutomaton); } public Automaton except( Automaton automaton) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (automaton == null) { throw new InternalException("automaton may not be null"); } if (!automaton.isStable) { throw new InternalException("automaton is not yet stable"); } Acceptation leftAcceptation = new Acceptation("left"); Acceptation rightAcceptation = new Acceptation("right"); Automaton leftAutomaton = accept(leftAcceptation).minimal(); Automaton rightAutomaton = automaton.accept(rightAcceptation).minimal(); Automaton combinedAutomaton = leftAutomaton.or(rightAutomaton) .minimal(); Automaton newAutomaton = new Automaton(combinedAutomaton.getAlphabet()); newAutomaton.addAcceptation(Acceptation.ACCEPT); SortedMap<State, State> oldStatetoNewStateMap = new TreeMap<State, State>(); for (State oldState : combinedAutomaton.getStates()) { State newState = oldState == combinedAutomaton.getStartState() ? newAutomaton .getStartState() : new State(newAutomaton); oldStatetoNewStateMap.put(oldState, newState); if (oldState.getAcceptations().size() == 1 && oldState.getAcceptations().first() .equals(leftAcceptation)) { newState.addAcceptation(Acceptation.ACCEPT); } } for (State oldSourceState : combinedAutomaton.getStates()) { State newSourceState = oldStatetoNewStateMap.get(oldSourceState); for (Map.Entry<RichSymbol, SortedSet<State>> entry : oldSourceState .getTransitions().entrySet()) { RichSymbol richSymbol = entry.getKey(); for (State oldTargetState : entry.getValue()) { State newTargetState = oldStatetoNewStateMap .get(oldTargetState); newSourceState.addTransition(richSymbol, newTargetState); } } } newAutomaton.stabilize(); return newAutomaton; } public Automaton and( Automaton automaton) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (automaton == null) { throw new InternalException("automaton may not be null"); } if (!automaton.isStable) { throw new InternalException("automaton is not yet stable"); } Acceptation leftAcceptation = new Acceptation("left"); Acceptation rightAcceptation = new Acceptation("right"); Automaton leftAutomaton = accept(leftAcceptation).minimal(); Automaton rightAutomaton = automaton.accept(rightAcceptation).minimal(); Automaton combinedAutomaton = leftAutomaton.or(rightAutomaton) .minimal(); Automaton newAutomaton = new Automaton(combinedAutomaton.getAlphabet()); newAutomaton.addAcceptation(Acceptation.ACCEPT); SortedMap<State, State> oldStatetoNewStateMap = new TreeMap<State, State>(); for (State oldState : combinedAutomaton.getStates()) { State newState = oldState == combinedAutomaton.getStartState() ? newAutomaton .getStartState() : new State(newAutomaton); oldStatetoNewStateMap.put(oldState, newState); if (oldState.getAcceptations().size() == 2) { newState.addAcceptation(Acceptation.ACCEPT); } } for (State oldSourceState : combinedAutomaton.getStates()) { State newSourceState = oldStatetoNewStateMap.get(oldSourceState); for (Map.Entry<RichSymbol, SortedSet<State>> entry : oldSourceState .getTransitions().entrySet()) { RichSymbol richSymbol = entry.getKey(); for (State oldTargetState : entry.getValue()) { State newTargetState = oldStatetoNewStateMap .get(oldTargetState); newSourceState.addTransition(richSymbol, newTargetState); } } } newAutomaton.stabilize(); return newAutomaton; } public Automaton subtract( Automaton automaton) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (automaton == null) { throw new InternalException("automaton may not be null"); } if (!automaton.isStable) { throw new InternalException("automaton is not yet stable"); } return new SubtractOperation(this, automaton).getNewAutomaton(); } public Automaton shortest() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } return new ShortestOperation(this).getNewAutomaton(); } public Automaton longest() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } return new LongestOperation(this).getNewAutomaton(); } public Automaton withMarkers() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } return new WithMarkersOperation(this).getNewAutomaton(); } public static Automaton getEpsilonLookAnyStarEnd() { Symbol any = new Symbol(new Interval(Bound.MIN, Bound.MAX)); Alphabet alphabet = new Alphabet(any); Automaton automaton = new Automaton(alphabet); State start = automaton.startState; State end = new State(automaton); start.addTransition(any.getLookaheadRichSymbol(), start); start.addTransition(RichSymbol.END, end); automaton.addAcceptation(Acceptation.ACCEPT); end.addAcceptation(Acceptation.ACCEPT); automaton.stabilize(); return automaton; } public static Automaton getSymbolLookAnyStarEnd( Symbol symbol) { if (symbol == null) { throw new InternalException("symbol may not be null"); } Symbol any = new Symbol(new Interval(Bound.MIN, Bound.MAX)); Alphabet anyAlphabet = new Alphabet(any); Alphabet symbolAlphabet = new Alphabet(symbol); AlphabetMergeResult alphabetMergeResult = anyAlphabet .mergeWith(symbolAlphabet); Alphabet alphabet = alphabetMergeResult.getNewAlphabet(); Automaton automaton = new Automaton(alphabet); State start = automaton.startState; State middle = new State(automaton); State end = new State(automaton); for (Symbol newSymbol : alphabetMergeResult.getNewSymbols(symbol)) { start.addTransition(newSymbol.getNormalRichSymbol(), middle); } for (Symbol newSymbol : alphabetMergeResult.getNewSymbols(any)) { middle.addTransition(newSymbol.getLookaheadRichSymbol(), middle); } middle.addTransition(RichSymbol.END, end); automaton.addAcceptation(Acceptation.ACCEPT); end.addAcceptation(Acceptation.ACCEPT); automaton.stabilize(); return automaton; } public static Automaton getEpsilonLookEnd() { Alphabet alphabet = new Alphabet(); Automaton automaton = new Automaton(alphabet); State start = automaton.startState; State end = new State(automaton); start.addTransition(RichSymbol.END, end); automaton.addAcceptation(Acceptation.ACCEPT); end.addAcceptation(Acceptation.ACCEPT); automaton.stabilize(); return automaton; } public static Automaton getEmptyAutomaton() { Automaton automaton = new Automaton(new Alphabet()); automaton.stabilize(); return automaton; } /** Collect all states associated with each acceptation. */ public Map<Acceptation, Set<State>> collectAcceptationStates() { Map<Acceptation, Set<State>> result = new HashMap<Acceptation, Set<State>>(); for (State state : getStates()) { for (Acceptation acceptation : state.getAcceptations()) { if (acceptation == Acceptation.ACCEPT) { continue; } Set<State> set = result.get(acceptation); if (set == null) { set = new TreeSet<State>(); result.put(acceptation, set); } set.add(state); } } return result; } /** Find an example of a shortest word for each state of the automaton. */ public Map<State, String> collectShortestWords() { WorkSet<State> todo = new WorkSet<State>(); Map<State, State> prev = new HashMap<State, State>(); Map<State, String> result = new HashMap<State, String>(); Set<State> inlook = new HashSet<State>(); State start = getStartState(); prev.put(start, null); result.put(start, ""); todo.add(start); while (todo.hasNext()) { State s = todo.next(); SortedMap<RichSymbol, SortedSet<State>> map = s.getTransitions(); for (RichSymbol rsym : map.keySet()) { if (rsym == null) { continue; } for (State s2 : map.get(rsym)) { if (result.get(s2) != null) { continue; } Symbol sym = rsym.getSymbol(); prev.put(s2, s); String w = result.get(s); if (sym != null) { if (inlook.contains(s)) { inlook.add(s2); } else if (rsym.isLookahead()) { w += "' Lookahead '"; inlook.add(s2); } w += sym.getExample(); } result.put(s2, w); todo.add(s2); } } } return result; } /** * Returns a comparator for rich symbols which can handle epsilon (null) * comparisons. */ static Comparator<RichSymbol> getRichSymbolComparator() { return Automaton.richSymbolComparator; } void identifyCyclicStatesOnLookaheadTransitions() { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (!isDeterministic()) { throw new InternalException("invalid operation"); } ComponentFinder<State> componentFinder = new ComponentFinder<State>( getStates(), lookaheadProgeny); for (State state : getStates()) { State representative = componentFinder.getRepresentative(state); state.setIsCyclic(componentFinder.getReach(representative) .contains(state)); } } /* public Automaton withPriorities( Context context) { if (!this.isStable) { throw new InternalException("this automaton is not yet stable"); } if (this.acceptations.size() == 1 && this.acceptations.first() == Acceptation.ACCEPT) { throw new InternalException("invalid operation"); } if (hasMarkers()) { throw new InternalException("invalid operation"); } if (context == null) { throw new InternalException("context may not be null"); } Automaton oldAutomaton = minimal(); Automaton newAutomaton = new Automaton(oldAutomaton.getAlphabet()); Map<Acceptation, MatchedToken> acceptationToMatchedTokenMap = new LinkedHashMap<Acceptation, MatchedToken>(); for (Acceptation acceptation : oldAutomaton.acceptations) { newAutomaton.addAcceptation(acceptation); MatchedToken matchedToken = context.getMatchedToken(acceptation .getName()); acceptationToMatchedTokenMap.put(acceptation, matchedToken); } SortedMap<State, State> oldStatetoNewStateMap = new TreeMap<State, State>(); Map<Acceptation, Set<State>> acceptationToStateSetMap = new LinkedHashMap<Acceptation, Set<State>>(); for (State oldState : oldAutomaton.getStates()) { State newState = oldState == oldAutomaton.getStartState() ? newAutomaton .getStartState() : new State(newAutomaton); oldStatetoNewStateMap.put(oldState, newState); for (Acceptation acceptation : oldState.getAcceptations()) { Set<State> stateSet = acceptationToStateSetMap.get(acceptation); if (stateSet == null) { stateSet = new LinkedHashSet<State>(); acceptationToStateSetMap.put(acceptation, stateSet); } stateSet.add(oldState); } } for (State oldSourceState : oldAutomaton.getStates()) { State newSourceState = oldStatetoNewStateMap.get(oldSourceState); for (Entry<RichSymbol, SortedSet<State>> entry : oldSourceState .getTransitions().entrySet()) { RichSymbol richSymbol = entry.getKey(); for (State oldTargetState : entry.getValue()) { State newTargetState = oldStatetoNewStateMap .get(oldTargetState); newSourceState.addTransition(richSymbol, newTargetState); } } } // set acceptations for (State oldState : oldAutomaton.getStates()) { State newState = oldStatetoNewStateMap.get(oldState); // no acceptation if (oldState.getAcceptations().size() == 0) { continue; } // one acceptation if (oldState.getAcceptations().size() == 1) { newState.addAcceptation(oldState.getAcceptations().first()); continue; } // more acceptations PairExtractor<Acceptation> pairExtractor = new PairExtractor<Acceptation>( oldState.getAcceptations()); // check for a total order between matched tokens for (Pair<Acceptation, Acceptation> pair : pairExtractor.getPairs()) { Acceptation leftAcceptation = pair.getLeft(); Acceptation rightAcceptation = pair.getRight(); MatchedToken leftMatchedToken = acceptationToMatchedTokenMap .get(leftAcceptation); MatchedToken rightMatchedToken = acceptationToMatchedTokenMap .get(rightAcceptation); if (leftMatchedToken.hasPriorityOver(rightMatchedToken) || rightMatchedToken.hasPriorityOver(leftMatchedToken)) { continue; } Set<State> leftStateSet = acceptationToStateSetMap .get(leftAcceptation); Set<State> rightStateSet = acceptationToStateSetMap .get(rightAcceptation); if (leftStateSet.size() == rightStateSet.size()) { throw CompilerException.lexerConflict(leftMatchedToken, rightMatchedToken); } if (leftStateSet.size() < rightStateSet.size()) { if (rightStateSet.containsAll(leftStateSet)) { leftMatchedToken .addNaturalPriorityOver(rightMatchedToken); } else { throw CompilerException.lexerConflict(leftMatchedToken, rightMatchedToken); } } else { if (leftStateSet.containsAll(rightStateSet)) { rightMatchedToken .addNaturalPriorityOver(leftMatchedToken); } else { throw CompilerException.lexerConflict(leftMatchedToken, rightMatchedToken); } } } // select highest priority acceptation Acceptation winningAcceptation = null; MatchedToken winningMatchedToken = null; for (Acceptation acceptation : oldState.getAcceptations()) { MatchedToken matchedToken = acceptationToMatchedTokenMap .get(acceptation); if (winningAcceptation == null) { winningAcceptation = acceptation; winningMatchedToken = matchedToken; } else if (matchedToken.hasPriorityOver(winningMatchedToken)) { winningAcceptation = acceptation; winningMatchedToken = matchedToken; } } newState.addAcceptation(winningAcceptation); } newAutomaton.stabilize(); return newAutomaton; } */ }
Add resetAcceptations() to Automaton. Signed-off-by: Jean Privat <[email protected]> Signed-off-by: Etienne M. Gagnon <[email protected]>
src/org/sablecc/sablecc/automaton/Automaton.java
Add resetAcceptations() to Automaton.
Java
apache-2.0
55c3a931fb5e46ef1e0ccfa41e554854692230e5
0
chrisvest/stormpot,chrisvest/stormpot
package stormpot; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import static org.junit.Assume.*; import java.lang.Thread.State; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; public class UnitKit { public static Thread fork(Callable procedure) { Thread thread = new Thread(asRunnable(procedure)); thread.start(); return thread; } public static Runnable asRunnable(final Callable procedure) { return new Runnable() { public void run() { try { procedure.call(); } catch (Exception e) { throw new RuntimeException(e); } } }; } public static Callable<Poolable> $claim(final Pool pool) { return new Callable<Poolable>() { public Poolable call() { return pool.claim(); } }; } public static Callable<Completion> $await(final Completion completion) { return new Callable<Completion>() { public Completion call() throws Exception { completion.await(); return completion; } }; } public static Callable<AtomicBoolean> $await( final Completion completion, final long timeout, final TimeUnit unit, final AtomicBoolean result) { return new Callable<AtomicBoolean>() { public AtomicBoolean call() throws Exception { result.set(completion.await(timeout, unit)); return result; } }; } public static void waitForThreadState(Thread thread, Thread.State targetState) { State currentState = thread.getState(); while (currentState != targetState) { assertThat(currentState, is(not(Thread.State.TERMINATED))); Thread.yield(); currentState = thread.getState(); } } public static void join(Thread thread) { try { thread.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } public static Completion shutdown(Pool pool) { assumeThat(pool, instanceOf(LifecycledPool.class)); return ((LifecycledPool) pool).shutdown(); } }
src/test/java/stormpot/UnitKit.java
package stormpot; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import static org.junit.Assume.*; import java.lang.Thread.State; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; public class UnitKit { public static Thread fork(Callable procedure) { Thread thread = new Thread(asRunnable(procedure)); thread.start(); return thread; } public static Runnable asRunnable(final Callable procedure) { return new Runnable() { public void run() { try { procedure.call(); } catch (Exception e) { throw new RuntimeException(e); } } }; } public static Callable<Poolable> $claim(final Pool pool) { return new Callable<Poolable>() { public Poolable call() { return pool.claim(); } }; } public static Callable<Completion> $await(final Completion completion) { return new Callable<Completion>() { public Completion call() throws Exception { completion.await(); return completion; } }; } public static Callable<AtomicBoolean> $await( final Completion completion, final long timeout, final TimeUnit unit, final AtomicBoolean result) { return new Callable<AtomicBoolean>() { public AtomicBoolean call() throws Exception { result.set(completion.await(timeout, unit)); return result; } }; } public static void waitForThreadState(Thread thread, Thread.State targetState) { State currentState = thread.getState(); while (currentState != targetState) { assertThat(currentState, is(not(Thread.State.TERMINATED))); Thread.yield(); currentState = thread.getState(); } } public static void join(Thread thread) { try { thread.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } public static Completion shutdown(Pool pool) { assumeThat(pool, instanceOf(LifecycledPool.class)); return ((LifecycledPool) pool).shutdown(); } }
remove unused import.
src/test/java/stormpot/UnitKit.java
remove unused import.
Java
apache-2.0
c009d28003664b61a6f6aada3f2ac04c3d1adcda
0
nextreports/nextreports-designer,nextreports/nextreports-designer
/* * 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.designer; import java.util.List; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import ro.nextreports.designer.action.BackToParentAction; import ro.nextreports.designer.action.ExitAction; import ro.nextreports.designer.action.OpenFromServerAction; import ro.nextreports.designer.action.OpenLayoutPerspectiveAction; import ro.nextreports.designer.action.PublishAction; import ro.nextreports.designer.action.SaveAction; import ro.nextreports.designer.action.SaveAsAction; import ro.nextreports.designer.action.chart.ImportChartAction; import ro.nextreports.designer.action.chart.NewChartAction; import ro.nextreports.designer.action.chart.NewChartFromQueryAction; import ro.nextreports.designer.action.chart.OpenChartAction; import ro.nextreports.designer.action.datasource.AddDataSourceAction; import ro.nextreports.designer.action.datasource.ExportDataSourceAction; import ro.nextreports.designer.action.datasource.ImportDataSourceAction; import ro.nextreports.designer.action.favorites.FavoriteEntry; import ro.nextreports.designer.action.favorites.FavoritesUtil; import ro.nextreports.designer.action.favorites.ManageFavoritesAction; import ro.nextreports.designer.action.favorites.OpenFavoriteAction; import ro.nextreports.designer.action.help.AboutAction; import ro.nextreports.designer.action.help.CheckForUpdateAction; import ro.nextreports.designer.action.help.HelpManualAction; import ro.nextreports.designer.action.help.HelpMovieAction; import ro.nextreports.designer.action.help.HelpStartupAction; import ro.nextreports.designer.action.help.SurveyAction; import ro.nextreports.designer.action.query.ImportQueryAction; import ro.nextreports.designer.action.query.NewQueryAction; import ro.nextreports.designer.action.query.OpenQueryAction; import ro.nextreports.designer.action.query.OpenQueryPerspectiveAction; import ro.nextreports.designer.action.report.ImportReportAction; import ro.nextreports.designer.action.report.NewReportAction; import ro.nextreports.designer.action.report.NewReportFromQueryAction; import ro.nextreports.designer.action.report.OpenReportAction; import ro.nextreports.designer.action.report.ViewReportSqlAction; import ro.nextreports.designer.action.report.WizardAction; import ro.nextreports.designer.action.tools.BackupAction; import ro.nextreports.designer.action.tools.ImportAction; import ro.nextreports.designer.action.tools.Language; import ro.nextreports.designer.action.tools.LanguageAction; import ro.nextreports.designer.action.tools.RestoreAction; import ro.nextreports.designer.action.tools.RestoreDockingAction; import ro.nextreports.designer.action.tools.SettingsAction; import ro.nextreports.designer.datasource.DefaultDataSourceManager; import ro.nextreports.designer.i18n.action.ManageI18NAction; import ro.nextreports.designer.template.report.action.ApplyTemplateAction; import ro.nextreports.designer.template.report.action.CreateTemplateAction; import ro.nextreports.designer.template.report.action.ExtractTemplateAction; import ro.nextreports.designer.template.report.action.ModifyTemplateAction; import ro.nextreports.designer.util.I18NSupport; import ro.nextreports.designer.util.ShortcutsUtil; import ro.nextreports.engine.exporter.ResultExporter; import com.jgoodies.looks.HeaderStyle; import com.jgoodies.looks.Options; import com.thoughtworks.xstream.XStream; /** * @author Decebal Suiu */ public class MainMenuBar extends JMenuBar { private static final long serialVersionUID = 1L; private AddDataSourceAction addDataSourceAction = new AddDataSourceAction(false); private ExportDataSourceAction exportDataSourceAction = new ExportDataSourceAction(false); private ImportDataSourceAction importDataSourceAction = new ImportDataSourceAction(false); private WizardAction wizardAction = new WizardAction(Globals.getMainFrame().getQueryBuilderPanel().getTree()); private NewQueryAction newQueryAction = new NewQueryAction(false); private OpenQueryAction openQueryAction = new OpenQueryAction(false); private NewReportAction newReportAction = new NewReportAction(false); private NewReportFromQueryAction newReportFromQueryAction = new NewReportFromQueryAction(null, null, false, ResultExporter.DEFAULT_TYPE); private OpenReportAction openReportAction = new OpenReportAction(false); private OpenFromServerAction openFromServerAction = new OpenFromServerAction(); private PublishAction publishAction = new PublishAction(); private ExitAction exitAction = new ExitAction(); private BackupAction backupAction = new BackupAction(); private RestoreAction restoreAction = new RestoreAction(); private ImportAction importAction = new ImportAction(); private SettingsAction settingsAction = new SettingsAction(); private ViewReportSqlAction viewReportSqlAction = new ViewReportSqlAction(); private ImportReportAction importReportAction = new ImportReportAction(false); private ImportQueryAction importQueryAction = new ImportQueryAction(false); private ApplyTemplateAction applyTemplateAction = new ApplyTemplateAction(true); private ExtractTemplateAction extractTemplateAction = new ExtractTemplateAction(); private OpenLayoutPerspectiveAction openLayoutPersAction = new OpenLayoutPerspectiveAction(); private ManageI18NAction manageI18nAction = new ManageI18NAction(); private NewChartAction newChartAction = new NewChartAction(false); private OpenChartAction openChartAction = new OpenChartAction(false); private NewChartFromQueryAction newChartFromQueryAction = new NewChartFromQueryAction(null, false); private ImportChartAction importChartAction = new ImportChartAction(false); private SaveAction saveAction = new SaveAction(); private SaveAsAction saveAsAction = new SaveAsAction(); private BackToParentAction backAction = new BackToParentAction(); private JMenu menuFavorites = new JMenu(I18NSupport.getString("menu_favorites")); public MainMenuBar() { putClientProperty(Options.HEADER_STYLE_KEY, HeaderStyle.BOTH); add(createFileMenu()); add(createViewsMenu()); add(createToolsMenu()); add(createHelpMenu()); actionUpdate(Globals.getConnection() != null); Globals.setMainMenuBar(this); } public void newChartActionUpdate() { publishAction.setEnabled(true); } public void newReportActionUpdate() { applyTemplateAction.setEnabled(true); extractTemplateAction.setEnabled(true); publishAction.setEnabled(true); } public void newQueryActionUpdate() { applyTemplateAction.setEnabled(false); extractTemplateAction.setEnabled(false); publishAction.setEnabled(false); } public void actionUpdate(boolean connected) { openQueryAction.setEnabled(connected); importQueryAction.setEnabled(connected); newReportAction.setEnabled(connected); newReportFromQueryAction.setEnabled(connected); openReportAction.setEnabled(connected); importReportAction.setEnabled(connected); openFromServerAction.setEnabled(connected); newChartAction.setEnabled(connected); openChartAction.setEnabled(connected); newChartFromQueryAction.setEnabled(connected); importChartAction.setEnabled(connected); saveAction.setEnabled(connected); saveAsAction.setEnabled(connected); } public void enableLayoutPerspective(boolean enable) { openLayoutPersAction.setEnabled(enable); manageI18nAction.setEnabled(enable); } private JMenu createFileMenu() { JMenu mnu = new JMenu(I18NSupport.getString("menu.file")); mnu.setMnemonic(ShortcutsUtil.getMnemonic("menu.file.mnemonic", new Integer('F'))); JMenu mnu1 = new JMenu(I18NSupport.getString("menu_new")); mnu1.add(addDataSourceAction); mnu1.add(newQueryAction); mnu1.add(newReportAction); mnu1.add(newReportFromQueryAction); mnu1.add(newChartAction); mnu1.add(newChartFromQueryAction); mnu.add(mnu1); JMenu mnu2 = new JMenu(I18NSupport.getString("menu_open")); mnu2.add(openQueryAction); mnu2.add(openReportAction); mnu2.add(openChartAction); mnu2.addSeparator(); backAction.setEnabled(false); mnu2.add(backAction); mnu.add(mnu2); JMenu mnu3 = new JMenu(I18NSupport.getString("menu_import")); if (!DefaultDataSourceManager.memoryDataSources()) { mnu3.add(importDataSourceAction); } mnu3.add(importQueryAction); mnu3.add(importReportAction); mnu3.add(importChartAction); mnu.add(mnu3); JMenu mnu4 = new JMenu(I18NSupport.getString("menu_export")); if (!DefaultDataSourceManager.memoryDataSources()) { mnu4.add(exportDataSourceAction); mnu.add(mnu4); } mnu.addSeparator(); menuFavorites = new JMenu(I18NSupport.getString("menu_favorites")); recreateMenuFavorites(); mnu.add(menuFavorites); mnu.addSeparator(); mnu.add(saveAction); mnu.add(saveAsAction); mnu.addSeparator(); mnu.add(exitAction); newQueryActionUpdate(); return mnu; } public void recreateMenuFavorites() { menuFavorites.removeAll(); XStream xstream = FavoritesUtil.createXStream(); List<FavoriteEntry> favorites = FavoritesUtil.loadFavorites(xstream); for (FavoriteEntry fav : favorites) { menuFavorites.add(new OpenFavoriteAction(fav)); } menuFavorites.addSeparator(); menuFavorites.add(new ManageFavoritesAction()); } private JMenu createViewsMenu() { JMenu perspectiveMenu = new JMenu(I18NSupport.getString("menu.perpective")); perspectiveMenu.setMnemonic(ShortcutsUtil.getMnemonic("menu.perspective.mnemonic", new Integer('P'))); JMenuItem item = new JMenuItem(new OpenQueryPerspectiveAction()); perspectiveMenu.add(item); item = new JMenuItem(openLayoutPersAction); enableLayoutPerspective(false); perspectiveMenu.add(item); return perspectiveMenu; } private JMenu createHelpMenu() { JMenu mnu = new JMenu(I18NSupport.getString("menu.help")); mnu.setMnemonic(ShortcutsUtil.getMnemonic("menu.help.mnemonic", new Integer('H'))); mnu.add(new CheckForUpdateAction()); mnu.addSeparator(); mnu.add(new HelpMovieAction()); mnu.add(new HelpManualAction()); mnu.add(new HelpStartupAction()); mnu.addSeparator(); mnu.add(new SurveyAction()); mnu.add(new AboutAction()); return mnu; } private JMenu createToolsMenu() { JMenu mnu = new JMenu(I18NSupport.getString("menu.tools")); mnu.setMnemonic(ShortcutsUtil.getMnemonic("menu.tools.mnemonic", new Integer('T'))); mnu.add(wizardAction); mnu.add(publishAction); mnu.add(openFromServerAction); mnu.add(viewReportSqlAction); mnu.addSeparator(); JMenu mnu2 = new JMenu(I18NSupport.getString("menu_templates")); mnu2.add(new CreateTemplateAction()); mnu2.add(new ModifyTemplateAction()); mnu2.add(applyTemplateAction); mnu2.add(extractTemplateAction); mnu.add(mnu2); mnu.addSeparator(); mnu.add(backupAction); mnu.add(restoreAction); mnu.add(importAction); mnu.add(settingsAction); mnu.addSeparator(); mnu.add(new RestoreDockingAction()); mnu.addSeparator(); mnu.add(manageI18nAction); mnu.add(createLanguageMenu()); return mnu; } private JMenu createLanguageMenu() { JMenu mnu = new JMenu(I18NSupport.getString("language")); mnu.setMnemonic(ShortcutsUtil.getMnemonic("menu.language.mnemonic", new Integer('L'))); for (Language lang : LanguageAction.getLanguages()) { mnu.add(new LanguageAction(lang.getLanguage())); } return mnu; } public void enableBackAction(boolean enable) { backAction.setEnabled(enable); } }
src/ro/nextreports/designer/MainMenuBar.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.designer; import java.util.List; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import ro.nextreports.designer.action.BackToParentAction; import ro.nextreports.designer.action.ExitAction; import ro.nextreports.designer.action.OpenFromServerAction; import ro.nextreports.designer.action.OpenLayoutPerspectiveAction; import ro.nextreports.designer.action.PublishAction; import ro.nextreports.designer.action.SaveAction; import ro.nextreports.designer.action.SaveAsAction; import ro.nextreports.designer.action.chart.ImportChartAction; import ro.nextreports.designer.action.chart.NewChartAction; import ro.nextreports.designer.action.chart.NewChartFromQueryAction; import ro.nextreports.designer.action.chart.OpenChartAction; import ro.nextreports.designer.action.datasource.AddDataSourceAction; import ro.nextreports.designer.action.datasource.ExportDataSourceAction; import ro.nextreports.designer.action.datasource.ImportDataSourceAction; import ro.nextreports.designer.action.favorites.FavoriteEntry; import ro.nextreports.designer.action.favorites.FavoritesUtil; import ro.nextreports.designer.action.favorites.ManageFavoritesAction; import ro.nextreports.designer.action.favorites.OpenFavoriteAction; import ro.nextreports.designer.action.help.AboutAction; import ro.nextreports.designer.action.help.CheckForUpdateAction; import ro.nextreports.designer.action.help.HelpManualAction; import ro.nextreports.designer.action.help.HelpMovieAction; import ro.nextreports.designer.action.help.HelpStartupAction; import ro.nextreports.designer.action.query.ImportQueryAction; import ro.nextreports.designer.action.query.NewQueryAction; import ro.nextreports.designer.action.query.OpenQueryAction; import ro.nextreports.designer.action.query.OpenQueryPerspectiveAction; import ro.nextreports.designer.action.report.ImportReportAction; import ro.nextreports.designer.action.report.NewReportAction; import ro.nextreports.designer.action.report.NewReportFromQueryAction; import ro.nextreports.designer.action.report.OpenReportAction; import ro.nextreports.designer.action.report.ViewReportSqlAction; import ro.nextreports.designer.action.report.WizardAction; import ro.nextreports.designer.action.tools.BackupAction; import ro.nextreports.designer.action.tools.ImportAction; import ro.nextreports.designer.action.tools.Language; import ro.nextreports.designer.action.tools.LanguageAction; import ro.nextreports.designer.action.tools.RestoreAction; import ro.nextreports.designer.action.tools.RestoreDockingAction; import ro.nextreports.designer.action.tools.SettingsAction; import ro.nextreports.designer.datasource.DefaultDataSourceManager; import ro.nextreports.designer.i18n.action.ManageI18NAction; import ro.nextreports.designer.template.report.action.ApplyTemplateAction; import ro.nextreports.designer.template.report.action.CreateTemplateAction; import ro.nextreports.designer.template.report.action.ExtractTemplateAction; import ro.nextreports.designer.template.report.action.ModifyTemplateAction; import ro.nextreports.designer.util.I18NSupport; import ro.nextreports.designer.util.ShortcutsUtil; import ro.nextreports.engine.exporter.ResultExporter; import com.jgoodies.looks.HeaderStyle; import com.jgoodies.looks.Options; import com.thoughtworks.xstream.XStream; /** * @author Decebal Suiu */ public class MainMenuBar extends JMenuBar { private static final long serialVersionUID = 1L; private AddDataSourceAction addDataSourceAction = new AddDataSourceAction(false); private ExportDataSourceAction exportDataSourceAction = new ExportDataSourceAction(false); private ImportDataSourceAction importDataSourceAction = new ImportDataSourceAction(false); private WizardAction wizardAction = new WizardAction(Globals.getMainFrame().getQueryBuilderPanel().getTree()); private NewQueryAction newQueryAction = new NewQueryAction(false); private OpenQueryAction openQueryAction = new OpenQueryAction(false); private NewReportAction newReportAction = new NewReportAction(false); private NewReportFromQueryAction newReportFromQueryAction = new NewReportFromQueryAction(null, null, false, ResultExporter.DEFAULT_TYPE); private OpenReportAction openReportAction = new OpenReportAction(false); private OpenFromServerAction openFromServerAction = new OpenFromServerAction(); private PublishAction publishAction = new PublishAction(); private ExitAction exitAction = new ExitAction(); private BackupAction backupAction = new BackupAction(); private RestoreAction restoreAction = new RestoreAction(); private ImportAction importAction = new ImportAction(); private SettingsAction settingsAction = new SettingsAction(); private ViewReportSqlAction viewReportSqlAction = new ViewReportSqlAction(); private ImportReportAction importReportAction = new ImportReportAction(false); private ImportQueryAction importQueryAction = new ImportQueryAction(false); private ApplyTemplateAction applyTemplateAction = new ApplyTemplateAction(true); private ExtractTemplateAction extractTemplateAction = new ExtractTemplateAction(); private OpenLayoutPerspectiveAction openLayoutPersAction = new OpenLayoutPerspectiveAction(); private ManageI18NAction manageI18nAction = new ManageI18NAction(); private NewChartAction newChartAction = new NewChartAction(false); private OpenChartAction openChartAction = new OpenChartAction(false); private NewChartFromQueryAction newChartFromQueryAction = new NewChartFromQueryAction(null, false); private ImportChartAction importChartAction = new ImportChartAction(false); private SaveAction saveAction = new SaveAction(); private SaveAsAction saveAsAction = new SaveAsAction(); private BackToParentAction backAction = new BackToParentAction(); private JMenu menuFavorites = new JMenu(I18NSupport.getString("menu_favorites")); public MainMenuBar() { putClientProperty(Options.HEADER_STYLE_KEY, HeaderStyle.BOTH); add(createFileMenu()); add(createViewsMenu()); add(createToolsMenu()); add(createHelpMenu()); actionUpdate(Globals.getConnection() != null); Globals.setMainMenuBar(this); } public void newChartActionUpdate() { publishAction.setEnabled(true); } public void newReportActionUpdate() { applyTemplateAction.setEnabled(true); extractTemplateAction.setEnabled(true); publishAction.setEnabled(true); } public void newQueryActionUpdate() { applyTemplateAction.setEnabled(false); extractTemplateAction.setEnabled(false); publishAction.setEnabled(false); } public void actionUpdate(boolean connected) { openQueryAction.setEnabled(connected); importQueryAction.setEnabled(connected); newReportAction.setEnabled(connected); newReportFromQueryAction.setEnabled(connected); openReportAction.setEnabled(connected); importReportAction.setEnabled(connected); openFromServerAction.setEnabled(connected); newChartAction.setEnabled(connected); openChartAction.setEnabled(connected); newChartFromQueryAction.setEnabled(connected); importChartAction.setEnabled(connected); saveAction.setEnabled(connected); saveAsAction.setEnabled(connected); } public void enableLayoutPerspective(boolean enable) { openLayoutPersAction.setEnabled(enable); manageI18nAction.setEnabled(enable); } private JMenu createFileMenu() { JMenu mnu = new JMenu(I18NSupport.getString("menu.file")); mnu.setMnemonic(ShortcutsUtil.getMnemonic("menu.file.mnemonic", new Integer('F'))); JMenu mnu1 = new JMenu(I18NSupport.getString("menu_new")); mnu1.add(addDataSourceAction); mnu1.add(newQueryAction); mnu1.add(newReportAction); mnu1.add(newReportFromQueryAction); mnu1.add(newChartAction); mnu1.add(newChartFromQueryAction); mnu.add(mnu1); JMenu mnu2 = new JMenu(I18NSupport.getString("menu_open")); mnu2.add(openQueryAction); mnu2.add(openReportAction); mnu2.add(openChartAction); mnu2.addSeparator(); backAction.setEnabled(false); mnu2.add(backAction); mnu.add(mnu2); JMenu mnu3 = new JMenu(I18NSupport.getString("menu_import")); if (!DefaultDataSourceManager.memoryDataSources()) { mnu3.add(importDataSourceAction); } mnu3.add(importQueryAction); mnu3.add(importReportAction); mnu3.add(importChartAction); mnu.add(mnu3); JMenu mnu4 = new JMenu(I18NSupport.getString("menu_export")); if (!DefaultDataSourceManager.memoryDataSources()) { mnu4.add(exportDataSourceAction); mnu.add(mnu4); } mnu.addSeparator(); menuFavorites = new JMenu(I18NSupport.getString("menu_favorites")); recreateMenuFavorites(); mnu.add(menuFavorites); mnu.addSeparator(); mnu.add(saveAction); mnu.add(saveAsAction); mnu.addSeparator(); mnu.add(exitAction); newQueryActionUpdate(); return mnu; } public void recreateMenuFavorites() { menuFavorites.removeAll(); XStream xstream = FavoritesUtil.createXStream(); List<FavoriteEntry> favorites = FavoritesUtil.loadFavorites(xstream); for (FavoriteEntry fav : favorites) { menuFavorites.add(new OpenFavoriteAction(fav)); } menuFavorites.addSeparator(); menuFavorites.add(new ManageFavoritesAction()); } private JMenu createViewsMenu() { JMenu perspectiveMenu = new JMenu(I18NSupport.getString("menu.perpective")); perspectiveMenu.setMnemonic(ShortcutsUtil.getMnemonic("menu.perspective.mnemonic", new Integer('P'))); JMenuItem item = new JMenuItem(new OpenQueryPerspectiveAction()); perspectiveMenu.add(item); item = new JMenuItem(openLayoutPersAction); enableLayoutPerspective(false); perspectiveMenu.add(item); return perspectiveMenu; } private JMenu createHelpMenu() { JMenu mnu = new JMenu(I18NSupport.getString("menu.help")); mnu.setMnemonic(ShortcutsUtil.getMnemonic("menu.help.mnemonic", new Integer('H'))); mnu.add(new CheckForUpdateAction()); mnu.addSeparator(); mnu.add(new HelpMovieAction()); mnu.add(new HelpManualAction()); mnu.add(new HelpStartupAction()); mnu.addSeparator(); mnu.add(new AboutAction()); return mnu; } private JMenu createToolsMenu() { JMenu mnu = new JMenu(I18NSupport.getString("menu.tools")); mnu.setMnemonic(ShortcutsUtil.getMnemonic("menu.tools.mnemonic", new Integer('T'))); mnu.add(wizardAction); mnu.add(publishAction); mnu.add(openFromServerAction); mnu.add(viewReportSqlAction); mnu.addSeparator(); JMenu mnu2 = new JMenu(I18NSupport.getString("menu_templates")); mnu2.add(new CreateTemplateAction()); mnu2.add(new ModifyTemplateAction()); mnu2.add(applyTemplateAction); mnu2.add(extractTemplateAction); mnu.add(mnu2); mnu.addSeparator(); mnu.add(backupAction); mnu.add(restoreAction); mnu.add(importAction); mnu.add(settingsAction); mnu.addSeparator(); mnu.add(new RestoreDockingAction()); mnu.addSeparator(); mnu.add(manageI18nAction); mnu.add(createLanguageMenu()); return mnu; } private JMenu createLanguageMenu() { JMenu mnu = new JMenu(I18NSupport.getString("language")); mnu.setMnemonic(ShortcutsUtil.getMnemonic("menu.language.mnemonic", new Integer('L'))); for (Language lang : LanguageAction.getLanguages()) { mnu.add(new LanguageAction(lang.getLanguage())); } return mnu; } public void enableBackAction(boolean enable) { backAction.setEnabled(enable); } }
add survey action to Help menu
src/ro/nextreports/designer/MainMenuBar.java
add survey action to Help menu
Java
apache-2.0
225f1d1ecf7e5d33035bbc546abd77c5696a22a3
0
ejeinc/Meganekko,ejeinc/Meganekko,ejeinc/Meganekko,ejeinc/Meganekko,ejeinc/Meganekko
package org.meganekkovr; import android.graphics.drawable.Drawable; import android.support.annotation.Nullable; import android.support.v4.util.ArrayMap; import android.view.View; import org.joml.Matrix4f; import org.joml.Quaternionf; import org.joml.Vector3f; import org.meganekkovr.animation.EntityAnimator; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; /** * Entity is a basic class in Meganekko. It is something on VR scene. * Entity has transform information such as {@link #setPosition(float, float, float) position}, * {@link #setScale(float, float, float) scale}, and {@link #setRotation(Quaternionf) rotation}. * It can have child Entities and {@link Component}s. * Entity which will be rendered has to have {@link GeometryComponent} and {@link SurfaceRendererComponent}. */ public class Entity { private final NativePointer nativePointer; private final Map<Class<? extends Component>, Component> components = new ArrayMap<>(); private final List<Entity> children = new CopyOnWriteArrayList<>(); private final Vector3f position = new Vector3f(); private final Vector3f scale = new Vector3f(1, 1, 1); private final Quaternionf rotation = new Quaternionf(); private final Matrix4f localMatrix = new Matrix4f(); private final Matrix4f worldModelMatrix = new Matrix4f(); private final float[] matrixValues = new float[16]; private MeganekkoApp app; private Entity parent; private boolean localMatrixUpdateRequired = true; private boolean worldMatrixUpdateRequired = true; private int id; private float opacity = 1.0f; private boolean updateOpacityRequired; private boolean visible = true; public Entity() { nativePointer = NativePointer.getInstance(newInstance()); } private static native void addSurfaceDef(long nativePtr, long surfacesPointer); private static native void setWorldModelMatrix(long nativePtr, float[] matrix); /** * Create Entity from {@link View}. New Entity has plane geometry. * * @param view View for surface. * @return new Entity */ public static Entity from(View view) { final Entity entity = new Entity(); entity.add(SurfaceRendererComponent.from(view)); entity.add(GeometryComponent.from(view)); return entity; } /** * Create Entity from {@link Drawable}. New Entity has plane geometry. * * @param drawable Drawable for surface. * @return new Entity */ public static Entity from(Drawable drawable) { final Entity entity = new Entity(); entity.add(SurfaceRendererComponent.from(drawable)); entity.add(GeometryComponent.from(drawable)); return entity; } /** * Override this to create own native instance. * Native class must be derived from {@code mgn::Entity}. * * @return Native pointer value return from C++ {@code new}. */ protected native long newInstance(); /** * This method is not valid until this is attached to {@link Scene}. * * @return MeganekkoApp. */ public MeganekkoApp getApp() { return app; } /** * For internal use only. * * @param app */ void setApp(MeganekkoApp app) { this.app = app; // Propagate to children for (Entity child : children) { child.setApp(app); } } public void setId(int id) { this.id = id; } public int getId() { return id; } /** * Set string id. * * @param id ID */ public void setId(String id) { setId(id.hashCode()); } /** * Find {@link Entity} from children. Typically, id is {@code R.id.xxx} value. * * @param id ID * @return Found Entity or {@code null} if it has no matched Entity with id. */ @Nullable public Entity findById(int id) { if (this.id == id) return this; for (Entity child : children) { Entity found = child.findById(id); if (found != null) return found; } return null; } /** * Find {@link Entity} from children. * * @param id ID * @return Found Entity or {@code null} if it has no matched Entity with id. */ public Entity findById(String id) { return findById(id.hashCode()); } /** * Called at every frame update. * * @param frame Frame information */ public void update(FrameInput frame) { // Notify to components for (Component component : components.values()) { component.update(frame); } // Notify to children for (Entity child : children) { child.update(frame); } // Update local model matrix if necessary. if (localMatrixUpdateRequired) { updateLocalMatrix(); invalidateWorldModelMatrix(); localMatrixUpdateRequired = false; } // Update world model matrix if necessary. if (worldMatrixUpdateRequired) { updateWorldModelMatrix(); worldMatrixUpdateRequired = false; // Update native side values worldModelMatrix.get(matrixValues); setWorldModelMatrix(nativePointer.get(), matrixValues); } // Update opacity if necessary. if (updateOpacityRequired) { updateOpacity(); updateOpacityRequired = false; } } /** * Update local matrix. */ public void updateLocalMatrix() { localMatrix.identity(); localMatrix.translate(position); localMatrix.rotate(rotation); localMatrix.scale(scale); } /** * Update world model matrix. */ public void updateWorldModelMatrix() { // parentMatrix * worldModelMatrix Entity parent = getParent(); if (parent != null) { Matrix4f parentMatrix = parent.getWorldModelMatrix(); parentMatrix.mul(localMatrix, worldModelMatrix); } else { // worldModelMatrix = localMatrix worldModelMatrix.set(localMatrix); } } /** * Get world model matrix. * * @return World model matrix. */ public Matrix4f getWorldModelMatrix() { return worldModelMatrix; } /** * Add {@link Component}. Note that only one Component can be added per class. * * @param component Component * @return {@code true} if Successfully added. Otherwise {@code false}. */ public boolean add(Component component) { final Class<? extends Component> componentClass = component.getClass(); if (!components.containsKey(componentClass)) { component.setEntity(this); component.onAttach(this); components.put(componentClass, component); return true; } return false; } /** * Remove {@link Component}. * * @param component Component. * @return {@code true} if Successfully removed. Otherwise {@code false}. */ public boolean remove(Component component) { return remove(component.getClass()); } /** * Remove {@link Component} with associated class. * * @param clazz Class of Component. * @param <T> Type * @return {@code true} if Successfully removed. Otherwise {@code false}. */ public <T extends Component> boolean remove(Class<T> clazz) { if (components.containsKey(clazz)) { Component component = components.get(clazz); component.onDetach(this); component.setEntity(null); components.remove(clazz); return true; } return false; } @SuppressWarnings("unchecked") public <T extends Component> T getComponent(Class<T> clazz) { return (T) components.get(clazz); } public boolean hasComponent(Class<? extends Component> clazz) { return components.containsKey(clazz); } /** * Add child {@link Entity}. * * @param child Child entity. * @return {@code true} if Successfully added. Otherwise {@code false}. */ public boolean add(Entity child) { final boolean added = children.add(child); if (added) { child.parent = this; child.setApp(app); } return added; } /** * Remove child {@link Entity}. * * @param child Child entity. * @return {@code true} if Successfully removed. Otherwise {@code false}. */ public boolean remove(Entity child) { final boolean removed = children.remove(child); if (removed) { child.parent = null; } return removed; } /** * Get children of Entity. Returned {@link List} can not be modified. * * @return Children of Entity. */ public List<Entity> getChildren() { return Collections.unmodifiableList(children); } /** * Get parent {@link Entity}. * * @return Parent entity. */ public Entity getParent() { return parent; } /** * For internal use only. * * @return native pointer value. */ public long getNativePointer() { return nativePointer.get(); } /** * For internal use only. * * @param surfacesPointer {@code &res.Surfaces} */ void collectSurfaceDefs(long surfacesPointer) { // Not visible if (!visible) return; addSurfaceDef(nativePointer.get(), surfacesPointer); for (Entity child : children) { child.collectSurfaceDefs(surfacesPointer); } } private void invalidateWorldModelMatrix() { worldMatrixUpdateRequired = true; // Propagate to children for (Entity child : children) { child.invalidateWorldModelMatrix(); } } /** * Set Entity's local position. * * @param x X component of position * @param y Y component of position * @param z Z component of position */ public void setPosition(float x, float y, float z) { this.position.set(x, y, z); localMatrixUpdateRequired = true; } /** * Set Entity's local position. * * @param x X component of position */ public void setX(float x) { this.position.x = x; localMatrixUpdateRequired = true; } /** * Set Entity's local position. * * @param y Y component of position */ public void setY(float y) { this.position.y = y; localMatrixUpdateRequired = true; } /** * Set Entity's local position. * * @param z Z component of position */ public void setZ(float z) { this.position.z = z; localMatrixUpdateRequired = true; } /** * Get Entity's local position. * * @return position */ public Vector3f getPosition() { return position; } /** * Set Entity's local position. * * @param position position */ public void setPosition(Vector3f position) { this.position.set(position); localMatrixUpdateRequired = true; } /** * Set Entity's local scale. * * @param x X component of scale * @param y Y component of scale * @param z Z component of scale */ public void setScale(float x, float y, float z) { this.scale.set(x, y, z); localMatrixUpdateRequired = true; } /** * Set Entity's local scale. * * @param x X component of scale */ public void setScaleX(float x) { this.scale.x = x; localMatrixUpdateRequired = true; } /** * Set Entity's local scale. * * @param y Y component of scale */ public void setScaleY(float y) { this.scale.y = y; localMatrixUpdateRequired = true; } /** * Set Entity's local scale. * * @param z Z component of scale */ public void setScaleZ(float z) { this.scale.z = z; localMatrixUpdateRequired = true; } /** * Get Entity's local scale. * * @return scale */ public Vector3f getScale() { return scale; } /** * Set Entity's local scale. * * @param scale scale */ public void setScale(Vector3f scale) { this.scale.set(scale); localMatrixUpdateRequired = true; } /** * Get Entity's local rotation. * * @return rotation */ public Quaternionf getRotation() { return rotation; } /** * Set rotation, as a quaternion. Sets the transform's current rotation in quaternion terms. * * @param rotation rotation */ public void setRotation(Quaternionf rotation) { this.rotation.set(rotation); localMatrixUpdateRequired = true; } /** * Get {@link View}. This works only for Entity which is created by {@link #from(View)} * or has {@link SurfaceRendererComponent} which is * created by {@link SurfaceRendererComponent#from(View)}. * * @return View */ public View view() { SurfaceRendererComponent surfaceRendererComponent = getComponent(SurfaceRendererComponent.class); if (surfaceRendererComponent == null) { return null; } SurfaceRendererComponent.CanvasRenderer canvasRenderer = surfaceRendererComponent.getCanvasRenderer(); if (canvasRenderer == null) { return null; } if (canvasRenderer instanceof SurfaceRendererComponent.ViewRenderer) { return ((SurfaceRendererComponent.ViewRenderer) canvasRenderer).getView(); } return null; } /** * Short hand for {@code new EntityAnimator(entity)}. * * @return new EntityAnimator */ public EntityAnimator animate() { return new EntityAnimator(this); } private void updateOpacity() { SurfaceRendererComponent surfaceRendererComponent = getComponent(SurfaceRendererComponent.class); if (surfaceRendererComponent != null) { surfaceRendererComponent.setOpacity(getRenderingOpacity()); } for (Entity child : children) { child.updateOpacity(); } } private float parentOpacity() { Entity parent = getParent(); return parent != null ? parent.getOpacity() : 1.0f; } /** * Get actual opacity used in rendering. * This value can be different with value returned from {@link #getOpacity()}. * * @return Rendering opacity */ public float getRenderingOpacity() { return opacity * parentOpacity(); } /** * Get opacity set with {@link #setOpacity(float)}. * Actual opacity used in rendering can get with {@link #getRenderingOpacity()}. * * @return opacity */ public float getOpacity() { return opacity; } /** * Set Entity's opacity. * * @param opacity Float in the range of 0.0 - 1.0 indicating how transparent the Entity is. */ public void setOpacity(float opacity) { // Prevent out of range if (opacity < 0) { opacity = 0; } else if (opacity > 1) { opacity = 1; } // Do nothing if previous value is same to new value if (this.opacity == opacity) return; this.opacity = opacity; updateOpacityRequired = true; } /** * Get visibility of this {@link Entity}. Note that this will return <b>its own visibility</b>. * * @return visibility */ public boolean isVisible() { return visible; } /** * Set visibility. If set to {@code false}, its children also become not be rendered. * Default value is {@code true}. * * @param visible visibility */ public void setVisible(boolean visible) { this.visible = visible; } /** * @return {@code true} if this entity and ancestors are all visible. Otherwise {@code false}. */ public boolean isShown() { if (!visible) return false; // Check parent visibility Entity parent = getParent(); if (parent == null) return true; return parent.isShown(); } }
library/src/main/java/org/meganekkovr/Entity.java
package org.meganekkovr; import android.graphics.drawable.Drawable; import android.support.annotation.Nullable; import android.support.v4.util.ArrayMap; import android.view.View; import org.joml.Matrix4f; import org.joml.Quaternionf; import org.joml.Vector3f; import org.meganekkovr.animation.EntityAnimator; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; /** * Entity is a basic class in Meganekko. It is something on VR scene. * Entity has transform information such as {@link #setPosition(float, float, float) position}, * {@link #setScale(float, float, float) scale}, and {@link #setRotation(Quaternionf) rotation}. * It can have child Entities and {@link Component}s. * Entity which will be rendered has to have {@link GeometryComponent} and {@link SurfaceRendererComponent}. */ public class Entity { private final NativePointer nativePointer; private final Map<Class<? extends Component>, Component> components = new ArrayMap<>(); private final List<Entity> children = new CopyOnWriteArrayList<>(); private final Vector3f position = new Vector3f(); private final Vector3f scale = new Vector3f(1, 1, 1); private final Quaternionf rotation = new Quaternionf(); private final Matrix4f localMatrix = new Matrix4f(); private final Matrix4f worldModelMatrix = new Matrix4f(); private final float[] matrixValues = new float[16]; private MeganekkoApp app; private Entity parent; private boolean localMatrixUpdateRequired = true; private boolean worldMatrixUpdateRequired = true; private int id; private float opacity = 1.0f; private boolean updateOpacityRequired; private boolean visible = true; public Entity() { nativePointer = NativePointer.getInstance(newInstance()); } private static native void addSurfaceDef(long nativePtr, long surfacesPointer); private static native void setWorldModelMatrix(long nativePtr, float[] matrix); /** * Create Entity from {@link View}. New Entity has plane geometry. * * @param view View for surface. * @return new Entity */ public static Entity from(View view) { final Entity entity = new Entity(); entity.add(SurfaceRendererComponent.from(view)); entity.add(GeometryComponent.from(view)); return entity; } /** * Create Entity from {@link Drawable}. New Entity has plane geometry. * * @param drawable Drawable for surface. * @return new Entity */ public static Entity from(Drawable drawable) { final Entity entity = new Entity(); entity.add(SurfaceRendererComponent.from(drawable)); entity.add(GeometryComponent.from(drawable)); return entity; } /** * Override this to create own native instance. * Native class must be derived from {@code mgn::Entity}. * * @return Native pointer value return from C++ {@code new}. */ protected native long newInstance(); /** * This method is not valid until this is attached to {@link Scene}. * * @return MeganekkoApp. */ public MeganekkoApp getApp() { return app; } /** * For internal use only. * * @param app */ void setApp(MeganekkoApp app) { this.app = app; // Propagate to children for (Entity child : children) { child.setApp(app); } } public void setId(int id) { this.id = id; } public int getId() { return id; } /** * Set string id. * * @param id ID */ public void setId(String id) { setId(id.hashCode()); } /** * Find {@link Entity} from children. Typically, id is {@code R.id.xxx} value. * * @param id ID * @return Found Entity or {@code null} if it has no matched Entity with id. */ @Nullable public Entity findById(int id) { if (this.id == id) return this; for (Entity child : children) { Entity found = child.findById(id); if (found != null) return found; } return null; } /** * Find {@link Entity} from children. * * @param id ID * @return Found Entity or {@code null} if it has no matched Entity with id. */ public Entity findById(String id) { return findById(id.hashCode()); } /** * Called at every frame update. * * @param frame Frame information */ public void update(FrameInput frame) { // Update local model matrix if necessary. if (localMatrixUpdateRequired) { updateLocalMatrix(); invalidateWorldModelMatrix(); localMatrixUpdateRequired = false; } // Update world model matrix if necessary. if (worldMatrixUpdateRequired) { updateWorldModelMatrix(); worldMatrixUpdateRequired = false; // Update native side values worldModelMatrix.get(matrixValues); setWorldModelMatrix(nativePointer.get(), matrixValues); } // Update opacity if necessary. if (updateOpacityRequired) { updateOpacity(); updateOpacityRequired = false; } // Notify to components for (Component component : components.values()) { component.update(frame); } // Notify to children for (Entity child : children) { child.update(frame); } } /** * Update local matrix. */ public void updateLocalMatrix() { localMatrix.identity(); localMatrix.translate(position); localMatrix.rotate(rotation); localMatrix.scale(scale); } /** * Update world model matrix. */ public void updateWorldModelMatrix() { // parentMatrix * worldModelMatrix Entity parent = getParent(); if (parent != null) { Matrix4f parentMatrix = parent.getWorldModelMatrix(); parentMatrix.mul(localMatrix, worldModelMatrix); } else { // worldModelMatrix = localMatrix worldModelMatrix.set(localMatrix); } } /** * Get world model matrix. * * @return World model matrix. */ public Matrix4f getWorldModelMatrix() { return worldModelMatrix; } /** * Add {@link Component}. Note that only one Component can be added per class. * * @param component Component * @return {@code true} if Successfully added. Otherwise {@code false}. */ public boolean add(Component component) { final Class<? extends Component> componentClass = component.getClass(); if (!components.containsKey(componentClass)) { component.setEntity(this); component.onAttach(this); components.put(componentClass, component); return true; } return false; } /** * Remove {@link Component}. * * @param component Component. * @return {@code true} if Successfully removed. Otherwise {@code false}. */ public boolean remove(Component component) { return remove(component.getClass()); } /** * Remove {@link Component} with associated class. * * @param clazz Class of Component. * @param <T> Type * @return {@code true} if Successfully removed. Otherwise {@code false}. */ public <T extends Component> boolean remove(Class<T> clazz) { if (components.containsKey(clazz)) { Component component = components.get(clazz); component.onDetach(this); component.setEntity(null); components.remove(clazz); return true; } return false; } @SuppressWarnings("unchecked") public <T extends Component> T getComponent(Class<T> clazz) { return (T) components.get(clazz); } public boolean hasComponent(Class<? extends Component> clazz) { return components.containsKey(clazz); } /** * Add child {@link Entity}. * * @param child Child entity. * @return {@code true} if Successfully added. Otherwise {@code false}. */ public boolean add(Entity child) { final boolean added = children.add(child); if (added) { child.parent = this; child.setApp(app); } return added; } /** * Remove child {@link Entity}. * * @param child Child entity. * @return {@code true} if Successfully removed. Otherwise {@code false}. */ public boolean remove(Entity child) { final boolean removed = children.remove(child); if (removed) { child.parent = null; } return removed; } /** * Get children of Entity. Returned {@link List} can not be modified. * * @return Children of Entity. */ public List<Entity> getChildren() { return Collections.unmodifiableList(children); } /** * Get parent {@link Entity}. * * @return Parent entity. */ public Entity getParent() { return parent; } /** * For internal use only. * * @return native pointer value. */ public long getNativePointer() { return nativePointer.get(); } /** * For internal use only. * * @param surfacesPointer {@code &res.Surfaces} */ void collectSurfaceDefs(long surfacesPointer) { // Not visible if (!visible) return; addSurfaceDef(nativePointer.get(), surfacesPointer); for (Entity child : children) { child.collectSurfaceDefs(surfacesPointer); } } private void invalidateWorldModelMatrix() { worldMatrixUpdateRequired = true; // Propagate to children for (Entity child : children) { child.invalidateWorldModelMatrix(); } } /** * Set Entity's local position. * * @param x X component of position * @param y Y component of position * @param z Z component of position */ public void setPosition(float x, float y, float z) { this.position.set(x, y, z); localMatrixUpdateRequired = true; } /** * Set Entity's local position. * * @param x X component of position */ public void setX(float x) { this.position.x = x; localMatrixUpdateRequired = true; } /** * Set Entity's local position. * * @param y Y component of position */ public void setY(float y) { this.position.y = y; localMatrixUpdateRequired = true; } /** * Set Entity's local position. * * @param z Z component of position */ public void setZ(float z) { this.position.z = z; localMatrixUpdateRequired = true; } /** * Get Entity's local position. * * @return position */ public Vector3f getPosition() { return position; } /** * Set Entity's local position. * * @param position position */ public void setPosition(Vector3f position) { this.position.set(position); localMatrixUpdateRequired = true; } /** * Set Entity's local scale. * * @param x X component of scale * @param y Y component of scale * @param z Z component of scale */ public void setScale(float x, float y, float z) { this.scale.set(x, y, z); localMatrixUpdateRequired = true; } /** * Set Entity's local scale. * * @param x X component of scale */ public void setScaleX(float x) { this.scale.x = x; localMatrixUpdateRequired = true; } /** * Set Entity's local scale. * * @param y Y component of scale */ public void setScaleY(float y) { this.scale.y = y; localMatrixUpdateRequired = true; } /** * Set Entity's local scale. * * @param z Z component of scale */ public void setScaleZ(float z) { this.scale.z = z; localMatrixUpdateRequired = true; } /** * Get Entity's local scale. * * @return scale */ public Vector3f getScale() { return scale; } /** * Set Entity's local scale. * * @param scale scale */ public void setScale(Vector3f scale) { this.scale.set(scale); localMatrixUpdateRequired = true; } /** * Get Entity's local rotation. * * @return rotation */ public Quaternionf getRotation() { return rotation; } /** * Set rotation, as a quaternion. Sets the transform's current rotation in quaternion terms. * * @param rotation rotation */ public void setRotation(Quaternionf rotation) { this.rotation.set(rotation); localMatrixUpdateRequired = true; } /** * Get {@link View}. This works only for Entity which is created by {@link #from(View)} * or has {@link SurfaceRendererComponent} which is * created by {@link SurfaceRendererComponent#from(View)}. * * @return View */ public View view() { SurfaceRendererComponent surfaceRendererComponent = getComponent(SurfaceRendererComponent.class); if (surfaceRendererComponent == null) { return null; } SurfaceRendererComponent.CanvasRenderer canvasRenderer = surfaceRendererComponent.getCanvasRenderer(); if (canvasRenderer == null) { return null; } if (canvasRenderer instanceof SurfaceRendererComponent.ViewRenderer) { return ((SurfaceRendererComponent.ViewRenderer) canvasRenderer).getView(); } return null; } /** * Short hand for {@code new EntityAnimator(entity)}. * * @return new EntityAnimator */ public EntityAnimator animate() { return new EntityAnimator(this); } private void updateOpacity() { SurfaceRendererComponent surfaceRendererComponent = getComponent(SurfaceRendererComponent.class); if (surfaceRendererComponent != null) { surfaceRendererComponent.setOpacity(getRenderingOpacity()); } for (Entity child : children) { child.updateOpacity(); } } private float parentOpacity() { Entity parent = getParent(); return parent != null ? parent.getOpacity() : 1.0f; } /** * Get actual opacity used in rendering. * This value can be different with value returned from {@link #getOpacity()}. * * @return Rendering opacity */ public float getRenderingOpacity() { return opacity * parentOpacity(); } /** * Get opacity set with {@link #setOpacity(float)}. * Actual opacity used in rendering can get with {@link #getRenderingOpacity()}. * * @return opacity */ public float getOpacity() { return opacity; } /** * Set Entity's opacity. * * @param opacity Float in the range of 0.0 - 1.0 indicating how transparent the Entity is. */ public void setOpacity(float opacity) { // Prevent out of range if (opacity < 0) { opacity = 0; } else if (opacity > 1) { opacity = 1; } // Do nothing if previous value is same to new value if (this.opacity == opacity) return; this.opacity = opacity; updateOpacityRequired = true; } /** * Get visibility of this {@link Entity}. Note that this will return <b>its own visibility</b>. * * @return visibility */ public boolean isVisible() { return visible; } /** * Set visibility. If set to {@code false}, its children also become not be rendered. * Default value is {@code true}. * * @param visible visibility */ public void setVisible(boolean visible) { this.visible = visible; } /** * @return {@code true} if this entity and ancestors are all visible. Otherwise {@code false}. */ public boolean isShown() { if (!visible) return false; // Check parent visibility Entity parent = getParent(); if (parent == null) return true; return parent.isShown(); } }
Change update() priority.
library/src/main/java/org/meganekkovr/Entity.java
Change update() priority.
Java
apache-2.0
b850dbe41ebc3d065fcb10d12c4194e8fe774b2f
0
bcdev/jpy,bcdev/jpy,bcdev/jpy,bcdev/jpy,bcdev/jpy
/* * Copyright 2015 Brockmann Consult GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file was modified by Illumon. * */ package org.jpy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.util.List; import java.io.FileNotFoundException; import java.util.Objects; import static org.jpy.PyLib.assertPythonRuns; /** * Represents a Python object (of Python/C API type {@code PyObject*}) in the Python interpreter. * * @author Norman Fomferra * @since 0.7 */ public class PyObject { /** * The value of the Python/C API {@code PyObject*} which this class represents. */ private final long pointer; PyObject(long pointer) { if (pointer == 0) { throw new IllegalArgumentException("pointer == 0"); } PyLib.incRef(pointer); this.pointer = pointer; } /** * Executes Python source code. * * @param code The Python source code. * @param mode The execution mode. * @return The result of executing the code as a Python object. */ public static PyObject executeCode(String code, PyInputMode mode) { return executeCode(code, mode, null, null); } /** * Executes Python source script. * * @param script The Python source script. * @param mode The execution mode. * @return The result of executing the script as a Python object. */ public static PyObject executeScript(String script, PyInputMode mode) throws FileNotFoundException { return executeScript(script, mode, null, null); } /** * Executes Python source code in the context specified by the {@code globals} and {@code locals} maps. * <p> * If a Java value in the {@code globals} and {@code locals} maps cannot be directly converted into a Python object, a Java wrapper will be created instead. * If a Java value is a wrapped Python object of type {@link PyObject}, it will be unwrapped. * * @param code The Python source code. * @param mode The execution mode. * @param globals The global variables to be set, or {@code null}. * @param locals The locals variables to be set, or {@code null}. * @return The result of executing the code as a Python object. */ public static PyObject executeCode(String code, PyInputMode mode, Object globals, Object locals) { Objects.requireNonNull(code, "code must not be null"); Objects.requireNonNull(mode, "mode must not be null"); return new PyObject(PyLib.executeCode(code, mode.value(), globals, locals)); } /** * Executes Python source script in the context specified by the {@code globals} and {@code locals} maps. * <p> * If a Java value in the {@code globals} and {@code locals} maps cannot be directly converted into a Python object, a Java wrapper will be created instead. * If a Java value is a wrapped Python object of type {@link PyObject}, it will be unwrapped. * * @param script The Python source script. * @param mode The execution mode. * @param globals The global variables to be set, or {@code null}. * @param locals The locals variables to be set, or {@code null}. * @return The result of executing the script as a Python object. * @throws FileNotFoundException if the script file is not found */ public static PyObject executeScript(String script, PyInputMode mode, Object globals, Object locals) throws FileNotFoundException { Objects.requireNonNull(script, "script must not be null"); Objects.requireNonNull(mode, "mode must not be null"); return new PyObject(PyLib.executeScript(script, mode.value(), globals, locals)); } /** * Decrements the reference count of the Python object which this class represents. * * @throws Throwable If any error occurs. */ @Override protected void finalize() throws Throwable { super.finalize(); // Don't remove this check. 'pointer == 0' really occurred, don't ask me how! if (pointer == 0) { throw new IllegalStateException("pointer == 0"); } PyLib.decRef(getPointer()); } /** * @return A unique pointer to the wrapped Python object. */ public final long getPointer() { return pointer; } /** * @return This Python object as a Java {@code int} value. */ public int getIntValue() { assertPythonRuns(); return PyLib.getIntValue(getPointer()); } /** * @return This Python object as a Java {@code boolean} value. */ public boolean getBooleanValue() { assertPythonRuns(); return PyLib.getBooleanValue(getPointer()); } /** * @return This Python object as a Java {@code double} value. */ public double getDoubleValue() { assertPythonRuns(); return PyLib.getDoubleValue(getPointer()); } /** * @return This Python object as a Java {@code String} value. */ public String getStringValue() { assertPythonRuns(); return PyLib.getStringValue(getPointer()); } /** * Gets this Python object as Java {@code Object} value. * <p> * If this Python object cannot be converted into a Java object, a Java wrapper of type {@link PyObject} will be returned. * If this Python object is a wrapped Java object, it will be unwrapped. * * @return This Python object as a Java {@code Object} value. */ public Object getObjectValue() { assertPythonRuns(); return PyLib.getObjectValue(getPointer()); } /** * Gets the Python type object for this wrapped object. * * @return This Python object's type as a {@code PyObject} wrapped value. */ public PyObject getType() { assertPythonRuns(); return new PyObject(PyLib.getType(getPointer())); } public boolean isDict() { assertPythonRuns(); return PyLib.pyDictCheck(getPointer()); } public boolean isList() { assertPythonRuns(); return PyLib.pyListCheck(getPointer()); } public boolean isBoolean() { assertPythonRuns(); return PyLib.pyBoolCheck(getPointer()); } public boolean isLong() { assertPythonRuns(); return PyLib.pyLongCheck(getPointer()); } public boolean isInt() { assertPythonRuns(); return PyLib.pyIntCheck(getPointer()); } public boolean isNone() { assertPythonRuns(); return PyLib.pyNoneCheck(getPointer()); } public boolean isFloat() { assertPythonRuns(); return PyLib.pyFloatCheck(getPointer()); } public boolean isCallable() { assertPythonRuns(); return PyLib.pyCallableCheck(getPointer()); } public boolean isString() { assertPythonRuns(); return PyLib.pyStringCheck(getPointer()); } public boolean isConvertible() { assertPythonRuns(); return PyLib.isConvertible(getPointer()); } public List<PyObject> asList() { if (!isList()) { throw new ClassCastException("Can not convert non-list type to a list!"); } return new PyListWrapper(this); } public PyDictWrapper asDict() { if (!isDict()) { throw new ClassCastException("Can not convert non-list type to a dictionary!"); } return new PyDictWrapper(this); } /** * Gets this Python object as Java {@code Object[]} value of the given item type. * Appropriate type conversions from Python to Java will be performed as needed. * <p> * If a Python item value cannot be converted into a Java item object, a Java wrapper of type {@link PyObject} will be returned. * If a Python item value is a wrapped Java object, it will be unwrapped. * If this Python object value is a wrapped Java array object of given type, it will be unwrapped. * * @param itemType The expected item type class. * @param <T> The expected item type name. * @return This Python object as a Java {@code Object[]} value. */ public <T> T[] getObjectArrayValue(Class<? extends T> itemType) { assertPythonRuns(); Objects.requireNonNull(itemType, "itemType must not be null"); return PyLib.getObjectArrayValue(getPointer(), itemType); } /** * Gets the Python value of a Python attribute. * <p> * If the Python value cannot be converted into a Java object, a Java wrapper of type {@link PyObject} will be returned. * If the Python value is a wrapped Java object, it will be unwrapped. * * @param name A name of the Python attribute. * @return A wrapper for the returned Python attribute value. */ public PyObject getAttribute(String name) { assertPythonRuns(); Objects.requireNonNull(name, "name must not be null"); long pointer = PyLib.getAttributeObject(getPointer(), name); return pointer != 0 ? new PyObject(pointer) : null; } /** * Gets the value of a Python attribute as Java object of a given type. * Appropriate type conversions from Python to Java will be performed using the given value type. * <p> * If the Python value cannot be converted into a Java object, a Java wrapper of type {@link PyObject} will be returned. * If the Python value is a wrapped Java object, it will be unwrapped. * * @param name A name of the Python attribute. * @param valueType The type of the value or {@code null}, if unknown. * @param <T> The expected value type name. * @return The Python attribute value as Java object. */ public <T> T getAttribute(String name, Class<? extends T> valueType) { assertPythonRuns(); Objects.requireNonNull(name, "name must not be null"); return PyLib.getAttributeValue(getPointer(), name, valueType); } /** * Sets the value of a Python attribute from the given Java object. * <p> * If the Java {@code value} cannot be directly converted into a Python object, a Java wrapper will be created instead. * If the Java {@code value} is a wrapped Python object of type {@link PyObject}, it will be unwrapped. * * @param name A name of the Python attribute. * @param value The new attribute value as Java object. May be {@code null}. * @param <T> The value type name. */ public <T> void setAttribute(String name, T value) { assertPythonRuns(); Objects.requireNonNull(name, "name must not be null"); PyLib.setAttributeValue(getPointer(), name, value, value != null ? value.getClass() : null); } /** * Deletes the value of a Python attribute. * * @param name the name of the Python attribute. */ public void delAttribute(String name) { assertPythonRuns(); Objects.requireNonNull(name, "name must not be null"); PyLib.delAttribute(getPointer(), name); } /** * Checks for the existence of a Python attribute.. * * @param name the name of the Python attribute. * @return whether this attribute exists for this object */ public boolean hasAttribute(String name) { assertPythonRuns(); Objects.requireNonNull(name, "name must not be null"); return PyLib.hasAttribute(getPointer(), name); } /** * Sets the value of a Python attribute from the given Java object and Java type (if given). * Appropriate type conversions from Java to Python will be performed using the given value type. * <p> * If the Java {@code value} cannot be directly converted into a Python object, a Java wrapper will be created instead. * If the Java {@code value} is a wrapped Python object of type {@link PyObject}, it will be unwrapped. * * @param name A name of the Python attribute. * @param value The new attribute value as Java object. * @param valueType The value type used for the conversion. May be {@code null}. * @param <T> The value type name. */ public <T> void setAttribute(String name, T value, Class<? extends T> valueType) { assertPythonRuns(); Objects.requireNonNull(name, "name must not be null"); PyLib.setAttributeValue(getPointer(), name, value, valueType); } /** * Call the callable Python method with the given name and arguments. * <p> * If a Java value in {@code args} cannot be directly converted into a Python object, a Java wrapper will be created instead. * If the Java value in {@code args} is a wrapped Python object of type {@link PyObject}, it will be unwrapped. * * @param name A name of a Python attribute that evaluates to a callable object. * @param args The arguments for the method call. * @return A wrapper for the returned Python object. */ public PyObject callMethod(String name, Object... args) { assertPythonRuns(); Objects.requireNonNull(name, "name must not be null"); long pointer = PyLib.callAndReturnObject(getPointer(), true, name, args.length, args, null); return pointer != 0 ? new PyObject(pointer) : null; } /** * Call the callable Python object with the given name and arguments. * <p> * If a Java value in {@code args} cannot be directly converted into a Python object, a Java wrapper will be created instead. * If the Java value in {@code args} is a wrapped Python object of type {@link PyObject}, it will be unwrapped. * * @param name A name of a Python attribute that evaluates to a callable object, * @param args The arguments for the call. * @return A wrapper for the returned Python object. */ public PyObject call(String name, Object... args) { assertPythonRuns(); Objects.requireNonNull(name, "name must not be null"); long pointer = PyLib.callAndReturnObject(getPointer(), false, name, args.length, args, null); return pointer != 0 ? new PyObject(pointer) : null; } /** * Create a Java proxy instance of this Python object which contains compatible methods to the ones provided in the * interface given by the {@code type} parameter. * * @param type The interface class. * @param <T> The interface name. * @return A (proxy) instance implementing the given interface. */ public <T> T createProxy(Class<T> type) { assertPythonRuns(); //noinspection unchecked Objects.requireNonNull(type, "type must not be null"); return (T) createProxy(PyLib.CallableKind.METHOD, type); } /** * Create a Java proxy instance of this Python object (or module) which contains compatible methods * (or functions) to the ones provided in the interfaces given by all the {@code type} parameters. * * @param callableKind The kind of calls to be made. * @param types The interface types. * @return A instance implementing the all the given interfaces which serves as a proxy for the given Python object (or module). */ public Object createProxy(PyLib.CallableKind callableKind, Class<?>... types) { assertPythonRuns(); ClassLoader classLoader = types[0].getClassLoader(); InvocationHandler invocationHandler = new PyProxyHandler(this, callableKind); return Proxy.newProxyInstance(classLoader, types, invocationHandler); } /** * Gets the python string representation of this object. * * @return A string representation of the object. * @see #getPointer() */ @Override public final String toString() { return PyLib.str(pointer); } /** * Gets a the python repr of this object * * @return A string representation of the object. * @see #getPointer() */ public final String repr() { return PyLib.repr(pointer); } /** * Indicates whether some other object is "equal to" this one. * * @param o The other object. * @return {@code true} if the other object is an instance of {@link org.jpy.PyObject} and if their pointers are equal, {@code false} otherwise. * @see #getPointer() */ @Override public final boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof PyObject)) { return false; } PyObject pyObject = (PyObject) o; return pointer == pyObject.pointer; } /** * Computes a hash code from this object's pointer value. * * @return A hash code value for this object. * @see #getPointer() */ @Override public final int hashCode() { return (int) (pointer ^ (pointer >>> 32)); } }
src/main/java/org/jpy/PyObject.java
/* * Copyright 2015 Brockmann Consult GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file was modified by Illumon. * */ package org.jpy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.util.List; import java.io.FileNotFoundException; import java.util.Objects; import static org.jpy.PyLib.assertPythonRuns; /** * Represents a Python object (of Python/C API type {@code PyObject*}) in the Python interpreter. * * @author Norman Fomferra * @since 0.7 */ public class PyObject implements java.io.Serializable { /** * The value of the Python/C API {@code PyObject*} which this class represents. */ private final long pointer; PyObject(long pointer) { if (pointer == 0) { throw new IllegalArgumentException("pointer == 0"); } PyLib.incRef(pointer); this.pointer = pointer; } /** * Executes Python source code. * * @param code The Python source code. * @param mode The execution mode. * @return The result of executing the code as a Python object. */ public static PyObject executeCode(String code, PyInputMode mode) { return executeCode(code, mode, null, null); } /** * Executes Python source script. * * @param script The Python source script. * @param mode The execution mode. * @return The result of executing the script as a Python object. */ public static PyObject executeScript(String script, PyInputMode mode) throws FileNotFoundException { return executeScript(script, mode, null, null); } /** * Executes Python source code in the context specified by the {@code globals} and {@code locals} maps. * <p> * If a Java value in the {@code globals} and {@code locals} maps cannot be directly converted into a Python object, a Java wrapper will be created instead. * If a Java value is a wrapped Python object of type {@link PyObject}, it will be unwrapped. * * @param code The Python source code. * @param mode The execution mode. * @param globals The global variables to be set, or {@code null}. * @param locals The locals variables to be set, or {@code null}. * @return The result of executing the code as a Python object. */ public static PyObject executeCode(String code, PyInputMode mode, Object globals, Object locals) { Objects.requireNonNull(code, "code must not be null"); Objects.requireNonNull(mode, "mode must not be null"); return new PyObject(PyLib.executeCode(code, mode.value(), globals, locals)); } /** * Executes Python source script in the context specified by the {@code globals} and {@code locals} maps. * <p> * If a Java value in the {@code globals} and {@code locals} maps cannot be directly converted into a Python object, a Java wrapper will be created instead. * If a Java value is a wrapped Python object of type {@link PyObject}, it will be unwrapped. * * @param script The Python source script. * @param mode The execution mode. * @param globals The global variables to be set, or {@code null}. * @param locals The locals variables to be set, or {@code null}. * @return The result of executing the script as a Python object. * @throws FileNotFoundException if the script file is not found */ public static PyObject executeScript(String script, PyInputMode mode, Object globals, Object locals) throws FileNotFoundException { Objects.requireNonNull(script, "script must not be null"); Objects.requireNonNull(mode, "mode must not be null"); return new PyObject(PyLib.executeScript(script, mode.value(), globals, locals)); } /** * Decrements the reference count of the Python object which this class represents. * * @throws Throwable If any error occurs. */ @Override protected void finalize() throws Throwable { super.finalize(); // Don't remove this check. 'pointer == 0' really occurred, don't ask me how! if (pointer == 0) { throw new IllegalStateException("pointer == 0"); } PyLib.decRef(getPointer()); } /** * @return A unique pointer to the wrapped Python object. */ public final long getPointer() { return pointer; } /** * @return This Python object as a Java {@code int} value. */ public int getIntValue() { assertPythonRuns(); return PyLib.getIntValue(getPointer()); } /** * @return This Python object as a Java {@code boolean} value. */ public boolean getBooleanValue() { assertPythonRuns(); return PyLib.getBooleanValue(getPointer()); } /** * @return This Python object as a Java {@code double} value. */ public double getDoubleValue() { assertPythonRuns(); return PyLib.getDoubleValue(getPointer()); } /** * @return This Python object as a Java {@code String} value. */ public String getStringValue() { assertPythonRuns(); return PyLib.getStringValue(getPointer()); } /** * Gets this Python object as Java {@code Object} value. * <p> * If this Python object cannot be converted into a Java object, a Java wrapper of type {@link PyObject} will be returned. * If this Python object is a wrapped Java object, it will be unwrapped. * * @return This Python object as a Java {@code Object} value. */ public Object getObjectValue() { assertPythonRuns(); return PyLib.getObjectValue(getPointer()); } /** * Gets the Python type object for this wrapped object. * * @return This Python object's type as a {@code PyObject} wrapped value. */ public PyObject getType() { assertPythonRuns(); return new PyObject(PyLib.getType(getPointer())); } public boolean isDict() { assertPythonRuns(); return PyLib.pyDictCheck(getPointer()); } public boolean isList() { assertPythonRuns(); return PyLib.pyListCheck(getPointer()); } public boolean isBoolean() { assertPythonRuns(); return PyLib.pyBoolCheck(getPointer()); } public boolean isLong() { assertPythonRuns(); return PyLib.pyLongCheck(getPointer()); } public boolean isInt() { assertPythonRuns(); return PyLib.pyIntCheck(getPointer()); } public boolean isNone() { assertPythonRuns(); return PyLib.pyNoneCheck(getPointer()); } public boolean isFloat() { assertPythonRuns(); return PyLib.pyFloatCheck(getPointer()); } public boolean isCallable() { assertPythonRuns(); return PyLib.pyCallableCheck(getPointer()); } public boolean isString() { assertPythonRuns(); return PyLib.pyStringCheck(getPointer()); } public boolean isConvertible() { assertPythonRuns(); return PyLib.isConvertible(getPointer()); } public List<PyObject> asList() { if (!isList()) { throw new ClassCastException("Can not convert non-list type to a list!"); } return new PyListWrapper(this); } public PyDictWrapper asDict() { if (!isDict()) { throw new ClassCastException("Can not convert non-list type to a dictionary!"); } return new PyDictWrapper(this); } /** * Gets this Python object as Java {@code Object[]} value of the given item type. * Appropriate type conversions from Python to Java will be performed as needed. * <p> * If a Python item value cannot be converted into a Java item object, a Java wrapper of type {@link PyObject} will be returned. * If a Python item value is a wrapped Java object, it will be unwrapped. * If this Python object value is a wrapped Java array object of given type, it will be unwrapped. * * @param itemType The expected item type class. * @param <T> The expected item type name. * @return This Python object as a Java {@code Object[]} value. */ public <T> T[] getObjectArrayValue(Class<? extends T> itemType) { assertPythonRuns(); Objects.requireNonNull(itemType, "itemType must not be null"); return PyLib.getObjectArrayValue(getPointer(), itemType); } /** * Gets the Python value of a Python attribute. * <p> * If the Python value cannot be converted into a Java object, a Java wrapper of type {@link PyObject} will be returned. * If the Python value is a wrapped Java object, it will be unwrapped. * * @param name A name of the Python attribute. * @return A wrapper for the returned Python attribute value. */ public PyObject getAttribute(String name) { assertPythonRuns(); Objects.requireNonNull(name, "name must not be null"); long pointer = PyLib.getAttributeObject(getPointer(), name); return pointer != 0 ? new PyObject(pointer) : null; } /** * Gets the value of a Python attribute as Java object of a given type. * Appropriate type conversions from Python to Java will be performed using the given value type. * <p> * If the Python value cannot be converted into a Java object, a Java wrapper of type {@link PyObject} will be returned. * If the Python value is a wrapped Java object, it will be unwrapped. * * @param name A name of the Python attribute. * @param valueType The type of the value or {@code null}, if unknown. * @param <T> The expected value type name. * @return The Python attribute value as Java object. */ public <T> T getAttribute(String name, Class<? extends T> valueType) { assertPythonRuns(); Objects.requireNonNull(name, "name must not be null"); return PyLib.getAttributeValue(getPointer(), name, valueType); } /** * Sets the value of a Python attribute from the given Java object. * <p> * If the Java {@code value} cannot be directly converted into a Python object, a Java wrapper will be created instead. * If the Java {@code value} is a wrapped Python object of type {@link PyObject}, it will be unwrapped. * * @param name A name of the Python attribute. * @param value The new attribute value as Java object. May be {@code null}. * @param <T> The value type name. */ public <T> void setAttribute(String name, T value) { assertPythonRuns(); Objects.requireNonNull(name, "name must not be null"); PyLib.setAttributeValue(getPointer(), name, value, value != null ? value.getClass() : null); } /** * Deletes the value of a Python attribute. * * @param name the name of the Python attribute. */ public void delAttribute(String name) { assertPythonRuns(); Objects.requireNonNull(name, "name must not be null"); PyLib.delAttribute(getPointer(), name); } /** * Checks for the existence of a Python attribute.. * * @param name the name of the Python attribute. * @return whether this attribute exists for this object */ public boolean hasAttribute(String name) { assertPythonRuns(); Objects.requireNonNull(name, "name must not be null"); return PyLib.hasAttribute(getPointer(), name); } /** * Sets the value of a Python attribute from the given Java object and Java type (if given). * Appropriate type conversions from Java to Python will be performed using the given value type. * <p> * If the Java {@code value} cannot be directly converted into a Python object, a Java wrapper will be created instead. * If the Java {@code value} is a wrapped Python object of type {@link PyObject}, it will be unwrapped. * * @param name A name of the Python attribute. * @param value The new attribute value as Java object. * @param valueType The value type used for the conversion. May be {@code null}. * @param <T> The value type name. */ public <T> void setAttribute(String name, T value, Class<? extends T> valueType) { assertPythonRuns(); Objects.requireNonNull(name, "name must not be null"); PyLib.setAttributeValue(getPointer(), name, value, valueType); } /** * Call the callable Python method with the given name and arguments. * <p> * If a Java value in {@code args} cannot be directly converted into a Python object, a Java wrapper will be created instead. * If the Java value in {@code args} is a wrapped Python object of type {@link PyObject}, it will be unwrapped. * * @param name A name of a Python attribute that evaluates to a callable object. * @param args The arguments for the method call. * @return A wrapper for the returned Python object. */ public PyObject callMethod(String name, Object... args) { assertPythonRuns(); Objects.requireNonNull(name, "name must not be null"); long pointer = PyLib.callAndReturnObject(getPointer(), true, name, args.length, args, null); return pointer != 0 ? new PyObject(pointer) : null; } /** * Call the callable Python object with the given name and arguments. * <p> * If a Java value in {@code args} cannot be directly converted into a Python object, a Java wrapper will be created instead. * If the Java value in {@code args} is a wrapped Python object of type {@link PyObject}, it will be unwrapped. * * @param name A name of a Python attribute that evaluates to a callable object, * @param args The arguments for the call. * @return A wrapper for the returned Python object. */ public PyObject call(String name, Object... args) { assertPythonRuns(); Objects.requireNonNull(name, "name must not be null"); long pointer = PyLib.callAndReturnObject(getPointer(), false, name, args.length, args, null); return pointer != 0 ? new PyObject(pointer) : null; } /** * Create a Java proxy instance of this Python object which contains compatible methods to the ones provided in the * interface given by the {@code type} parameter. * * @param type The interface class. * @param <T> The interface name. * @return A (proxy) instance implementing the given interface. */ public <T> T createProxy(Class<T> type) { assertPythonRuns(); //noinspection unchecked Objects.requireNonNull(type, "type must not be null"); return (T) createProxy(PyLib.CallableKind.METHOD, type); } /** * Create a Java proxy instance of this Python object (or module) which contains compatible methods * (or functions) to the ones provided in the interfaces given by all the {@code type} parameters. * * @param callableKind The kind of calls to be made. * @param types The interface types. * @return A instance implementing the all the given interfaces which serves as a proxy for the given Python object (or module). */ public Object createProxy(PyLib.CallableKind callableKind, Class<?>... types) { assertPythonRuns(); ClassLoader classLoader = types[0].getClassLoader(); InvocationHandler invocationHandler = new PyProxyHandler(this, callableKind); return Proxy.newProxyInstance(classLoader, types, invocationHandler); } /** * Gets the python string representation of this object. * * @return A string representation of the object. * @see #getPointer() */ @Override public final String toString() { return PyLib.str(pointer); } /** * Gets a the python repr of this object * * @return A string representation of the object. * @see #getPointer() */ public final String repr() { return PyLib.repr(pointer); } /** * Indicates whether some other object is "equal to" this one. * * @param o The other object. * @return {@code true} if the other object is an instance of {@link org.jpy.PyObject} and if their pointers are equal, {@code false} otherwise. * @see #getPointer() */ @Override public final boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof PyObject)) { return false; } PyObject pyObject = (PyObject) o; return pointer == pyObject.pointer; } /** * Computes a hash code from this object's pointer value. * * @return A hash code value for this object. * @see #getPointer() */ @Override public final int hashCode() { return (int) (pointer ^ (pointer >>> 32)); } }
PyObject shall not be Serializable. This is a reverse of pull request #80.
src/main/java/org/jpy/PyObject.java
PyObject shall not be Serializable. This is a reverse of pull request #80.
Java
bsd-2-clause
eb74f6acd3bb2aa94f085228a15263b274ed1287
0
bogovicj/bigdataviewer-core,bigdataviewer/bigdataviewer-core,bigdataviewer/bigdataviewer-core,bogovicj/bigdataviewer-core
package viewer; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.IOException; import java.net.URL; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.BorderFactory; import javax.swing.InputMap; import javax.swing.JComponent; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.KeyStroke; public class HelpFrame { private static JFrame frame = null; /** * Instantiates and displays a JFrame that lists the help file for the SPIM viewer UI. */ public HelpFrame() { this( HelpFrame.class.getResource( "Help.html" ) ); } /** * Instantiates and displays a JFrame that lists the content of a html file * specified by its {@link URL}. */ public HelpFrame(URL helpFile) { if ( frame != null ) frame.toFront(); else { try { frame = new JFrame( "Help" ); final JEditorPane editorPane = new JEditorPane( helpFile ); editorPane.setEditable( false ); editorPane.setBorder( BorderFactory.createEmptyBorder( 10, 0, 10, 10 ) ); final JScrollPane editorScrollPane = new JScrollPane( editorPane ); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED ); editorScrollPane.setPreferredSize( new Dimension( 800, 800 ) ); final Container content = frame.getContentPane(); content.add( editorScrollPane, BorderLayout.CENTER ); frame.addWindowListener( new WindowAdapter() { @Override public void windowClosing( final WindowEvent e ) { frame = null; } } ); final ActionMap am = frame.getRootPane().getActionMap(); final InputMap im = frame.getRootPane().getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT ); final Object hideKey = new Object(); final Action hideAction = new AbstractAction() { private static final long serialVersionUID = 6288745091648466880L; @Override public void actionPerformed( final ActionEvent e ) { frame.dispose(); frame = null; } }; im.put( KeyStroke.getKeyStroke( KeyEvent.VK_ESCAPE, 0 ), hideKey ); am.put( hideKey, hideAction ); frame.pack(); frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE ); frame.setVisible( true ); } catch ( final IOException e ) { e.printStackTrace(); } } } }
src/main/java/viewer/HelpFrame.java
package viewer; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.IOException; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.BorderFactory; import javax.swing.InputMap; import javax.swing.JComponent; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.KeyStroke; public class HelpFrame { private static JFrame frame = null; public HelpFrame() { if ( frame != null ) frame.toFront(); else { try { frame = new JFrame( "Help" ); final JEditorPane editorPane = new JEditorPane( new HelpFrame().getClass().getResource( "Help.html" ) ); editorPane.setEditable( false ); editorPane.setBorder( BorderFactory.createEmptyBorder( 10, 0, 10, 10 ) ); final JScrollPane editorScrollPane = new JScrollPane( editorPane ); editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED ); editorScrollPane.setPreferredSize( new Dimension( 800, 800 ) ); final Container content = frame.getContentPane(); content.add( editorScrollPane, BorderLayout.CENTER ); frame.addWindowListener( new WindowAdapter() { @Override public void windowClosing( final WindowEvent e ) { frame = null; } } ); final ActionMap am = frame.getRootPane().getActionMap(); final InputMap im = frame.getRootPane().getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT ); final Object hideKey = new Object(); final Action hideAction = new AbstractAction() { private static final long serialVersionUID = 6288745091648466880L; @Override public void actionPerformed( final ActionEvent e ) { frame.dispose(); frame = null; } }; im.put( KeyStroke.getKeyStroke( KeyEvent.VK_ESCAPE, 0 ), hideKey ); am.put( hideKey, hideAction ); frame.pack(); frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE ); frame.setVisible( true ); } catch ( final IOException e ) { e.printStackTrace(); } } } }
Make the HelpFrame re-usable for other help texts Signed-off-by: Jean-Yves Tinevez <[email protected]>
src/main/java/viewer/HelpFrame.java
Make the HelpFrame re-usable for other help texts
Java
bsd-3-clause
252b7aa831100cab5cd3af1b7e98a8077a945356
0
muloem/xins,muloem/xins,muloem/xins
/* * $Id$ */ package org.xins.util; import org.xins.util.text.FastStringBuffer; /** * Utility class for converting numbers to unsigned hex strings and vice * versa. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>) * * @since XINS 0.73 */ public class HexConverter extends Object { //------------------------------------------------------------------------- // Class fields //------------------------------------------------------------------------- /** * Array that contains the hexadecimal digits, from 0 to 9 and from a to z. */ private static final char[] DIGITS = { '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , 'a' , 'b' , 'c' , 'd' , 'e' , 'f' }; /** * The number of characters written when converting a <code>long</code> to * an unsigned hex string. */ private static final int LENGTH = 16; /** * The radix when converting (16). */ private static final long RADIX = 16L; /** * The radix mask. Equal to {@link #RADIX}<code> - 1</code>. */ private static final long MASK = RADIX - 1L; /** * Array of 16 zero characters. */ private static final char[] SIXTEEN_ZEROES = new char[] { '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0' }; //------------------------------------------------------------------------- // Class functions //------------------------------------------------------------------------- /** * Convert the specified <code>long</code> to an unsigned number text * string. The returned string will always consist of 16 characters, zeroes * will be prepended as necessary. * * @param n * the number to be converted to a text string. * * @return * the text string, cannot be <code>null</code>, the length is always 16 * (i.e. <code><em>return</em>.</code>{@link String#length() length()}<code> == 16</code>). */ public static String toHexString(long n) { char[] chars = new char[LENGTH]; int pos = LENGTH - 1; // Convert the long to a hex string until the remainder is 0 for (; n != 0; n >>>= 4) { chars[pos--] = DIGITS[(int) (n & MASK)]; } // Fill the rest with '0' characters for (; pos >= 0; pos--) { chars[pos] = '0'; } return new String(chars, 0, LENGTH); } /** * Converts the specified <code>long</code> to unsigned number and appends * it to the specified string buffer. Exactly 16 characters will be * appended, all between <code>'0'</code> to <code>'9'</code> or between * <code>'a'</code> and <code>'f'</code>. * * @param buffer * the string buffer to append to, cannot be <code>null</code>. * * @param n * the number to be converted to a text string. * * @throws IllegalArgumentException * if <code>buffer == null</code>. */ public static void toHexString(FastStringBuffer buffer, long n) { // Check preconditions if (buffer == null) { throw new IllegalArgumentException("buffer == null"); } // Append 16 zero characters to the buffer buffer.append(SIXTEEN_ZEROES); int pos = LENGTH - 1; // Convert the long to a hex string until the remainder is 0 for (; n != 0; n >>>= 4) { buffer.setChar(pos--, DIGITS[(int) (n & MASK)]); } } /** * Parses the a 16-digit unsigned hex number in the specified string. * * @param s * the hexadecimal string, cannot be <code>null</code>. * * @param index * the starting index in the string, must be &gt;= 0. * * @return * the value of the parsed unsigned hexadecimal string. * * @throws IllegalArgumentException * if <code>s == null || index &lt; 0 || <code>s.</code>{@link String#length() length()}<code> &lt; index + 16</code>). * * @throws NumberFormatException * if any of the characters in the specified range of the string is not * a hex digit (<code>'0'</code> to <code>'9'</code> and * <code>'a'</code> to <code>'f'</code>). */ public static long parseHexString(String s, int index) throws IllegalArgumentException, NumberFormatException { // Check preconditions if (s == null) { throw new IllegalArgumentException("s == null"); } else if (s.length() < index + 16) { throw new IllegalArgumentException("s.length() (" + s.length() + ") < index (" + index + ") + 16 (" + (index + 16) + ')'); } long n = 0L; final int CHAR_ZERO = (int) '0'; final int CHAR_NINE = (int) '9'; final int CHAR_A = (int) 'a'; final int CHAR_F = (int) 'f'; final int CHAR_A_FACTOR = CHAR_A - 10; // Loop through all characters int last = index + 16; for (int i = index; i < last; i++) { int c = (int) s.charAt(i); n <<= 4; if (c >= CHAR_ZERO && c <= CHAR_NINE) { n |= (c - CHAR_ZERO); } else if (c >= CHAR_A && c <= CHAR_F) { n |= (c - CHAR_A_FACTOR); } else { throw new NumberFormatException("s.charAt(" + i + ") == '" + s.charAt(i) + '\''); } } return n; } /** * Parses the specified 16-digit unsigned hex string. * * @param s * the hexadecimal string, cannot be <code>null</code> and must have * size 16 * (i.e. <code>s.</code>{@link String#length() length()}<code> == 16</code>). * * @return * the value of the parsed unsigned hexadecimal string. * * @throws IllegalArgumentException * if <code>s == null || s.</code>{@link String#length() length()}<code> != 16</code>. * * @throws NumberFormatException * if any of the characters in the specified string is not a hex digit * (<code>'0'</code> to <code>'9'</code> and <code>'a'</code> to * <code>'f'</code>). */ public static long parseHexString(String s) throws IllegalArgumentException, NumberFormatException { // Check preconditions if (s == null) { throw new IllegalArgumentException("s == null"); } else if (s.length() != 16) { throw new IllegalArgumentException("s.length() != 16"); } return parseHexString(s, 0); } //------------------------------------------------------------------------- // Constructors //------------------------------------------------------------------------- /** * Creates a new <code>HexConverter</code> object. */ private HexConverter() { // empty } //------------------------------------------------------------------------- // Fields //------------------------------------------------------------------------- //------------------------------------------------------------------------- // Methods //------------------------------------------------------------------------- }
src/java-common/org/xins/util/text/HexConverter.java
/* * $Id$ */ package org.xins.util; import org.xins.util.text.FastStringBuffer; /** * Utility class for converting numbers to unsigned hex strings and vice * versa. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>) * * @since XINS 0.73 */ public class HexConverter extends Object { //------------------------------------------------------------------------- // Class fields //------------------------------------------------------------------------- /** * Array that contains the hexadecimal digits, from 0 to 9 and from a to z. */ private static final char[] DIGITS = { '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , 'a' , 'b' , 'c' , 'd' , 'e' , 'f' }; /** * The number of characters written when converting a <code>long</code> to * an unsigned hex string. */ private static final int LENGTH = 16; /** * The radix when converting (16). */ private static final long RADIX = 16L; /** * The radix mask. Equal to {@link #RADIX}<code> - 1</code>. */ private static final long MASK = RADIX - 1L; /** * Array of 16 zero characters. */ private static final char[] SIXTEEN_ZEROES = new char[] { '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0' }; //------------------------------------------------------------------------- // Class functions //------------------------------------------------------------------------- /** * Convert the specified <code>long</code> to an unsigned number text * string. The returned string will always consist of 16 characters, zeroes * will be prepended as necessary. * * @param n * the number to be converted to a text string. * * @return * the text string, cannot be <code>null</code>, the length is always 16 * (i.e. <code><em>return</em>.</code>{@link String#length() length()}<code> == 16</code>). */ public static String toHexString(long n) { char[] chars = new char[LENGTH]; int pos = LENGTH - 1; // Convert the long to a hex string until the remainder is 0 for (; n != 0; n >>>= 4) { chars[pos--] = DIGITS[(int) (n & MASK)]; } // Fill the rest with '0' characters for (; pos >= 0; pos--) { chars[pos] = '0'; } return new String(chars, 0, LENGTH); } /** * Converts the specified <code>long</code> to unsigned number and appends * it to the specified string buffer. Exactly 16 characters will be * appended, all between <code>'0'</code> to <code>'9'</code> or between * <code>'a'</code> and <code>'f'</code>. * * @param buffer * the string buffer to append to, cannot be <code>null</code>. * * @param n * the number to be converted to a text string. * * @throws IllegalArgumentException * if <code>buffer == null</code>. */ public static void toHexString(FastStringBuffer buffer, long n) { // Check preconditions if (buffer == null) { throw new IllegalArgumentException("buffer == null"); } // Append 16 zero characters to the buffer buffer.append(ZEROES); int pos = LENGTH - 1; // Convert the long to a hex string until the remainder is 0 for (; n != 0; n >>>= 4) { buffer.setChar(pos--, DIGITS[(int) (n & MASK)]); } } /** * Parses the a 16-digit unsigned hex number in the specified string. * * @param s * the hexadecimal string, cannot be <code>null</code>. * * @param index * the starting index in the string, must be &gt;= 0. * * @return * the value of the parsed unsigned hexadecimal string. * * @throws IllegalArgumentException * if <code>s == null || index &lt; 0 || <code>s.</code>{@link String#length() length()}<code> &lt; index + 16</code>). * * @throws NumberFormatException * if any of the characters in the specified range of the string is not * a hex digit (<code>'0'</code> to <code>'9'</code> and * <code>'a'</code> to <code>'f'</code>). */ public static long parseHexString(String s, int index) throws IllegalArgumentException, NumberFormatException { // Check preconditions if (s == null) { throw new IllegalArgumentException("s == null"); } else if (s.length() < index + 16) { throw new IllegalArgumentException("s.length() (" + s.length() + ") < index (" + index + ") + 16 (" + (index + 16) + ')'); } long n = 0L; final int CHAR_ZERO = (int) '0'; final int CHAR_NINE = (int) '9'; final int CHAR_A = (int) 'a'; final int CHAR_F = (int) 'f'; final int CHAR_A_FACTOR = CHAR_A - 10; // Loop through all characters int last = index + 16; for (int i = index; i < last; i++) { int c = (int) s.charAt(i); n <<= 4; if (c >= CHAR_ZERO && c <= CHAR_NINE) { n |= (c - CHAR_ZERO); } else if (c >= CHAR_A && c <= CHAR_F) { n |= (c - CHAR_A_FACTOR); } else { throw new NumberFormatException("s.charAt(" + i + ") == '" + s.charAt(i) + '\''); } } return n; } /** * Parses the specified 16-digit unsigned hex string. * * @param s * the hexadecimal string, cannot be <code>null</code> and must have * size 16 * (i.e. <code>s.</code>{@link String#length() length()}<code> == 16</code>). * * @return * the value of the parsed unsigned hexadecimal string. * * @throws IllegalArgumentException * if <code>s == null || s.</code>{@link String#length() length()}<code> != 16</code>. * * @throws NumberFormatException * if any of the characters in the specified string is not a hex digit * (<code>'0'</code> to <code>'9'</code> and <code>'a'</code> to * <code>'f'</code>). */ public static long parseHexString(String s) throws IllegalArgumentException, NumberFormatException { // Check preconditions if (s == null) { throw new IllegalArgumentException("s == null"); } else if (s.length() != 16) { throw new IllegalArgumentException("s.length() != 16"); } return parseHexString(s, 0); } //------------------------------------------------------------------------- // Constructors //------------------------------------------------------------------------- /** * Creates a new <code>LongUtils</code> object. */ private LongUtils() { // empty } //------------------------------------------------------------------------- // Fields //------------------------------------------------------------------------- //------------------------------------------------------------------------- // Methods //------------------------------------------------------------------------- }
Fixed compiler errors.
src/java-common/org/xins/util/text/HexConverter.java
Fixed compiler errors.
Java
bsd-3-clause
2c3d3a4bc21a6e4ac0ee443684b3c7e014576117
0
Team2338/Fumper
package team.gif; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.buttons.Button; import edu.wpi.first.wpilibj.buttons.DigitalIOButton; import edu.wpi.first.wpilibj.buttons.JoystickButton; import team.gif.commands.*; public class OI { public static final Joystick leftStick = new Joystick(1); public static final rightStick = new Joystick(2); public static final auxStick = new Joystick(3); private final Button leftTrigger = new JoystickButton(leftStick, 1); private final Button right2 = new JoystickButton(rightStick, 2); private final Button right3 = new JoystickButton(rightStick, 3); private final Button right6 = new JoystickButton(rightStick, 6); private final Button right7 = new JoystickButton(rightStick, 7); public static final Button auxTrigger = new JoystickButton(rightStick, 1); public OI() { leftTrigger.whileHeld(new ShifterHigh()); right2.whileHeld(new CollectorReceive()); right2.whenPressed(new EarsOpen()); right3.whileHeld(new CollectorPass()); right3.whenPressed(new EarsOpen()); right3.whenReleased(new CollectorStandby()); right3.whenReleased(new EarsClosed()); right6.whileHeld(new BumperUp()); right7.whileHeld(new CollectorRaise()); } }
src/team/gif/OI.java
package team.gif; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.buttons.Button; import edu.wpi.first.wpilibj.buttons.DigitalIOButton; import edu.wpi.first.wpilibj.buttons.JoystickButton; import team.gif.commands.*; public class OI { public static final Joystick leftStick = new Joystick(1), rightStick = new Joystick(2), auxStick = new Joystick(3); private final Button leftTrigger = new JoystickButton(leftStick, 1), aux2 = new JoystickButton(rightStick, 2), aux3 = new JoystickButton(rightStick, 3), aux6 = new JoystickButton(rightStick, 6), aux7 = new JoystickButton(rightStick, 7); public static final Button auxTrigger = new JoystickButton(rightStick, 1); public OI() { leftTrigger.whileHeld(new ShifterHigh()); aux2.whileHeld(new CollectorReceive()); aux2.whenPressed(new EarsOpen()); aux3.whileHeld(new CollectorPass()); aux3.whenPressed(new EarsOpen()); aux3.whenReleased(new CollectorStandby()); aux3.whenReleased(new EarsClosed()); aux6.whileHeld(new BumperUp()); aux7.whileHeld(new CollectorRaise()); } }
Update OI.java
src/team/gif/OI.java
Update OI.java
Java
bsd-3-clause
ecc66c895635aa2cddda8d5d3232fb4edbce6966
0
interdroid/ibis-ipl,interdroid/ibis-ipl,interdroid/ibis-ipl
/* $Id$ */ package ibis.rmi.impl; import ibis.rmi.Remote; import ibis.rmi.RemoteException; import ibis.rmi.server.RemoteStub; import ibis.rmi.server.ServerRef; import java.io.ObjectOutput; // TODO: implement getClientHost public class UnicastServerRef extends UnicastRef implements ServerRef, java.io.Serializable { public UnicastServerRef() { GUID = "//" + RTS.getHostname() + "/" + (new java.rmi.server.UID()).toString(); } public RemoteStub exportObject(Remote impl, Object portData) throws RemoteException { try { RemoteStub stub = RTS.exportObject(impl, new UnicastRef(GUID)); return stub; } catch (Exception e) { throw new RemoteException(e.getMessage(), e); } } public String getRefClass(ObjectOutput out) { return "UnicastServerRef"; } public String getClientHost() { // TODO: return null; } }
src/ibis/rmi/impl/UnicastServerRef.java
/* $Id$ */ package ibis.rmi.impl; import ibis.rmi.Remote; import ibis.rmi.RemoteException; import ibis.rmi.server.RemoteStub; import ibis.rmi.server.ServerRef; // TODO: implement getClientHost public class UnicastServerRef extends UnicastRef implements ServerRef, java.io.Serializable { public UnicastServerRef() { GUID = "//" + RTS.getHostname() + "/" + (new java.rmi.server.UID()).toString(); } public RemoteStub exportObject(Remote impl, Object portData) throws RemoteException { try { RemoteStub stub = RTS.exportObject(impl, new UnicastRef(GUID)); return stub; } catch (Exception e) { throw new RemoteException(e.getMessage(), e); } } public String getClientHost() { // TODO: return null; } }
Fix: UnicastServerRef became UnicastRef after serialization git-svn-id: f22e84ca493ccad7df8d2727bca69d1c9fc2e5c5@3188 aaf88347-d911-0410-b711-e54d386773bb
src/ibis/rmi/impl/UnicastServerRef.java
Fix: UnicastServerRef became UnicastRef after serialization
Java
mit
e8686503719c2b948a6b90d68adaf41a1bcf02a1
0
dmpe/Homeworks5,dmpe/Homeworks5,dmpe/Homeworks5
package novy; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.concurrent.LinkedBlockingQueue; /** * Class which we use to implement the interface and store Mensch in Queue */ public class Server extends UnicastRemoteObject implements Prod_Con_Methods { Mensch ms; LinkedBlockingQueue<Mensch> lbq; public Server() throws RemoteException { super(); // required to avoid the 'rmic' step lbq = new LinkedBlockingQueue<Mensch>(10); } public void produce(Mensch e) throws RemoteException, InterruptedException { this.ms = e; lbq.put(e); } public Mensch consume() throws RemoteException, InterruptedException { return lbq.take(); } public int size() { return lbq.size(); } }
Assignment4/src/novy/Server.java
package novy; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.concurrent.LinkedBlockingQueue; /** * Class which we use to implement the interface and store Mensch in Queue */ public class Server extends UnicastRemoteObject implements Prod_Con_Methods { Mensch ms; LinkedBlockingQueue<Mensch> lbq; public Server() throws RemoteException { super(); lbq = new LinkedBlockingQueue<Mensch>(10); } public void produce(Mensch e) throws RemoteException, InterruptedException { this.ms = e; lbq.put(e); } public Mensch consume() throws RemoteException, InterruptedException { return lbq.take(); } public int size() { return lbq.size(); } }
Update Server.java
Assignment4/src/novy/Server.java
Update Server.java
Java
mit
7001b6c1c6f2a99978949210c998df05383c1e3f
0
aemreunal/iBeaconServer,aemreunal/iBeaconServer
package com.dteknoloji.controller; import java.util.List; import javax.validation.ConstraintViolationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.transaction.TransactionSystemException; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import org.springframework.web.util.UriComponentsBuilder; import com.dteknoloji.config.GlobalSettings; import com.dteknoloji.domain.Beacon; import com.dteknoloji.domain.BeaconGroup; import com.dteknoloji.domain.Project; import com.dteknoloji.service.BeaconGroupService; import com.dteknoloji.service.BeaconService; import com.dteknoloji.service.ProjectService; /* ************************** * Copyright (c) 2014 * * * * This code belongs to: * * * * Ahmet Emre Ünal * * S001974 * * * * [email protected] * * [email protected] * * * * aemreunal.com * ************************** */ @Controller @RequestMapping("/Project") public class ProjectController { @Autowired private ProjectService projectService; @Autowired private BeaconService beaconService; @Autowired private BeaconGroupService beaconGroupService; /** * Get all project (Optionally, all with matching criteria) * * @param projectName * (Optional) The name of the project * @param ownerName * (Optional) The name of the owner * @param ownerID * (Optional) The ID of the owner * * @return All existing projects (Optionally, all that match the given criteria) */ @RequestMapping(method = RequestMethod.GET, produces = "application/json") public ResponseEntity<List<Project>> getAllProjects( @RequestParam(value = "name", required = false, defaultValue = "") String projectName, @RequestParam(value = "ownerName", required = false, defaultValue = "") String ownerName, @RequestParam(value = "ownerID", required = false, defaultValue = "") String ownerID) { if (projectName.equals("") && ownerName.equals("") && ownerID.equals("")) { return new ResponseEntity<List<Project>>(projectService.findAll(), HttpStatus.OK); } else { return getProjectsWithMatchingCriteria(projectName, ownerName, ownerID); } } /** * Returns the list of projects that match a given criteria * * @param projectName * (Optional) The name of the project * @param ownerName * (Optional) The name of the owner * @param ownerID * (Optional) The ID of the owner * * @return The list of projects that match the given criteria */ private ResponseEntity<List<Project>> getProjectsWithMatchingCriteria(String projectName, String ownerName, String ownerID) { Long ownerIDAsLong; if (ownerID.equals("")) { ownerIDAsLong = null; } else { try { ownerIDAsLong = Long.valueOf(ownerID); } catch (NumberFormatException e) { return new ResponseEntity<List<Project>>(HttpStatus.BAD_REQUEST); } } List<Project> projects = projectService.findProjectsBySpecs(projectName, ownerName, ownerIDAsLong); if (projects.size() == 0) { return new ResponseEntity<List<Project>>(HttpStatus.NOT_FOUND); } return new ResponseEntity<List<Project>>(projects, HttpStatus.OK); } /** * Get the project with the specified ID * * @param id * The ID of the project * * @return The project */ @RequestMapping(method = RequestMethod.GET, value = "/{id}", produces = "application/json") public ResponseEntity<Project> viewProject(@PathVariable String id) { Long projectIDAsLong; try { projectIDAsLong = Long.valueOf(id); } catch (NumberFormatException e) { return new ResponseEntity<Project>(HttpStatus.BAD_REQUEST); } Project project = projectService.findById(projectIDAsLong); if (project == null) { return new ResponseEntity<Project>(HttpStatus.NOT_FOUND); } return new ResponseEntity<Project>(project, HttpStatus.OK); } /** * Create a new project * * @param project * The project as JSON object * @param builder * The URI builder for post-creation redirect * * @return The created project */ @RequestMapping(method = RequestMethod.POST) public ResponseEntity<Project> createProject(@RequestBody Project project, UriComponentsBuilder builder) { try { Project newProject = projectService.save(project); if (GlobalSettings.DEBUGGING) { System.out.println("Saved project with Name = \'" + newProject.getName() + "\' ID = \'" + newProject.getProjectId() + "\'"); } HttpHeaders headers = new HttpHeaders(); headers.setLocation(builder.path("/Project/{id}").buildAndExpand(newProject.getProjectId().toString()).toUri()); return new ResponseEntity<Project>(newProject, headers, HttpStatus.CREATED); } catch (ConstraintViolationException | TransactionSystemException e) { if (GlobalSettings.DEBUGGING) { System.err.println("Unable to save project! Constraint violation detected!"); } return new ResponseEntity<Project>(HttpStatus.BAD_REQUEST); } } /** * Create a new beacon in project * <p/> * {@literal @}Transactional mark via http://stackoverflow.com/questions/11812432/spring-data-hibernate * * @param id * The ID of the project to create the beacon in * @param restBeacon * The beacon as JSON object * @param builder * The URI builder for post-creation redirect * * @return The created beacon */ @Transactional @RequestMapping(method = RequestMethod.POST, value = "/{id}/CreateBeacon", produces = "application/json") public ResponseEntity<Beacon> createBeaconInProject(@PathVariable String id, @RequestBody Beacon restBeacon, UriComponentsBuilder builder) { Long projectIDAsLong; try { projectIDAsLong = Long.valueOf(id); } catch (NumberFormatException e) { return new ResponseEntity<Beacon>(HttpStatus.BAD_REQUEST); } Project project = projectService.findById(projectIDAsLong); if (project == null) { return new ResponseEntity<Beacon>(HttpStatus.NOT_FOUND); } restBeacon.setProject(project); Beacon newBeacon; try { newBeacon = beaconService.save(restBeacon); } catch (ConstraintViolationException | TransactionSystemException e) { if (GlobalSettings.DEBUGGING) { System.err.println("Unable to save beacon! Constraint violation detected!"); } return new ResponseEntity<Beacon>(HttpStatus.BAD_REQUEST); } if (GlobalSettings.DEBUGGING) { System.out.println("Saved beacon with UUID = \'" + newBeacon.getUuid() + "\' major = \'" + newBeacon.getMajor() + "\' minor = \'" + newBeacon.getMinor() + "\' in project with ID = \'" + projectIDAsLong + "\'"); } // project.addBeacon(newBeacon); // projectService.save(project); HttpHeaders headers = new HttpHeaders(); headers.setLocation(builder.path("/Beacon/{id}").buildAndExpand(newBeacon.getBeaconId().toString()).toUri()); return new ResponseEntity<Beacon>(newBeacon, headers, HttpStatus.CREATED); } /** * Create a new beacon group in project * <p/> * {@literal @}Transactional mark via http://stackoverflow.com/questions/11812432/spring-data-hibernate * * @param id * The ID of the project to create the beacon group in * @param restBeaconGroup * The beacon group as JSON object * @param builder * The URI builder for post-creation redirect * * @return The created beacon group */ @Transactional @RequestMapping(method = RequestMethod.POST, value = "/{id}/CreateBeaconGroup", produces = "application/json") public ResponseEntity<BeaconGroup> createBeaconGroupInProject(@PathVariable String id, @RequestBody BeaconGroup restBeaconGroup, UriComponentsBuilder builder) { Long projectIDAsLong; try { projectIDAsLong = Long.valueOf(id); } catch (NumberFormatException e) { return new ResponseEntity<BeaconGroup>(HttpStatus.BAD_REQUEST); } Project project = projectService.findById(projectIDAsLong); if (project == null) { return new ResponseEntity<BeaconGroup>(HttpStatus.NOT_FOUND); } restBeaconGroup.setProject(project); BeaconGroup newBeaconGroup; try { newBeaconGroup = beaconGroupService.save(restBeaconGroup); } catch (ConstraintViolationException | TransactionSystemException e) { if (GlobalSettings.DEBUGGING) { System.err.println("Unable to save beacon group! Constraint violation detected!"); } return new ResponseEntity<BeaconGroup>(HttpStatus.BAD_REQUEST); } if (GlobalSettings.DEBUGGING) { System.out.println("Saved beacon group with ID = \'" + newBeaconGroup.getBeaconGroupId() + "\' name = \'" + newBeaconGroup.getName() + "\' in project with ID = \'" + projectIDAsLong + "\'"); } // project.addBeaconGroup(newBeaconGroup); // projectService.save(project); HttpHeaders headers = new HttpHeaders(); headers.setLocation(builder.path("/BeaconGroup/{id}").buildAndExpand(newBeaconGroup.getBeaconGroupId().toString()).toUri()); return new ResponseEntity<BeaconGroup>(newBeaconGroup, headers, HttpStatus.CREATED); } /** * Get beacon objects that belong to a project. * * @param id * The ID of the project * * @return The list of beacons that belong to the project with the specified ID */ @RequestMapping(method = RequestMethod.GET, value = "/{id}/beacons", produces = "application/json") public ResponseEntity<List<Beacon>> viewBeaconsOfProject(@PathVariable String id) { Long projectIDAsLong; try { projectIDAsLong = Long.valueOf(id); } catch (NumberFormatException e) { return new ResponseEntity<List<Beacon>>(HttpStatus.BAD_REQUEST); } Project project = projectService.findById(projectIDAsLong); if (project == null) { return new ResponseEntity<List<Beacon>>(HttpStatus.NOT_FOUND); } return new ResponseEntity<List<Beacon>>(project.getBeacons(), HttpStatus.OK); } /** * Delete the specified project * * @param id * The ID of the project to delete * * @return The deleted project */ @RequestMapping(method = RequestMethod.DELETE, value = "/{id}", produces = "application/json") public ResponseEntity<Project> deleteProject(@PathVariable String id) { Long projectIDAsLong; try { projectIDAsLong = Long.valueOf(id); } catch (NumberFormatException e) { return new ResponseEntity<Project>(HttpStatus.BAD_REQUEST); } Project project = projectService.findById(projectIDAsLong); if (project == null) { return new ResponseEntity<Project>(HttpStatus.NOT_FOUND); } boolean deleted = projectService.delete(projectIDAsLong); if (deleted) { return new ResponseEntity<Project>(project, HttpStatus.OK); } return new ResponseEntity<Project>(HttpStatus.FORBIDDEN); } }
src/main/java/com/dteknoloji/controller/ProjectController.java
package com.dteknoloji.controller; import java.util.List; import javax.validation.ConstraintViolationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.transaction.TransactionSystemException; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import org.springframework.web.util.UriComponentsBuilder; import com.dteknoloji.config.GlobalSettings; import com.dteknoloji.domain.Beacon; import com.dteknoloji.domain.BeaconGroup; import com.dteknoloji.domain.Project; import com.dteknoloji.service.BeaconGroupService; import com.dteknoloji.service.BeaconService; import com.dteknoloji.service.ProjectService; /* ************************** * Copyright (c) 2014 * * * * This code belongs to: * * * * Ahmet Emre Ünal * * S001974 * * * * [email protected] * * [email protected] * * * * aemreunal.com * ************************** */ @Controller @RequestMapping("/Project") public class ProjectController { @Autowired private ProjectService projectService; @Autowired private BeaconService beaconService; @Autowired private BeaconGroupService beaconGroupService; /** * Get all project (Optionally, all with matching criteria) * * @param projectName * (Optional) The name of the project * @param ownerName * (Optional) The name of the owner * @param ownerID * (Optional) The ID of the owner * * @return All existing projects (Optionally, all that match the given criteria) */ @RequestMapping(method = RequestMethod.GET, produces = "application/json") public ResponseEntity<List<Project>> getAllProjects( @RequestParam(value = "name", required = false, defaultValue = "") String projectName, @RequestParam(value = "ownerName", required = false, defaultValue = "") String ownerName, @RequestParam(value = "ownerID", required = false, defaultValue = "") String ownerID) { if (projectName.equals("") && ownerName.equals("") && ownerID.equals("")) { return new ResponseEntity<List<Project>>(projectService.findAll(), HttpStatus.OK); } else { return getProjectsWithMatchingCriteria(projectName, ownerName, ownerID); } } /** * Returns the list of projects that match a given criteria * * @param projectName * (Optional) The name of the project * @param ownerName * (Optional) The name of the owner * @param ownerID * (Optional) The ID of the owner * * @return The list of projects that match the given criteria */ private ResponseEntity<List<Project>> getProjectsWithMatchingCriteria(String projectName, String ownerName, String ownerID) { Long ownerIDAsLong; if (ownerID.equals("")) { ownerIDAsLong = null; } else { try { ownerIDAsLong = Long.valueOf(ownerID); } catch (NumberFormatException e) { return new ResponseEntity<List<Project>>(HttpStatus.BAD_REQUEST); } } List<Project> projects = projectService.findProjectsBySpecs(projectName, ownerName, ownerIDAsLong); if (projects.size() == 0) { return new ResponseEntity<List<Project>>(HttpStatus.NOT_FOUND); } return new ResponseEntity<List<Project>>(projects, HttpStatus.OK); } /** * Get the project with the specified ID * * @param id * The ID of the project * * @return The project */ @RequestMapping(method = RequestMethod.GET, value = "/{id}", produces = "application/json") public ResponseEntity<Project> viewProject(@PathVariable String id) { Long projectIDAsLong; try { projectIDAsLong = Long.valueOf(id); } catch (NumberFormatException e) { return new ResponseEntity<Project>(HttpStatus.BAD_REQUEST); } Project project = projectService.findById(projectIDAsLong); if (project == null) { return new ResponseEntity<Project>(HttpStatus.NOT_FOUND); } return new ResponseEntity<Project>(project, HttpStatus.OK); } /** * Create a new project * * @param project * The project as JSON object * @param builder * The URI builder for post-creation redirect * * @return The created project */ @RequestMapping(method = RequestMethod.POST) public ResponseEntity<Project> createProject(@RequestBody Project project, UriComponentsBuilder builder) { try { Project newProject = projectService.save(project); if (GlobalSettings.DEBUGGING) { System.out.println("Saved project with Name = \'" + newProject.getName() + "\' ID = \'" + newProject.getProjectId() + "\'"); } HttpHeaders headers = new HttpHeaders(); headers.setLocation(builder.path("/Project/{id}").buildAndExpand(newProject.getProjectId().toString()).toUri()); return new ResponseEntity<Project>(newProject, headers, HttpStatus.CREATED); } catch (ConstraintViolationException | TransactionSystemException e) { if (GlobalSettings.DEBUGGING) { System.err.println("Unable to save project! Constraint violation detected!"); } return new ResponseEntity<Project>(HttpStatus.BAD_REQUEST); } } /** * Create a new beacon in project * <p/> * {@literal @}Transactional mark via http://stackoverflow.com/questions/11812432/spring-data-hibernate * * @param id * The ID of the project to create the beacon in * @param restBeacon * The beacon as JSON object * @param builder * The URI builder for post-creation redirect * * @return The created beacon */ @Transactional @RequestMapping(method = RequestMethod.POST, value = "/{id}/CreateBeacon", produces = "application/json") public ResponseEntity<Beacon> createBeaconInProject(@PathVariable String id, @RequestBody Beacon restBeacon, UriComponentsBuilder builder) { Long projectIDAsLong; try { projectIDAsLong = Long.valueOf(id); } catch (NumberFormatException e) { return new ResponseEntity<Beacon>(HttpStatus.BAD_REQUEST); } Project project = projectService.findById(projectIDAsLong); if (project == null) { return new ResponseEntity<Beacon>(HttpStatus.NOT_FOUND); } restBeacon.setProject(project); Beacon newBeacon; try { newBeacon = beaconService.save(restBeacon); } catch (ConstraintViolationException | TransactionSystemException e) { if (GlobalSettings.DEBUGGING) { System.err.println("Unable to save beacon! Constraint violation detected!"); } return new ResponseEntity<Beacon>(HttpStatus.BAD_REQUEST); } if (GlobalSettings.DEBUGGING) { System.out.println("Saved beacon with UUID = \'" + newBeacon.getUuid() + "\' major = \'" + newBeacon.getMajor() + "\' minor = \'" + newBeacon.getMinor() + "\' in project with ID = \'" + projectIDAsLong + "\'"); } // project.addBeacon(newBeacon); // projectService.save(project); HttpHeaders headers = new HttpHeaders(); headers.setLocation(builder.path("/Beacon/{id}").buildAndExpand(newBeacon.getBeaconId().toString()).toUri()); return new ResponseEntity<Beacon>(newBeacon, headers, HttpStatus.CREATED); } /** * Create a new beacon group in project * <p/> * {@literal @}Transactional mark via http://stackoverflow.com/questions/11812432/spring-data-hibernate * * @param id * The ID of the project to create the beacon group in * @param restBeaconGroup * The beacon group as JSON object * @param builder * The URI builder for post-creation redirect * * @return The created beacon group */ @Transactional @RequestMapping(method = RequestMethod.POST, value = "/{id}/CreateBeaconGroup", produces = "application/json") public ResponseEntity<BeaconGroup> createBeaconGroupInProject(@PathVariable String id, @RequestBody BeaconGroup restBeaconGroup, UriComponentsBuilder builder) { Long projectIDAsLong; try { projectIDAsLong = Long.valueOf(id); } catch (NumberFormatException e) { return new ResponseEntity<BeaconGroup>(HttpStatus.BAD_REQUEST); } Project project = projectService.findById(projectIDAsLong); if (project == null) { return new ResponseEntity<BeaconGroup>(HttpStatus.NOT_FOUND); } restBeaconGroup.setProject(project); BeaconGroup newBeaconGroup; try { newBeaconGroup = beaconGroupService.save(restBeaconGroup); } catch (ConstraintViolationException | TransactionSystemException e) { if (GlobalSettings.DEBUGGING) { System.err.println("Unable to save beacon group! Constraint violation detected!"); } return new ResponseEntity<BeaconGroup>(HttpStatus.BAD_REQUEST); } if (GlobalSettings.DEBUGGING) { System.out.println("Saved beacon group with ID = \'" + newBeaconGroup.getBeaconGroupId() + "\' name = \'" + newBeaconGroup.getName() + "\' in project with ID = \'" + projectIDAsLong + "\'"); } project.addBeaconGroup(newBeaconGroup); projectService.save(project); HttpHeaders headers = new HttpHeaders(); headers.setLocation(builder.path("/BeaconGroup/{id}").buildAndExpand(newBeaconGroup.getBeaconGroupId().toString()).toUri()); return new ResponseEntity<BeaconGroup>(newBeaconGroup, headers, HttpStatus.CREATED); } /** * Get beacon objects that belong to a project. * * @param id * The ID of the project * * @return The list of beacons that belong to the project with the specified ID */ @RequestMapping(method = RequestMethod.GET, value = "/{id}/beacons", produces = "application/json") public ResponseEntity<List<Beacon>> viewBeaconsOfProject(@PathVariable String id) { Long projectIDAsLong; try { projectIDAsLong = Long.valueOf(id); } catch (NumberFormatException e) { return new ResponseEntity<List<Beacon>>(HttpStatus.BAD_REQUEST); } Project project = projectService.findById(projectIDAsLong); if (project == null) { return new ResponseEntity<List<Beacon>>(HttpStatus.NOT_FOUND); } return new ResponseEntity<List<Beacon>>(project.getBeacons(), HttpStatus.OK); } /** * Delete the specified project * * @param id * The ID of the project to delete * * @return The deleted project */ @RequestMapping(method = RequestMethod.DELETE, value = "/{id}", produces = "application/json") public ResponseEntity<Project> deleteProject(@PathVariable String id) { Long projectIDAsLong; try { projectIDAsLong = Long.valueOf(id); } catch (NumberFormatException e) { return new ResponseEntity<Project>(HttpStatus.BAD_REQUEST); } Project project = projectService.findById(projectIDAsLong); if (project == null) { return new ResponseEntity<Project>(HttpStatus.NOT_FOUND); } boolean deleted = projectService.delete(projectIDAsLong); if (deleted) { return new ResponseEntity<Project>(project, HttpStatus.OK); } return new ResponseEntity<Project>(HttpStatus.FORBIDDEN); } }
Comment-out project saving on beacon group creation
src/main/java/com/dteknoloji/controller/ProjectController.java
Comment-out project saving on beacon group creation
Java
mit
dedcb0896fc57133149c334e7b7b9b0a1be7c253
0
nguyenquyhy/Sponge-Discord,DevOnTheRocks/DiscordBridge,Rebelcraft/DiscordBridge,nguyenquyhy/DiscordBridge
package com.nguyenquyhy.spongediscord; import com.google.inject.Inject; import com.nguyenquyhy.spongediscord.commands.*; import com.nguyenquyhy.spongediscord.database.*; import com.nguyenquyhy.spongediscord.utils.ConfigUtil; import ninja.leaping.configurate.commented.CommentedConfigurationNode; import ninja.leaping.configurate.hocon.HoconConfigurationLoader; import ninja.leaping.configurate.loader.ConfigurationLoader; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.spongepowered.api.Game; import org.spongepowered.api.Sponge; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.GenericArguments; import org.spongepowered.api.command.source.CommandBlockSource; import org.spongepowered.api.command.source.ConsoleSource; import org.spongepowered.api.command.spec.CommandSpec; import org.spongepowered.api.config.ConfigDir; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.game.state.GamePreInitializationEvent; import org.spongepowered.api.event.game.state.GameStartedServerEvent; import org.spongepowered.api.event.game.state.GameStoppingServerEvent; import org.spongepowered.api.event.message.MessageChannelEvent; import org.spongepowered.api.event.network.ClientConnectionEvent; import org.spongepowered.api.plugin.Plugin; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.format.TextColors; import org.spongepowered.api.text.format.TextStyles; import org.spongepowered.api.text.serializer.TextSerializers; import sx.blah.discord.api.ClientBuilder; import sx.blah.discord.api.Event; import sx.blah.discord.api.IDiscordClient; import sx.blah.discord.api.IListener; import sx.blah.discord.handle.impl.events.GuildCreateEvent; import sx.blah.discord.handle.impl.events.MessageReceivedEvent; import sx.blah.discord.handle.impl.events.MessageSendEvent; import sx.blah.discord.handle.impl.events.ReadyEvent; import sx.blah.discord.handle.impl.obj.Invite; import sx.blah.discord.handle.obj.IChannel; import sx.blah.discord.handle.obj.IMessage; import sx.blah.discord.util.DiscordException; import sx.blah.discord.util.HTTP429Exception; import sx.blah.discord.util.MissingPermissionsException; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; /** * Created by Hy on 1/4/2016. */ @Plugin(id = "com.nguyenquyhy.spongediscord", name = "Sponge Discord", version = "1.2.0") public class SpongeDiscord { public static String DEBUG = ""; public static String BOT_TOKEN = ""; public static String CHANNEL_ID = ""; public static String INVITE_CODE = ""; public static String JOINED_MESSAGE = ""; public static String LEFT_MESSAGE = ""; public static String MESSAGE_DISCORD_TEMPLATE = ""; public static String MESSAGE_DISCORD_ANONYMOUS_TEMPLATE = ""; public static String MESSAGE_MINECRAFT_TEMPLATE = ""; public static String MESSAGE_DISCORD_SERVER_UP = ""; public static String MESSAGE_DISCORD_SERVER_DOWN = ""; public static String NONCE = "sponge-discord"; private static IDiscordClient consoleClient = null; private static final Map<UUID, IDiscordClient> clients = new HashMap<UUID, IDiscordClient>(); private static IDiscordClient defaultClient = null; private static Set<UUID> unauthenticatedPlayers = new HashSet<>(100); @Inject private Logger logger; @Inject @ConfigDir(sharedRoot = false) private Path configDir; @Inject private Game game; private MessageProvider messageProvider = new MessageProvider(); private IStorage storage; private static SpongeDiscord instance; @Listener public void onPreInitialization(GamePreInitializationEvent event) { instance = this; loadConfiguration(); } @Listener public void onServerStart(GameStartedServerEvent event) { CommandSpec defaultLoginCmd = CommandSpec.builder() .description(Text.of("Log in and set a Discord account for unauthenticated users")) .arguments( GenericArguments.onlyOne(GenericArguments.string(Text.of("email"))), GenericArguments.onlyOne(GenericArguments.string(Text.of("password")))) .executor(new DefaultLoginCommand()) .build(); CommandSpec defaultLogoutCmd = CommandSpec.builder() .description(Text.of("Log out of default Discord account")) .executor(new DefaultLogoutCommand()) .build(); CommandSpec defaultCmd = CommandSpec.builder() .permission("spongediscord.default") .description(Text.of("Commands to set/unset default Discord account for unauthenticated users")) .child(defaultLoginCmd, "login", "l") .child(defaultLogoutCmd, "logout", "lo") .build(); CommandSpec loginCmd = CommandSpec.builder() //.permission("spongediscord.login") .description(Text.of("Login to your Discord account and bind to current Minecraft account")) .arguments( GenericArguments.onlyOne(GenericArguments.string(Text.of("email"))), GenericArguments.onlyOne(GenericArguments.string(Text.of("password")))) .executor(new LoginCommand()) .build(); CommandSpec logoutCmd = CommandSpec.builder() //.permission("spongediscord.login") .description(Text.of("Logout of your Discord account and unbind from current Minecraft account")) .executor(new LogoutCommand()) .build(); CommandSpec reloadCmd = CommandSpec.builder() .permission("spongediscord.reload") .description(Text.of("Reload Sponge Discord configuration")) .executor(new ReloadCommand()) .build(); CommandSpec broadcastCmd = CommandSpec.builder() .permission("spongediscord.broadcast") .description(Text.of("Broadcast message to Discord and online Minecraft accounts")) .arguments(GenericArguments.onlyOne(GenericArguments.string(Text.of("message")))) .executor(new BroadcastCommand()) .build(); CommandSpec mainCommandSpec = CommandSpec.builder() //.permission("spongediscord") .description(Text.of("Discord in Minecraft")) .child(defaultCmd, "default", "d") .child(loginCmd, "login", "l") .child(logoutCmd, "logout", "lo") .child(reloadCmd, "reload") .child(broadcastCmd, "broadcast", "b") .build(); game.getCommandManager().register(this, mainCommandSpec, "discord", "d"); getLogger().info("/discord command registered."); String cachedToken = getStorage().getDefaultToken(); if (StringUtils.isNotBlank(BOT_TOKEN)) { getLogger().info("Logging in to bot Discord account..."); try { ClientBuilder clientBuilder = new ClientBuilder(); IDiscordClient client = clientBuilder.withToken(BOT_TOKEN).asBot().build(); prepareDefaultClient(client, null); client.login(); } catch (DiscordException e) { e.printStackTrace(); } } else if (StringUtils.isNotBlank(cachedToken)) { getLogger().info("Logging in to default Discord account..."); try { ClientBuilder clientBuilder = new ClientBuilder(); IDiscordClient client = clientBuilder.withToken(cachedToken).build(); prepareDefaultClient(client, null); client.login(); } catch (DiscordException e) { e.printStackTrace(); } } } @Listener public void onServerStop(GameStoppingServerEvent event) { if (defaultClient != null && defaultClient.isReady()) { IChannel channel = defaultClient.getChannelByID(CHANNEL_ID); if (channel != null) { try { channel.sendMessage(MESSAGE_DISCORD_SERVER_DOWN, NONCE, false); } catch (HTTP429Exception e) { e.printStackTrace(); } catch (DiscordException e) { e.printStackTrace(); } catch (MissingPermissionsException e) { e.printStackTrace(); } } } } @Listener public void onJoin(ClientConnectionEvent.Join event) throws URISyntaxException { Optional<Player> player = event.getCause().first(Player.class); if (player.isPresent()) { UUID playerId = player.get().getUniqueId(); boolean loggedIn = false; if (!clients.containsKey(playerId)) { String cachedToken = getStorage().getToken(playerId); if (null != cachedToken && !cachedToken.isEmpty()) { player.get().sendMessage(Text.of(TextColors.GRAY, "Logging in to Discord...")); try { ClientBuilder clientBuilder = new ClientBuilder(); IDiscordClient client = clientBuilder.withToken(cachedToken).build(); prepareClient(client, player.get()); client.login(); loggedIn = true; } catch (DiscordException e) { SpongeDiscord.getInstance().getLogger().error("Cannot login to Discord! " + e.getMessage()); } } } if (!loggedIn) { unauthenticatedPlayers.add(playerId); if (StringUtils.isNotBlank(JOINED_MESSAGE) && defaultClient != null && defaultClient.isReady()) { try { IChannel channel = defaultClient.getChannelByID(CHANNEL_ID); channel.sendMessage(String.format(JOINED_MESSAGE, player.get().getName()), NONCE, false); } catch (DiscordException e) { e.printStackTrace(); } catch (HTTP429Exception e) { e.printStackTrace(); } catch (MissingPermissionsException e) { e.printStackTrace(); } } } } } @Listener public void onDisconnect(ClientConnectionEvent.Disconnect event) throws IOException, HTTP429Exception, DiscordException, MissingPermissionsException { Optional<Player> player = event.getCause().first(Player.class); if (player.isPresent()) { UUID playerId = player.get().getUniqueId(); if (CHANNEL_ID != null && !CHANNEL_ID.isEmpty() && StringUtils.isNotBlank(LEFT_MESSAGE)) { IDiscordClient client = clients.get(playerId); if (client != null && client.isReady()) { IChannel channel = client.getChannelByID(CHANNEL_ID); channel.sendMessage(String.format(LEFT_MESSAGE, player.get().getName()), NONCE, false); } else if (defaultClient != null && defaultClient.isReady()) { IChannel channel = defaultClient.getChannelByID(CHANNEL_ID); channel.sendMessage(String.format(LEFT_MESSAGE, player.get().getName()), NONCE, false); } } removeAndLogoutClient(playerId); unauthenticatedPlayers.remove(playerId); getLogger().info(player.get().getName() + " has disconnected!"); } } @Listener public void onChat(MessageChannelEvent.Chat event) throws IOException, HTTP429Exception, DiscordException, MissingPermissionsException { if (CHANNEL_ID != null && !CHANNEL_ID.isEmpty()) { String plainString = event.getRawMessage().toPlain().trim(); if (StringUtils.isNotBlank(plainString) && !plainString.startsWith("/")) { Optional<Player> player = event.getCause().first(Player.class); if (player.isPresent()) { UUID playerId = player.get().getUniqueId(); if (clients.containsKey(playerId)) { IChannel channel = clients.get(playerId).getChannelByID(CHANNEL_ID); channel.sendMessage(String.format(MESSAGE_DISCORD_TEMPLATE, plainString), NONCE, false); } else if (defaultClient != null) { IChannel channel = defaultClient.getChannelByID(CHANNEL_ID); channel.sendMessage(String.format(MESSAGE_DISCORD_ANONYMOUS_TEMPLATE.replace("%a", player.get().getName().replace("_", "\\_")), plainString), NONCE, false); } } } } } public static SpongeDiscord getInstance() { return instance; } public Logger getLogger() { return logger; } public IStorage getStorage() { return storage; } public void loadConfiguration() { try { if (!Files.exists(configDir)) { Files.createDirectories(configDir); } Path configFile = Paths.get(configDir + "/config.conf"); ConfigurationLoader<CommentedConfigurationNode> configLoader = HoconConfigurationLoader.builder().setPath(configFile).build(); CommentedConfigurationNode configNode; if (!Files.exists(configFile)) { Files.createFile(configFile); getLogger().info("[Sponge-Discord]: Created default configuration, ConfigDatabase will not run until you have edited this file!"); } configNode = configLoader.load(); DEBUG = configNode.getNode("Debug").getString(); BOT_TOKEN = ConfigUtil.readString(configNode, "BotToken", ""); CHANNEL_ID = ConfigUtil.readString(configNode, "Channel", ""); INVITE_CODE = ConfigUtil.readString(configNode, "InviteCode", ""); JOINED_MESSAGE = ConfigUtil.readString(configNode, "JoinedMessageTemplate", "_%s just joined the server_"); LEFT_MESSAGE = ConfigUtil.readString(configNode, "LeftMessageTemplate", "_%s just left the server_"); MESSAGE_DISCORD_TEMPLATE = ConfigUtil.readString(configNode, "MessageInDiscordTemplate", "%s"); MESSAGE_DISCORD_ANONYMOUS_TEMPLATE = ConfigUtil.readString(configNode, "MessageInDiscordAnonymousTemplate", "_<%a>_ %s"); MESSAGE_MINECRAFT_TEMPLATE = ConfigUtil.readString(configNode, "MessageInMinecraftTemplate", "&7<%a> &f%s"); MESSAGE_DISCORD_SERVER_UP = ConfigUtil.readString(configNode, "MessageInDiscordServerUp", "Server has started."); MESSAGE_DISCORD_SERVER_DOWN = ConfigUtil.readString(configNode, "MessageInDiscordServerDown", "Server has stopped."); String tokenStore = ConfigUtil.readString(configNode, "TokenStore", "JSON"); configLoader.save(configNode); // TODO: exit if channel is empty if (StringUtils.isBlank(CHANNEL_ID)) { getLogger().error("Channel ID is not set!"); } switch (tokenStore) { case "InMemory": storage = new InMemoryStorage(); getLogger().info("Use InMemory storage."); break; case "JSON": storage = new JsonFileStorage(configDir); getLogger().info("Use JSON storage."); break; default: getLogger().warn("Invalid TokenStore config. JSON setting with be used!"); storage = new JsonFileStorage(configDir); break; } getLogger().info("Configuration loaded. Channel " + CHANNEL_ID); } catch (IOException e) { e.printStackTrace(); getLogger().error("[Sponge-Discord]: Couldn't create default configuration file!"); } } public void prepareClient(IDiscordClient client, CommandSource commandSource) { client.getDispatcher().registerListener(new IListener<ReadyEvent>() { @Override public void handle(ReadyEvent readyEvent) { try { String name = client.getOurUser().getName(); commandSource.sendMessage(Text.of(TextColors.GOLD, TextStyles.BOLD, "You have logged in to Discord account " + name + "!")); if (commandSource instanceof Player) { Player player = (Player) commandSource; UUID playerId = player.getUniqueId(); unauthenticatedPlayers.remove(playerId); SpongeDiscord.addClient(playerId, client); getStorage().putToken(playerId, client.getToken()); } else if (commandSource instanceof ConsoleSource) { commandSource.sendMessage(Text.of("WARNING: This Discord account will be used only for this console session!")); SpongeDiscord.addClient(null, client); } else if (commandSource instanceof CommandBlockSource) { commandSource.sendMessage(Text.of(TextColors.GREEN, "Account is valid!")); return; } if (CHANNEL_ID != null && !CHANNEL_ID.isEmpty()) { IChannel channel = client.getChannelByID(CHANNEL_ID); if (channel == null) { SpongeDiscord.getInstance().getLogger().info("Accepting channel invite"); acceptInvite(client); } else { channelJoined(client, channel, commandSource); } } } catch (IOException e) { e.printStackTrace(); } catch (DiscordException e) { e.printStackTrace(); } catch (HTTP429Exception e) { e.printStackTrace(); } catch (MissingPermissionsException e) { e.printStackTrace(); } } }); client.getDispatcher().registerListener(new IListener<MessageSendEvent>() { @Override public void handle(MessageSendEvent event) { handleMessageReceivedEvent(event.getMessage(), commandSource); } }); client.getDispatcher().registerListener(new IListener<MessageReceivedEvent>() { @Override public void handle(MessageReceivedEvent event) { handleMessageReceivedEvent(event.getMessage(), commandSource); } }); client.getDispatcher().registerListener(new IListener<GuildCreateEvent>() { @Override public void handle(GuildCreateEvent event) { handleGuildCreateEvent(event, client, commandSource); } }); } public void prepareDefaultClient(IDiscordClient client, CommandSource commandSource) { client.getDispatcher().registerListener(new IListener<ReadyEvent>() { @Override public void handle(ReadyEvent readyEvent) { try { String name = client.getOurUser().getName(); String text = "Discord account " + name + " will be used for all unauthenticated users!"; if (commandSource != null) commandSource.sendMessage(Text.of(TextColors.GOLD, TextStyles.BOLD, text)); else getLogger().info(text); defaultClient = client; getStorage().putDefaultToken(client.getToken()); if (CHANNEL_ID != null && !CHANNEL_ID.isEmpty()) { IChannel channel = client.getChannelByID(CHANNEL_ID); if (channel == null) { getLogger().info("Accepting channel invite for default account..."); acceptInvite(client); } else { channelJoined(client, channel, commandSource); } } } catch (IOException e) { e.printStackTrace(); } catch (DiscordException e) { e.printStackTrace(); } catch (HTTP429Exception e) { e.printStackTrace(); } catch (MissingPermissionsException e) { e.printStackTrace(); } } }); client.getDispatcher().registerListener(new IListener<MessageSendEvent>() { @Override public void handle(MessageSendEvent event) { handleMessageReceivedEvent(event.getMessage(), commandSource); } }); client.getDispatcher().registerListener(new IListener<MessageReceivedEvent>() { @Override public void handle(MessageReceivedEvent messageReceivedEvent) { handleMessageReceivedEvent(messageReceivedEvent.getMessage(), null); } }); client.getDispatcher().registerListener(new IListener<GuildCreateEvent>() { @Override public void handle(GuildCreateEvent guildCreateEvent) { handleGuildCreateEvent(guildCreateEvent, client, commandSource); } }); } public static CommandResult logoutDefault(CommandSource commandSource) throws IOException, HTTP429Exception, DiscordException { if (defaultClient != null) { defaultClient.logout(); defaultClient = null; getInstance().getStorage().removeDefaultToken(); if (commandSource != null) { commandSource.sendMessage(Text.of(TextColors.YELLOW, "Default Discord account is removed.")); } } return CommandResult.success(); } public static CommandResult login(CommandSource commandSource, String email, String password, boolean defaultAccount) { if (defaultAccount) { if (defaultClient != null) { try { defaultClient.logout(); commandSource.sendMessage(Text.of("Logged out of current default account.")); } catch (HTTP429Exception e) { e.printStackTrace(); } catch (DiscordException e) { e.printStackTrace(); } } } else { logout(commandSource, true); } IDiscordClient client = null; try { ClientBuilder clientBuilder = new ClientBuilder().withLogin(email, password); client = clientBuilder.build(); if (defaultAccount) SpongeDiscord.getInstance().prepareDefaultClient(client, commandSource); else SpongeDiscord.getInstance().prepareClient(client, commandSource); client.login(); } catch (DiscordException e) { e.printStackTrace(); } if (client.getToken() != null) { return CommandResult.success(); } else { commandSource.sendMessage(Text.of(TextColors.RED, "Invalid username and/or password!")); return CommandResult.empty(); } } public static CommandResult logout(CommandSource commandSource, boolean isSilence) { if (commandSource instanceof Player) { Player player = (Player) commandSource; UUID playerId = player.getUniqueId(); try { SpongeDiscord.getInstance().getStorage().removeToken(playerId); } catch (IOException e) { e.printStackTrace(); commandSource.sendMessage(Text.of(TextColors.RED, "Cannot remove cached token!")); } SpongeDiscord.removeAndLogoutClient(playerId); unauthenticatedPlayers.add(player.getUniqueId()); if (!isSilence) commandSource.sendMessage(Text.of(TextColors.YELLOW, "Logged out of Discord!")); return CommandResult.success(); } else if (commandSource instanceof ConsoleSource) { SpongeDiscord.removeAndLogoutClient(null); commandSource.sendMessage(Text.of("Logged out of Discord!")); return CommandResult.success(); } else if (commandSource instanceof CommandBlockSource) { commandSource.sendMessage(Text.of(TextColors.YELLOW, "Cannot log out from command blocks!")); return CommandResult.empty(); } return CommandResult.empty(); } public static CommandResult broadcast(CommandSource commandSource, String message) throws IOException, HTTP429Exception, DiscordException, MissingPermissionsException { if (CHANNEL_ID != null && !CHANNEL_ID.isEmpty()) { if (defaultClient == null) { commandSource.sendMessage(Text.of(TextColors.RED, "You have to set up a default account first!")); return CommandResult.empty(); } IChannel channel = defaultClient.getChannelByID(CHANNEL_ID); channel.sendMessage(String.format(MESSAGE_DISCORD_TEMPLATE, "_<Broadcast>_ " + message), NONCE, false); Collection<Player> players = Sponge.getServer().getOnlinePlayers(); for (Player player : players) { player.sendMessage(Text.of(TextStyles.ITALIC, "<Broadcast> " + message)); } } return CommandResult.success(); } private void handleMessageReceivedEvent(IMessage message, CommandSource commandSource) { if (message.getChannel().getID().equals(CHANNEL_ID) && !NONCE.equals(message.getNonce())) { String content = message.getContent(); String author = message.getAuthor().getName(); Text formattedMessage = TextSerializers.FORMATTING_CODE.deserialize(String.format(MESSAGE_MINECRAFT_TEMPLATE.replace("%a", author), content)); if (commandSource != null) { commandSource.sendMessage(formattedMessage); } else { // This case is used for default account for (UUID playerUUID : unauthenticatedPlayers) { Optional<Player> player = Sponge.getServer().getPlayer(playerUUID); if (player.isPresent()) { player.get().sendMessage(formattedMessage); } } } } } private IChannel acceptInvite(IDiscordClient client) { if (INVITE_CODE != null && !INVITE_CODE.isEmpty()) { Invite invite = new Invite(client, INVITE_CODE, null); try { invite.accept(); return client.getChannelByID(CHANNEL_ID); } catch (Exception e) { getLogger().error("Cannot accept invitation " + INVITE_CODE); e.printStackTrace(); } } return null; } private void handleGuildCreateEvent(GuildCreateEvent event, IDiscordClient client, CommandSource commandSource) { IChannel channel = event.getGuild().getChannelByID(CHANNEL_ID); try { channelJoined(client, channel, commandSource); } catch (IOException e) { e.printStackTrace(); } catch (DiscordException e) { e.printStackTrace(); } catch (HTTP429Exception e) { e.printStackTrace(); } catch (MissingPermissionsException e) { e.printStackTrace(); } } private void channelJoined(IDiscordClient client, IChannel channel, CommandSource src) throws IOException, HTTP429Exception, DiscordException, MissingPermissionsException { if (channel != null) { if (client != defaultClient) { String playerName = "console"; if (src instanceof Player) { Player player = (Player) src; playerName = player.getName(); } if (JOINED_MESSAGE != null) channel.sendMessage(String.format(JOINED_MESSAGE, playerName), NONCE, false); getLogger().info(playerName + " connected to Discord channel."); } else { getLogger().info("Default account has connected to Discord channel."); if (StringUtils.isNotBlank(MESSAGE_DISCORD_SERVER_UP)) channel.sendMessage(MESSAGE_DISCORD_SERVER_UP, NONCE, false); } } } private static void addClient(UUID player, IDiscordClient client) { if (player == null) { consoleClient = client; } else { clients.put(player, client); } } private static void removeAndLogoutClient(UUID player) { if (player == null) { try { consoleClient.logout(); } catch (HTTP429Exception e) { e.printStackTrace(); } catch (DiscordException e) { e.printStackTrace(); } consoleClient = null; } else { if (clients.containsKey(player)) { IDiscordClient client = clients.get(player); if (client.isReady()) { try { client.logout(); } catch (HTTP429Exception e) { e.printStackTrace(); } catch (DiscordException e) { e.printStackTrace(); } } clients.remove(player); } } } }
src/main/java/com/nguyenquyhy/spongediscord/SpongeDiscord.java
package com.nguyenquyhy.spongediscord; import com.google.inject.Inject; import com.nguyenquyhy.spongediscord.commands.*; import com.nguyenquyhy.spongediscord.database.*; import com.nguyenquyhy.spongediscord.utils.ConfigUtil; import ninja.leaping.configurate.commented.CommentedConfigurationNode; import ninja.leaping.configurate.hocon.HoconConfigurationLoader; import ninja.leaping.configurate.loader.ConfigurationLoader; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.spongepowered.api.Game; import org.spongepowered.api.Sponge; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.GenericArguments; import org.spongepowered.api.command.source.CommandBlockSource; import org.spongepowered.api.command.source.ConsoleSource; import org.spongepowered.api.command.spec.CommandSpec; import org.spongepowered.api.config.ConfigDir; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.game.state.GamePreInitializationEvent; import org.spongepowered.api.event.game.state.GameStartedServerEvent; import org.spongepowered.api.event.game.state.GameStoppingServerEvent; import org.spongepowered.api.event.message.MessageChannelEvent; import org.spongepowered.api.event.network.ClientConnectionEvent; import org.spongepowered.api.plugin.Plugin; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.format.TextColors; import org.spongepowered.api.text.format.TextStyles; import org.spongepowered.api.text.serializer.TextSerializers; import sx.blah.discord.api.ClientBuilder; import sx.blah.discord.api.Event; import sx.blah.discord.api.IDiscordClient; import sx.blah.discord.api.IListener; import sx.blah.discord.handle.impl.events.GuildCreateEvent; import sx.blah.discord.handle.impl.events.MessageReceivedEvent; import sx.blah.discord.handle.impl.events.MessageSendEvent; import sx.blah.discord.handle.impl.events.ReadyEvent; import sx.blah.discord.handle.impl.obj.Invite; import sx.blah.discord.handle.obj.IChannel; import sx.blah.discord.handle.obj.IMessage; import sx.blah.discord.util.DiscordException; import sx.blah.discord.util.HTTP429Exception; import sx.blah.discord.util.MissingPermissionsException; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; /** * Created by Hy on 1/4/2016. */ @Plugin(id = "com.nguyenquyhy.spongediscord", name = "Sponge Discord", version = "1.2.0") public class SpongeDiscord { public static String DEBUG = ""; public static String BOT_TOKEN = ""; public static String CHANNEL_ID = ""; public static String INVITE_CODE = ""; public static String JOINED_MESSAGE = ""; public static String LEFT_MESSAGE = ""; public static String MESSAGE_DISCORD_TEMPLATE = ""; public static String MESSAGE_DISCORD_ANONYMOUS_TEMPLATE = ""; public static String MESSAGE_MINECRAFT_TEMPLATE = ""; public static String MESSAGE_DISCORD_SERVER_UP = ""; public static String MESSAGE_DISCORD_SERVER_DOWN = ""; public static String NONCE = "sponge-discord"; private static IDiscordClient consoleClient = null; private static final Map<UUID, IDiscordClient> clients = new HashMap<UUID, IDiscordClient>(); private static IDiscordClient defaultClient = null; private static Set<UUID> unauthenticatedPlayers = new HashSet<>(100); @Inject private Logger logger; @Inject @ConfigDir(sharedRoot = false) private Path configDir; @Inject private Game game; private MessageProvider messageProvider = new MessageProvider(); private IStorage storage; private static SpongeDiscord instance; @Listener public void onPreInitialization(GamePreInitializationEvent event) { instance = this; loadConfiguration(); } @Listener public void onServerStart(GameStartedServerEvent event) { CommandSpec defaultLoginCmd = CommandSpec.builder() .description(Text.of("Log in and set a Discord account for unauthenticated users")) .arguments( GenericArguments.onlyOne(GenericArguments.string(Text.of("email"))), GenericArguments.onlyOne(GenericArguments.string(Text.of("password")))) .executor(new DefaultLoginCommand()) .build(); CommandSpec defaultLogoutCmd = CommandSpec.builder() .description(Text.of("Log out of default Discord account")) .executor(new DefaultLogoutCommand()) .build(); CommandSpec defaultCmd = CommandSpec.builder() .permission("spongediscord.default") .description(Text.of("Commands to set/unset default Discord account for unauthenticated users")) .child(defaultLoginCmd, "login", "l") .child(defaultLogoutCmd, "logout", "lo") .build(); CommandSpec loginCmd = CommandSpec.builder() //.permission("spongediscord.login") .description(Text.of("Login to your Discord account and bind to current Minecraft account")) .arguments( GenericArguments.onlyOne(GenericArguments.string(Text.of("email"))), GenericArguments.onlyOne(GenericArguments.string(Text.of("password")))) .executor(new LoginCommand()) .build(); CommandSpec logoutCmd = CommandSpec.builder() //.permission("spongediscord.login") .description(Text.of("Logout of your Discord account and unbind from current Minecraft account")) .executor(new LogoutCommand()) .build(); CommandSpec reloadCmd = CommandSpec.builder() .permission("spongediscord.reload") .description(Text.of("Reload Sponge Discord configuration")) .executor(new ReloadCommand()) .build(); CommandSpec broadcastCmd = CommandSpec.builder() .permission("spongediscord.broadcast") .description(Text.of("Broadcast message to Discord and online Minecraft accounts")) .arguments(GenericArguments.onlyOne(GenericArguments.string(Text.of("message")))) .executor(new BroadcastCommand()) .build(); CommandSpec mainCommandSpec = CommandSpec.builder() //.permission("spongediscord") .description(Text.of("Discord in Minecraft")) .child(defaultCmd, "default", "d") .child(loginCmd, "login", "l") .child(logoutCmd, "logout", "lo") .child(reloadCmd, "reload") .child(broadcastCmd, "broadcast", "b") .build(); game.getCommandManager().register(this, mainCommandSpec, "discord", "d"); getLogger().info("/discord command registered."); String cachedToken = getStorage().getDefaultToken(); if (StringUtils.isNotBlank(BOT_TOKEN)) { getLogger().info("Logging in to bot Discord account..."); try { ClientBuilder clientBuilder = new ClientBuilder(); IDiscordClient client = clientBuilder.withToken(BOT_TOKEN).asBot().build(); prepareDefaultClient(client, null); client.login(); } catch (DiscordException e) { e.printStackTrace(); } } else if (StringUtils.isNotBlank(cachedToken)) { getLogger().info("Logging in to default Discord account..."); try { ClientBuilder clientBuilder = new ClientBuilder(); IDiscordClient client = clientBuilder.withToken(cachedToken).build(); prepareDefaultClient(client, null); client.login(); } catch (DiscordException e) { e.printStackTrace(); } } } @Listener public void onServerStop(GameStoppingServerEvent event) { if (defaultClient != null && defaultClient.isReady()) { IChannel channel = defaultClient.getChannelByID(CHANNEL_ID); if (channel != null) { try { channel.sendMessage(MESSAGE_DISCORD_SERVER_DOWN, NONCE, false); } catch (HTTP429Exception e) { e.printStackTrace(); } catch (DiscordException e) { e.printStackTrace(); } catch (MissingPermissionsException e) { e.printStackTrace(); } } } } @Listener public void onJoin(ClientConnectionEvent.Join event) throws URISyntaxException { Optional<Player> player = event.getCause().first(Player.class); if (player.isPresent()) { UUID playerId = player.get().getUniqueId(); boolean loggedIn = false; if (!clients.containsKey(playerId)) { String cachedToken = getStorage().getToken(playerId); if (null != cachedToken && !cachedToken.isEmpty()) { player.get().sendMessage(Text.of(TextColors.GRAY, "Logging in to Discord...")); try { ClientBuilder clientBuilder = new ClientBuilder(); IDiscordClient client = clientBuilder.withToken(cachedToken).build(); prepareClient(client, player.get()); client.login(); loggedIn = true; } catch (DiscordException e) { SpongeDiscord.getInstance().getLogger().error("Cannot login to Discord! " + e.getMessage()); } } } if (!loggedIn) { unauthenticatedPlayers.add(playerId); if (StringUtils.isNotBlank(JOINED_MESSAGE) && defaultClient != null && defaultClient.isReady()) { try { IChannel channel = defaultClient.getChannelByID(CHANNEL_ID); channel.sendMessage(String.format(JOINED_MESSAGE, player.get().getName()), NONCE, false); } catch (DiscordException e) { e.printStackTrace(); } catch (HTTP429Exception e) { e.printStackTrace(); } catch (MissingPermissionsException e) { e.printStackTrace(); } } } } } @Listener public void onDisconnect(ClientConnectionEvent.Disconnect event) throws IOException, HTTP429Exception, DiscordException, MissingPermissionsException { Optional<Player> player = event.getCause().first(Player.class); if (player.isPresent()) { UUID playerId = player.get().getUniqueId(); if (CHANNEL_ID != null && !CHANNEL_ID.isEmpty() && StringUtils.isNotBlank(LEFT_MESSAGE)) { IDiscordClient client = clients.get(playerId); if (client != null && client.isReady()) { IChannel channel = client.getChannelByID(CHANNEL_ID); channel.sendMessage(String.format(LEFT_MESSAGE, player.get().getName()), NONCE, false); } else if (defaultClient != null && defaultClient.isReady()) { IChannel channel = defaultClient.getChannelByID(CHANNEL_ID); channel.sendMessage(String.format(LEFT_MESSAGE, player.get().getName()), NONCE, false); } } removeAndLogoutClient(playerId); unauthenticatedPlayers.remove(playerId); getLogger().info(player.get().getName() + " has disconnected!"); } } @Listener public void onChat(MessageChannelEvent.Chat event) throws IOException, HTTP429Exception, DiscordException, MissingPermissionsException { if (CHANNEL_ID != null && !CHANNEL_ID.isEmpty()) { String plainString = event.getRawMessage().toPlain().trim(); if (StringUtils.isNotBlank(plainString) && !plainString.startsWith("/")) { Optional<Player> player = event.getCause().first(Player.class); if (player.isPresent()) { UUID playerId = player.get().getUniqueId(); if (clients.containsKey(playerId)) { IChannel channel = clients.get(playerId).getChannelByID(CHANNEL_ID); channel.sendMessage(String.format(MESSAGE_DISCORD_TEMPLATE, plainString), NONCE, false); } else if (defaultClient != null) { IChannel channel = defaultClient.getChannelByID(CHANNEL_ID); channel.sendMessage(String.format(MESSAGE_DISCORD_ANONYMOUS_TEMPLATE.replace("%a", player.get().getName()), plainString), NONCE, false); } } } } } public static SpongeDiscord getInstance() { return instance; } public Logger getLogger() { return logger; } public IStorage getStorage() { return storage; } public void loadConfiguration() { try { if (!Files.exists(configDir)) { Files.createDirectories(configDir); } Path configFile = Paths.get(configDir + "/config.conf"); ConfigurationLoader<CommentedConfigurationNode> configLoader = HoconConfigurationLoader.builder().setPath(configFile).build(); CommentedConfigurationNode configNode; if (!Files.exists(configFile)) { Files.createFile(configFile); getLogger().info("[Sponge-Discord]: Created default configuration, ConfigDatabase will not run until you have edited this file!"); } configNode = configLoader.load(); DEBUG = configNode.getNode("Debug").getString(); BOT_TOKEN = ConfigUtil.readString(configNode, "BotToken", ""); CHANNEL_ID = ConfigUtil.readString(configNode, "Channel", ""); INVITE_CODE = ConfigUtil.readString(configNode, "InviteCode", ""); JOINED_MESSAGE = ConfigUtil.readString(configNode, "JoinedMessageTemplate", "_%s just joined the server_"); LEFT_MESSAGE = ConfigUtil.readString(configNode, "LeftMessageTemplate", "_%s just left the server_"); MESSAGE_DISCORD_TEMPLATE = ConfigUtil.readString(configNode, "MessageInDiscordTemplate", "%s"); MESSAGE_DISCORD_ANONYMOUS_TEMPLATE = ConfigUtil.readString(configNode, "MessageInDiscordAnonymousTemplate", "_<%a>_ %s"); MESSAGE_MINECRAFT_TEMPLATE = ConfigUtil.readString(configNode, "MessageInMinecraftTemplate", "&7<%a> &f%s"); MESSAGE_DISCORD_SERVER_UP = ConfigUtil.readString(configNode, "MessageInDiscordServerUp", "Server has started."); MESSAGE_DISCORD_SERVER_DOWN = ConfigUtil.readString(configNode, "MessageInDiscordServerDown", "Server has stopped."); String tokenStore = ConfigUtil.readString(configNode, "TokenStore", "JSON"); configLoader.save(configNode); // TODO: exit if channel is empty if (StringUtils.isBlank(CHANNEL_ID)) { getLogger().error("Channel ID is not set!"); } switch (tokenStore) { case "InMemory": storage = new InMemoryStorage(); getLogger().info("Use InMemory storage."); break; case "JSON": storage = new JsonFileStorage(configDir); getLogger().info("Use JSON storage."); break; default: getLogger().warn("Invalid TokenStore config. JSON setting with be used!"); storage = new JsonFileStorage(configDir); break; } getLogger().info("Configuration loaded. Channel " + CHANNEL_ID); } catch (IOException e) { e.printStackTrace(); getLogger().error("[Sponge-Discord]: Couldn't create default configuration file!"); } } public void prepareClient(IDiscordClient client, CommandSource commandSource) { client.getDispatcher().registerListener(new IListener<ReadyEvent>() { @Override public void handle(ReadyEvent readyEvent) { try { String name = client.getOurUser().getName(); commandSource.sendMessage(Text.of(TextColors.GOLD, TextStyles.BOLD, "You have logged in to Discord account " + name + "!")); if (commandSource instanceof Player) { Player player = (Player) commandSource; UUID playerId = player.getUniqueId(); unauthenticatedPlayers.remove(playerId); SpongeDiscord.addClient(playerId, client); getStorage().putToken(playerId, client.getToken()); } else if (commandSource instanceof ConsoleSource) { commandSource.sendMessage(Text.of("WARNING: This Discord account will be used only for this console session!")); SpongeDiscord.addClient(null, client); } else if (commandSource instanceof CommandBlockSource) { commandSource.sendMessage(Text.of(TextColors.GREEN, "Account is valid!")); return; } if (CHANNEL_ID != null && !CHANNEL_ID.isEmpty()) { IChannel channel = client.getChannelByID(CHANNEL_ID); if (channel == null) { SpongeDiscord.getInstance().getLogger().info("Accepting channel invite"); acceptInvite(client); } else { channelJoined(client, channel, commandSource); } } } catch (IOException e) { e.printStackTrace(); } catch (DiscordException e) { e.printStackTrace(); } catch (HTTP429Exception e) { e.printStackTrace(); } catch (MissingPermissionsException e) { e.printStackTrace(); } } }); client.getDispatcher().registerListener(new IListener<MessageSendEvent>() { @Override public void handle(MessageSendEvent event) { handleMessageReceivedEvent(event.getMessage(), commandSource); } }); client.getDispatcher().registerListener(new IListener<MessageReceivedEvent>() { @Override public void handle(MessageReceivedEvent event) { handleMessageReceivedEvent(event.getMessage(), commandSource); } }); client.getDispatcher().registerListener(new IListener<GuildCreateEvent>() { @Override public void handle(GuildCreateEvent event) { handleGuildCreateEvent(event, client, commandSource); } }); } public void prepareDefaultClient(IDiscordClient client, CommandSource commandSource) { client.getDispatcher().registerListener(new IListener<ReadyEvent>() { @Override public void handle(ReadyEvent readyEvent) { try { String name = client.getOurUser().getName(); String text = "Discord account " + name + " will be used for all unauthenticated users!"; if (commandSource != null) commandSource.sendMessage(Text.of(TextColors.GOLD, TextStyles.BOLD, text)); else getLogger().info(text); defaultClient = client; getStorage().putDefaultToken(client.getToken()); if (CHANNEL_ID != null && !CHANNEL_ID.isEmpty()) { IChannel channel = client.getChannelByID(CHANNEL_ID); if (channel == null) { getLogger().info("Accepting channel invite for default account..."); acceptInvite(client); } else { channelJoined(client, channel, commandSource); } } } catch (IOException e) { e.printStackTrace(); } catch (DiscordException e) { e.printStackTrace(); } catch (HTTP429Exception e) { e.printStackTrace(); } catch (MissingPermissionsException e) { e.printStackTrace(); } } }); client.getDispatcher().registerListener(new IListener<MessageSendEvent>() { @Override public void handle(MessageSendEvent event) { handleMessageReceivedEvent(event.getMessage(), commandSource); } }); client.getDispatcher().registerListener(new IListener<MessageReceivedEvent>() { @Override public void handle(MessageReceivedEvent messageReceivedEvent) { handleMessageReceivedEvent(messageReceivedEvent.getMessage(), null); } }); client.getDispatcher().registerListener(new IListener<GuildCreateEvent>() { @Override public void handle(GuildCreateEvent guildCreateEvent) { handleGuildCreateEvent(guildCreateEvent, client, commandSource); } }); } public static CommandResult logoutDefault(CommandSource commandSource) throws IOException, HTTP429Exception, DiscordException { if (defaultClient != null) { defaultClient.logout(); defaultClient = null; getInstance().getStorage().removeDefaultToken(); if (commandSource != null) { commandSource.sendMessage(Text.of(TextColors.YELLOW, "Default Discord account is removed.")); } } return CommandResult.success(); } public static CommandResult login(CommandSource commandSource, String email, String password, boolean defaultAccount) { if (defaultAccount) { if (defaultClient != null) { try { defaultClient.logout(); commandSource.sendMessage(Text.of("Logged out of current default account.")); } catch (HTTP429Exception e) { e.printStackTrace(); } catch (DiscordException e) { e.printStackTrace(); } } } else { logout(commandSource, true); } IDiscordClient client = null; try { ClientBuilder clientBuilder = new ClientBuilder().withLogin(email, password); client = clientBuilder.build(); if (defaultAccount) SpongeDiscord.getInstance().prepareDefaultClient(client, commandSource); else SpongeDiscord.getInstance().prepareClient(client, commandSource); client.login(); } catch (DiscordException e) { e.printStackTrace(); } if (client.getToken() != null) { return CommandResult.success(); } else { commandSource.sendMessage(Text.of(TextColors.RED, "Invalid username and/or password!")); return CommandResult.empty(); } } public static CommandResult logout(CommandSource commandSource, boolean isSilence) { if (commandSource instanceof Player) { Player player = (Player) commandSource; UUID playerId = player.getUniqueId(); try { SpongeDiscord.getInstance().getStorage().removeToken(playerId); } catch (IOException e) { e.printStackTrace(); commandSource.sendMessage(Text.of(TextColors.RED, "Cannot remove cached token!")); } SpongeDiscord.removeAndLogoutClient(playerId); unauthenticatedPlayers.add(player.getUniqueId()); if (!isSilence) commandSource.sendMessage(Text.of(TextColors.YELLOW, "Logged out of Discord!")); return CommandResult.success(); } else if (commandSource instanceof ConsoleSource) { SpongeDiscord.removeAndLogoutClient(null); commandSource.sendMessage(Text.of("Logged out of Discord!")); return CommandResult.success(); } else if (commandSource instanceof CommandBlockSource) { commandSource.sendMessage(Text.of(TextColors.YELLOW, "Cannot log out from command blocks!")); return CommandResult.empty(); } return CommandResult.empty(); } public static CommandResult broadcast(CommandSource commandSource, String message) throws IOException, HTTP429Exception, DiscordException, MissingPermissionsException { if (CHANNEL_ID != null && !CHANNEL_ID.isEmpty()) { if (defaultClient == null) { commandSource.sendMessage(Text.of(TextColors.RED, "You have to set up a default account first!")); return CommandResult.empty(); } IChannel channel = defaultClient.getChannelByID(CHANNEL_ID); channel.sendMessage(String.format(MESSAGE_DISCORD_TEMPLATE, "_<Broadcast>_ " + message), NONCE, false); Collection<Player> players = Sponge.getServer().getOnlinePlayers(); for (Player player : players) { player.sendMessage(Text.of(TextStyles.ITALIC, "<Broadcast> " + message)); } } return CommandResult.success(); } private void handleMessageReceivedEvent(IMessage message, CommandSource commandSource) { if (message.getChannel().getID().equals(CHANNEL_ID) && !NONCE.equals(message.getNonce())) { String content = message.getContent(); String author = message.getAuthor().getName(); Text formattedMessage = TextSerializers.FORMATTING_CODE.deserialize(String.format(MESSAGE_MINECRAFT_TEMPLATE.replace("%a", author), content)); if (commandSource != null) { commandSource.sendMessage(formattedMessage); } else { // This case is used for default account for (UUID playerUUID : unauthenticatedPlayers) { Optional<Player> player = Sponge.getServer().getPlayer(playerUUID); if (player.isPresent()) { player.get().sendMessage(formattedMessage); } } } } } private IChannel acceptInvite(IDiscordClient client) { if (INVITE_CODE != null && !INVITE_CODE.isEmpty()) { Invite invite = new Invite(client, INVITE_CODE, null); try { invite.accept(); return client.getChannelByID(CHANNEL_ID); } catch (Exception e) { getLogger().error("Cannot accept invitation " + INVITE_CODE); e.printStackTrace(); } } return null; } private void handleGuildCreateEvent(GuildCreateEvent event, IDiscordClient client, CommandSource commandSource) { IChannel channel = event.getGuild().getChannelByID(CHANNEL_ID); try { channelJoined(client, channel, commandSource); } catch (IOException e) { e.printStackTrace(); } catch (DiscordException e) { e.printStackTrace(); } catch (HTTP429Exception e) { e.printStackTrace(); } catch (MissingPermissionsException e) { e.printStackTrace(); } } private void channelJoined(IDiscordClient client, IChannel channel, CommandSource src) throws IOException, HTTP429Exception, DiscordException, MissingPermissionsException { if (channel != null) { if (client != defaultClient) { String playerName = "console"; if (src instanceof Player) { Player player = (Player) src; playerName = player.getName(); } if (JOINED_MESSAGE != null) channel.sendMessage(String.format(JOINED_MESSAGE, playerName), NONCE, false); getLogger().info(playerName + " connected to Discord channel."); } else { getLogger().info("Default account has connected to Discord channel."); if (StringUtils.isNotBlank(MESSAGE_DISCORD_SERVER_UP)) channel.sendMessage(MESSAGE_DISCORD_SERVER_UP, NONCE, false); } } } private static void addClient(UUID player, IDiscordClient client) { if (player == null) { consoleClient = client; } else { clients.put(player, client); } } private static void removeAndLogoutClient(UUID player) { if (player == null) { try { consoleClient.logout(); } catch (HTTP429Exception e) { e.printStackTrace(); } catch (DiscordException e) { e.printStackTrace(); } consoleClient = null; } else { if (clients.containsKey(player)) { IDiscordClient client = clients.get(player); if (client.isReady()) { try { client.logout(); } catch (HTTP429Exception e) { e.printStackTrace(); } catch (DiscordException e) { e.printStackTrace(); } } clients.remove(player); } } } }
Support player name with _
src/main/java/com/nguyenquyhy/spongediscord/SpongeDiscord.java
Support player name with _
Java
mit
0c02a854f8c7d6905d972ba122984897a687d065
0
bigown/SOpt,bigown/SOpt,maniero/SOpt,maniero/SOpt,maniero/SOpt,bigown/SOpt,maniero/SOpt,bigown/SOpt,maniero/SOpt,bigown/SOpt,maniero/SOpt,maniero/SOpt,maniero/SOpt,maniero/SOpt,maniero/SOpt,maniero/SOpt,bigown/SOpt,maniero/SOpt,bigown/SOpt,bigown/SOpt,maniero/SOpt,maniero/SOpt,bigown/SOpt,maniero/SOpt,bigown/SOpt,maniero/SOpt
import java.util.*; public class Estudos{ public static void main(String[] args) { String palavra = "Java"; Scanner in = new Scanner(System.in); System.out.print("Informe um inteiro: "); int indice = in.nextInt(); try { System.out.println("O caractere no índice informado é " + palavra.charAt(indice)); } catch(StringIndexOutOfBoundsException e) { System.out.println("Erro:" + e.getMessage()); } } } //http://pt.stackoverflow.com/q/17025/101
Java/Exception/throws.java
import java.util.*; public class Estudos{ public static void main(String[] args){ String palavra = "Java"; Scanner in = new Scanner(System.in); System.out.print("Informe um inteiro: "); int indice = in.nextInt(); try { System.out.println("O caractere no índice " + "informado é " + palavra.charAt(indice)); } catch(StringIndexOutOfBoundsException e) { System.out.println("Erro:" + e.getMessage()); } } } //http://pt.stackoverflow.com/q/17025/101
http://pt.stackoverflow.com/q/17025/101
Java/Exception/throws.java
http://pt.stackoverflow.com/q/17025/101
Java
mit
fb8958f0af5a0a3e7c17760ce7860cd6c3bf4a6a
0
restfb/restfb
/* * Copyright (c) 2010 Mark Allen. * * 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.restfb.util; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * A collection of reflection-related utility methods. * * @author <a href="http://restfb.com">Mark Allen</a> * @author ikabiljo * @author ScottHernandez * * @since 1.6 */ public final class ReflectionUtils { private static final Map<PairForCaching, List<?>> FIELDS_WITH_ANNOTATION_CACHE = Collections.synchronizedMap(new HashMap<PairForCaching, List<?>>()); /** * Prevents instantiation. */ private ReflectionUtils() {} /** * Is the given {@code object} a primitive type or wrapper for a primitive * type? * * @param object * The object to check for primitive-ness. * @return {@code true} if {@code object} is a primitive type or wrapper for a * primitive type, {@code false} otherwise. */ public static boolean isPrimitive(Object object) { if (object == null) return false; Class<?> type = object.getClass(); return object instanceof String || (object instanceof Integer || Integer.TYPE.equals(type)) || (object instanceof Boolean || Boolean.TYPE.equals(type)) || (object instanceof Long || Long.TYPE.equals(type)) || (object instanceof Double || Double.TYPE.equals(type)) || (object instanceof Float || Float.TYPE.equals(type)) || (object instanceof Byte || Byte.TYPE.equals(type)) || (object instanceof Short || Short.TYPE.equals(type)) || (object instanceof Character || Character.TYPE.equals(type)); } /** * Finds fields on the given {@code type} and all of its superclasses * annotated with annotations of type {@code annotationType}. * * @param <T> * The annotation type. * @param type * The target type token. * @param annotationType * The annotation type token. * @return A list of field/annotation pairs. */ public static <T extends Annotation> List<FieldWithAnnotation<T>> findFieldsWithAnnotation( Class<?> type, Class<T> annotationType) { PairForCaching pairForCaching = new PairForCaching(type, annotationType); @SuppressWarnings("unchecked") List<FieldWithAnnotation<T>> cachedResults = (List<FieldWithAnnotation<T>>) FIELDS_WITH_ANNOTATION_CACHE .get(pairForCaching); if (cachedResults != null) return cachedResults; List<FieldWithAnnotation<T>> fieldsWithAnnotation = new ArrayList<FieldWithAnnotation<T>>(); // Walk all superclasses looking for annotated fields until we hit // Object while (!Object.class.equals(type)) { for (Field field : type.getDeclaredFields()) { T annotation = field.getAnnotation(annotationType); if (annotation != null) fieldsWithAnnotation .add(new FieldWithAnnotation<T>(field, annotation)); } type = type.getSuperclass(); } fieldsWithAnnotation = Collections.unmodifiableList(fieldsWithAnnotation); FIELDS_WITH_ANNOTATION_CACHE.put(pairForCaching, fieldsWithAnnotation); return fieldsWithAnnotation; } /** * Gets all accessor methods for the given {@code clazz}. * * @param clazz * The class for which accessors are extracted. * @return All accessor methods for the given {@code clazz}. */ public static List<Method> getAccessors(Class<?> clazz) { if (clazz == null) throw new IllegalArgumentException( "The 'clazz' parameter cannot be null."); List<Method> methods = new ArrayList<Method>(); for (Method method : clazz.getMethods()) { String methodName = method.getName(); if (!"getClass".equals(methodName) && !"hashCode".equals(methodName) && method.getReturnType() != null && !Void.class.equals(method.getReturnType()) && method.getParameterTypes().length == 0 && ((methodName.startsWith("get") && methodName.length() > 3) || (methodName.startsWith("is") && methodName.length() > 2) || (methodName .startsWith("has") && methodName.length() > 3))) methods.add(method); } // Order the methods alphabetically by name Collections.sort(methods, new Comparator<Method>() { /** * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ @Override public int compare(Method method1, Method method2) { return method1.getName().compareTo(method2.getName()); } }); return Collections.unmodifiableList(methods); } /** * Reflection-based implementation of {@link Object#toString()}. * * @param object * The object to convert to a string representation. * @return A string representation of {@code object}. * @throws IllegalStateException * If an error occurs while performing reflection operations. */ public static String toString(Object object) { StringBuilder buffer = new StringBuilder(object.getClass().getSimpleName()); buffer.append("["); boolean first = true; for (Method method : getAccessors(object.getClass())) { if (first) first = false; else buffer.append(" "); try { String methodName = method.getName(); int offset = methodName.startsWith("is") ? 2 : 3; methodName = methodName.substring(offset, offset + 1).toLowerCase() + methodName.substring(offset + 1); buffer.append(methodName); buffer.append("="); // Accessors are guaranteed to take no parameters and return a value buffer.append(method.invoke(object)); } catch (Exception e) { throw new IllegalStateException("Unable to reflectively invoke " + method + " on " + object.getClass(), e); } } buffer.append("]"); return buffer.toString(); } /** * Reflection-based implementation of {@link Object#hashCode()}. * * @param object * The object to hash. * @return A hashcode for {@code object}. * @throws IllegalStateException * If an error occurs while performing reflection operations. */ public static int hashCode(Object object) { if (object == null) return 0; int hashCode = 17; for (Method method : getAccessors(object.getClass())) { try { Object result = method.invoke(object); if (result != null) hashCode = hashCode * 31 + result.hashCode(); } catch (Exception e) { throw new IllegalStateException("Unable to reflectively invoke " + method + " on " + object, e); } } return hashCode; } /** * Reflection-based implementation of {@link Object#equals(Object)}. * * @param object1 * One object to compare. * @param object2 * Another object to compare. * @return {@code true} if the objects are equal, {@code false} otherwise. * @throws IllegalStateException * If an error occurs while performing reflection operations. */ public static boolean equals(Object object1, Object object2) { if (object1 == null && object2 == null) return true; if (!(object1 != null && object2 != null)) return false; // Bail if the classes aren't at least one-way assignable to each other if (!(object1.getClass().isInstance(object2) || object2.getClass() .isInstance(object1))) return false; // Only compare accessors that are present in both classes Set<Method> accessorMethodsIntersection = new HashSet<Method>(getAccessors(object1.getClass())); accessorMethodsIntersection.retainAll(getAccessors(object2.getClass())); for (Method method : accessorMethodsIntersection) { try { Object result1 = method.invoke(object1); Object result2 = method.invoke(object2); if (result1 == null && result2 == null) continue; if (!(result1 != null && result2 != null)) return false; if (!result1.equals(result2)) return false; } catch (Exception e) { throw new IllegalStateException("Unable to reflectively invoke " + method, e); } } return true; } /** * A field/annotation pair. * * @author <a href="http://restfb.com">Mark Allen</a> */ public static class FieldWithAnnotation<T extends Annotation> { /** * A field. */ private Field field; /** * An annotation on the field. */ private T annotation; /** * Creates a field/annotation pair. * * @param field * A field. * @param annotation * An annotation on the field. */ public FieldWithAnnotation(Field field, T annotation) { this.field = field; this.annotation = annotation; } /** * Gets the field. * * @return The field. */ public Field getField() { return field; } /** * Gets the annotation on the field. * * @return The annotation on the field. */ public T getAnnotation() { return annotation; } /** * @see java.lang.Object#toString() */ @Override public String toString() { return String.format("Field %s.%s (%s): %s", field.getDeclaringClass() .getName(), field.getName(), field.getType(), annotation); } } /** * * @author ikabiljo */ private static final class PairForCaching { private final Class<?> clazz; private final Class<? extends Annotation> annotation; /** * * @param clazz * @param annotation */ public PairForCaching(Class<?> clazz, Class<? extends Annotation> annotation) { this.clazz = clazz; this.annotation = annotation; } /** * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (annotation == null ? 0 : annotation.hashCode()); result = prime * result + (clazz == null ? 0 : clazz.hashCode()); return result; } /** * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PairForCaching other = (PairForCaching) obj; if (annotation == null) { if (other.annotation != null) return false; } else if (!annotation.equals(other.annotation)) { return false; } if (clazz == null) { if (other.clazz != null) return false; } else if (!clazz.equals(other.clazz)) { return false; } return true; } } }
RestFB/source/library/com/restfb/util/ReflectionUtils.java
/* * Copyright (c) 2010 Mark Allen. * * 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.restfb.util; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; /** * A collection of reflection-related utility methods. * * @author <a href="http://restfb.com">Mark Allen</a> * @author ScottHernandez * @since 1.6 */ public final class ReflectionUtils { /** * Prevents instantiation. */ private ReflectionUtils() {} /** * Is the given {@code object} a primitive type or wrapper for a primitive * type? * * @param object * The object to check for primitive-ness. * @return {@code true} if {@code object} is a primitive type or wrapper for a * primitive type, {@code false} otherwise. */ public static boolean isPrimitive(Object object) { if (object == null) return false; Class<?> type = object.getClass(); return object instanceof String || (object instanceof Integer || Integer.TYPE.equals(type)) || (object instanceof Boolean || Boolean.TYPE.equals(type)) || (object instanceof Long || Long.TYPE.equals(type)) || (object instanceof Double || Double.TYPE.equals(type)) || (object instanceof Float || Float.TYPE.equals(type)) || (object instanceof Byte || Byte.TYPE.equals(type)) || (object instanceof Short || Short.TYPE.equals(type)) || (object instanceof Character || Character.TYPE.equals(type)); } /** * Finds fields on the given {@code type} and all of its superclasses * annotated with annotations of type {@code annotationType}. * * @param <T> * The annotation type. * @param type * The target type token. * @param annotationType * The annotation type token. * @return A list of field/annotation pairs. */ public static <T extends Annotation> List<FieldWithAnnotation<T>> findFieldsWithAnnotation( Class<?> type, Class<T> annotationType) { // TODO: cache off results per type instead of reflecting every time List<FieldWithAnnotation<T>> fieldsWithAnnotation = new ArrayList<FieldWithAnnotation<T>>(); // Walk all superclasses looking for annotated fields until we hit // Object while (!Object.class.equals(type)) { for (Field field : type.getDeclaredFields()) { T annotation = field.getAnnotation(annotationType); if (annotation != null) fieldsWithAnnotation .add(new FieldWithAnnotation<T>(field, annotation)); } type = type.getSuperclass(); } return Collections.unmodifiableList(fieldsWithAnnotation); } /** * Gets all accessor methods for the given {@code clazz}. * * @param clazz * The class for which accessors are extracted. * @return All accessor methods for the given {@code clazz}. */ public static List<Method> getAccessors(Class<?> clazz) { if (clazz == null) throw new IllegalArgumentException( "The 'clazz' parameter cannot be null."); List<Method> methods = new ArrayList<Method>(); for (Method method : clazz.getMethods()) { String methodName = method.getName(); if (!"getClass".equals(methodName) && !"hashCode".equals(methodName) && method.getReturnType() != null && !Void.class.equals(method.getReturnType()) && method.getParameterTypes().length == 0 && ((methodName.startsWith("get") && methodName.length() > 3) || (methodName.startsWith("is") && methodName.length() > 2) || (methodName .startsWith("has") && methodName.length() > 3))) methods.add(method); } // Order the methods alphabetically by name Collections.sort(methods, new Comparator<Method>() { /** * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ @Override public int compare(Method method1, Method method2) { return method1.getName().compareTo(method2.getName()); } }); return Collections.unmodifiableList(methods); } /** * TODO: document and test * * @param <T> * @param type * @param annotationType * @return */ public static <T extends Annotation> List<MethodWithAnnotation<T>> findMethodsWithAnnotation( Class<?> type, Class<T> annotationType) { // TODO: cache off results per type instead of reflecting every time List<MethodWithAnnotation<T>> methodsWithAnnotation = new ArrayList<MethodWithAnnotation<T>>(); // Walk all superclasses looking for annotated methods until we hit // Object while (!Object.class.equals(type)) { if (type == null) break; for (Method method : type.getDeclaredMethods()) { T annotation = method.getAnnotation(annotationType); if (annotation != null) methodsWithAnnotation.add(new MethodWithAnnotation<T>(method, annotation)); } type = type.getSuperclass(); } return Collections.unmodifiableList(methodsWithAnnotation); } /** * Get the (first) class that parameterizes the Field supplied. * * TODO: finish docs, test * * @param field * the field * @return the class that parameterizes the field, or null if field is not * parameterized */ public static Class<?> getParameterizedClass(final Field field) { return getParameterizedClass(field, 0); } /** * Get the class that parameterizes the Field supplied, at the index supplied * (field can be parameterized with multiple param classes). * * TODO: finish docs, test * * @param field * the field * @param index * the index of the parameterizing class * @return the class that parameterizes the field, or null if field is not * parameterized */ public static Class<?> getParameterizedClass(final Field field, final int index) { if (field.getGenericType() instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType) field.getGenericType(); if ((ptype.getActualTypeArguments() != null) && (ptype.getActualTypeArguments().length <= index)) { return null; } Type paramType = ptype.getActualTypeArguments()[index]; if (paramType instanceof GenericArrayType) { Class<?> arrayType = (Class<?>) ((GenericArrayType) paramType).getGenericComponentType(); return Array.newInstance(arrayType, 0).getClass(); } else { if (paramType instanceof ParameterizedType) { ParameterizedType paramPType = (ParameterizedType) paramType; return (Class<?>) paramPType.getRawType(); } else { if (paramType instanceof TypeVariable<?>) { // TODO: Figure out what to do... Walk back up the to // the parent class and try to get the variable type // from the T/V/X throw new RuntimeException("Generic Typed Class not supported: <" + ((TypeVariable<?>) paramType).getName() + "> = " + ((TypeVariable<?>) paramType).getBounds()[0]); } else if (paramType instanceof Class<?>) { return (Class<?>) paramType; } else { throw new RuntimeException( "Unknown type... pretty bad... call for help, wave your hands... yeah!"); } } } } return null; } /** * Reflection-based implementation of {@link Object#toString()}. * * @param object * The object to convert to a string representation. * @return A string representation of {@code object}. * @throws IllegalStateException * If an error occurs while performing reflection operations. */ public static String toString(Object object) { StringBuilder buffer = new StringBuilder(object.getClass().getSimpleName()); buffer.append("["); boolean first = true; for (Method method : getAccessors(object.getClass())) { if (first) first = false; else buffer.append(" "); try { String methodName = method.getName(); int offset = methodName.startsWith("is") ? 2 : 3; methodName = methodName.substring(offset, offset + 1).toLowerCase() + methodName.substring(offset + 1); buffer.append(methodName); buffer.append("="); // Accessors are guaranteed to take no parameters and return a value buffer.append(method.invoke(object)); } catch (Exception e) { throw new IllegalStateException("Unable to reflectively invoke " + method + " on " + object.getClass(), e); } } buffer.append("]"); return buffer.toString(); } /** * Reflection-based implementation of {@link Object#hashCode()}. * * @param object * The object to hash. * @return A hashcode for {@code object}. * @throws IllegalStateException * If an error occurs while performing reflection operations. */ public static int hashCode(Object object) { if (object == null) return 0; int hashCode = 17; for (Method method : getAccessors(object.getClass())) { try { Object result = method.invoke(object); if (result != null) hashCode = hashCode * 31 + result.hashCode(); } catch (Exception e) { throw new IllegalStateException("Unable to reflectively invoke " + method + " on " + object, e); } } return hashCode; } /** * Reflection-based implementation of {@link Object#equals(Object)}. * * @param object1 * One object to compare. * @param object2 * Another object to compare. * @return {@code true} if the objects are equal, {@code false} otherwise. * @throws IllegalStateException * If an error occurs while performing reflection operations. */ public static boolean equals(Object object1, Object object2) { if (object1 == null && object2 == null) return true; if (!(object1 != null && object2 != null)) return false; // Bail if the classes aren't at least one-way assignable to each other if (!(object1.getClass().isInstance(object2) || object2.getClass() .isInstance(object1))) return false; // Only compare accessors that are present in both classes Set<Method> accessorMethodsIntersection = new HashSet<Method>(getAccessors(object1.getClass())); accessorMethodsIntersection.retainAll(getAccessors(object2.getClass())); for (Method method : accessorMethodsIntersection) { try { Object result1 = method.invoke(object1); Object result2 = method.invoke(object2); if (result1 == null && result2 == null) continue; if (!(result1 != null && result2 != null)) return false; if (!result1.equals(result2)) return false; } catch (Exception e) { throw new IllegalStateException("Unable to reflectively invoke " + method, e); } } return true; } /** * A field/annotation pair. * * @author <a href="http://restfb.com">Mark Allen</a> */ public static class FieldWithAnnotation<T extends Annotation> { /** * A field. */ private Field field; /** * An annotation on the field. */ private T annotation; /** * Creates a field/annotation pair. * * @param field * A field. * @param annotation * An annotation on the field. */ public FieldWithAnnotation(Field field, T annotation) { this.field = field; this.annotation = annotation; } /** * Gets the field. * * @return The field. */ public Field getField() { return field; } /** * Gets the annotation on the field. * * @return The annotation on the field. */ public T getAnnotation() { return annotation; } /** * @see java.lang.Object#toString() */ @Override public String toString() { return String.format("Field %s.%s (%s): %s", field.getDeclaringClass() .getName(), field.getName(), field.getType(), annotation); } } /** * A method/annotation pair. * * @author ScottHernandez */ public static class MethodWithAnnotation<T extends Annotation> { /** * A method. */ private Method method; /** * An annotation on the method. */ private T annotation; /** * Creates a method/annotation pair. * * @param method * A method. * @param annotation * An annotation on the method. */ public MethodWithAnnotation(Method method, T annotation) { this.method = method; this.annotation = annotation; } /** * Gets the method. * * @return The method. */ public Method getMethod() { return method; } /** * Gets the annotation on the method. * * @return The annotation on the method. */ public T getAnnotation() { return annotation; } /** * @see java.lang.Object#toString() */ @Override public String toString() { return String.format("Method %s %s.%s : %s", method.getReturnType(), method.getDeclaringClass().getName(), method.getName(), annotation); } } }
1.6 - Issue 69: Performance optimization - caching results from reflection. Thanks to ikabiljo
RestFB/source/library/com/restfb/util/ReflectionUtils.java
1.6 - Issue 69: Performance optimization - caching results from reflection. Thanks to ikabiljo
Java
mit
da53f7d3d51f3a4e80b47d59da3fe0aa41e973aa
0
markovandooren/rejuse,markovandooren/rejuse
package be.kuleuven.cs.distrinet.rejuse.predicate; import be.kuleuven.cs.distrinet.rejuse.action.Nothing; /** * A convenience class of predicate thay do not throw exceptions. * * @deprecated Simply use Nothing as the exception parameter. Lack of * Multiple inheritance makes SafePredicate too annoying to use. * @author Marko van Dooren */ public abstract class SafePredicate<T> extends AbstractPredicate<T,Nothing> { }
src/be/kuleuven/cs/distrinet/rejuse/predicate/SafePredicate.java
package be.kuleuven.cs.distrinet.rejuse.predicate; import be.kuleuven.cs.distrinet.rejuse.action.Nothing; /** * A convenience class of predicate thay do not throw exceptions. * * @author Marko van Dooren */ public abstract class SafePredicate<T> extends AbstractPredicate<T,Nothing> { }
Made SafePredicate @deprecated
src/be/kuleuven/cs/distrinet/rejuse/predicate/SafePredicate.java
Made SafePredicate @deprecated
Java
epl-1.0
07d3cad9680b7c01c934d2abd65489d2ddb75c4b
0
CyberdyneOfCerrado/Backups
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. * Erick Batista do Nascimento */ package GUI; import iteradores.IteradorBackups; import java.awt.Color; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Frame; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; import java.awt.Dimension; import java.io.File; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.JScrollBar; import enuns.DiasSemana; import objetos.Backup; import objetos.Dias; import objetos.RegraBackup; import nucleo.Core; import bancoDeDados.CarregaBanco; /** * * @author erick7 */ public class GuiMain extends JFrame { /** * */ private static final long serialVersionUID = 1L; FundoJpane imgc; public static boolean isCancelado=false; private boolean controle; private JPanel fundo; private int screenX,screenY; private int tempx,tempy; private TJtextArea cdic; private JLabel t1; private JLabel textoTile1; private JLabel textoTile3; private JLabel textoTile4; private JButton tile1; private JButton tile3; private JButton tile4; private TJtextField cnome; static private JScrollPane scr; private TJtextField cbac; private boolean flag=false; private JLabel tlv; private TJlabel tp1; private TJlabel tl1,tl2,tl3; private JButton Search; private JButton Searchs; private JButton conf; private JButton age; private JLabel tla; private TJlabel tpa; private JPanel dia; private JButton seg; private JButton ter; private JButton quar; private JButton quin; private JButton sex; private JButton sab; private JButton dom; private FundoJpane horas; private TJbutton h0; private TJbutton h1; private TJbutton h2; private TJbutton h3; private TJbutton h4; private TJbutton h5; private TJbutton h6; private TJbutton h7; private TJbutton h8; private TJbutton h9; private TJbutton h10; private TJbutton h11; private TJbutton h12; private TJbutton h13; private TJbutton h14; private TJbutton h15; private TJbutton h16; private TJbutton h17; private TJbutton h18; private TJbutton h19; private TJbutton h20; private TJbutton h21; private TJbutton h22; private TJbutton h23; private FundoJpane minutos; private TJbutton m0; private TJbutton m1; private TJbutton m3; private TJbutton m2; private TJbutton m4; private TJbutton m5; private TJbutton m6; private TJbutton m7; private TJbutton m8; private TJbutton m9; private TJbutton m10; private TJbutton m11; private TJbutton m12; private TJbutton m13; private TJbutton m14; private TJbutton m15; private TJbutton m16; private TJbutton m17; private TJbutton m18; private TJbutton m19; private TJbutton m20; private TJbutton m21; private TJbutton m22; private TJbutton m23; private TJbutton m24; private TJbutton m25; private TJbutton m26; private TJbutton m27; private TJbutton m28; private TJbutton m29; private TJbutton m31; private TJbutton m32; private TJbutton m33; private TJbutton m34; private TJbutton m35; private TJbutton m36; private TJbutton m30; private TJbutton m37; private TJbutton m38; private TJbutton m39; private TJbutton m40; private TJbutton m41; private TJbutton m42; private TJbutton m43; private TJbutton m44; private TJbutton m45; private TJbutton m46; private TJbutton m48; private TJbutton m47; private TJbutton m49; private TJbutton m50; private TJbutton m51; private TJbutton m52; private TJbutton m53; private TJbutton m54; private TJbutton m55; private TJbutton m56; private TJbutton m57; private TJbutton m58; private TJbutton m59; private JScrollPane scrolldia; private TJbutton diau; private TJbutton diad; private TJlabel lbdia; private TJlabel lbdh; private JScrollPane scrollHora; private TJbutton hu; private TJbutton hd; private TJbutton mu; private TJbutton md; private JScrollPane scrollMinutos; private TJlabel lbm; private TJbutton confa; private FundoJpane ld; private FundoJpane lh; private FundoJpane lm; private Core core; private Backup B; private RegraBackup R; private Dias D; private TJcheck check; private JScrollPane scrollRegra; private TJbutton cancela; private TJbutton fechar; private FundoJpane imgci; GuiMain() { setUndecorated(true); setResizable(false); setSize(800,500); setBackground(new Color(0, 0, 0, 0)); setLocationRelativeTo(null); constroiFrame(); core = new Core(); } //Elementos do JFrame que sustentam a janela private void constroiFrame () { //montando estrutura de fundo ImageIcon icf = new ImageIcon(getClass().getResource("/GUI/Imagens/load.gif")); Image imf = icf.getImage(); fundo=new FundoJpane(imf,0,0,0,0); fundo.setLayout(null); fundo.setBounds(0,0,800,500); fundo.addMouseListener(new AcaoCoordenadasFrameMovimentacao()); fundo.addMouseMotionListener(new AcaoCoordenadasTelaMovimentacao()); add(fundo); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); this.setIconImage(null); setVisible(true); controleTelaLoading(); //fim fundo } private void constroiFundoFrame(){ setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ImageIcon icf = new ImageIcon(getClass().getResource("/GUI/Imagens/Jfundo.png")); Image imf = icf.getImage(); ((FundoJpane) fundo).alterarImagem(imf); fechar = new TJbutton("X",0,0,0,0); fechar.setBounds(767,6,16,25); fechar.addActionListener(new AcaoFechar()); fechar.setContentAreaFilled(false); fechar.setOpaque(false); fechar.setForeground(Color.BLACK); fechar.setFont(new Font("Consolas",Font.BOLD,18)); fechar.setBorderPainted(false); fundo.add(fechar); JButton min = new TJbutton("-",0,0,0,0); min.setBounds(748,2,16,25); min.addActionListener(new AcaoMinimizar()); min.setContentAreaFilled(false); min.setOpaque(false); min.setForeground(Color.BLACK); min.setFont(new Font("Consolas",Font.BOLD,32)); min.setBorderPainted(false); fundo.add(min); //tela inicio telaInicio(); } private void controleTelaLoading(){ CarregaBanco b = new CarregaBanco(); if(b.inciaBanco())constroiFundoFrame(); } //tela incial comea aqui private void telaInicio() { t1=new TJlabel("Incio",0,0,0,0); t1.setFont(new Font("CordiaUPC",Font.PLAIN,83)); t1.setForeground(Color.BLACK); textoTile1=new TJlabel("Novo backup",0,0,0,0); textoTile1.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,31)); textoTile1.setForeground(Color.BLACK); ImageIcon tl1i = new ImageIcon(getClass().getResource("/GUI/Imagens/NovoBackup.png")); tile1=new TJbutton("",0,0,0,0); tile1.setIcon(tl1i); tile1.addActionListener(new AcaoNovoCadastro()); ImageIcon tl3i = new ImageIcon(getClass().getResource("/GUI/Imagens/rodaRegra.png")); tile3=new TJbutton("",0,0,0,0); tile3.setIcon(tl3i); textoTile3=new TJlabel("Rodar regra de backup",0,0,0,0); textoTile3.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,31)); textoTile3.setForeground(Color.BLACK); tile3.addActionListener(new AcaoRodaRegra()); ImageIcon tl4 = new ImageIcon(getClass().getResource("/GUI/Imagens/duplicata.png")); tile4=new TJbutton("",0,0,0,0); tile4.setIcon(tl4); textoTile4=new TJlabel("Buscar arquivos duplicados",0,0,0,0); textoTile4.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,31)); textoTile4.setForeground(Color.BLACK); Runnable text = new AcaoMovimentoDeObjetos(50,25,799,114,t1,fundo); new Thread(text).start(); Runnable rt1 = new AcaoMovimentoDeObjetos(118,148,80,80,tile1,fundo); new Thread(rt1).start(); Runnable rtt1 = new AcaoMovimentoDeObjetos(203,171,799,41,textoTile1,fundo); new Thread(rtt1).start(); Runnable rt3 = new AcaoMovimentoDeObjetos(118,233,80,80,tile3,fundo); new Thread(rt3).start(); Runnable rtt3 = new AcaoMovimentoDeObjetos(203,256,799,41,textoTile3,fundo); new Thread(rtt3).start(); Runnable rt4 = new AcaoMovimentoDeObjetos(118,318,80,80,tile4,fundo); new Thread(rt4).start(); Runnable rtt4 = new AcaoMovimentoDeObjetos(203,341,799,41,textoTile4,fundo); new Thread(rtt4).start(); } private void esconderInicio() { Runnable text = new AcaoRecolherObjetos(50,25,799,114,t1,fundo); new Thread(text).start(); Runnable rt1 = new AcaoRecolherObjetos(118,148,80,80,tile1,fundo); new Thread(rt1).start(); Runnable rtt1 = new AcaoRecolherObjetos(203,171,799,41,textoTile1,fundo); new Thread(rtt1).start(); Runnable rt3 = new AcaoRecolherObjetos(118,233,80,80,tile3,fundo); new Thread(rt3).start(); Runnable rtt3 = new AcaoRecolherObjetos(203,256,799,41,textoTile3,fundo); new Thread(rtt3).start(); Runnable rt4 = new AcaoRecolherObjetos(118,318,80,80,tile4,fundo); new Thread(rt4).start(); Runnable rtt4 = new AcaoRecolherObjetos(203,341,799,41,textoTile4,fundo); new Thread(rtt4).start(); } //listeners da tela de inicio class AcaoNovoCadastro implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { telaCadastro(); esconderInicio(); } } class AcaoRodaRegra implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { esconderInicio(); regraBackup(); } } //tela de concluso //setBounds (horizontal,vertical,largura,altura); private void concluido(){ ImageIcon v1 = new ImageIcon(getClass().getResource("/GUI/Imagens/back.png")); tlv=new JLabel(v1); tlv.addMouseListener(new AcaoChamarTelaVoltaInicio(true)); Runnable voltar= new AcaoMovimentoDeObjetos(50,6,22,22,tlv,fundo); new Thread(voltar).start(); t1=new TJlabel("Concludo",0,0,0,0); t1.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,81)); t1.setForeground(Color.BLACK); ImageIcon tl1i = new ImageIcon(getClass().getResource("/GUI/Imagens/ok.png")); Image temp= tl1i.getImage(); imgc = new FundoJpane(temp,0,0,0,0); Runnable icone = new AcaoMovimentoDeObjetos(185,200,100,100,imgc,fundo); new Thread(icone).start(); Runnable text = new AcaoMovimentoDeObjetos(300,180,799,114,t1,fundo); new Thread(text).start(); } private void esconderConcluido(){ Runnable icone = new AcaoRecolherObjetos(185,200,100,100,imgc,fundo); new Thread(icone).start(); Runnable text = new AcaoRecolherObjetos(300,180,799,114,t1,fundo); new Thread(text).start(); } // tela de cadastro private void telaCadastro() { ImageIcon v1 = new ImageIcon(getClass().getResource("/GUI/Imagens/back.png")); tlv=new JLabel(v1); tlv.addMouseListener(new AcaoChamarTelaVoltaInicio(false)); Runnable voltar= new AcaoMovimentoDeObjetos(50,6,22,22,tlv,fundo); new Thread(voltar).start(); tp1=new TJlabel("Novo backup",0,0,0,0); tp1.setFont(new Font("CordiaUPC",Font.PLAIN,83)); tp1.setForeground(Color.BLACK); Runnable text = new AcaoMovimentoDeObjetos(50,25,799,114,tp1,fundo); new Thread(text).start(); //nome tl1=new TJlabel("Nome",0,0,0,0); tl1.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,31)); tl1.setForeground(Color.BLACK); Runnable nome = new AcaoMovimentoDeObjetos(50,140,100,38,tl1,fundo); new Thread(nome).start(); cnome = new TJtextField(0,0,0,0); cnome.setEditable(true); cnome.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,20)); cnome.setForeground(Color.BLACK); Runnable anome = new AcaoMovimentoDeObjetos(50,179,650,38,cnome,fundo); new Thread(anome).start(); //diretorio Backup tl3=new TJlabel("Diretrio de destino do backup",0,0,0,0); tl3.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,31)); tl3.setForeground(Color.BLACK); Runnable bac = new AcaoMovimentoDeObjetos(50,333,700,38,tl3,fundo); new Thread(bac).start(); cbac = new TJtextField(0,0,0,0); cbac.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,20)); cbac.setForeground(Color.BLACK); cbac.setEditable(false); Runnable abac = new AcaoMovimentoDeObjetos(50,372,650,38,cbac,fundo); new Thread(abac).start(); //fim //diretorio arquivo tl2=new TJlabel("Diretrios e arquivos de origem",0,0,0,0); tl2.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,31)); tl2.setForeground(Color.BLACK); Runnable dic = new AcaoMovimentoDeObjetos(50,217,700,38,tl2,fundo); new Thread(dic).start(); cdic = new TJtextArea(0,0,0,0); cdic.setLineWrap(true); cdic.setWrapStyleWord(true); cdic.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,20)); cdic.setForeground(Color.black); cdic.setEditable(false); cdic.setBounds(0, 0, WIDTH,HEIGHT); scr = new JScrollPane(cdic); scr.getVerticalScrollBar().addAdjustmentListener(new AcaoRolagemAutomatica()); scr.setBorder(new CompoundBorder(new EmptyBorder(0, 0, 0, 0),new LineBorder(Color.BLACK))); scr.setOpaque(false);// scr.getViewport().setOpaque(false);// scr.setBounds(0,0,648,74); Runnable adic = new AcaoMovimentoDeObjetos(50,256,650,76,scr,fundo); new Thread(adic).start(); //botao procura pasta para backup Search=new TJbutton("",0,0,0,0); ImageIcon i1 = new ImageIcon(getClass().getResource("/GUI/Imagens/sea.jpg")); Search.setIcon(i1); Search.addActionListener(new AcaoChooserBackup(this));//backup Runnable sea1=new AcaoMovimentoDeObjetos(700,372,38,38,Search,fundo); new Thread(sea1).start(); //botao procura arquivos Searchs=new TJbutton("",0,0,0,0); ImageIcon i2 = new ImageIcon(getClass().getResource("/GUI/Imagens/sea.jpg")); Searchs.setIcon(i2); Searchs.addActionListener(new AcaoChooserDiretorio(this));//origem Runnable sea2=new AcaoMovimentoDeObjetos(700,256,38,38,Searchs,fundo); new Thread(sea2).start(); //botao confirma conf=new TJbutton("Confirmar",0,0,0,255); conf.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,18)); conf.setForeground(Color.WHITE); conf.addActionListener(new GravarCadastro()); Runnable cf=new AcaoMovimentoDeObjetos(50,432,90,38,conf,fundo); new Thread(cf).start(); //boto agenda age=new TJbutton("Agendamento",0,0,0,255); age.setForeground(Color.white); age.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,18)); age.addActionListener(new AcaoChamarTelaAgenda()); Runnable ag=new AcaoMovimentoDeObjetos(650,432,90,38,age,fundo); new Thread(ag).start(); //fim //setBounds (horizontal,vertical,largura,altura); } private void esconderCadastro(){ Runnable sea1=new AcaoRecolherObjetos(700,372,38,38,Search,fundo); new Thread(sea1).start(); Runnable sea2=new AcaoRecolherObjetos(700,256,38,38,Searchs,fundo); new Thread(sea2).start(); Runnable voltar= new AcaoRecolherObjetos(50,6,22,22,tlv,fundo); new Thread(voltar).start(); Runnable text = new AcaoRecolherObjetos(50,25,799,114,tp1,fundo); new Thread(text).start(); Runnable nome = new AcaoRecolherObjetos(50,140,100,38,tl1,fundo); new Thread(nome).start(); Runnable anome = new AcaoRecolherObjetos(50,179,620,38,cnome,fundo); new Thread(anome).start(); Runnable dic = new AcaoRecolherObjetos(50,217,700,38,tl2,fundo); new Thread(dic).start(); Runnable adic = new AcaoRecolherObjetos(50,256,620,76,scr,fundo); new Thread(adic).start(); Runnable bac = new AcaoRecolherObjetos(50,333,700,38,tl3,fundo); new Thread(bac).start(); Runnable abac = new AcaoRecolherObjetos(50,372,620,38,cbac,fundo); new Thread(abac).start(); Runnable ag=new AcaoRecolherObjetos(650,432,90,38,age,fundo); new Thread(ag).start(); Runnable cf=new AcaoRecolherObjetos(50,432,90,38,conf,fundo); new Thread(cf).start(); } //listener Cadastro class GravarCadastro implements ActionListener{ @Override public void actionPerformed(ActionEvent arg0) { if(cdic.getText().isEmpty() && cbac.getText().isEmpty() && cnome.getText().isEmpty()){ JOptionPane.showMessageDialog(null,"Todos os campos so obrigatrios"); }else{ R=new RegraBackup(cbac.getText(),cdic.getText()); B=new Backup(cnome.getText(), new Date().toString()); core.criarBackup(B,R); esconderCadastro(); concluido(); } } } class AcaoChooserDiretorio implements ActionListener{ private JFileChooser chooser; private JFrame j; public AcaoChooserDiretorio(JFrame j){ this.j=j; } String caminho=""; @Override public void actionPerformed(ActionEvent e) { chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); chooser.setMultiSelectionEnabled(true); int r=chooser.showOpenDialog(j); if (r == JFileChooser.APPROVE_OPTION){ File[] file=chooser.getSelectedFiles(); try{ for(File temp:file) { caminho+=temp.getAbsolutePath()+"|\n"; cdic.setText(caminho); } }catch (Exception erro){ JOptionPane.showMessageDialog(j,"Erro ao carregar o caminho!"); } } } } class AcaoChooserBackup implements ActionListener{ private JFrame j; private JFileChooser chooserb; public AcaoChooserBackup(JFrame j){ this.j=j; } String caminho=""; @Override public void actionPerformed(ActionEvent e) { chooserb = new JFileChooser(); chooserb.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); chooserb.setMultiSelectionEnabled(false); int r=chooserb.showOpenDialog(j); if (r == JFileChooser.APPROVE_OPTION){ File file=chooserb.getSelectedFile(); try{ cbac.setText(file.getAbsolutePath()+"|"); }catch (Exception erro){ JOptionPane.showMessageDialog(j,"Erro ao carregar o caminho!"); } } } } class AcaoChamarTelaVoltaInicio implements MouseListener{ boolean c=false; AcaoChamarTelaVoltaInicio(boolean c) { this.c=c; } @Override public void mouseClicked(MouseEvent arg0) { if(c==true){ esconderConcluido(); Runnable voltar= new AcaoRecolherObjetos(50,6,22,22,tlv,fundo); new Thread(voltar).start(); }else esconderCadastro(); telaInicio(); } @Override public void mouseEntered(MouseEvent arg0) {} @Override public void mouseExited(MouseEvent arg0) {} @Override public void mousePressed(MouseEvent arg0) {} @Override public void mouseReleased(MouseEvent arg0) {} } class AcaoChamarTelaAgenda implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { esconderCadastro(); telaAgendamento(); } } class AcaoRolagemAutomatica implements AdjustmentListener{ //rolagem automatica @Override public void adjustmentValueChanged(AdjustmentEvent e) { if(flag) { e.getAdjustable().setValue(e.getAdjustable().getMaximum()); } flag = false; } } //fim listener cadastro //tela de agendamento de dia //setBounds (horizontal,vertical,largura,altura); private void telaAgendamento(){ ImageIcon v1 = new ImageIcon(getClass().getResource("/GUI/Imagens/back.png")); tla=new JLabel(v1); tla.addMouseListener(new AcaoChamarTelaVoltaCadastro()); Runnable voltar= new AcaoMovimentoDeObjetos(50,6,22,22,tla,fundo); new Thread(voltar).start(); tpa=new TJlabel("Agendar Backup",0,0,0,0); tpa.setFont(new Font("CordiaUPC",Font.PLAIN,83)); tpa.setForeground(Color.BLACK); //escolha de dia dia = new JPanel(); dia.setLayout(null); dia.setPreferredSize(new Dimension(100,477)); dia.setOpaque(false); seg=new TJbutton("Segunda",0,0,0,255); seg.setBounds(1,53,99,50); dia.add(seg); ter=new TJbutton("Tera",0,0,0,255); ter.setBounds(1,106,99,50); dia.add(ter); quar=new TJbutton("Quarta",0,0,0,255); quar.setBounds(1,159,99,50); dia.add(quar); quin=new TJbutton("Quinta",0,0,0,255); quin.setBounds(1,212,99,50); dia.add(quin); sex=new TJbutton("Sexta",0,0,0,255); sex.setBounds(1,265,99,50); dia.add(sex); sab=new TJbutton("Sbado",0,0,0,255); sab.setBounds(1,318,99,50); dia.add(sab); dom=new TJbutton("Domingo",0,0,0,255); dom.setBounds(1,371,99,50); dia.add(dom); scrolldia = new JScrollPane(dia); scrolldia.setOpaque(false); scrolldia.getViewport().setOpaque(false); scrolldia.setEnabled(false); scrolldia.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrolldia.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER); scrolldia.setBorder(null); diau = new TJbutton("",0,0,0,0); ImageIcon idiau = new ImageIcon(getClass().getResource("/GUI/Imagens/UP.png")); diau.setIcon(idiau); diau.addMouseListener(new AcaoSubirScroll(scrolldia)); diau.setBorder(null); diad = new TJbutton("",0,0,0,0); ImageIcon idiad = new ImageIcon(getClass().getResource("/GUI/Imagens/Down.png")); diad.setIcon(idiad); diad.addMouseListener(new AcaoDescerScroll(scrolldia)); diad.setBorder(null); lbdia = new TJlabel(null,0,0,0,0); lbdia.setText("Dia"); lbdia.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,30)); //fim escolha de dia //escolha Horas horas=new FundoJpane(null,0,0,0,0); horas.setLayout(null); horas.setPreferredSize(new Dimension(52,1378)); horas.setOpaque(false); h0=new TJbutton("00",0,0,0,255); h0.setBounds(1,53,50,50); horas.add(h0); h1=new TJbutton("01",0,0,0,255); h1.setBounds(1,106,50,50); horas.add(h1); h2=new TJbutton("02",0,0,0,255); h2.setBounds(1,159,50,50); horas.add(h2); h3=new TJbutton("03",0,0,0,255); h3.setBounds(1,212,50,50); horas.add(h3); h4=new TJbutton("04",0,0,0,255); h4.setBounds(1,265,50,50); horas.add(h4); h5=new TJbutton("05",0,0,0,255); h5.setBounds(1,318,50,50); horas.add(h5); h6=new TJbutton("06",0,0,0,255); h6.setBounds(1,371,50,50); horas.add(h6); h7=new TJbutton("07",0,0,0,255); h7.setBounds(1,424,50,50); horas.add(h7); h8=new TJbutton("08",0,0,0,255); h8.setBounds(1,477,50,50); horas.add(h8); h9=new TJbutton("09",0,0,0,255); h9.setBounds(1,530,50,50); horas.add(h9); h10=new TJbutton("10",0,0,0,255); h10.setBounds(1,583,50,50); horas.add(h10); h11=new TJbutton("11",0,0,0,255); h11.setBounds(1,636,50,50); horas.add(h11); h12=new TJbutton("12",0,0,0,255); h12.setBounds(1,689,50,50); horas.add(h12); h13=new TJbutton("13",0,0,0,255); h13.setBounds(1,742,50,50); horas.add(h13); h14=new TJbutton("14",0,0,0,255); h14.setBounds(1,795,50,50); horas.add(h14); h15=new TJbutton("15",0,0,0,255); h15.setBounds(1,848,50,50); horas.add(h15); h16=new TJbutton("16",0,0,0,255); h16.setBounds(1,901,50,50); horas.add(h16); h17=new TJbutton("17",0,0,0,255); h17.setBounds(1,954,50,50); horas.add(h17); h18=new TJbutton("18",0,0,0,255); h18.setBounds(1,1007,50,50); horas.add(h18); h19=new TJbutton("19",0,0,0,255); h19.setBounds(1,1060,50,50); horas.add(h19); h20=new TJbutton("20",0,0,0,255); h20.setBounds(1,1113,50,50); horas.add(h20); h21=new TJbutton("21",0,0,0,255); h21.setBounds(1,1166,50,50); horas.add(h21); h22=new TJbutton("22",0,0,0,255); h22.setBounds(1,1219,50,50); horas.add(h22); h23=new TJbutton("23",0,0,0,255); h23.setBounds(1,1272,50,50); horas.add(h23); lbdh = new TJlabel(null,0,0,0,0); lbdh.setText("Hora"); lbdh.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,30)); scrollHora = new JScrollPane(horas); scrollHora.setOpaque(false); scrollHora.getViewport().setOpaque(false); scrollHora.setEnabled(false); scrollHora.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrollHora.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER); scrollHora.setBorder(null); hu = new TJbutton("",0,0,0,0); ImageIcon ihu = new ImageIcon(getClass().getResource("/GUI/Imagens/UP.png")); hu.setIcon(ihu); hu.addMouseListener(new AcaoSubirScroll(scrollHora)); hu.setBorder(null); hd = new TJbutton("",0,0,0,0); ImageIcon ihd = new ImageIcon(getClass().getResource("/GUI/Imagens/Down.png")); hd.setIcon(ihd); hd.addMouseListener(new AcaoDescerScroll(scrollHora)); hd.setBorder(null); //escolha minutos minutos=new FundoJpane(null,0,0,0,0); minutos.setLayout(null); minutos.setPreferredSize(new Dimension(52,3286)); minutos.setOpaque(false); m0=new TJbutton("00",0,0,0,255); m0.setBounds(1,53,50,50); minutos.add(m0); m1=new TJbutton("01",0,0,0,255); m1.setBounds(1,106,50,50); minutos.add(m1); m2=new TJbutton("02",0,0,0,255); m2.setBounds(1,159,50,50); minutos.add(m2); m3=new TJbutton("03",0,0,0,255); m3.setBounds(1,212,50,50); minutos.add(m3); m4=new TJbutton("04",0,0,0,255); m4.setBounds(1,265,50,50); minutos.add(m4); m5=new TJbutton("05",0,0,0,255); m5.setBounds(1,318,50,50); minutos.add(m5); m6=new TJbutton("06",0,0,0,255); m6.setBounds(1,371,50,50); minutos.add(m6); m7=new TJbutton("07",0,0,0,255); m7.setBounds(1,424,50,50); minutos.add(m7); m8=new TJbutton("08",0,0,0,255); m8.setBounds(1,477,50,50); minutos.add(m8); m9=new TJbutton("09",0,0,0,255); m9.setBounds(1,530,50,50); minutos.add(m9); m10=new TJbutton("10",0,0,0,255); m10.setBounds(1,583,50,50); minutos.add(m10); m11=new TJbutton("11",0,0,0,255); m11.setBounds(1,636,50,50); minutos.add(m11); m12=new TJbutton("12",0,0,0,255); m12.setBounds(1,689,50,50); minutos.add(m12); m13=new TJbutton("13",0,0,0,255); m13.setBounds(1,742,50,50); minutos.add(m13); m14=new TJbutton("14",0,0,0,255); m14.setBounds(1,795,50,50); minutos.add(m14); m15=new TJbutton("15",0,0,0,255); m15.setBounds(1,848,50,50); minutos.add(m15); m16=new TJbutton("16",0,0,0,255); m16.setBounds(1,901,50,50); minutos.add(m16); m17=new TJbutton("17",0,0,0,255); m17.setBounds(1,954,50,50); minutos.add(m17); m18=new TJbutton("18",0,0,0,255); m18.setBounds(1,1007,50,50); minutos.add(m18); m19=new TJbutton("19",0,0,0,255); m19.setBounds(1,1060,50,50); minutos.add(m19); m20=new TJbutton("20",0,0,0,255); m20.setBounds(1,1113,50,50); minutos.add(m20); m21=new TJbutton("21",0,0,0,255); m21.setBounds(1,1166,50,50); minutos.add(m21); m22=new TJbutton("22",0,0,0,255); m22.setBounds(1,1219,50,50); minutos.add(m22); m23=new TJbutton("23",0,0,0,255); m23.setBounds(1,1272,50,50); minutos.add(m23); m24=new TJbutton("24",0,0,0,255); m24.setBounds(1,1325,50,50); minutos.add(m24); m25=new TJbutton("25",0,0,0,255); m25.setBounds(1,1378,50,50); minutos.add(m25); m26=new TJbutton("26",0,0,0,255); m26.setBounds(1,1431,50,50); minutos.add(m26); m27=new TJbutton("27",0,0,0,255); m27.setBounds(1,1484,50,50); minutos.add(m27); m28=new TJbutton("28",0,0,0,255); m28.setBounds(1,1537,50,50); minutos.add(m28); m29=new TJbutton("29",0,0,0,255); m29.setBounds(1,1590,50,50); minutos.add(m29); m30=new TJbutton("30",0,0,0,255); m30.setBounds(1,1643,50,50); minutos.add(m30); m31=new TJbutton("31",0,0,0,255); m31.setBounds(1,1696,50,50); minutos.add(m31); m32=new TJbutton("32",0,0,0,255); m32.setBounds(1,1749,50,50); minutos.add(m32); m33=new TJbutton("33",0,0,0,255); m33.setBounds(1,1802,50,50); minutos.add(m33); m34=new TJbutton("34",0,0,0,255); m34.setBounds(1,1855,50,50); minutos.add(m34); m35=new TJbutton("35",0,0,0,255); m35.setBounds(1,1908,50,50); minutos.add(m35); m36=new TJbutton("36",0,0,0,255); m36.setBounds(1,1961,50,50); minutos.add(m36); m37=new TJbutton("37",0,0,0,255); m37.setBounds(1,2014,50,50); minutos.add(m37); m38=new TJbutton("38",0,0,0,255); m38.setBounds(1,2067,50,50); minutos.add(m38); m39=new TJbutton("39",0,0,0,255); m39.setBounds(1,2120,50,50); minutos.add(m39); m40=new TJbutton("40",0,0,0,255); m40.setBounds(1,2173,50,50); minutos.add(m40); m41=new TJbutton("41",0,0,0,255); m41.setBounds(1,2226,50,50); minutos.add(m41); m42=new TJbutton("42",0,0,0,255); m42.setBounds(1,2279,50,50); minutos.add(m42); m43=new TJbutton("43",0,0,0,255); m43.setBounds(1,2332,50,50); minutos.add(m43); m44=new TJbutton("44",0,0,0,255); m44.setBounds(1,2385,50,50); minutos.add(m44); m45=new TJbutton("45",0,0,0,255); m45.setBounds(1,2438,50,50); minutos.add(m45); m46=new TJbutton("46",0,0,0,255); m46.setBounds(1,2491,50,50); minutos.add(m46); m47=new TJbutton("47",0,0,0,255); m47.setBounds(1,2544,50,50); minutos.add(m47); m48=new TJbutton("48",0,0,0,255); m48.setBounds(1,2597,50,50); minutos.add(m48); m49=new TJbutton("49",0,0,0,255); m49.setBounds(1,2650,50,50); minutos.add(m49); m50=new TJbutton("50",0,0,0,255); m50.setBounds(1,2703,50,50); minutos.add(m50); m51=new TJbutton("51",0,0,0,255); m51.setBounds(1,2756,50,50); minutos.add(m51); m52=new TJbutton("52",0,0,0,255); m52.setBounds(1,2809,50,50); minutos.add(m52); m53=new TJbutton("53",0,0,0,255); m53.setBounds(1,2862,50,50); minutos.add(m53); m54=new TJbutton("54",0,0,0,255); m54.setBounds(1,2915,50,50); minutos.add(m54); m55=new TJbutton("55",0,0,0,255); m55.setBounds(1,2968,50,50); minutos.add(m55); m56=new TJbutton("56",0,0,0,255); m56.setBounds(1,3021,50,50); minutos.add(m56); m57=new TJbutton("57",0,0,0,255); m57.setBounds(1,3074,50,50); minutos.add(m57); m58=new TJbutton("58",0,0,0,255); m58.setBounds(1,3127,50,50); minutos.add(m58); m59=new TJbutton("59",0,0,0,255); m59.setBounds(1,3180,50,50); minutos.add(m59); lbm = new TJlabel(null,0,0,0,0); lbm.setText("Minuto"); lbm.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,30)); lbm.setBounds(430,257,70,50); fundo.add(lbm); scrollMinutos = new JScrollPane(minutos); scrollMinutos.setOpaque(false); scrollMinutos.getViewport().setOpaque(false); scrollMinutos.setEnabled(false); scrollMinutos.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrollMinutos.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER); scrollMinutos.setBorder(null); mu = new TJbutton("",0,0,0,0); ImageIcon imu = new ImageIcon(getClass().getResource("/GUI/Imagens/UP.png")); mu.setIcon(imu); mu.addMouseListener(new AcaoSubirScroll(scrollMinutos)); mu.setBorder(null); md = new TJbutton("",0,0,0,0); ImageIcon imd = new ImageIcon(getClass().getResource("/GUI/Imagens/Down.png")); md.setIcon(imd); md.addMouseListener(new AcaoDescerScroll(scrollMinutos)); md.setBorder(null); //fim minutos confa=new TJbutton("Agendar e confirmar",0,0,0,255); confa.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,18)); confa.setForeground(Color.WHITE); confa.addActionListener(new SalvaAgendamento()); confa.setBounds(325,432,150,38); fundo.add(confa); ImageIcon icd = new ImageIcon(getClass().getResource("/GUI/Imagens/100.png")); Image id=icd.getImage(); ld=new FundoJpane(id,0,0,0,0); ld.setBounds(100,208,99,156); lh=new FundoJpane(id,0,0,0,0); lh.setBounds(300,208,51,156); lm=new FundoJpane(id,0,0,0,0); lm.setBounds(500,208,51,156); check=new TJcheck("Desligar o computador aps a execuo.",0,0,0,0); check.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,30)); check.setForeground(Color.BLACK); check.setFocusable(false); //threads de movimento //setBounds (horizontal,vertical,largura,altura); Runnable min= new AcaoMovimentoDeObjetos(500,208,51,156,scrollMinutos,fundo); new Thread(min).start(); Runnable upm = new AcaoMovimentoDeObjetos(550,260,17,27,mu,fundo); new Thread(upm).start(); Runnable dwm = new AcaoMovimentoDeObjetos(550,288,17,27,md,fundo); new Thread(dwm).start(); Runnable text = new AcaoMovimentoDeObjetos(50,25,799,114,tpa,fundo); new Thread(text).start(); Runnable day= new AcaoMovimentoDeObjetos(100,208,99,156,scrolldia,fundo); new Thread(day).start(); Runnable upd = new AcaoMovimentoDeObjetos(200,260,17,27,diau,fundo); new Thread(upd).start(); Runnable dwd = new AcaoMovimentoDeObjetos(200,288,17,27,diad,fundo); new Thread(dwd).start(); Runnable lbd = new AcaoMovimentoDeObjetos(50,257,50,50,lbdia,fundo); new Thread(lbd).start(); Runnable lbh = new AcaoMovimentoDeObjetos(250,257,50,50,lbdh,fundo); new Thread(lbh).start(); Runnable hor= new AcaoMovimentoDeObjetos(300,208,51,156,scrollHora,fundo); new Thread(hor).start(); Runnable uph = new AcaoMovimentoDeObjetos(350,260,17,27,hu,fundo); new Thread(uph).start(); Runnable dwh = new AcaoMovimentoDeObjetos(350,288,17,27,hd,fundo); new Thread(dwh).start(); Runnable chd = new AcaoMovimentoDeObjetos(50,328,799,114,check,fundo); new Thread(chd).start(); fundo.add(ld); fundo.add(lh); fundo.add(lm); //setBounds (horizontal,vertical,largura,altura); } private DiasSemana getDia(JScrollPane scr){; DiasSemana dia=null; JScrollBar scroll = scr.getVerticalScrollBar(); int temp=scroll.getValue()+53,resul; resul=temp/53; switch(resul){ case 1: dia=DiasSemana.SEGUNDA; break; case 2: dia=DiasSemana.TERCA; break; case 3: dia=DiasSemana.QUARTA; break; case 4: dia=DiasSemana.QUINTA; break; case 5: dia=DiasSemana.SEXTA; break; case 6: dia=DiasSemana.SABADO; break; case 7: dia=DiasSemana.DOMINGO; break; } return dia; } private String getMinuto(JScrollPane scr){; JScrollBar scroll = scr.getVerticalScrollBar(); int temp=scroll.getValue()+53,resul; resul=temp/53; resul--; String minuto=String.valueOf(resul); return minuto; } private String getHora(JScrollPane scr){; JScrollBar scroll = scr.getVerticalScrollBar(); int temp=scroll.getValue()+53,resul; resul=temp/53; resul--; String hora=String.valueOf(resul); return hora; } //esconder agendamento private void esconderAgendamento(){ Runnable chd = new AcaoRecolherObjetos(50,328,799,114,check,fundo); new Thread(chd).start(); Runnable d= new AcaoRecolherObjetos(100,208,99,156,ld,fundo); new Thread(d).start(); Runnable h= new AcaoRecolherObjetos(300,208,51,156,lh,fundo); new Thread(h).start(); Runnable m= new AcaoRecolherObjetos(500,208,51,156,lm,fundo); new Thread(m).start(); Runnable cf=new AcaoRecolherObjetos(355,432,90,38,confa,fundo); new Thread(cf).start(); Runnable voltar= new AcaoRecolherObjetos(50,6,22,22,tla,fundo); new Thread(voltar).start(); Runnable text = new AcaoRecolherObjetos(50,25,799,114,tpa,fundo); new Thread(text).start(); Runnable day= new AcaoRecolherObjetos(100,208,99,156,scrolldia,fundo); new Thread(day).start(); Runnable upd = new AcaoRecolherObjetos(200,260,17,27,diau,fundo); new Thread(upd).start(); Runnable dwd = new AcaoRecolherObjetos(200,288,17,27,diad,fundo); new Thread(dwd).start(); Runnable lbd = new AcaoRecolherObjetos(50,257,50,50,lbdia,fundo); new Thread(lbd).start(); Runnable lbh = new AcaoRecolherObjetos(250,257,50,50,lbdh,fundo); new Thread(lbh).start(); Runnable hor= new AcaoRecolherObjetos(300,208,51,156,scrollHora,fundo); new Thread(hor).start(); Runnable uph = new AcaoRecolherObjetos(350,260,17,27,hu,fundo); new Thread(uph).start(); Runnable dwh = new AcaoRecolherObjetos(350,288,17,27,hd,fundo); new Thread(dwh).start(); Runnable min= new AcaoRecolherObjetos(500,208,51,156,scrollMinutos,fundo); new Thread(min).start(); Runnable upm = new AcaoRecolherObjetos(550,260,17,27,mu,fundo); new Thread(upm).start(); Runnable dwm = new AcaoRecolherObjetos(550,288,17,27,md,fundo); new Thread(dwm).start(); Runnable mlb = new AcaoRecolherObjetos(430,257,70,50,lbm,fundo); new Thread(mlb).start(); } //listener agendamento class SalvaAgendamento implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { System.out.println("Agendado dia: "+getDia(scrolldia)+" s "+getHora(scrollHora)+":"+getMinuto(scrollMinutos)); if(cdic.getText().isEmpty() && cbac.getText().isEmpty() && cnome.getText().isEmpty()){ JOptionPane.showMessageDialog(null,"Todos os campos so obrigatrios"); }else{ boolean des; if(check.isSelected())des=true; else des=false; R=new RegraBackup(cbac.getText(),cdic.getText()); B=new Backup(cnome.getText(), new Date().toString()); D=new Dias(getDia(scrolldia),getHora(scrollHora)+":"+getMinuto(scrollMinutos),des); core.criarBackup(B,R,D); esconderAgendamento(); esconderCadastro(); concluido(); } } } class AcaoChamarTelaVoltaCadastro implements MouseListener{ @Override public void mouseClicked(MouseEvent e) { esconderAgendamento(); Runnable sea1=new AcaoMovimentoDeObjetos(700,372,38,38,Search,fundo); new Thread(sea1).start(); Runnable sea2=new AcaoMovimentoDeObjetos(700,256,38,38,Searchs,fundo); new Thread(sea2).start(); Runnable voltar= new AcaoMovimentoDeObjetos(50,6,22,22,tlv,fundo); new Thread(voltar).start(); Runnable text = new AcaoMovimentoDeObjetos(50,25,799,114,tp1,fundo); new Thread(text).start(); Runnable nome = new AcaoMovimentoDeObjetos(50,140,100,38,tl1,fundo); new Thread(nome).start(); Runnable dic = new AcaoMovimentoDeObjetos(50,217,700,38,tl2,fundo); new Thread(dic).start(); Runnable adic = new AcaoMovimentoDeObjetos(50,256,650,76,scr,fundo); new Thread(adic).start(); Runnable bac = new AcaoMovimentoDeObjetos(50,333,700,38,tl3,fundo); new Thread(bac).start(); Runnable ag=new AcaoMovimentoDeObjetos(650,432,90,38,age,fundo); new Thread(ag).start(); Runnable cf=new AcaoMovimentoDeObjetos(50,432,90,38,conf,fundo); new Thread(cf).start(); Runnable anome = new AcaoMovimentoDeObjetos(50,179,650,38,cnome,fundo); new Thread(anome).start(); Runnable abac = new AcaoMovimentoDeObjetos(50,372,650,38,cbac,fundo); new Thread(abac).start(); } @Override public void mousePressed(MouseEvent e) {} @Override public void mouseReleased(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} } class AcaoDescerScroll implements MouseListener{ private JScrollPane scr; boolean cont=false; public AcaoDescerScroll(JScrollPane scr) { this.scr=scr; } @Override public void mouseClicked(MouseEvent arg0) {} @Override public void mouseEntered(MouseEvent arg0) {} @Override public void mouseExited(MouseEvent arg0) {} @Override public void mousePressed(MouseEvent arg0) { Runnable descer = new Correr(false,scr); new Thread(descer).start(); } @Override public void mouseReleased(MouseEvent arg0) { controle=false; } } class AcaoSubirScroll implements MouseListener{ private JScrollPane scr; public AcaoSubirScroll(JScrollPane scr) { this.scr=scr; } @Override public void mouseClicked(MouseEvent arg0) {} @Override public void mouseEntered(MouseEvent arg0) {} @Override public void mouseExited(MouseEvent arg0) {} @Override public void mousePressed(MouseEvent arg0) { Runnable subir = new Correr(true,scr); new Thread(subir).start(); } @Override public void mouseReleased(MouseEvent arg0) { controle=false; } } class Correr implements Runnable{ boolean c; private JScrollPane scr; Correr(boolean c,JScrollPane scr){ this.c=c; controle=true; this.scr=scr; } @Override public void run() { while(controle){ try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(c==false){ JScrollBar scroll = scr.getVerticalScrollBar(); if(scroll.getValue()<=scroll.getMaximum()-53)scroll.setValue(scroll.getValue()+53); }else{ JScrollBar scroll = scr.getVerticalScrollBar(); if(scroll.getValue()>0)scroll.setValue(scroll.getValue()-53); } } } } //tela regra de backup class AcaoRegraToMenu implements MouseListener{ @Override public void mouseClicked(MouseEvent arg0) { escondeRegra(); telaInicio(); } @Override public void mouseEntered(MouseEvent arg0) {} @Override public void mouseExited(MouseEvent arg0) {} @Override public void mousePressed(MouseEvent arg0) {} @Override public void mouseReleased(MouseEvent arg0) {} } private void escondeRegra(){ Runnable text = new AcaoRecolherObjetos(50,25,799,114,tp1,fundo); new Thread(text).start(); Runnable sr = new AcaoRecolherObjetos(50,140,715,333,scrollRegra,fundo); new Thread(sr).start(); Runnable voltar= new AcaoRecolherObjetos(50,6,22,22,tlv,fundo); new Thread(voltar).start(); } private void regraBackup(){ //setBounds (horizontal,vertical,largura,altura); //fundo das informaes ImageIcon v1 = new ImageIcon(getClass().getResource("/GUI/Imagens/back.png")); tlv=new JLabel(v1); tlv.addMouseListener(new AcaoRegraToMenu()); Runnable voltar= new AcaoMovimentoDeObjetos(50,6,22,22,tlv,fundo); new Thread(voltar).start(); tp1=new TJlabel("Rodar Regra de backup",0,0,0,0); tp1.setFont(new Font("CordiaUPC",Font.PLAIN,83)); tp1.setForeground(Color.BLACK); Runnable text = new AcaoMovimentoDeObjetos(50,25,799,114,tp1,fundo); new Thread(text).start(); Backup ba; int cont=0,cp=1; IteradorBackups ib; int largura=710,altura=125; FundoJpane area = new FundoJpane(null,0,0,0,0); area.setLayout(new FlowLayout()); area.setPreferredSize(new Dimension(largura,altura)); ib=core.resgatarBackups(); scrollRegra = new JScrollPane(area); scrollRegra.setBorder(null); scrollRegra.setOpaque(false);// scrollRegra.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrollRegra.getViewport().setOpaque(false); while(ib.hasNext()){ ba=null; ba=ib.next(); area.add(criarInfo(ba,cont,125*cp,0,700,123)); cp++; cont++; System.out.println(cont); if(ib.hasNext())area.setPreferredSize(new Dimension(largura,altura*cp)); } Runnable sr = new AcaoMovimentoDeObjetos(50,140,715,333,scrollRegra,fundo); new Thread(sr).start(); //fim fundo info //motor de apresentao } public void iniCarregamento() { escondeRegra(); //setBounds (horizontal,vertical,largura,altura); Runnable escondeX = new AcaoRecolherObjetos(767,6,16,25,fechar,fundo); new Thread(escondeX).start(); ImageIcon tl1i = new ImageIcon(getClass().getResource("/GUI/Imagens/load2.gif")); Image temp= tl1i.getImage(); imgci = new FundoJpane(temp,0,0,0,0); Runnable gifLoad = new AcaoMovimentoDeObjetos(286,121,219,190,imgci,fundo); new Thread(gifLoad).start(); cancela = new TJbutton("Cancelar",0,0,0,255); cancela.setForeground(Color.white); cancela.addActionListener(new BotaoCancela()); Runnable cancel = new AcaoMovimentoDeObjetos(304,384,168,57,cancela,fundo); new Thread(cancel).start(); } class BotaoCancela implements ActionListener{ @Override public void actionPerformed(ActionEvent arg0) { Runnable escondeX = new AcaoMovimentoDeObjetos(767,6,16,25,fechar,fundo); new Thread(escondeX).start(); isCancelado=true; } } public void stopCarregamento(){ //setBounds (horizontal,vertical,largura,altura); Runnable text = new AcaoRecolherObjetos(199,88,380,269,imgci,fundo); new Thread(text).start(); Runnable cancel = new AcaoRecolherObjetos(304,384,168,57,cancela,fundo); new Thread(cancel).start(); Runnable escondeX = new AcaoMovimentoDeObjetos(767,6,16,25,fechar,fundo); new Thread(escondeX).start(); concluido(); } private JPanel criarInfo(Backup b,int p,int h, int v, int l,int a){ //tamanho da letra 18 //setBounds (horizontal,vertical,largura,altura); Integer i = new Integer(p); FundoJpane celula = new FundoJpane(null,0,0,0,0); celula.setBackground(Color.BLACK); celula.setLayout(null); celula.setPreferredSize(new Dimension(700,123)); TJlabel nome=new TJlabel("Nome do Backup:",0,0,0,0); nome.setBounds(0,0,157,18); nome.setBorder(null); nome.setFont(new Font("Microsoft Yi Baiti",Font.BOLD,20)); nome.setForeground(Color.black); celula.add(nome); TJlabel data=new TJlabel("Data de Criao:",0,0,0,0); data.setBounds(0,20,147,18); data.setBorder(null); data.setFont(new Font("Microsoft Yi Baiti",Font.BOLD,20)); data.setForeground(Color.black); celula.add(data); TJlabel origem=new TJlabel("Caminho do backup:",0,0,0,0); origem.setBounds(0,40,184,18); origem.setFont(new Font("Microsoft Yi Baiti",Font.BOLD,20)); origem.setBorder(null); origem.setForeground(Color.black); celula.add(origem); //setBounds (horizontal,vertical,largura,altura); TJtextField cnome = new TJtextField(0,0,0,0); cnome.setBorder(null); cnome.setForeground(Color.black); cnome.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,20)); cnome.setBounds(140,0,700,18); celula.add(cnome); TJtextField cdata = new TJtextField(0,0,0,0); cdata.setBorder(null); cdata.setForeground(Color.black); cdata.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,20)); cdata.setBounds(135,20,700,18); celula.add(cdata); TJtextField corigem = new TJtextField(0,0,0,0); corigem.setBorder(null); corigem.setForeground(Color.black); corigem.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,20)); corigem.setBounds(160,40,700,18); celula.add(corigem); cnome.setEditable(false); cnome.setFocusable(false); cdata.setEditable(false); cdata.setFocusable(false); corigem.setEditable(false); corigem.setFocusable(false); cnome.setText(b.getNomeBackup()); cdata.setText(b.getDataInicio()); corigem.setText(b.getRegra().getDestino()); TJbutton rodar = new TJbutton("Rodar regra",0,0,0,255); rodar.setForeground(Color.white); TJcheck checkzip=new TJcheck("Salvar sada em Zip.",0,0,0,0); checkzip.setFont(new Font("Microsoft Yi Baiti",Font.BOLD,20)); checkzip.setForeground(Color.BLACK); checkzip.setFocusable(false); checkzip.setBounds(0,65,230,18); celula.add(checkzip); //setBounds (horizontal,vertical,largura,altura); rodar.setBounds(231,65,134,30); rodar.addActionListener(new ExecutarRegra(i,checkzip)); celula.add(rodar); celula.setBounds(h,v,l,a); return celula; } class ExecutarRegra implements ActionListener{ int num,cont=0; TJcheck zip; Backup ba; IteradorBackups ib=core.resgatarBackups(); ExecutarRegra(int num, TJcheck zip){ this.num=num; this.zip=zip; } @Override public void actionPerformed(ActionEvent arg0) { iniCarregamento(); Runnable send = new enviarRegra(zip,ba,ib,cont,num); new Thread(send).start(); } } class enviarRegra implements Runnable{ TJcheck zip; Backup ba; IteradorBackups ib; int cont,num; enviarRegra(TJcheck zip,Backup ba,IteradorBackups ib,int cont,int num) { this.zip=zip; this.ba=ba; this.ib=ib; this.cont=cont; this.num=num; } @Override public void run() { while(cont<=num && ib.hasNext()){ ba=ib.next(); cont++; } core.rodarBackup(ba, zip.isSelected()); } } //Minhas classes de movimento class AcaoMovimentoDeObjetos implements Runnable{ private int x,y,alt,larg; private JButton b=null; private JLabel l=null; private JPanel j; private TJtextField t=null; private TJtextArea a=null; private JScrollPane r=null; private JPanel p=null; private TJcheck c=null; public AcaoMovimentoDeObjetos(int x,int y,int larg,int alt,JLabel l,JPanel j){ this.x=x; this.y=y; this.l=l; this.j=j; this.alt=alt; this.larg=larg; } public AcaoMovimentoDeObjetos(int x,int y,int larg,int alt,TJcheck c,JPanel j){ this.x=x; this.y=y; this.c=c; this.j=j; this.alt=alt; this.larg=larg; } public AcaoMovimentoDeObjetos(int x,int y,int larg,int alt,JButton b,JPanel j){ this.x=x; this.y=y; this.b=b; this.j=j; this.alt=alt; this.larg=larg; } public AcaoMovimentoDeObjetos(int x,int y,int larg,int alt,TJtextField t,JPanel j){ this.x=x; this.y=y; this.j=j; this.alt=alt; this.larg=larg; this.t=t; } public AcaoMovimentoDeObjetos(int x,int y,int larg,int alt,TJtextArea a,JPanel j){ this.x=x; this.y=y; this.j=j; this.alt=alt; this.larg=larg; this.a=a; } public AcaoMovimentoDeObjetos(int x,int y,int larg,int alt,JScrollPane r,JPanel j){ this.x=x; this.y=y; this.j=j; this.alt=alt; this.larg=larg; this.r=r; } public AcaoMovimentoDeObjetos(int x,int y,int larg,int alt,FundoJpane p,JPanel j){ this.x=x; this.y=y; this.j=j; this.alt=alt; this.larg=larg; this.p=p; } @Override public void run() { int temp=800,pi=50;//numero de pixel por velocidade while(temp>=x) { try { Thread.sleep(10);//velocidade } catch (InterruptedException ex) { Logger.getLogger(AcaoMovimentoDeObjetos.class.getName()).log(Level.SEVERE, null, ex); } if(b!=null) { b.setBounds(temp, y, larg, alt); temp-=pi; j.add(b); } if(l!=null) { l.setBounds(temp, y, larg, alt); temp-=pi; j.add(l); } if(t!=null) { t.setBounds(temp, y, larg, alt); temp-=pi; j.add(t); } if(a!=null) { a.setBounds(temp, y, larg, alt); temp-=pi; j.add(a); } if(r!=null) { r.setBounds(temp, y, larg, alt); temp-=pi; j.add(r); j.revalidate(); } if(p!=null) { p.setBounds(temp, y, larg, alt); temp-=pi; j.add(p); } if(c!=null) { c.setBounds(temp, y, larg, alt); temp-=pi; j.add(c); } } //correo de posio if(b!=null) { b.setBounds(x, y, larg, alt); j.add(b); } if(l!=null) { l.setBounds(x, y, larg, alt); j.add(l); } if(t!=null) { t.setBounds(x, y, larg, alt); j.add(t); } if(a!=null) { a.setBounds(x, y, larg, alt); j.add(a); } if(r!=null) { r.setBounds(x, y, larg, alt); j.add(r); j.revalidate(); } if(p!=null) { p.setBounds(x, y, larg, alt); j.add(p); } if(c!=null) { c.setBounds(x, y, larg, alt); j.add(c); } j.repaint(); Thread.interrupted(); } } class AcaoRecolherObjetos implements Runnable{ private int x,y,alt,larg; private JButton b=null; private JLabel l=null; private JPanel j; private TJtextField t=null; private TJtextArea a=null; private JScrollPane r=null; private JPanel p=null; private TJcheck c=null; public AcaoRecolherObjetos(int x,int y,int larg,int alt,JLabel l,JPanel j){ this.x=x; this.y=y; this.l=l; this.j=j; this.alt=alt; this.larg=larg; } public AcaoRecolherObjetos(int x,int y,int larg,int alt,TJcheck c,JPanel j){ this.x=x; this.y=y; this.c=c; this.j=j; this.alt=alt; this.larg=larg; } public AcaoRecolherObjetos(int x,int y,int larg,int alt,JButton b,JPanel j){ this.x=x; this.y=y; this.b=b; this.j=j; this.alt=alt; this.larg=larg; } public AcaoRecolherObjetos(int x,int y,int larg,int alt,JPanel p,JPanel j){ this.x=x; this.y=y; this.j=j; this.alt=alt; this.larg=larg; this.p=p; } public AcaoRecolherObjetos(int x,int y,int larg,int alt,TJtextField t,JPanel j){ this.x=x; this.y=y; this.j=j; this.alt=alt; this.larg=larg; this.t=t; } public AcaoRecolherObjetos(int x,int y,int larg,int alt,TJtextArea a,JPanel j){ this.x=x; this.y=y; this.j=j; this.alt=alt; this.larg=larg; this.a=a; } public AcaoRecolherObjetos(int x,int y,int larg,int alt,JScrollPane r,JPanel j){ this.x=x; this.y=y; this.j=j; this.alt=alt; this.larg=larg; this.r=r; } @Override public void run() { int temp=x; while(temp<=800+768) { try { Thread.sleep(10); } catch (InterruptedException ex) { Logger.getLogger(AcaoRecolherObjetos.class.getName()).log(Level.SEVERE, null, ex); } if(b!=null) { b.setBounds(temp, y, larg, alt); temp+=50; j.add(b); } if(l!=null) { l.setBounds(temp, y, larg, alt); temp+=50; j.add(l); } if(p!=null) { p.setBounds(temp, y, larg, alt); temp+=50; j.add(p); } if(t!=null) { t.setBounds(temp, y, larg, alt); temp+=50; j.add(t); } if(a!=null) { a.setBounds(temp, y, larg, alt); temp+=50; j.add(a); } if(r!=null) { r.setBounds(temp, y, larg, alt); temp+=50; j.add(r); } if(c!=null) { c.setBounds(temp, y, larg, alt); temp+=50; j.add(c); } } j.repaint(); Thread.interrupted(); } } //listeners arrastar a tela class AcaoCoordenadasFrameMovimentacao implements MouseListener{ @Override public void mouseClicked(MouseEvent e) {} @Override public void mousePressed(MouseEvent e) { tempx = e.getX(); tempy = e.getY(); } @Override public void mouseReleased(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} } class AcaoCoordenadasTelaMovimentacao implements MouseMotionListener{ @Override public void mouseDragged(MouseEvent e) { screenX = e.getXOnScreen(); screenY = e.getYOnScreen(); setLocation(screenX-tempx, screenY-tempy); } @Override public void mouseMoved(MouseEvent e) { } } //listeners Botoes Close E MIN class AcaoFechar implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { System.exit(1); } } class AcaoMinimizar implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { setState(Frame.ICONIFIED); } } //fim da classe }
src/GUI/GuiMain.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. * Erick Batista do Nascimento */ package GUI; import iteradores.IteradorBackups; import java.awt.Color; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Frame; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; import java.awt.Dimension; import java.io.File; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.JScrollBar; import enuns.DiasSemana; import objetos.Backup; import objetos.Dias; import objetos.RegraBackup; import nucleo.Core; import bancoDeDados.CarregaBanco; /** * * @author erick7 */ public class GuiMain extends JFrame { /** * */ private static final long serialVersionUID = 1L; FundoJpane imgc; public static boolean isCancelado=false; private boolean controle; private JPanel fundo; private int screenX,screenY; private int tempx,tempy; private TJtextArea cdic; private JLabel t1; private JLabel textoTile1; private JLabel textoTile3; private JLabel textoTile4; private JButton tile1; private JButton tile3; private JButton tile4; private TJtextField cnome; static private JScrollPane scr; private TJtextField cbac; private boolean flag=false; private JLabel tlv; private TJlabel tp1; private TJlabel tl1,tl2,tl3; private JButton Search; private JButton Searchs; private JButton conf; private JButton age; private JLabel tla; private TJlabel tpa; private JPanel dia; private JButton seg; private JButton ter; private JButton quar; private JButton quin; private JButton sex; private JButton sab; private JButton dom; private FundoJpane horas; private TJbutton h0; private TJbutton h1; private TJbutton h2; private TJbutton h3; private TJbutton h4; private TJbutton h5; private TJbutton h6; private TJbutton h7; private TJbutton h8; private TJbutton h9; private TJbutton h10; private TJbutton h11; private TJbutton h12; private TJbutton h13; private TJbutton h14; private TJbutton h15; private TJbutton h16; private TJbutton h17; private TJbutton h18; private TJbutton h19; private TJbutton h20; private TJbutton h21; private TJbutton h22; private TJbutton h23; private FundoJpane minutos; private TJbutton m0; private TJbutton m1; private TJbutton m3; private TJbutton m2; private TJbutton m4; private TJbutton m5; private TJbutton m6; private TJbutton m7; private TJbutton m8; private TJbutton m9; private TJbutton m10; private TJbutton m11; private TJbutton m12; private TJbutton m13; private TJbutton m14; private TJbutton m15; private TJbutton m16; private TJbutton m17; private TJbutton m18; private TJbutton m19; private TJbutton m20; private TJbutton m21; private TJbutton m22; private TJbutton m23; private TJbutton m24; private TJbutton m25; private TJbutton m26; private TJbutton m27; private TJbutton m28; private TJbutton m29; private TJbutton m31; private TJbutton m32; private TJbutton m33; private TJbutton m34; private TJbutton m35; private TJbutton m36; private TJbutton m30; private TJbutton m37; private TJbutton m38; private TJbutton m39; private TJbutton m40; private TJbutton m41; private TJbutton m42; private TJbutton m43; private TJbutton m44; private TJbutton m45; private TJbutton m46; private TJbutton m48; private TJbutton m47; private TJbutton m49; private TJbutton m50; private TJbutton m51; private TJbutton m52; private TJbutton m53; private TJbutton m54; private TJbutton m55; private TJbutton m56; private TJbutton m57; private TJbutton m58; private TJbutton m59; private JScrollPane scrolldia; private TJbutton diau; private TJbutton diad; private TJlabel lbdia; private TJlabel lbdh; private JScrollPane scrollHora; private TJbutton hu; private TJbutton hd; private TJbutton mu; private TJbutton md; private JScrollPane scrollMinutos; private TJlabel lbm; private TJbutton confa; private FundoJpane ld; private FundoJpane lh; private FundoJpane lm; private Core core; private Backup B; private RegraBackup R; private Dias D; private TJcheck check; private JScrollPane scrollRegra; private TJbutton cancela; private TJbutton fechar; private FundoJpane imgci; GuiMain() { setUndecorated(true); setResizable(false); setSize(800,500); setBackground(new Color(0, 0, 0, 0)); setLocationRelativeTo(null); constroiFrame(); core = new Core(); } //Elementos do JFrame que sustentam a janela private void constroiFrame () { //montando estrutura de fundo ImageIcon icf = new ImageIcon(getClass().getResource("/GUI/Imagens/load.gif")); Image imf = icf.getImage(); fundo=new FundoJpane(imf,0,0,0,0); fundo.setLayout(null); fundo.setBounds(0,0,800,500); fundo.addMouseListener(new AcaoCoordenadasFrameMovimentacao()); fundo.addMouseMotionListener(new AcaoCoordenadasTelaMovimentacao()); add(fundo); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); this.setIconImage(null); setVisible(true); controleTelaLoading(); //fim fundo } private void constroiFundoFrame(){ setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ImageIcon icf = new ImageIcon(getClass().getResource("/GUI/Imagens/Jfundo.png")); Image imf = icf.getImage(); ((FundoJpane) fundo).alterarImagem(imf); fechar = new TJbutton("X",0,0,0,0); fechar.setBounds(767,6,16,25); fechar.addActionListener(new AcaoFechar()); fechar.setContentAreaFilled(false); fechar.setOpaque(false); fechar.setForeground(Color.BLACK); fechar.setFont(new Font("Consolas",Font.BOLD,18)); fechar.setBorderPainted(false); fundo.add(fechar); JButton min = new TJbutton("-",0,0,0,0); min.setBounds(748,2,16,25); min.addActionListener(new AcaoMinimizar()); min.setContentAreaFilled(false); min.setOpaque(false); min.setForeground(Color.BLACK); min.setFont(new Font("Consolas",Font.BOLD,32)); min.setBorderPainted(false); fundo.add(min); //tela inicio telaInicio(); } private void controleTelaLoading(){ CarregaBanco b = new CarregaBanco(); if(b.inciaBanco())constroiFundoFrame(); } //tela incial comea aqui private void telaInicio() { t1=new TJlabel("Incio",0,0,0,0); t1.setFont(new Font("CordiaUPC",Font.PLAIN,83)); t1.setForeground(Color.BLACK); textoTile1=new TJlabel("Novo backup",0,0,0,0); textoTile1.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,31)); textoTile1.setForeground(Color.BLACK); ImageIcon tl1i = new ImageIcon(getClass().getResource("/GUI/Imagens/NovoBackup.png")); tile1=new TJbutton("",0,0,0,0); tile1.setIcon(tl1i); tile1.addActionListener(new AcaoNovoCadastro()); ImageIcon tl3i = new ImageIcon(getClass().getResource("/GUI/Imagens/rodaRegra.png")); tile3=new TJbutton("",0,0,0,0); tile3.setIcon(tl3i); textoTile3=new TJlabel("Rodar regra de backup",0,0,0,0); textoTile3.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,31)); textoTile3.setForeground(Color.BLACK); tile3.addActionListener(new AcaoRodaRegra()); ImageIcon tl4 = new ImageIcon(getClass().getResource("/GUI/Imagens/duplicata.png")); tile4=new TJbutton("",0,0,0,0); tile4.setIcon(tl4); textoTile4=new TJlabel("Buscar arquivos duplicados",0,0,0,0); textoTile4.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,31)); textoTile4.setForeground(Color.BLACK); Runnable text = new AcaoMovimentoDeObjetos(50,25,799,114,t1,fundo); new Thread(text).start(); Runnable rt1 = new AcaoMovimentoDeObjetos(118,148,80,80,tile1,fundo); new Thread(rt1).start(); Runnable rtt1 = new AcaoMovimentoDeObjetos(203,171,799,41,textoTile1,fundo); new Thread(rtt1).start(); Runnable rt3 = new AcaoMovimentoDeObjetos(118,233,80,80,tile3,fundo); new Thread(rt3).start(); Runnable rtt3 = new AcaoMovimentoDeObjetos(203,256,799,41,textoTile3,fundo); new Thread(rtt3).start(); Runnable rt4 = new AcaoMovimentoDeObjetos(118,318,80,80,tile4,fundo); new Thread(rt4).start(); Runnable rtt4 = new AcaoMovimentoDeObjetos(203,341,799,41,textoTile4,fundo); new Thread(rtt4).start(); } private void esconderInicio() { Runnable text = new AcaoRecolherObjetos(50,25,799,114,t1,fundo); new Thread(text).start(); Runnable rt1 = new AcaoRecolherObjetos(118,148,80,80,tile1,fundo); new Thread(rt1).start(); Runnable rtt1 = new AcaoRecolherObjetos(203,171,799,41,textoTile1,fundo); new Thread(rtt1).start(); Runnable rt3 = new AcaoRecolherObjetos(118,233,80,80,tile3,fundo); new Thread(rt3).start(); Runnable rtt3 = new AcaoRecolherObjetos(203,256,799,41,textoTile3,fundo); new Thread(rtt3).start(); Runnable rt4 = new AcaoRecolherObjetos(118,318,80,80,tile4,fundo); new Thread(rt4).start(); Runnable rtt4 = new AcaoRecolherObjetos(203,341,799,41,textoTile4,fundo); new Thread(rtt4).start(); } //listeners da tela de inicio class AcaoNovoCadastro implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { telaCadastro(); esconderInicio(); } } class AcaoRodaRegra implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { esconderInicio(); regraBackup(); } } //tela de concluso //setBounds (horizontal,vertical,largura,altura); private void concluido(){ ImageIcon v1 = new ImageIcon(getClass().getResource("/GUI/Imagens/back.png")); tlv=new JLabel(v1); tlv.addMouseListener(new AcaoChamarTelaVoltaInicio(true)); Runnable voltar= new AcaoMovimentoDeObjetos(50,6,22,22,tlv,fundo); new Thread(voltar).start(); t1=new TJlabel("Concludo",0,0,0,0); t1.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,81)); t1.setForeground(Color.BLACK); ImageIcon tl1i = new ImageIcon(getClass().getResource("/GUI/Imagens/ok.png")); Image temp= tl1i.getImage(); imgc = new FundoJpane(temp,0,0,0,0); Runnable icone = new AcaoMovimentoDeObjetos(185,200,100,100,imgc,fundo); new Thread(icone).start(); Runnable text = new AcaoMovimentoDeObjetos(300,180,799,114,t1,fundo); new Thread(text).start(); } private void esconderConcluido(){ Runnable icone = new AcaoRecolherObjetos(185,200,100,100,imgc,fundo); new Thread(icone).start(); Runnable text = new AcaoRecolherObjetos(300,180,799,114,t1,fundo); new Thread(text).start(); } // tela de cadastro private void telaCadastro() { ImageIcon v1 = new ImageIcon(getClass().getResource("/GUI/Imagens/back.png")); tlv=new JLabel(v1); tlv.addMouseListener(new AcaoChamarTelaVoltaInicio(false)); Runnable voltar= new AcaoMovimentoDeObjetos(50,6,22,22,tlv,fundo); new Thread(voltar).start(); tp1=new TJlabel("Novo backup",0,0,0,0); tp1.setFont(new Font("CordiaUPC",Font.PLAIN,83)); tp1.setForeground(Color.BLACK); Runnable text = new AcaoMovimentoDeObjetos(50,25,799,114,tp1,fundo); new Thread(text).start(); //nome tl1=new TJlabel("Nome",0,0,0,0); tl1.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,31)); tl1.setForeground(Color.BLACK); Runnable nome = new AcaoMovimentoDeObjetos(50,140,100,38,tl1,fundo); new Thread(nome).start(); cnome = new TJtextField(0,0,0,0); cnome.setEditable(true); cnome.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,20)); cnome.setForeground(Color.BLACK); Runnable anome = new AcaoMovimentoDeObjetos(50,179,650,38,cnome,fundo); new Thread(anome).start(); //diretorio Backup tl3=new TJlabel("Diretrio de destino do backup",0,0,0,0); tl3.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,31)); tl3.setForeground(Color.BLACK); Runnable bac = new AcaoMovimentoDeObjetos(50,333,700,38,tl3,fundo); new Thread(bac).start(); cbac = new TJtextField(0,0,0,0); cbac.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,20)); cbac.setForeground(Color.BLACK); cbac.setEditable(false); Runnable abac = new AcaoMovimentoDeObjetos(50,372,650,38,cbac,fundo); new Thread(abac).start(); //fim //diretorio arquivo tl2=new TJlabel("Diretrios e arquivos de origem",0,0,0,0); tl2.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,31)); tl2.setForeground(Color.BLACK); Runnable dic = new AcaoMovimentoDeObjetos(50,217,700,38,tl2,fundo); new Thread(dic).start(); cdic = new TJtextArea(0,0,0,0); cdic.setLineWrap(true); cdic.setWrapStyleWord(true); cdic.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,20)); cdic.setForeground(Color.black); cdic.setEditable(false); cdic.setBounds(0, 0, WIDTH,HEIGHT); scr = new JScrollPane(cdic); scr.getVerticalScrollBar().addAdjustmentListener(new AcaoRolagemAutomatica()); scr.setBorder(new CompoundBorder(new EmptyBorder(0, 0, 0, 0),new LineBorder(Color.BLACK))); scr.setOpaque(false);// scr.getViewport().setOpaque(false);// scr.setBounds(0,0,648,74); Runnable adic = new AcaoMovimentoDeObjetos(50,256,650,76,scr,fundo); new Thread(adic).start(); //botao procura pasta para backup Search=new TJbutton("",0,0,0,0); ImageIcon i1 = new ImageIcon(getClass().getResource("/GUI/Imagens/sea.jpg")); Search.setIcon(i1); Search.addActionListener(new AcaoChooserBackup(this));//backup Runnable sea1=new AcaoMovimentoDeObjetos(700,372,38,38,Search,fundo); new Thread(sea1).start(); //botao procura arquivos Searchs=new TJbutton("",0,0,0,0); ImageIcon i2 = new ImageIcon(getClass().getResource("/GUI/Imagens/sea.jpg")); Searchs.setIcon(i2); Searchs.addActionListener(new AcaoChooserDiretorio(this));//origem Runnable sea2=new AcaoMovimentoDeObjetos(700,256,38,38,Searchs,fundo); new Thread(sea2).start(); //botao confirma conf=new TJbutton("Confirmar",0,0,0,255); conf.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,18)); conf.setForeground(Color.WHITE); conf.addActionListener(new GravarCadastro()); Runnable cf=new AcaoMovimentoDeObjetos(50,432,90,38,conf,fundo); new Thread(cf).start(); //boto agenda age=new TJbutton("Agendamento",0,0,0,255); age.setForeground(Color.white); age.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,18)); age.addActionListener(new AcaoChamarTelaAgenda()); Runnable ag=new AcaoMovimentoDeObjetos(650,432,90,38,age,fundo); new Thread(ag).start(); //fim //setBounds (horizontal,vertical,largura,altura); } private void esconderCadastro(){ Runnable sea1=new AcaoRecolherObjetos(700,372,38,38,Search,fundo); new Thread(sea1).start(); Runnable sea2=new AcaoRecolherObjetos(700,256,38,38,Searchs,fundo); new Thread(sea2).start(); Runnable voltar= new AcaoRecolherObjetos(50,6,22,22,tlv,fundo); new Thread(voltar).start(); Runnable text = new AcaoRecolherObjetos(50,25,799,114,tp1,fundo); new Thread(text).start(); Runnable nome = new AcaoRecolherObjetos(50,140,100,38,tl1,fundo); new Thread(nome).start(); Runnable anome = new AcaoRecolherObjetos(50,179,620,38,cnome,fundo); new Thread(anome).start(); Runnable dic = new AcaoRecolherObjetos(50,217,700,38,tl2,fundo); new Thread(dic).start(); Runnable adic = new AcaoRecolherObjetos(50,256,620,76,scr,fundo); new Thread(adic).start(); Runnable bac = new AcaoRecolherObjetos(50,333,700,38,tl3,fundo); new Thread(bac).start(); Runnable abac = new AcaoRecolherObjetos(50,372,620,38,cbac,fundo); new Thread(abac).start(); Runnable ag=new AcaoRecolherObjetos(650,432,90,38,age,fundo); new Thread(ag).start(); Runnable cf=new AcaoRecolherObjetos(50,432,90,38,conf,fundo); new Thread(cf).start(); } //listener Cadastro class GravarCadastro implements ActionListener{ @Override public void actionPerformed(ActionEvent arg0) { if(cdic.getText().isEmpty() && cbac.getText().isEmpty() && cnome.getText().isEmpty()){ JOptionPane.showMessageDialog(null,"Todos os campos so obrigatrios"); }else{ R=new RegraBackup(cbac.getText(),cdic.getText()); B=new Backup(cnome.getText(), new Date().toString()); core.criarBackup(B,R); esconderCadastro(); concluido(); } } } class AcaoChooserDiretorio implements ActionListener{ private JFileChooser chooser; private JFrame j; public AcaoChooserDiretorio(JFrame j){ this.j=j; } String caminho=""; @Override public void actionPerformed(ActionEvent e) { chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); chooser.setMultiSelectionEnabled(true); int r=chooser.showOpenDialog(j); if (r == JFileChooser.APPROVE_OPTION){ File[] file=chooser.getSelectedFiles(); try{ for(File temp:file) { caminho+=temp.getAbsolutePath()+"|\n"; cdic.setText(caminho); } }catch (Exception erro){ JOptionPane.showMessageDialog(j,"Erro ao carregar o caminho!"); } } } } class AcaoChooserBackup implements ActionListener{ private JFrame j; private JFileChooser chooserb; public AcaoChooserBackup(JFrame j){ this.j=j; } String caminho=""; @Override public void actionPerformed(ActionEvent e) { chooserb = new JFileChooser(); chooserb.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); chooserb.setMultiSelectionEnabled(false); int r=chooserb.showOpenDialog(j); if (r == JFileChooser.APPROVE_OPTION){ File file=chooserb.getSelectedFile(); try{ cbac.setText(file.getAbsolutePath()+"|"); }catch (Exception erro){ JOptionPane.showMessageDialog(j,"Erro ao carregar o caminho!"); } } } } class AcaoChamarTelaVoltaInicio implements MouseListener{ boolean c=false; AcaoChamarTelaVoltaInicio(boolean c) { this.c=c; } @Override public void mouseClicked(MouseEvent arg0) { if(c==true){ esconderConcluido(); Runnable voltar= new AcaoRecolherObjetos(50,6,22,22,tlv,fundo); new Thread(voltar).start(); }else esconderCadastro(); telaInicio(); } @Override public void mouseEntered(MouseEvent arg0) {} @Override public void mouseExited(MouseEvent arg0) {} @Override public void mousePressed(MouseEvent arg0) {} @Override public void mouseReleased(MouseEvent arg0) {} } class AcaoChamarTelaAgenda implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { esconderCadastro(); telaAgendamento(); } } class AcaoRolagemAutomatica implements AdjustmentListener{ //rolagem automatica @Override public void adjustmentValueChanged(AdjustmentEvent e) { if(flag) { e.getAdjustable().setValue(e.getAdjustable().getMaximum()); } flag = false; } } //fim listener cadastro //tela de agendamento de dia //setBounds (horizontal,vertical,largura,altura); private void telaAgendamento(){ ImageIcon v1 = new ImageIcon(getClass().getResource("/GUI/Imagens/back.png")); tla=new JLabel(v1); tla.addMouseListener(new AcaoChamarTelaVoltaCadastro()); Runnable voltar= new AcaoMovimentoDeObjetos(50,6,22,22,tla,fundo); new Thread(voltar).start(); tpa=new TJlabel("Agendar Backup",0,0,0,0); tpa.setFont(new Font("CordiaUPC",Font.PLAIN,83)); tpa.setForeground(Color.BLACK); //escolha de dia dia = new JPanel(); dia.setLayout(null); dia.setPreferredSize(new Dimension(100,477)); dia.setOpaque(false); seg=new TJbutton("Segunda",0,0,0,255); seg.setBounds(1,53,99,50); dia.add(seg); ter=new TJbutton("Tera",0,0,0,255); ter.setBounds(1,106,99,50); dia.add(ter); quar=new TJbutton("Quarta",0,0,0,255); quar.setBounds(1,159,99,50); dia.add(quar); quin=new TJbutton("Quinta",0,0,0,255); quin.setBounds(1,212,99,50); dia.add(quin); sex=new TJbutton("Sexta",0,0,0,255); sex.setBounds(1,265,99,50); dia.add(sex); sab=new TJbutton("Sbado",0,0,0,255); sab.setBounds(1,318,99,50); dia.add(sab); dom=new TJbutton("Domingo",0,0,0,255); dom.setBounds(1,371,99,50); dia.add(dom); scrolldia = new JScrollPane(dia); scrolldia.setOpaque(false); scrolldia.getViewport().setOpaque(false); scrolldia.setEnabled(false); scrolldia.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrolldia.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER); scrolldia.setBorder(null); diau = new TJbutton("",0,0,0,0); ImageIcon idiau = new ImageIcon(getClass().getResource("/GUI/Imagens/UP.png")); diau.setIcon(idiau); diau.addMouseListener(new AcaoSubirScroll(scrolldia)); diau.setBorder(null); diad = new TJbutton("",0,0,0,0); ImageIcon idiad = new ImageIcon(getClass().getResource("/GUI/Imagens/Down.png")); diad.setIcon(idiad); diad.addMouseListener(new AcaoDescerScroll(scrolldia)); diad.setBorder(null); lbdia = new TJlabel(null,0,0,0,0); lbdia.setText("Dia"); lbdia.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,30)); //fim escolha de dia //escolha Horas horas=new FundoJpane(null,0,0,0,0); horas.setLayout(null); horas.setPreferredSize(new Dimension(52,1378)); horas.setOpaque(false); h0=new TJbutton("00",0,0,0,255); h0.setBounds(1,53,50,50); horas.add(h0); h1=new TJbutton("01",0,0,0,255); h1.setBounds(1,106,50,50); horas.add(h1); h2=new TJbutton("02",0,0,0,255); h2.setBounds(1,159,50,50); horas.add(h2); h3=new TJbutton("03",0,0,0,255); h3.setBounds(1,212,50,50); horas.add(h3); h4=new TJbutton("04",0,0,0,255); h4.setBounds(1,265,50,50); horas.add(h4); h5=new TJbutton("05",0,0,0,255); h5.setBounds(1,318,50,50); horas.add(h5); h6=new TJbutton("06",0,0,0,255); h6.setBounds(1,371,50,50); horas.add(h6); h7=new TJbutton("07",0,0,0,255); h7.setBounds(1,424,50,50); horas.add(h7); h8=new TJbutton("08",0,0,0,255); h8.setBounds(1,477,50,50); horas.add(h8); h9=new TJbutton("09",0,0,0,255); h9.setBounds(1,530,50,50); horas.add(h9); h10=new TJbutton("10",0,0,0,255); h10.setBounds(1,583,50,50); horas.add(h10); h11=new TJbutton("11",0,0,0,255); h11.setBounds(1,636,50,50); horas.add(h11); h12=new TJbutton("12",0,0,0,255); h12.setBounds(1,689,50,50); horas.add(h12); h13=new TJbutton("13",0,0,0,255); h13.setBounds(1,742,50,50); horas.add(h13); h14=new TJbutton("14",0,0,0,255); h14.setBounds(1,795,50,50); horas.add(h14); h15=new TJbutton("15",0,0,0,255); h15.setBounds(1,848,50,50); horas.add(h15); h16=new TJbutton("16",0,0,0,255); h16.setBounds(1,901,50,50); horas.add(h16); h17=new TJbutton("17",0,0,0,255); h17.setBounds(1,954,50,50); horas.add(h17); h18=new TJbutton("18",0,0,0,255); h18.setBounds(1,1007,50,50); horas.add(h18); h19=new TJbutton("19",0,0,0,255); h19.setBounds(1,1060,50,50); horas.add(h19); h20=new TJbutton("20",0,0,0,255); h20.setBounds(1,1113,50,50); horas.add(h20); h21=new TJbutton("21",0,0,0,255); h21.setBounds(1,1166,50,50); horas.add(h21); h22=new TJbutton("22",0,0,0,255); h22.setBounds(1,1219,50,50); horas.add(h22); h23=new TJbutton("23",0,0,0,255); h23.setBounds(1,1272,50,50); horas.add(h23); lbdh = new TJlabel(null,0,0,0,0); lbdh.setText("Hora"); lbdh.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,30)); scrollHora = new JScrollPane(horas); scrollHora.setOpaque(false); scrollHora.getViewport().setOpaque(false); scrollHora.setEnabled(false); scrollHora.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrollHora.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER); scrollHora.setBorder(null); hu = new TJbutton("",0,0,0,0); ImageIcon ihu = new ImageIcon(getClass().getResource("/GUI/Imagens/UP.png")); hu.setIcon(ihu); hu.addMouseListener(new AcaoSubirScroll(scrollHora)); hu.setBorder(null); hd = new TJbutton("",0,0,0,0); ImageIcon ihd = new ImageIcon(getClass().getResource("/GUI/Imagens/Down.png")); hd.setIcon(ihd); hd.addMouseListener(new AcaoDescerScroll(scrollHora)); hd.setBorder(null); //escolha minutos minutos=new FundoJpane(null,0,0,0,0); minutos.setLayout(null); minutos.setPreferredSize(new Dimension(52,3286)); minutos.setOpaque(false); m0=new TJbutton("00",0,0,0,255); m0.setBounds(1,53,50,50); minutos.add(m0); m1=new TJbutton("01",0,0,0,255); m1.setBounds(1,106,50,50); minutos.add(m1); m2=new TJbutton("02",0,0,0,255); m2.setBounds(1,159,50,50); minutos.add(m2); m3=new TJbutton("03",0,0,0,255); m3.setBounds(1,212,50,50); minutos.add(m3); m4=new TJbutton("04",0,0,0,255); m4.setBounds(1,265,50,50); minutos.add(m4); m5=new TJbutton("05",0,0,0,255); m5.setBounds(1,318,50,50); minutos.add(m5); m6=new TJbutton("06",0,0,0,255); m6.setBounds(1,371,50,50); minutos.add(m6); m7=new TJbutton("07",0,0,0,255); m7.setBounds(1,424,50,50); minutos.add(m7); m8=new TJbutton("08",0,0,0,255); m8.setBounds(1,477,50,50); minutos.add(m8); m9=new TJbutton("09",0,0,0,255); m9.setBounds(1,530,50,50); minutos.add(m9); m10=new TJbutton("10",0,0,0,255); m10.setBounds(1,583,50,50); minutos.add(m10); m11=new TJbutton("11",0,0,0,255); m11.setBounds(1,636,50,50); minutos.add(m11); m12=new TJbutton("12",0,0,0,255); m12.setBounds(1,689,50,50); minutos.add(m12); m13=new TJbutton("13",0,0,0,255); m13.setBounds(1,742,50,50); minutos.add(m13); m14=new TJbutton("14",0,0,0,255); m14.setBounds(1,795,50,50); minutos.add(m14); m15=new TJbutton("15",0,0,0,255); m15.setBounds(1,848,50,50); minutos.add(m15); m16=new TJbutton("16",0,0,0,255); m16.setBounds(1,901,50,50); minutos.add(m16); m17=new TJbutton("17",0,0,0,255); m17.setBounds(1,954,50,50); minutos.add(m17); m18=new TJbutton("18",0,0,0,255); m18.setBounds(1,1007,50,50); minutos.add(m18); m19=new TJbutton("19",0,0,0,255); m19.setBounds(1,1060,50,50); minutos.add(m19); m20=new TJbutton("20",0,0,0,255); m20.setBounds(1,1113,50,50); minutos.add(m20); m21=new TJbutton("21",0,0,0,255); m21.setBounds(1,1166,50,50); minutos.add(m21); m22=new TJbutton("22",0,0,0,255); m22.setBounds(1,1219,50,50); minutos.add(m22); m23=new TJbutton("23",0,0,0,255); m23.setBounds(1,1272,50,50); minutos.add(m23); m24=new TJbutton("24",0,0,0,255); m24.setBounds(1,1325,50,50); minutos.add(m24); m25=new TJbutton("25",0,0,0,255); m25.setBounds(1,1378,50,50); minutos.add(m25); m26=new TJbutton("26",0,0,0,255); m26.setBounds(1,1431,50,50); minutos.add(m26); m27=new TJbutton("27",0,0,0,255); m27.setBounds(1,1484,50,50); minutos.add(m27); m28=new TJbutton("28",0,0,0,255); m28.setBounds(1,1537,50,50); minutos.add(m28); m29=new TJbutton("29",0,0,0,255); m29.setBounds(1,1590,50,50); minutos.add(m29); m30=new TJbutton("30",0,0,0,255); m30.setBounds(1,1643,50,50); minutos.add(m30); m31=new TJbutton("31",0,0,0,255); m31.setBounds(1,1696,50,50); minutos.add(m31); m32=new TJbutton("32",0,0,0,255); m32.setBounds(1,1749,50,50); minutos.add(m32); m33=new TJbutton("33",0,0,0,255); m33.setBounds(1,1802,50,50); minutos.add(m33); m34=new TJbutton("34",0,0,0,255); m34.setBounds(1,1855,50,50); minutos.add(m34); m35=new TJbutton("35",0,0,0,255); m35.setBounds(1,1908,50,50); minutos.add(m35); m36=new TJbutton("36",0,0,0,255); m36.setBounds(1,1961,50,50); minutos.add(m36); m37=new TJbutton("37",0,0,0,255); m37.setBounds(1,2014,50,50); minutos.add(m37); m38=new TJbutton("38",0,0,0,255); m38.setBounds(1,2067,50,50); minutos.add(m38); m39=new TJbutton("39",0,0,0,255); m39.setBounds(1,2120,50,50); minutos.add(m39); m40=new TJbutton("40",0,0,0,255); m40.setBounds(1,2173,50,50); minutos.add(m40); m41=new TJbutton("41",0,0,0,255); m41.setBounds(1,2226,50,50); minutos.add(m41); m42=new TJbutton("42",0,0,0,255); m42.setBounds(1,2279,50,50); minutos.add(m42); m43=new TJbutton("43",0,0,0,255); m43.setBounds(1,2332,50,50); minutos.add(m43); m44=new TJbutton("44",0,0,0,255); m44.setBounds(1,2385,50,50); minutos.add(m44); m45=new TJbutton("45",0,0,0,255); m45.setBounds(1,2438,50,50); minutos.add(m45); m46=new TJbutton("46",0,0,0,255); m46.setBounds(1,2491,50,50); minutos.add(m46); m47=new TJbutton("47",0,0,0,255); m47.setBounds(1,2544,50,50); minutos.add(m47); m48=new TJbutton("48",0,0,0,255); m48.setBounds(1,2597,50,50); minutos.add(m48); m49=new TJbutton("49",0,0,0,255); m49.setBounds(1,2650,50,50); minutos.add(m49); m50=new TJbutton("50",0,0,0,255); m50.setBounds(1,2703,50,50); minutos.add(m50); m51=new TJbutton("51",0,0,0,255); m51.setBounds(1,2756,50,50); minutos.add(m51); m52=new TJbutton("52",0,0,0,255); m52.setBounds(1,2809,50,50); minutos.add(m52); m53=new TJbutton("53",0,0,0,255); m53.setBounds(1,2862,50,50); minutos.add(m53); m54=new TJbutton("54",0,0,0,255); m54.setBounds(1,2915,50,50); minutos.add(m54); m55=new TJbutton("55",0,0,0,255); m55.setBounds(1,2968,50,50); minutos.add(m55); m56=new TJbutton("56",0,0,0,255); m56.setBounds(1,3021,50,50); minutos.add(m56); m57=new TJbutton("57",0,0,0,255); m57.setBounds(1,3074,50,50); minutos.add(m57); m58=new TJbutton("58",0,0,0,255); m58.setBounds(1,3127,50,50); minutos.add(m58); m59=new TJbutton("59",0,0,0,255); m59.setBounds(1,3180,50,50); minutos.add(m59); lbm = new TJlabel(null,0,0,0,0); lbm.setText("Minuto"); lbm.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,30)); lbm.setBounds(430,257,70,50); fundo.add(lbm); scrollMinutos = new JScrollPane(minutos); scrollMinutos.setOpaque(false); scrollMinutos.getViewport().setOpaque(false); scrollMinutos.setEnabled(false); scrollMinutos.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrollMinutos.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER); scrollMinutos.setBorder(null); mu = new TJbutton("",0,0,0,0); ImageIcon imu = new ImageIcon(getClass().getResource("/GUI/Imagens/UP.png")); mu.setIcon(imu); mu.addMouseListener(new AcaoSubirScroll(scrollMinutos)); mu.setBorder(null); md = new TJbutton("",0,0,0,0); ImageIcon imd = new ImageIcon(getClass().getResource("/GUI/Imagens/Down.png")); md.setIcon(imd); md.addMouseListener(new AcaoDescerScroll(scrollMinutos)); md.setBorder(null); //fim minutos confa=new TJbutton("Agendar e confirmar",0,0,0,255); confa.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,18)); confa.setForeground(Color.WHITE); confa.addActionListener(new SalvaAgendamento()); confa.setBounds(325,432,150,38); fundo.add(confa); ImageIcon icd = new ImageIcon(getClass().getResource("/GUI/Imagens/100.png")); Image id=icd.getImage(); ld=new FundoJpane(id,0,0,0,0); ld.setBounds(100,208,99,156); lh=new FundoJpane(id,0,0,0,0); lh.setBounds(300,208,51,156); lm=new FundoJpane(id,0,0,0,0); lm.setBounds(500,208,51,156); check=new TJcheck("Desligar o computador aps a execuo.",0,0,0,0); check.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,30)); check.setForeground(Color.BLACK); check.setFocusable(false); //threads de movimento //setBounds (horizontal,vertical,largura,altura); Runnable min= new AcaoMovimentoDeObjetos(500,208,51,156,scrollMinutos,fundo); new Thread(min).start(); Runnable upm = new AcaoMovimentoDeObjetos(550,260,17,27,mu,fundo); new Thread(upm).start(); Runnable dwm = new AcaoMovimentoDeObjetos(550,288,17,27,md,fundo); new Thread(dwm).start(); Runnable text = new AcaoMovimentoDeObjetos(50,25,799,114,tpa,fundo); new Thread(text).start(); Runnable day= new AcaoMovimentoDeObjetos(100,208,99,156,scrolldia,fundo); new Thread(day).start(); Runnable upd = new AcaoMovimentoDeObjetos(200,260,17,27,diau,fundo); new Thread(upd).start(); Runnable dwd = new AcaoMovimentoDeObjetos(200,288,17,27,diad,fundo); new Thread(dwd).start(); Runnable lbd = new AcaoMovimentoDeObjetos(50,257,50,50,lbdia,fundo); new Thread(lbd).start(); Runnable lbh = new AcaoMovimentoDeObjetos(250,257,50,50,lbdh,fundo); new Thread(lbh).start(); Runnable hor= new AcaoMovimentoDeObjetos(300,208,51,156,scrollHora,fundo); new Thread(hor).start(); Runnable uph = new AcaoMovimentoDeObjetos(350,260,17,27,hu,fundo); new Thread(uph).start(); Runnable dwh = new AcaoMovimentoDeObjetos(350,288,17,27,hd,fundo); new Thread(dwh).start(); Runnable chd = new AcaoMovimentoDeObjetos(50,328,799,114,check,fundo); new Thread(chd).start(); fundo.add(ld); fundo.add(lh); fundo.add(lm); //setBounds (horizontal,vertical,largura,altura); } private DiasSemana getDia(JScrollPane scr){; DiasSemana dia=null; JScrollBar scroll = scr.getVerticalScrollBar(); int temp=scroll.getValue()+53,resul; resul=temp/53; switch(resul){ case 1: dia=DiasSemana.SEGUNDA; break; case 2: dia=DiasSemana.TERCA; break; case 3: dia=DiasSemana.QUARTA; break; case 4: dia=DiasSemana.QUINTA; break; case 5: dia=DiasSemana.SEXTA; break; case 6: dia=DiasSemana.SABADO; break; case 7: dia=DiasSemana.DOMINGO; break; } return dia; } private String getMinuto(JScrollPane scr){; JScrollBar scroll = scr.getVerticalScrollBar(); int temp=scroll.getValue()+53,resul; resul=temp/53; resul--; String minuto=String.valueOf(resul); return minuto; } private String getHora(JScrollPane scr){; JScrollBar scroll = scr.getVerticalScrollBar(); int temp=scroll.getValue()+53,resul; resul=temp/53; resul--; String hora=String.valueOf(resul); return hora; } //esconder agendamento private void esconderAgendamento(){ Runnable chd = new AcaoRecolherObjetos(50,328,799,114,check,fundo); new Thread(chd).start(); Runnable d= new AcaoRecolherObjetos(100,208,99,156,ld,fundo); new Thread(d).start(); Runnable h= new AcaoRecolherObjetos(300,208,51,156,lh,fundo); new Thread(h).start(); Runnable m= new AcaoRecolherObjetos(500,208,51,156,lm,fundo); new Thread(m).start(); Runnable cf=new AcaoRecolherObjetos(355,432,90,38,confa,fundo); new Thread(cf).start(); Runnable voltar= new AcaoRecolherObjetos(50,6,22,22,tla,fundo); new Thread(voltar).start(); Runnable text = new AcaoRecolherObjetos(50,25,799,114,tpa,fundo); new Thread(text).start(); Runnable day= new AcaoRecolherObjetos(100,208,99,156,scrolldia,fundo); new Thread(day).start(); Runnable upd = new AcaoRecolherObjetos(200,260,17,27,diau,fundo); new Thread(upd).start(); Runnable dwd = new AcaoRecolherObjetos(200,288,17,27,diad,fundo); new Thread(dwd).start(); Runnable lbd = new AcaoRecolherObjetos(50,257,50,50,lbdia,fundo); new Thread(lbd).start(); Runnable lbh = new AcaoRecolherObjetos(250,257,50,50,lbdh,fundo); new Thread(lbh).start(); Runnable hor= new AcaoRecolherObjetos(300,208,51,156,scrollHora,fundo); new Thread(hor).start(); Runnable uph = new AcaoRecolherObjetos(350,260,17,27,hu,fundo); new Thread(uph).start(); Runnable dwh = new AcaoRecolherObjetos(350,288,17,27,hd,fundo); new Thread(dwh).start(); Runnable min= new AcaoRecolherObjetos(500,208,51,156,scrollMinutos,fundo); new Thread(min).start(); Runnable upm = new AcaoRecolherObjetos(550,260,17,27,mu,fundo); new Thread(upm).start(); Runnable dwm = new AcaoRecolherObjetos(550,288,17,27,md,fundo); new Thread(dwm).start(); Runnable mlb = new AcaoRecolherObjetos(430,257,70,50,lbm,fundo); new Thread(mlb).start(); } //listener agendamento class SalvaAgendamento implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { System.out.println("Agendado dia: "+getDia(scrolldia)+" s "+getHora(scrollHora)+":"+getMinuto(scrollMinutos)); if(cdic.getText().isEmpty() && cbac.getText().isEmpty() && cnome.getText().isEmpty()){ JOptionPane.showMessageDialog(null,"Todos os campos so obrigatrios"); }else{ boolean des; if(check.isSelected())des=true; else des=false; R=new RegraBackup(cbac.getText(),cdic.getText()); B=new Backup(cnome.getText(), new Date().toString()); D=new Dias(getDia(scrolldia),getHora(scrollHora)+":"+getMinuto(scrollMinutos),des); core.criarBackup(B,R,D); esconderAgendamento(); esconderCadastro(); concluido(); } } } class AcaoChamarTelaVoltaCadastro implements MouseListener{ @Override public void mouseClicked(MouseEvent e) { esconderAgendamento(); Runnable sea1=new AcaoMovimentoDeObjetos(700,372,38,38,Search,fundo); new Thread(sea1).start(); Runnable sea2=new AcaoMovimentoDeObjetos(700,256,38,38,Searchs,fundo); new Thread(sea2).start(); Runnable voltar= new AcaoMovimentoDeObjetos(50,6,22,22,tlv,fundo); new Thread(voltar).start(); Runnable text = new AcaoMovimentoDeObjetos(50,25,799,114,tp1,fundo); new Thread(text).start(); Runnable nome = new AcaoMovimentoDeObjetos(50,140,100,38,tl1,fundo); new Thread(nome).start(); Runnable dic = new AcaoMovimentoDeObjetos(50,217,700,38,tl2,fundo); new Thread(dic).start(); Runnable adic = new AcaoMovimentoDeObjetos(50,256,650,76,scr,fundo); new Thread(adic).start(); Runnable bac = new AcaoMovimentoDeObjetos(50,333,700,38,tl3,fundo); new Thread(bac).start(); Runnable ag=new AcaoMovimentoDeObjetos(650,432,90,38,age,fundo); new Thread(ag).start(); Runnable cf=new AcaoMovimentoDeObjetos(50,432,90,38,conf,fundo); new Thread(cf).start(); Runnable anome = new AcaoMovimentoDeObjetos(50,179,650,38,cnome,fundo); new Thread(anome).start(); Runnable abac = new AcaoMovimentoDeObjetos(50,372,650,38,cbac,fundo); new Thread(abac).start(); } @Override public void mousePressed(MouseEvent e) {} @Override public void mouseReleased(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} } class AcaoDescerScroll implements MouseListener{ private JScrollPane scr; boolean cont=false; public AcaoDescerScroll(JScrollPane scr) { this.scr=scr; } @Override public void mouseClicked(MouseEvent arg0) {} @Override public void mouseEntered(MouseEvent arg0) {} @Override public void mouseExited(MouseEvent arg0) {} @Override public void mousePressed(MouseEvent arg0) { Runnable descer = new Correr(false,scr); new Thread(descer).start(); } @Override public void mouseReleased(MouseEvent arg0) { controle=false; } } class AcaoSubirScroll implements MouseListener{ private JScrollPane scr; public AcaoSubirScroll(JScrollPane scr) { this.scr=scr; } @Override public void mouseClicked(MouseEvent arg0) {} @Override public void mouseEntered(MouseEvent arg0) {} @Override public void mouseExited(MouseEvent arg0) {} @Override public void mousePressed(MouseEvent arg0) { Runnable subir = new Correr(true,scr); new Thread(subir).start(); } @Override public void mouseReleased(MouseEvent arg0) { controle=false; } } class Correr implements Runnable{ boolean c; private JScrollPane scr; Correr(boolean c,JScrollPane scr){ this.c=c; controle=true; this.scr=scr; } @Override public void run() { while(controle){ try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(c==false){ JScrollBar scroll = scr.getVerticalScrollBar(); if(scroll.getValue()<=scroll.getMaximum()-53)scroll.setValue(scroll.getValue()+53); }else{ JScrollBar scroll = scr.getVerticalScrollBar(); if(scroll.getValue()>0)scroll.setValue(scroll.getValue()-53); } } } } //tela regra de backup class AcaoRegraToMenu implements MouseListener{ @Override public void mouseClicked(MouseEvent arg0) { escondeRegra(); telaInicio(); } @Override public void mouseEntered(MouseEvent arg0) {} @Override public void mouseExited(MouseEvent arg0) {} @Override public void mousePressed(MouseEvent arg0) {} @Override public void mouseReleased(MouseEvent arg0) {} } private void escondeRegra(){ Runnable text = new AcaoRecolherObjetos(50,25,799,114,tp1,fundo); new Thread(text).start(); Runnable sr = new AcaoRecolherObjetos(50,140,715,333,scrollRegra,fundo); new Thread(sr).start(); Runnable voltar= new AcaoRecolherObjetos(50,6,22,22,tlv,fundo); new Thread(voltar).start(); } private void regraBackup(){ //setBounds (horizontal,vertical,largura,altura); //fundo das informaes ImageIcon v1 = new ImageIcon(getClass().getResource("/GUI/Imagens/back.png")); tlv=new JLabel(v1); tlv.addMouseListener(new AcaoRegraToMenu()); Runnable voltar= new AcaoMovimentoDeObjetos(50,6,22,22,tlv,fundo); new Thread(voltar).start(); tp1=new TJlabel("Rodar Regra de backup",0,0,0,0); tp1.setFont(new Font("CordiaUPC",Font.PLAIN,83)); tp1.setForeground(Color.BLACK); Runnable text = new AcaoMovimentoDeObjetos(50,25,799,114,tp1,fundo); new Thread(text).start(); Backup ba; int cont=0,cp=1; IteradorBackups ib; int largura=710,altura=125; FundoJpane area = new FundoJpane(null,0,0,0,0); area.setLayout(new FlowLayout()); area.setPreferredSize(new Dimension(largura,altura)); ib=core.resgatarBackups(); scrollRegra = new JScrollPane(area); scrollRegra.setBorder(null); scrollRegra.setOpaque(false);// scrollRegra.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrollRegra.getViewport().setOpaque(false); while(ib.hasNext()){ ba=null; ba=ib.next(); area.add(criarInfo(ba,cont,125*cp,0,700,123)); cp++; cont++; System.out.println(cont); if(ib.hasNext())area.setPreferredSize(new Dimension(largura,altura*cp)); } Runnable sr = new AcaoMovimentoDeObjetos(50,140,715,333,scrollRegra,fundo); new Thread(sr).start(); //fim fundo info //motor de apresentao } public void iniCarregamento() { escondeRegra(); Runnable escondeX = new AcaoRecolherObjetos(767,6,16,25,fechar,fundo); new Thread(escondeX).start(); ImageIcon tl1i = new ImageIcon(getClass().getResource("/GUI/Imagens/load2.gif")); Image temp= tl1i.getImage(); imgci = new FundoJpane(temp,0,0,0,0); Runnable gifLoad = new AcaoMovimentoDeObjetos(199,88,380,269,imgci,fundo); new Thread(gifLoad).start(); cancela = new TJbutton("Cancelar",0,0,0,255); cancela.setForeground(Color.white); cancela.addActionListener(new BotaoCancela()); Runnable cancel = new AcaoMovimentoDeObjetos(304,384,168,57,cancela,fundo); new Thread(cancel).start(); } class BotaoCancela implements ActionListener{ @Override public void actionPerformed(ActionEvent arg0) { Runnable escondeX = new AcaoMovimentoDeObjetos(767,6,16,25,fechar,fundo); new Thread(escondeX).start(); isCancelado=true; } } public void stopCarregamento(){ Runnable text = new AcaoRecolherObjetos(199,88,380,269,imgc,fundo); new Thread(text).start(); Runnable cancel = new AcaoRecolherObjetos(304,384,168,57,cancela,fundo); new Thread(cancel).start(); concluido(); } private JPanel criarInfo(Backup b,int p,int h, int v, int l,int a){ //tamanho da letra 18 //setBounds (horizontal,vertical,largura,altura); Integer i = new Integer(p); FundoJpane celula = new FundoJpane(null,0,0,0,0); celula.setBackground(Color.BLACK); celula.setLayout(null); celula.setPreferredSize(new Dimension(700,123)); TJlabel nome=new TJlabel("Nome do Backup:",0,0,0,0); nome.setBounds(0,0,157,18); nome.setBorder(null); nome.setFont(new Font("Microsoft Yi Baiti",Font.BOLD,20)); nome.setForeground(Color.black); celula.add(nome); TJlabel data=new TJlabel("Data de Criao:",0,0,0,0); data.setBounds(0,20,147,18); data.setBorder(null); data.setFont(new Font("Microsoft Yi Baiti",Font.BOLD,20)); data.setForeground(Color.black); celula.add(data); TJlabel origem=new TJlabel("Caminho do backup:",0,0,0,0); origem.setBounds(0,40,184,18); origem.setFont(new Font("Microsoft Yi Baiti",Font.BOLD,20)); origem.setBorder(null); origem.setForeground(Color.black); celula.add(origem); //setBounds (horizontal,vertical,largura,altura); TJtextField cnome = new TJtextField(0,0,0,0); cnome.setBorder(null); cnome.setForeground(Color.black); cnome.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,20)); cnome.setBounds(140,0,700,18); celula.add(cnome); TJtextField cdata = new TJtextField(0,0,0,0); cdata.setBorder(null); cdata.setForeground(Color.black); cdata.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,20)); cdata.setBounds(135,20,700,18); celula.add(cdata); TJtextField corigem = new TJtextField(0,0,0,0); corigem.setBorder(null); corigem.setForeground(Color.black); corigem.setFont(new Font("Microsoft Yi Baiti",Font.PLAIN,20)); corigem.setBounds(160,40,700,18); celula.add(corigem); cnome.setEditable(false); cnome.setFocusable(false); cdata.setEditable(false); cdata.setFocusable(false); corigem.setEditable(false); corigem.setFocusable(false); cnome.setText(b.getNomeBackup()); cdata.setText(b.getDataInicio()); corigem.setText(b.getRegra().getDestino()); TJbutton rodar = new TJbutton("Rodar regra",0,0,0,255); rodar.setForeground(Color.white); TJcheck checkzip=new TJcheck("Salvar sada em Zip.",0,0,0,0); checkzip.setFont(new Font("Microsoft Yi Baiti",Font.BOLD,20)); checkzip.setForeground(Color.BLACK); checkzip.setFocusable(false); checkzip.setBounds(0,65,230,18); celula.add(checkzip); //setBounds (horizontal,vertical,largura,altura); rodar.setBounds(231,65,134,30); rodar.addActionListener(new ExecutarRegra(i,checkzip)); celula.add(rodar); celula.setBounds(h,v,l,a); return celula; } class ExecutarRegra implements ActionListener{ int num,cont=0; TJcheck zip; Backup ba; IteradorBackups ib=core.resgatarBackups(); ExecutarRegra(int num, TJcheck zip){ this.num=num; this.zip=zip; } @Override public void actionPerformed(ActionEvent arg0) { iniCarregamento(); while(cont<=num && ib.hasNext()){ ba=ib.next(); cont++; } core.rodarBackup(ba, zip.isSelected()); } } //Minhas classes de movimento class AcaoMovimentoDeObjetos implements Runnable{ private int x,y,alt,larg; private JButton b=null; private JLabel l=null; private JPanel j; private TJtextField t=null; private TJtextArea a=null; private JScrollPane r=null; private JPanel p=null; private TJcheck c=null; public AcaoMovimentoDeObjetos(int x,int y,int larg,int alt,JLabel l,JPanel j){ this.x=x; this.y=y; this.l=l; this.j=j; this.alt=alt; this.larg=larg; } public AcaoMovimentoDeObjetos(int x,int y,int larg,int alt,TJcheck c,JPanel j){ this.x=x; this.y=y; this.c=c; this.j=j; this.alt=alt; this.larg=larg; } public AcaoMovimentoDeObjetos(int x,int y,int larg,int alt,JButton b,JPanel j){ this.x=x; this.y=y; this.b=b; this.j=j; this.alt=alt; this.larg=larg; } public AcaoMovimentoDeObjetos(int x,int y,int larg,int alt,TJtextField t,JPanel j){ this.x=x; this.y=y; this.j=j; this.alt=alt; this.larg=larg; this.t=t; } public AcaoMovimentoDeObjetos(int x,int y,int larg,int alt,TJtextArea a,JPanel j){ this.x=x; this.y=y; this.j=j; this.alt=alt; this.larg=larg; this.a=a; } public AcaoMovimentoDeObjetos(int x,int y,int larg,int alt,JScrollPane r,JPanel j){ this.x=x; this.y=y; this.j=j; this.alt=alt; this.larg=larg; this.r=r; } public AcaoMovimentoDeObjetos(int x,int y,int larg,int alt,FundoJpane p,JPanel j){ this.x=x; this.y=y; this.j=j; this.alt=alt; this.larg=larg; this.p=p; } @Override public void run() { int temp=800,pi=50;//numero de pixel por velocidade while(temp>=x) { try { Thread.sleep(10);//velocidade } catch (InterruptedException ex) { Logger.getLogger(AcaoMovimentoDeObjetos.class.getName()).log(Level.SEVERE, null, ex); } if(b!=null) { b.setBounds(temp, y, larg, alt); temp-=pi; j.add(b); } if(l!=null) { l.setBounds(temp, y, larg, alt); temp-=pi; j.add(l); } if(t!=null) { t.setBounds(temp, y, larg, alt); temp-=pi; j.add(t); } if(a!=null) { a.setBounds(temp, y, larg, alt); temp-=pi; j.add(a); } if(r!=null) { r.setBounds(temp, y, larg, alt); temp-=pi; j.add(r); j.revalidate(); } if(p!=null) { p.setBounds(temp, y, larg, alt); temp-=pi; j.add(p); } if(c!=null) { c.setBounds(temp, y, larg, alt); temp-=pi; j.add(c); } } //correo de posio if(b!=null) { b.setBounds(x, y, larg, alt); j.add(b); } if(l!=null) { l.setBounds(x, y, larg, alt); j.add(l); } if(t!=null) { t.setBounds(x, y, larg, alt); j.add(t); } if(a!=null) { a.setBounds(x, y, larg, alt); j.add(a); } if(r!=null) { r.setBounds(x, y, larg, alt); j.add(r); j.revalidate(); } if(p!=null) { p.setBounds(x, y, larg, alt); j.add(p); } if(c!=null) { c.setBounds(x, y, larg, alt); j.add(c); } j.repaint(); Thread.interrupted(); } } class AcaoRecolherObjetos implements Runnable{ private int x,y,alt,larg; private JButton b=null; private JLabel l=null; private JPanel j; private TJtextField t=null; private TJtextArea a=null; private JScrollPane r=null; private JPanel p=null; private TJcheck c=null; public AcaoRecolherObjetos(int x,int y,int larg,int alt,JLabel l,JPanel j){ this.x=x; this.y=y; this.l=l; this.j=j; this.alt=alt; this.larg=larg; } public AcaoRecolherObjetos(int x,int y,int larg,int alt,TJcheck c,JPanel j){ this.x=x; this.y=y; this.c=c; this.j=j; this.alt=alt; this.larg=larg; } public AcaoRecolherObjetos(int x,int y,int larg,int alt,JButton b,JPanel j){ this.x=x; this.y=y; this.b=b; this.j=j; this.alt=alt; this.larg=larg; } public AcaoRecolherObjetos(int x,int y,int larg,int alt,JPanel p,JPanel j){ this.x=x; this.y=y; this.j=j; this.alt=alt; this.larg=larg; this.p=p; } public AcaoRecolherObjetos(int x,int y,int larg,int alt,TJtextField t,JPanel j){ this.x=x; this.y=y; this.j=j; this.alt=alt; this.larg=larg; this.t=t; } public AcaoRecolherObjetos(int x,int y,int larg,int alt,TJtextArea a,JPanel j){ this.x=x; this.y=y; this.j=j; this.alt=alt; this.larg=larg; this.a=a; } public AcaoRecolherObjetos(int x,int y,int larg,int alt,JScrollPane r,JPanel j){ this.x=x; this.y=y; this.j=j; this.alt=alt; this.larg=larg; this.r=r; } @Override public void run() { int temp=x; while(temp<=800+768) { try { Thread.sleep(10); } catch (InterruptedException ex) { Logger.getLogger(AcaoRecolherObjetos.class.getName()).log(Level.SEVERE, null, ex); } if(b!=null) { b.setBounds(temp, y, larg, alt); temp+=50; j.add(b); } if(l!=null) { l.setBounds(temp, y, larg, alt); temp+=50; j.add(l); } if(p!=null) { p.setBounds(temp, y, larg, alt); temp+=50; j.add(p); } if(t!=null) { t.setBounds(temp, y, larg, alt); temp+=50; j.add(t); } if(a!=null) { a.setBounds(temp, y, larg, alt); temp+=50; j.add(a); } if(r!=null) { r.setBounds(temp, y, larg, alt); temp+=50; j.add(r); } if(c!=null) { c.setBounds(temp, y, larg, alt); temp+=50; j.add(c); } } j.repaint(); Thread.interrupted(); } } //listeners arrastar a tela class AcaoCoordenadasFrameMovimentacao implements MouseListener{ @Override public void mouseClicked(MouseEvent e) {} @Override public void mousePressed(MouseEvent e) { tempx = e.getX(); tempy = e.getY(); } @Override public void mouseReleased(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} } class AcaoCoordenadasTelaMovimentacao implements MouseMotionListener{ @Override public void mouseDragged(MouseEvent e) { screenX = e.getXOnScreen(); screenY = e.getYOnScreen(); setLocation(screenX-tempx, screenY-tempy); } @Override public void mouseMoved(MouseEvent e) { } } //listeners Botoes Close E MIN class AcaoFechar implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { System.exit(1); } } class AcaoMinimizar implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { setState(Frame.ICONIFIED); } } //fim da classe }
load concluido
src/GUI/GuiMain.java
load concluido
Java
lgpl-2.1
833e848e2dffd4afccdb648c88a42e410b8c8a78
0
ekiwi/jade-mirror,ekiwi/jade-mirror,ekiwi/jade-mirror,ekiwi/jade-mirror
/***************************************************************** JADE - Java Agent DEvelopment Framework is a framework to develop multi-agent systems in compliance with the FIPA specifications. Copyright (C) 2000 CSELT S.p.A. GNU Lesser General Public License 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, version 2.1 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *****************************************************************/ package jade.core.behaviours; import java.util.Hashtable; import jade.util.leap.*; import jade.util.leap.Serializable; import jade.core.Agent; // DEBUG //import jade.proto.*; /** Composite behaviour with Finite State Machine based children scheduling. It is a <code>CompositeBehaviour</code> that executes its children behaviours according to a FSM defined by the user. More specifically each child represents a state in the FSM. The class provides methods to register states (sub-behaviours) and transitions that defines how sub-behaviours will be scheduled. <p> At a minimum, the following steps are needed in order to properly define a <code>FSMBehaviour</code>: <ul> <li> register a single Behaviour as the initial state of the FSM by calling the method <code>registerFirstState</code>; <li> register one or more Behaviours as the final states of the FSM by calling the method <code>registerLastState</code>; <li> register one or more Behaviours as the intermediate states of the FSM by calling the method <code>registerState</code>; <li> for each state of the FSM, register the transitions to the other states by calling the method <code>registerTransition</code>; <li> the method <code>registerDefaultTransition</code> is also useful in order to register a default transition from a state to another state independently on the termination event of the source state. </ul> A number of other methods are available in this class for generic tasks, such as getting the current state or the name of a state, ... @see jade.core.behaviours.SequentialBehaviour @see jade.core.behaviours.ParallelBehaviour @author Giovanni Caire - CSELT @version $Date$ $Revision$ */ public class FSMBehaviour extends SerialBehaviour { private Map states = new HashMap(); private Behaviour current = null; private List lastStates = new ArrayList(); private String firstName = null; private String currentName = null; private String previousName = null; private int lastExitValue; // These variables are used to force a transition on a given state at runtime private boolean transitionForced = false; private String forcedTransitionDest = null; private TransitionTable theTransitionTable = new TransitionTable(); /** Default constructor, does not set the owner agent. */ public FSMBehaviour() { super(); } /** This constructor sets the owner agent. @param a The agent this behaviour belongs to. */ public FSMBehaviour(Agent a) { super(a); } /** Register a <code>Behaviour</code> as a state of this <code>FSMBehaviour</code>. When the FSM reaches this state the registered <code>Behaviour</code> will be executed. @param state The <code>Behaviour</code> representing the state @param name The name identifying the state. */ public void registerState(Behaviour state, String name) { state.setBehaviourName(name); state.setParent(this); state.setAgent(myAgent); states.put(name, state); } /** Register a <code>Behaviour</code> as the initial state of this <code>FSMBehaviour</code>. @param state The <code>Behaviour</code> representing the state @param name The name identifying the state. */ public void registerFirstState(Behaviour state, String name) { registerState(state, name); firstName = name; } /** Register a <code>Behaviour</code> as a final state of this <code>FSMBehaviour</code>. When the FSM reaches this state the registered <code>Behaviour</code> will be executed and, when completed, the <code>FSMBehaviour</code> will terminate too. @param state The <code>Behaviour</code> representing the state @param name The name identifying the state. */ public void registerLastState(Behaviour state, String name) { registerState(state, name); if (!lastStates.contains(name)) { lastStates.add(name); } } /** Register a transition in the FSM defining the policy for children scheduling of this <code>FSMBehaviour</code>. @param s1 The name of the state this transition starts from @param s2 The name of the state this transition leads to @param event The termination event that fires this transition as returned by the <code>onEnd()</code> method of the <code>Behaviour</code> representing state s1. @see jade.core.behaviours.Behaviour#onEnd() */ public void registerTransition(String s1, String s2, int event) { theTransitionTable.addTransition(s1, s2, event, null); } /** Register a transition in the FSM defining the policy for children scheduling of this <code>FSMBehaviour</code>. When this transition is fired the states indicated in the <code>toBeReset</code> parameter are reset. This is particularly useful for transitions that lead to states that have already been visited. @param s1 The name of the state this transition starts from @param s2 The name of the state this transition leads to @param event The termination event that fires this transition as returned by the <code>onEnd()</code> method of the <code>Behaviour</code> representing state s1. @param toBeReset An array of strings including the names of the states to be reset. @see jade.core.behaviours.Behaviour#onEnd() */ public void registerTransition(String s1, String s2, int event, String[] toBeReset) { theTransitionTable.addTransition(s1, s2, event, toBeReset); } /** Register a default transition in the FSM defining the policy for children scheduling of this <code>FSMBehaviour</code>. This transition will be fired when state s1 terminates with an event that is not explicitly associated to any transition. @param s1 The name of the state this transition starts from @param s2 The name of the state this transition leads to */ public void registerDefaultTransition(String s1, String s2) { theTransitionTable.addDefaultTransition(s1, s2, null); } /** Register a default transition in the FSM defining the policy for children scheduling of this <code>FSMBehaviour</code>. This transition will be fired when state s1 terminates with an event that is not explicitly associated to any transition. When this transition is fired the states indicated in the <code>toBeReset</code> parameter are reset. This is particularly useful for transitions that lead to states that have already been visited. @param s1 The name of the state this transition starts from @param s2 The name of the state this transition leads to @param toBeReset An array of strings including the names of the states to be reset. */ public void registerDefaultTransition(String s1, String s2, String[] toBeReset) { theTransitionTable.addDefaultTransition(s1, s2, toBeReset); } /** @return the <code>Behaviour</code> representing the state whose name is name. */ public Behaviour getState(String name) { Behaviour b = null; if (name != null) { b = (Behaviour) states.get(name); } return b; } /** @return the name of the state represented by <code>Behaviour</code> state. */ public String getName(Behaviour state) { Iterator it = states.keySet().iterator(); while (it.hasNext()) { String name = (String) it.next(); Behaviour s = (Behaviour) states.get(name); if (state == s) { return name; } } return null; } /** @return the exit value of the last executed state. */ public int getLastExitValue() { return lastExitValue; } /** Override the onEnd() method to return the exit value of the last executed state. */ public int onEnd() { return getLastExitValue(); } /** Prepare the first child for execution. The first child is the <code>Behaviour</code> registered as the first state of this <code>FSMBehaviour</code> @see jade.core.behaviours.CompositeBehaviour#scheduleFirst */ protected void scheduleFirst() { if (transitionForced) { currentName = forcedTransitionDest; transitionForced = false; } else { // Normal case: go to the first state currentName = firstName; } current = getState(currentName); // DEBUG //System.out.println(myAgent.getLocalName()+" is Executing state "+currentName); } /** This method schedules the next child to be executed. It checks whether the current child is completed and, in this case, fires a suitable transition (according to the termination event of the current child) and schedules the child representing the new state. @param currentDone a flag indicating whether the just executed child has completed or not. @param currentResult the termination value (as returned by <code>onEnd()</code>) of the just executed child in the case this child has completed (otherwise this parameter is meaningless) @see jade.core.behaviours.CompositeBehaviour#scheduleNext(boolean, int) */ protected void scheduleNext(boolean currentDone, int currentResult) { if (currentDone) { try { previousName = currentName; if (transitionForced) { currentName = forcedTransitionDest; transitionForced = false; } else { // Normal case: use the TransitionTable to select the next state Transition t = theTransitionTable.getTransition(currentName, currentResult); resetStates(t.toBeReset); currentName = t.dest; } current = getState(currentName); if (current == null) { throw new NullPointerException(); } } catch (NullPointerException npe) { throw new RuntimeException("Inconsistent FSM. State: "+previousName+" event: "+currentResult); } // DEBUG //System.out.println(myAgent.getLocalName()+ " is Executing state "+currentName); } } /** Check whether this <code>FSMBehaviour</code> must terminate. @return true when the last child has terminated and it represents a final state. false otherwise @see jade.core.behaviours.CompositeBehaviour#checkTermination */ protected boolean checkTermination(boolean currentDone, int currentResult) { if (currentDone) { lastExitValue = currentResult; return lastStates.contains(currentName); } return false; } /** Get the current child @see jade.core.behaviours.CompositeBehaviour#getCurrent */ protected Behaviour getCurrent() { return current; } /** Return a Collection view of the children of this <code>SequentialBehaviour</code> @see jade.core.behaviours.CompositeBehaviour#getChildren */ public Collection getChildren() { return states.values(); } /** */ protected void forceTransitionTo(String next) { // Just check that the forced transition leads into a valid state Behaviour b = getState(next); if (b != null) { transitionForced = true; forcedTransitionDest = next; } } /** Put this FSMBehaviour back in the initial condition */ public void reset() { super.reset(); transitionForced = false; forcedTransitionDest = null; } /** Reset the children behaviours registered in the states indicated in the <code>states</code> parameter @param states the names of the states that have to be reset */ public void resetStates(String[] states) { if (states != null) { for(int i=0; i < states.length; i++){ Behaviour b = getState(states[i]); b.reset(); } } } /** * Handle block/restart notifications. An * <code>FSMBehaviour</code> is blocked <em>only</em> when * its currently active child is blocked, and becomes ready again * when its current child is ready. This method takes care of the * various possibilities. * @param rce The event to handle. * protected void handle(RunnableChangedEvent rce) { if(rce.isUpwards()) { // Upwards notification if (rce.getSource() == this) { // If the event is from this behaviour, set the new // runnable state and notify upwords. super.handle(rce); } else if (rce.getSource() == getCurrent()) { // If the event is from the currently executing child, // create a new event, set the new runnable state and // notify upwords. myEvent.init(rce.isRunnable(), NOTIFY_UP); super.handle(myEvent); } else { // If the event is from another child, just ignore it } } else { // Downwards notifications // Copy the state and pass it downwords only to the // current child setRunnable(rce.isRunnable()); Behaviour b = getCurrent(); if (b != null) { b.handle(rce); } } }*/ /** * Inner class implementing the FSM transition table */ class TransitionTable implements Serializable { private Hashtable transitions = new Hashtable(); private static final long serialVersionUID = 3487495895819003L; void addTransition(String s1, String s2, int event, String[] toBeReset) { TransitionsFromState tfs = null; if (!transitions.containsKey(s1)) { tfs = new TransitionsFromState(); transitions.put(s1, tfs); } else { tfs = (TransitionsFromState) transitions.get(s1); } tfs.put(new Integer(event), new Transition(s2, toBeReset)); } void addDefaultTransition(String s1, String s2, String[] toBeReset) { TransitionsFromState tfs = null; if (!transitions.containsKey(s1)) { tfs = new TransitionsFromState(); transitions.put(s1, tfs); } else { tfs = (TransitionsFromState) transitions.get(s1); } tfs.setDefaultTransition(new Transition(s2, toBeReset)); } Transition getTransition(String s, int event) { TransitionsFromState tfs = (TransitionsFromState) transitions.get(s); Transition t = (Transition) tfs.get(new Integer(event)); return t; } } class Transition implements Serializable { private String dest; private String[] toBeReset; private static final long serialVersionUID = 3487495895819004L; public Transition(String d, String[] rs) { dest = d; toBeReset = rs; } } class TransitionsFromState extends Hashtable { private Transition defaultTransition = null; private static final long serialVersionUID = 3487495895819005L; void setDefaultTransition(Transition dt) { defaultTransition = dt; } public Object get(Object key) { Transition t = (Transition) super.get(key); if (t == null) { t = defaultTransition; } return t; } } //#MIDP_EXCLUDE_BEGIN // For persistence service private java.util.Map getSubBehaviours() { java.util.Map result = new java.util.HashMap(); Set keys = states.keySet(); Iterator it = keys.iterator(); while(it.hasNext()) { Object key = it.next(); result.put(key, states.get(key)); } return result; } // For persistence service private void setSubBehaviours(java.util.Map behaviours) { states.clear(); java.util.Set entries = behaviours.entrySet(); java.util.Iterator it = entries.iterator(); while(it.hasNext()) { java.util.Map.Entry e = (java.util.Map.Entry)it.next(); states.put(e.getKey(), e.getValue()); } } //#MIDP_EXCLUDE_END }
src/jade/core/behaviours/FSMBehaviour.java
/***************************************************************** JADE - Java Agent DEvelopment Framework is a framework to develop multi-agent systems in compliance with the FIPA specifications. Copyright (C) 2000 CSELT S.p.A. GNU Lesser General Public License 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, version 2.1 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *****************************************************************/ package jade.core.behaviours; import java.util.Hashtable; import jade.util.leap.*; import jade.util.leap.Serializable; import jade.core.Agent; // DEBUG //import jade.proto.*; /** Composite behaviour with Finite State Machine based children scheduling. It is a <code>CompositeBehaviour</code> that executes its children behaviours according to a FSM defined by the user. More specifically each child represents a state in the FSM. The class provides methods to register states (sub-behaviours) and transitions that defines how sub-behaviours will be scheduled. <p> At a minimum, the following steps are needed in order to properly define a <code>FSMBehaviour</code>: <ul> <li> register a single Behaviour as the initial state of the FSM by calling the method <code>registerFirstState</code>; <li> register one or more Behaviours as the final states of the FSM by calling the method <code>registerLastState</code>; <li> register one or more Behaviours as the intermediate states of the FSM by calling the method <code>registerState</code>; <li> for each state of the FSM, register the transitions to the other states by calling the method <code>registerTransition</code>; <li> the method <code>registerDefaultTransition</code> is also useful in order to register a default transition from a state to another state independently on the termination event of the source state. </ul> A number of other methods are available in this class for generic tasks, such as getting the current state or the name of a state, ... @see jade.core.behaviours.SequentialBehaviour @see jade.core.behaviours.ParallelBehaviour @author Giovanni Caire - CSELT @version $Date$ $Revision$ */ public class FSMBehaviour extends SerialBehaviour { private Map states = new HashMap(); private Behaviour current = null; private List lastStates = new ArrayList(); private String firstName = null; private String currentName = null; private String previousName = null; private int lastExitValue; // These variables are used to force a transition on a given state at runtime private boolean transitionForced = false; private String forcedTransitionDest = null; private TransitionTable theTransitionTable = new TransitionTable(); /** Default constructor, does not set the owner agent. */ public FSMBehaviour() { super(); } /** This constructor sets the owner agent. @param a The agent this behaviour belongs to. */ public FSMBehaviour(Agent a) { super(a); } /** Register a <code>Behaviour</code> as a state of this <code>FSMBehaviour</code>. When the FSM reaches this state the registered <code>Behaviour</code> will be executed. @param state The <code>Behaviour</code> representing the state @param name The name identifying the state. */ public void registerState(Behaviour state, String name) { state.setBehaviourName(name); state.setParent(this); state.setAgent(myAgent); states.put(name, state); } /** Register a <code>Behaviour</code> as the initial state of this <code>FSMBehaviour</code>. @param state The <code>Behaviour</code> representing the state @param name The name identifying the state. */ public void registerFirstState(Behaviour state, String name) { registerState(state, name); firstName = name; } /** Register a <code>Behaviour</code> as a final state of this <code>FSMBehaviour</code>. When the FSM reaches this state the registered <code>Behaviour</code> will be executed and, when completed, the <code>FSMBehaviour</code> will terminate too. @param state The <code>Behaviour</code> representing the state @param name The name identifying the state. */ public void registerLastState(Behaviour state, String name) { registerState(state, name); if (!lastStates.contains(name)) { lastStates.add(name); } } /** Register a transition in the FSM defining the policy for children scheduling of this <code>FSMBehaviour</code>. @param s1 The name of the state this transition starts from @param s2 The name of the state this transition leads to @param event The termination event that fires this transition as returned by the <code>onEnd()</code> method of the <code>Behaviour</code> representing state s1. @see jade.core.behaviours.Behaviour#onEnd() */ public void registerTransition(String s1, String s2, int event) { theTransitionTable.addTransition(s1, s2, event, null); } /** Register a transition in the FSM defining the policy for children scheduling of this <code>FSMBehaviour</code>. When this transition is fired the states indicated in the <code>toBeReset</code> parameter are reset. This is particularly useful for transitions that lead to states that have already been visited. @param s1 The name of the state this transition starts from @param s2 The name of the state this transition leads to @param event The termination event that fires this transition as returned by the <code>onEnd()</code> method of the <code>Behaviour</code> representing state s1. @param toBeReset An array of strings including the names of the states to be reset. @see jade.core.behaviours.Behaviour#onEnd() */ public void registerTransition(String s1, String s2, int event, String[] toBeReset) { theTransitionTable.addTransition(s1, s2, event, toBeReset); } /** Register a default transition in the FSM defining the policy for children scheduling of this <code>FSMBehaviour</code>. This transition will be fired when state s1 terminates with an event that is not explicitly associated to any transition. @param s1 The name of the state this transition starts from @param s2 The name of the state this transition leads to */ public void registerDefaultTransition(String s1, String s2) { theTransitionTable.addDefaultTransition(s1, s2, null); } /** Register a default transition in the FSM defining the policy for children scheduling of this <code>FSMBehaviour</code>. This transition will be fired when state s1 terminates with an event that is not explicitly associated to any transition. When this transition is fired the states indicated in the <code>toBeReset</code> parameter are reset. This is particularly useful for transitions that lead to states that have already been visited. @param s1 The name of the state this transition starts from @param s2 The name of the state this transition leads to @param toBeReset An array of strings including the names of the states to be reset. */ public void registerDefaultTransition(String s1, String s2, String[] toBeReset) { theTransitionTable.addDefaultTransition(s1, s2, toBeReset); } /** @return the <code>Behaviour</code> representing the state whose name is name. */ public Behaviour getState(String name) { Behaviour b = null; if (name != null) { b = (Behaviour) states.get(name); } return b; } /** @return the name of the state represented by <code>Behaviour</code> state. */ public String getName(Behaviour state) { Iterator it = states.keySet().iterator(); while (it.hasNext()) { String name = (String) it.next(); Behaviour s = (Behaviour) states.get(name); if (state == s) { return name; } } return null; } /** @return the exit value of the last executed state. */ public int getLastExitValue() { return lastExitValue; } /** Override the onEnd() method to return the exit value of the last executed state. */ public int onEnd() { return getLastExitValue(); } /** Prepare the first child for execution. The first child is the <code>Behaviour</code> registered as the first state of this <code>FSMBehaviour</code> @see jade.core.behaviours.CompositeBehaviour#scheduleFirst */ protected void scheduleFirst() { if (transitionForced) { currentName = forcedTransitionDest; transitionForced = false; } else { // Normal case: go to the first state currentName = firstName; } current = getState(currentName); // DEBUG //if (this instanceof SubscriptionResponder || this instanceof SubscriptionInitiator) //System.out.println(myAgent.getLocalName()+" is Executing state "+currentName); } /** This method schedules the next child to be executed. It checks whether the current child is completed and, in this case, fires a suitable transition (according to the termination event of the current child) and schedules the child representing the new state. @param currentDone a flag indicating whether the just executed child has completed or not. @param currentResult the termination value (as returned by <code>onEnd()</code>) of the just executed child in the case this child has completed (otherwise this parameter is meaningless) @see jade.core.behaviours.CompositeBehaviour#scheduleNext(boolean, int) */ protected void scheduleNext(boolean currentDone, int currentResult) { if (currentDone) { try { previousName = currentName; if (transitionForced) { currentName = forcedTransitionDest; transitionForced = false; } else { // Normal case: use the TransitionTable to select the next state Transition t = theTransitionTable.getTransition(currentName, currentResult); resetStates(t.toBeReset); currentName = t.dest; } current = getState(currentName); if (current == null) { throw new NullPointerException(); } } catch (NullPointerException npe) { throw new RuntimeException("Inconsistent FSM. State: "+previousName+" event: "+currentResult); } // DEBUG //if (this instanceof SubscriptionResponder || this instanceof SubscriptionInitiator) //System.out.println(myAgent.getLocalName()+ " is Executing state "+currentName); } } /** Check whether this <code>FSMBehaviour</code> must terminate. @return true when the last child has terminated and it represents a final state. false otherwise @see jade.core.behaviours.CompositeBehaviour#checkTermination */ protected boolean checkTermination(boolean currentDone, int currentResult) { if (currentDone) { lastExitValue = currentResult; return lastStates.contains(currentName); } return false; } /** Get the current child @see jade.core.behaviours.CompositeBehaviour#getCurrent */ protected Behaviour getCurrent() { return current; } /** Return a Collection view of the children of this <code>SequentialBehaviour</code> @see jade.core.behaviours.CompositeBehaviour#getChildren */ public Collection getChildren() { return states.values(); } /** */ protected void forceTransitionTo(String next) { // Just check that the forced transition leads into a valid state Behaviour b = getState(next); if (b != null) { transitionForced = true; forcedTransitionDest = next; } } /** Put this FSMBehaviour back in the initial condition */ public void reset() { super.reset(); transitionForced = false; forcedTransitionDest = null; } /** Reset the children behaviours registered in the states indicated in the <code>states</code> parameter @param states the names of the states that have to be reset */ public void resetStates(String[] states) { if (states != null) { for(int i=0; i < states.length; i++){ Behaviour b = getState(states[i]); b.reset(); } } } /** * Handle block/restart notifications. An * <code>FSMBehaviour</code> is blocked <em>only</em> when * its currently active child is blocked, and becomes ready again * when its current child is ready. This method takes care of the * various possibilities. * @param rce The event to handle. * protected void handle(RunnableChangedEvent rce) { if(rce.isUpwards()) { // Upwards notification if (rce.getSource() == this) { // If the event is from this behaviour, set the new // runnable state and notify upwords. super.handle(rce); } else if (rce.getSource() == getCurrent()) { // If the event is from the currently executing child, // create a new event, set the new runnable state and // notify upwords. myEvent.init(rce.isRunnable(), NOTIFY_UP); super.handle(myEvent); } else { // If the event is from another child, just ignore it } } else { // Downwards notifications // Copy the state and pass it downwords only to the // current child setRunnable(rce.isRunnable()); Behaviour b = getCurrent(); if (b != null) { b.handle(rce); } } }*/ /** * Inner class implementing the FSM transition table */ class TransitionTable implements Serializable { private Hashtable transitions = new Hashtable(); private static final long serialVersionUID = 3487495895819003L; void addTransition(String s1, String s2, int event, String[] toBeReset) { TransitionsFromState tfs = null; if (!transitions.containsKey(s1)) { tfs = new TransitionsFromState(); transitions.put(s1, tfs); } else { tfs = (TransitionsFromState) transitions.get(s1); } tfs.put(new Integer(event), new Transition(s2, toBeReset)); } void addDefaultTransition(String s1, String s2, String[] toBeReset) { TransitionsFromState tfs = null; if (!transitions.containsKey(s1)) { tfs = new TransitionsFromState(); transitions.put(s1, tfs); } else { tfs = (TransitionsFromState) transitions.get(s1); } tfs.setDefaultTransition(new Transition(s2, toBeReset)); } Transition getTransition(String s, int event) { TransitionsFromState tfs = (TransitionsFromState) transitions.get(s); Transition t = (Transition) tfs.get(new Integer(event)); return t; } } class Transition implements Serializable { private String dest; private String[] toBeReset; private static final long serialVersionUID = 3487495895819004L; public Transition(String d, String[] rs) { dest = d; toBeReset = rs; } } class TransitionsFromState extends Hashtable { private Transition defaultTransition = null; private static final long serialVersionUID = 3487495895819005L; void setDefaultTransition(Transition dt) { defaultTransition = dt; } public Object get(Object key) { Transition t = (Transition) super.get(key); if (t == null) { t = defaultTransition; } return t; } } //#MIDP_EXCLUDE_BEGIN // For persistence service private java.util.Map getSubBehaviours() { java.util.Map result = new java.util.HashMap(); Set keys = states.keySet(); Iterator it = keys.iterator(); while(it.hasNext()) { Object key = it.next(); result.put(key, states.get(key)); } return result; } // For persistence service private void setSubBehaviours(java.util.Map behaviours) { states.clear(); java.util.Set entries = behaviours.entrySet(); java.util.Iterator it = entries.iterator(); while(it.hasNext()) { java.util.Map.Entry e = (java.util.Map.Entry)it.next(); states.put(e.getKey(), e.getValue()); } } //#MIDP_EXCLUDE_END }
Removed old commented code
src/jade/core/behaviours/FSMBehaviour.java
Removed old commented code
Java
apache-2.0
92c77c38fe3ddc28f33a3a01817a99651d9c6263
0
fishercoder1534/Leetcode,fishercoder1534/Leetcode,fishercoder1534/Leetcode,fishercoder1534/Leetcode,fishercoder1534/Leetcode
package com.fishercoder.solutions; public class _275 { public static class Solution1 { public int hIndex(int[] citations) { int left = 0; int len = citations.length; int right = len - 1; while (left <= right) { int mid = left + (right - left) / 2; if (citations[mid] >= (len - mid)) { right = mid - 1; } else { left = mid + 1; } } return len - left; } } }
src/main/java/com/fishercoder/solutions/_275.java
package com.fishercoder.solutions; /** * 275. H-Index II * * Follow up for H-Index: What if the citations array is sorted in ascending order? * Could you optimize your algorithm? */ public class _275 { public static class Solution1 { public int hIndex(int[] citations) { int left = 0; int len = citations.length; int right = len - 1; while (left <= right) { int mid = left + (right - left) / 2; if (citations[mid] >= (len - mid)) { right = mid - 1; } else { left = mid + 1; } } return len - left; } } }
refactor 275
src/main/java/com/fishercoder/solutions/_275.java
refactor 275
Java
apache-2.0
85855803669c4dcaf34ad250d05389789225bc2e
0
sfunk1x/CoffeeMud,sfunk1x/CoffeeMud,bozimmerman/CoffeeMud,Tycheo/coffeemud,oriontribunal/CoffeeMud,Tycheo/coffeemud,sfunk1x/CoffeeMud,bozimmerman/CoffeeMud,oriontribunal/CoffeeMud,bozimmerman/CoffeeMud,Tycheo/coffeemud,oriontribunal/CoffeeMud,oriontribunal/CoffeeMud,Tycheo/coffeemud,MaxRau/CoffeeMud,sfunk1x/CoffeeMud,MaxRau/CoffeeMud,MaxRau/CoffeeMud,bozimmerman/CoffeeMud,MaxRau/CoffeeMud
package com.planet_ink.coffee_mud.MOBS; import java.util.*; import com.planet_ink.coffee_mud.utils.*; import com.planet_ink.coffee_mud.interfaces.*; import com.planet_ink.coffee_mud.common.*; public class StdMOB implements MOB { public String ID(){return "StdMOB";} protected String Username=""; private String clanID=null; private int clanRole=0; protected CharStats baseCharStats=new DefaultCharStats(); protected CharStats charStats=new DefaultCharStats(); protected EnvStats envStats=new DefaultEnvStats(); protected EnvStats baseEnvStats=new DefaultEnvStats(); protected PlayerStats playerStats=null; protected boolean amDead=false; protected Room location=null; protected Room lastLocation=null; protected Rideable riding=null; protected Session mySession=null; protected boolean pleaseDestroy=false; protected byte[] description=null; protected String displayText=""; protected byte[] miscText=null; protected long tickStatus=Tickable.STATUS_NOT; /* instantiated item types word, contained, owned*/ protected Vector inventory=new Vector(); /* instantiated creature types listed as followers*/ protected Vector followers=new Vector(); /* All Ability codes, including languages*/ protected Vector abilities=new Vector(); /* instantiated affects on this user*/ protected Vector affects=new Vector(); protected Vector behaviors=new Vector(); // gained attributes protected int Experience=0; protected int ExpNextLevel=1000; protected int Practices=0; protected int Trains=0; protected long AgeHours=0; protected int Money=0; protected int attributesBitmap=0; public long getAgeHours(){return AgeHours;} public int getPractices(){return Practices;} public int getExperience(){return Experience;} public int getExpNextLevel(){return ExpNextLevel;} public int getExpNeededLevel() { if(ExpNextLevel<=getExperience()) ExpNextLevel=getExperience()+1000; return ExpNextLevel-getExperience(); } public int getTrains(){return Trains;} public int getMoney(){return Money;} public int getBitmap(){return attributesBitmap;} public void setAgeHours(long newVal){ AgeHours=newVal;} public void setExperience(int newVal){ Experience=newVal; } public void setExpNextLevel(int newVal){ ExpNextLevel=newVal;} public void setPractices(int newVal){ Practices=newVal;} public void setTrains(int newVal){ Trains=newVal;} public void setMoney(int newVal){ Money=newVal;} public void setBitmap(int newVal) { attributesBitmap=newVal; if(mySession!=null) mySession.setTermID(((Util.bset(attributesBitmap,MOB.ATT_ANSI))?1:0)+((Util.bset(attributesBitmap,MOB.ATT_SOUND))?2:0)); } protected int minuteCounter=0; private int movesSinceTick=0; // the core state values public CharState curState=new DefaultCharState(); public CharState maxState=new DefaultCharState(); public CharState baseState=new DefaultCharState(); private long lastTickedDateTime=System.currentTimeMillis(); public long lastTickedDateTime(){return lastTickedDateTime;} // mental characteristics protected int Alignment=0; protected String WorshipCharID=""; protected String LeigeID=""; protected int WimpHitPoint=0; protected int QuestPoint=0; protected int DeityIndex=-1; public String getLeigeID(){return LeigeID;} public String getWorshipCharID(){return WorshipCharID;} public int getAlignment(){return Alignment;} public int getWimpHitPoint(){return WimpHitPoint;} public int getQuestPoint(){return QuestPoint;} public void setLeigeID(String newVal){LeigeID=newVal;} public void setAlignment(int newVal) { if(newVal<0) newVal=0; if(newVal>1000) newVal=1000; Alignment=newVal; } public void setWorshipCharID(String newVal){ WorshipCharID=newVal;} public void setWimpHitPoint(int newVal){ WimpHitPoint=newVal;} public void setQuestPoint(int newVal){ QuestPoint=newVal;} public Deity getMyDeity() { if(getWorshipCharID().length()==0) return null; Deity bob=CMMap.getDeity(getWorshipCharID()); if(bob==null) setWorshipCharID(""); return bob; } // location! protected Room StartRoom=null; public Room getStartRoom(){return StartRoom;} public void setStartRoom(Room newVal){StartRoom=newVal;} protected MOB victim=null; protected MOB amFollowing=null; protected MOB soulMate=null; private double speeder=0.0; protected int atRange=-1; private long peaceTime=0; public long peaceTime(){return peaceTime;} public String Name() { return Username; } public void setName(String newName){Username=newName;} public String name() { if(envStats().newName()!=null) return envStats().newName(); return Username; } public Environmental newInstance() { return new StdMOB(); } public StdMOB(){} protected void cloneFix(MOB E) { affects=new Vector(); baseEnvStats=E.baseEnvStats().cloneStats(); envStats=E.envStats().cloneStats(); baseCharStats=E.baseCharStats().cloneCharStats(); charStats=E.charStats().cloneCharStats(); baseState=E.baseState().cloneCharState(); curState=E.curState().cloneCharState(); maxState=E.maxState().cloneCharState(); pleaseDestroy=false; inventory=new Vector(); followers=new Vector(); abilities=new Vector(); affects=new Vector(); behaviors=new Vector(); for(int i=0;i<E.inventorySize();i++) { Item I2=E.fetchInventory(i); if(I2!=null) { Item I=(Item)I2.copyOf(); I.setOwner(this); inventory.addElement(I); } } for(int i=0;i<inventorySize();i++) { Item I2=fetchInventory(i); if((I2!=null) &&(I2.container()!=null) &&(!isMine(I2.container()))) for(int ii=0;ii<E.inventorySize();ii++) if((E.fetchInventory(ii)==I2.container())&&(ii<inventorySize())) { I2.setContainer(fetchInventory(ii)); break;} } for(int i=0;i<E.numAbilities();i++) { Ability A2=E.fetchAbility(i); if(A2!=null) abilities.addElement(A2.copyOf()); } for(int i=0;i<E.numAffects();i++) { Ability A=(Ability)E.fetchAffect(i); if((A!=null)&&(!A.canBeUninvoked())) addAffect((Ability)A.copyOf()); } for(int i=0;i<E.numBehaviors();i++) { Behavior B=E.fetchBehavior(i); if(B!=null) behaviors.addElement((Behavior)B.copyOf()); } } public Environmental copyOf() { try { StdMOB E=(StdMOB)this.clone(); E.cloneFix(this); return E; } catch(CloneNotSupportedException e) { return this.newInstance(); } } public boolean isGeneric(){return false;} public EnvStats envStats() { return envStats; } public EnvStats baseEnvStats() { return baseEnvStats; } public void recoverEnvStats() { envStats=baseEnvStats.cloneStats(); if(location()!=null) location().affectEnvStats(this,envStats); envStats().setWeight(envStats().weight()+(int)Math.round(Util.div(getMoney(),100.0))); if(riding()!=null) riding().affectEnvStats(this,envStats); if(getMyDeity()!=null) getMyDeity().affectEnvStats(this,envStats); if(charStats!=null) { charStats().getCurrentClass().affectEnvStats(this,envStats); charStats().getMyRace().affectEnvStats(this,envStats); } for(int i=0;i<inventorySize();i++) { Item item=fetchInventory(i); if(item!=null) { item.recoverEnvStats(); item.affectEnvStats(this,envStats); } } for(int a=0;a<numAffects();a++) { Ability affect=fetchAffect(a); if(affect!=null) affect.affectEnvStats(this,envStats); } /* the follower light exception*/ if(!Sense.isLightSource(this)) for(int f=0;f<numFollowers();f++) if(Sense.isLightSource(fetchFollower(f))) envStats.setDisposition(envStats().disposition()|EnvStats.IS_LIGHTSOURCE); } public void setBaseEnvStats(EnvStats newBaseEnvStats) { baseEnvStats=newBaseEnvStats.cloneStats(); } public int maxCarry() { double str=new Integer(charStats().getStat(CharStats.STRENGTH)).doubleValue(); double bodyWeight=0.0; if(charStats().getMyRace()==baseCharStats().getMyRace()) bodyWeight=new Integer(baseEnvStats().weight()).doubleValue(); else bodyWeight=new Integer(charStats().getMyRace().getMaxWeight()).doubleValue(); return (int)Math.round(bodyWeight + ((str+10.0)*str*bodyWeight/150.0) + (str*5.0)); } public int maxFollowers() { return ((int)Math.round(Util.div(charStats().getStat(CharStats.CHARISMA),4.0))+1); } public CharStats baseCharStats(){return baseCharStats;} public CharStats charStats(){return charStats;} public void recoverCharStats() { baseCharStats.setClassLevel(baseCharStats.getCurrentClass(),baseEnvStats().level()-baseCharStats().combinedSubLevels()); charStats=baseCharStats().cloneCharStats(); if(riding()!=null) riding().affectCharStats(this,charStats); if(getMyDeity()!=null) getMyDeity().affectCharStats(this,charStats); for(int a=0;a<numAffects();a++) { Ability affect=fetchAffect(a); if(affect!=null) affect.affectCharStats(this,charStats); } for(int i=0;i<inventorySize();i++) { Item item=fetchInventory(i); if(item!=null) item.affectCharStats(this,charStats); } if(location()!=null) location().affectCharStats(this,charStats); charStats.getCurrentClass().affectCharStats(this,charStats); charStats.getMyRace().affectCharStats(this,charStats); } public void setBaseCharStats(CharStats newBaseCharStats) { baseCharStats=newBaseCharStats.cloneCharStats(); } public void affectEnvStats(Environmental affected, EnvStats affectableStats) { if((Sense.isLightSource(this))&&(affected instanceof Room)) { if(Sense.isInDark(affected)) affectableStats.setDisposition(affectableStats.disposition()-EnvStats.IS_DARK); affectableStats.setDisposition(affectableStats.disposition()|EnvStats.IS_LIGHTSOURCE); } } public void affectCharState(MOB affectedMob, CharState affectableMaxState) {} public CharState curState(){return curState;} public CharState maxState(){return maxState;} public CharState baseState(){return baseState;} public PlayerStats playerStats() { if((playerStats==null)&&(soulMate!=null)) return soulMate.playerStats(); return playerStats; } public void setPlayerStats(PlayerStats newStats){playerStats=newStats;} public void setBaseState(CharState newState) { baseState=newState.cloneCharState(); maxState=newState.cloneCharState(); } public void resetToMaxState() { recoverMaxState(); curState=maxState.cloneCharState(); } public void recoverMaxState() { maxState=baseState.cloneCharState(); if(charStats.getMyRace()!=null) charStats.getMyRace().affectCharState(this,maxState); if(riding()!=null) riding().affectCharState(this,maxState); for(int a=0;a<numAffects();a++) { Ability affect=fetchAffect(a); if(affect!=null) affect.affectCharState(this,maxState); } for(int i=0;i<inventorySize();i++) { Item item=fetchInventory(i); if(item!=null) item.affectCharState(this,maxState); } if(location()!=null) location().affectCharState(this,maxState); } public boolean amDead() { return amDead||pleaseDestroy; } public void destroy() { removeFromGame(); while(numBehaviors()>0) delBehavior(fetchBehavior(0)); while(numAffects()>0) delAffect(fetchAffect(0)); while(numAbilities()>0) delAbility(fetchAbility(0)); while(inventorySize()>0) { Item I=fetchInventory(0); I.destroy(); delInventory(I); } } public void removeFromGame() { pleaseDestroy=true; if(location!=null) { location().delInhabitant(this); if(mySession!=null) location().show(this,null,Affect.MSG_OK_ACTION,"<S-NAME> vanish(es) in a puff of smoke."); } setFollowing(null); Vector oldFollowers=new Vector(); while(numFollowers()>0) { MOB follower=fetchFollower(0); if(follower!=null) { if(follower.isMonster()) oldFollowers.addElement(follower); follower.setFollowing(null); delFollower(follower); } } if(!isMonster()) { for(int f=0;f<oldFollowers.size();f++) { MOB follower=(MOB)oldFollowers.elementAt(f); if(follower.location()!=null) { MOB newFol=(MOB)follower.copyOf(); newFol.baseEnvStats().setRejuv(0); newFol.text(); follower.killMeDead(false); addFollower(newFol); } } session().setKillFlag(true); } } public String getClanID(){return ((clanID==null)?"":clanID);} public void setClanID(String clan){clanID=clan;} public int getClanRole(){return clanRole;} public void setClanRole(int role){clanRole=role;} public void bringToLife(Room newLocation, boolean resetStats) { amDead=false; if((miscText!=null)&&(resetStats)) { if(CommonStrings.getBoolVar(CommonStrings.SYSTEMB_MOBCOMPRESS)) setMiscText(Util.decompressString(miscText)); else setMiscText(new String(miscText)); } if(getStartRoom()==null) setStartRoom(isMonster()?newLocation:CMMap.getStartRoom(this)); setLocation(newLocation); if(location()==null) { setLocation(getStartRoom()); if(location()==null) { Log.errOut("StdMOB",Username+" cannot get a location."); return; } } if(!location().isInhabitant(this)) location().addInhabitant(this); pleaseDestroy=false; // will ensure no duplicate ticks, this obj, this id ExternalPlay.startTickDown(this,Host.MOB_TICK,1); tick(this,Host.MOB_TICK); // slap on the butt for(int a=0;a<numAbilities();a++) { Ability A=fetchAbility(a); if(A!=null) A.autoInvocation(this); } location().recoverRoomStats(); if((!isGeneric())&&(resetStats)) resetToMaxState(); if(Sense.isSleeping(this)) tell("(You are asleep)"); else ExternalPlay.look(this,null,true); } public boolean isInCombat() { if(victim==null) return false; if((victim.location()==null) ||(location()==null) ||(victim.location()!=location()) ||(victim.amDead())) { if((victim instanceof StdMOB) &&(((StdMOB)victim).victim==this)) victim.setVictim(null); setVictim(null); return false; } return true; } public boolean mayIFight(MOB mob) { if(mob==null) return false; if(location()==null) return false; if(mob.location()==null) return false; if(mob.amDead()) return false; if(mob.curState().getHitPoints()<=0) return false; if(amDead()) return false; if(curState().getHitPoints()<=0) return false; if(mob.isMonster()) return true; if(isMonster()){ MOB fol=amFollowing(); if((fol!=null)&&(!fol.isMonster())) return fol.mayIFight(mob); return true; } if(mob==this) return true; if(CommonStrings.getVar(CommonStrings.SYSTEM_PKILL).startsWith("ALWAYS")) return true; if(CommonStrings.getVar(CommonStrings.SYSTEM_PKILL).startsWith("NEVER")) return false; if(!Util.bset(getBitmap(),MOB.ATT_PLAYERKILL)) return false; if(!Util.bset(mob.getBitmap(),MOB.ATT_PLAYERKILL)) return false; return true; } public boolean mayPhysicallyAttack(MOB mob) { if((!mayIFight(mob)) ||(location()!=mob.location()) ||(!location().isInhabitant(this)) ||(!mob.location().isInhabitant(mob))) return false; return true; } public int adjustedAttackBonus() { double att=new Integer( envStats().attackAdjustment() +((charStats().getStat(CharStats.STRENGTH)-9)*3)).doubleValue(); if(curState().getHunger()<1) att=att*.9; if(curState().getThirst()<1) att=att*.9; if(curState().getFatigue()>CharState.FATIGUED_MILLIS) att=att*.8; return (int)Math.round(att); } public int adjustedArmor() { double arm=new Integer(((charStats().getStat(CharStats.DEXTERITY)-9)*3) +50).doubleValue(); if((envStats().disposition()&EnvStats.IS_SLEEPING)>0) arm=0.0; if(arm>0.0) { if(curState().getHunger()<1) arm=arm*.85; if(curState().getThirst()<1) arm=arm*.85; if(curState().getFatigue()>CharState.FATIGUED_MILLIS) arm=arm*.85; if((envStats().disposition()&EnvStats.IS_SITTING)>0) arm=arm*.75; } return (int)Math.round(envStats().armor()-arm); } public int adjustedDamage(Weapon weapon, MOB target) { double damageAmount=0.0; if(target!=null) { if((weapon!=null)&&((weapon.weaponClassification()==Weapon.CLASS_RANGED)||(weapon.weaponClassification()==Weapon.CLASS_THROWN))) damageAmount = new Integer(Dice.roll(1, weapon.envStats().damage(),1)).doubleValue(); else damageAmount = new Integer(Dice.roll(1, envStats().damage(), (charStats().getStat(CharStats.STRENGTH) / 3)-2)).doubleValue(); if(!Sense.canBeSeenBy(target,this)) damageAmount *=.5; if(Sense.isSleeping(target)) damageAmount *=1.5; else if(Sense.isSitting(target)) damageAmount *=1.2; } else if((weapon!=null)&&((weapon.weaponClassification()==Weapon.CLASS_RANGED)||(weapon.weaponClassification()==Weapon.CLASS_THROWN))) damageAmount = new Integer(weapon.envStats().damage()+1).doubleValue(); else damageAmount = new Integer(envStats().damage()+(charStats().getStat(CharStats.STRENGTH) / 3)-2).doubleValue(); if(curState().getHunger() < 1) damageAmount *= .8; if(curState().getFatigue()>CharState.FATIGUED_MILLIS) damageAmount *=.8; if(curState().getThirst() < 1) damageAmount *= .9; if(damageAmount<1.0) damageAmount=1.0; return (int)Math.round(damageAmount); } public void setAtRange(int newRange){atRange=newRange;} public int rangeToTarget(){return atRange;} public int maxRange(){return maxRange(null);} public int minRange(){return maxRange(null);} public int maxRange(Environmental tool) { int max=0; if(tool!=null) max=tool.maxRange(); if((location()!=null)&&(location().maxRange()<max)) max=location().maxRange(); return max; } public int minRange(Environmental tool) { if(tool!=null) return tool.minRange(); return 0; } public void makePeace() { MOB myVictim=victim; setVictim(null); if(myVictim!=null) { MOB oldVictim=myVictim.getVictim(); if(oldVictim==this) myVictim.makePeace(); } } public MOB getVictim() { if(!isInCombat()) return null; return victim; } public void setVictim(MOB mob) { if(mob==null) setAtRange(-1); if(victim==mob) return; if(mob==this) return; victim=mob; recoverEnvStats(); recoverCharStats(); recoverMaxState(); if(mob!=null) { if((mob.location()==null) ||(location()==null) ||(mob.amDead()) ||(amDead()) ||(mob.location()!=location()) ||(!location().isInhabitant(this)) ||(!location().isInhabitant(mob))) { if(victim!=null) victim.setVictim(null); victim=null; } else { mob.recoverCharStats(); mob.recoverEnvStats(); mob.recoverMaxState(); } } } public DeadBody killMeDead(boolean createBody) { Room deathRoom=null; if(isMonster()) deathRoom=location(); else deathRoom=CMMap.getBodyRoom(this); if(location()!=null) location().delInhabitant(this); DeadBody Body=null; if(createBody) Body=charStats().getMyRace().getCorpse(this,deathRoom); amDead=true; makePeace(); setRiding(null); for(int a=numAffects()-1;a>=0;a--) { Ability A=fetchAffect(a); if(A!=null) A.unInvoke(); } setLocation(null); while(numFollowers()>0) { MOB follower=fetchFollower(0); if(follower!=null) { follower.setFollowing(null); delFollower(follower); } } setFollowing(null); if((!isMonster())&&(soulMate()==null)) bringToLife(CMMap.getDeathRoom(this),true); if(Body!=null) Body.startTicker(deathRoom); deathRoom.recoverRoomStats(); return Body; } public Room location() { if(location==null) return lastLocation; return location; } public void setLocation(Room newRoom) { lastLocation=location; location=newRoom; } public Rideable riding(){return riding;} public void setRiding(Rideable ride) { if((ride!=null)&&(riding()!=null)&&(riding()==ride)&&(riding().amRiding(this))) return; if((riding()!=null)&&(riding().amRiding(this))) riding().delRider(this); riding=ride; if((riding()!=null)&&(!riding().amRiding(this))) riding().addRider(this); } public Session session() { return mySession; } public void setSession(Session newSession) { mySession=newSession; setBitmap(getBitmap()); } public Weapon myNaturalWeapon() { if((charStats()!=null)&&(charStats().getMyRace()!=null)) return charStats().getMyRace().myNaturalWeapon(); return (Weapon)CMClass.getWeapon("Natural"); } public String displayText(MOB viewer) { if((displayText.length()==0) ||(!name().equals(name())) ||(Sense.isSleeping(this)) ||(Sense.isSitting(this)) ||(riding()!=null) ||((this instanceof Rideable)&&(((Rideable)this).numRiders()>0)) ||(isInCombat())) { StringBuffer sendBack=null; sendBack=new StringBuffer(name()); sendBack.append(" "); sendBack.append(Sense.dispositionString(this,Sense.flag_is)); sendBack.append(" here"); if(riding()!=null) { sendBack.append(" "+riding().stateString(this)+" "); if(riding()==viewer) sendBack.append("YOU"); else sendBack.append(riding().name()); } else if((this instanceof Rideable) &&(((Rideable)this).numRiders()>0) &&(((Rideable)this).stateStringSubject(((Rideable)this).fetchRider(0)).length()>0)) { Rideable me=(Rideable)this; String first=me.stateStringSubject(me.fetchRider(0)); sendBack.append(" "+first+" "); for(int r=0;r<me.numRiders();r++) { Rider rider=me.fetchRider(r); if((rider!=null)&&(me.stateStringSubject(rider).equals(first))) { if(r>0) { sendBack.append(", "); if(r==me.numRiders()-1) sendBack.append("and "); } if(rider==viewer) sendBack.append("you"); else sendBack.append(rider.name()); } } } if((isInCombat())&&(Sense.canMove(this))&&(!Sense.isSleeping(this))) { sendBack.append(" fighting "); if(getVictim()==viewer) sendBack.append("YOU"); else sendBack.append(getVictim().name()); } sendBack.append("."); return sendBack.toString(); } else return displayText; } public String displayText() { return displayText; } public void setDisplayText(String newDisplayText) { displayText=newDisplayText; } public String description() { if((description==null)||(description.length==0)) return ""; else if(CommonStrings.getBoolVar(CommonStrings.SYSTEMB_MOBDCOMPRESS)) return Util.decompressString(description); else return new String(description); } public void setDescription(String newDescription) { if(newDescription.length()==0) description=null; else if(CommonStrings.getBoolVar(CommonStrings.SYSTEMB_MOBDCOMPRESS)) description=Util.compressString(newDescription); else description=newDescription.getBytes(); } public void setMiscText(String newText) { if(newText.length()==0) miscText=null; else if(CommonStrings.getBoolVar(CommonStrings.SYSTEMB_MOBCOMPRESS)) miscText=Util.compressString(newText); else miscText=newText.getBytes(); } public String text() { if((miscText==null)||(miscText.length==0)) return ""; else if(CommonStrings.getBoolVar(CommonStrings.SYSTEMB_MOBCOMPRESS)) return Util.decompressString(miscText); else return new String(miscText); } public String healthText() { if((charStats()!=null)&&(charStats().getMyRace()!=null)) return charStats().getMyRace().healthText(this); return CommonStrings.standardMobCondition(this); } public void establishRange(MOB source, MOB target, Environmental tool) { // establish and enforce range if((source.rangeToTarget()<0)) { if(source.riding()!=null) { if((target==riding())||(source.riding().amRiding(target))) source.setAtRange(0); else if((source.riding() instanceof MOB) &&(((MOB)source.riding()).isInCombat()) &&(((MOB)source.riding()).getVictim()==target) &&(((MOB)source.riding()).rangeToTarget()>=0) &&(((MOB)source.riding()).rangeToTarget()<rangeToTarget())) { source.setAtRange(((MOB)source.riding()).rangeToTarget()); recoverEnvStats(); return; } else for(int r=0;r<source.riding().numRiders();r++) { Rider rider=source.riding().fetchRider(r); if(!(rider instanceof MOB)) continue; MOB otherMOB=(MOB)rider; if((otherMOB!=null) &&(otherMOB!=this) &&(otherMOB.isInCombat()) &&(otherMOB.getVictim()==target) &&(otherMOB.rangeToTarget()>=0) &&(otherMOB.rangeToTarget()<rangeToTarget())) { source.setAtRange(otherMOB.rangeToTarget()); source.recoverEnvStats(); return; } } } if(target.getVictim()==source) { if(target.rangeToTarget()>=0) source.setAtRange(target.rangeToTarget()); else source.setAtRange(maxRange(tool)); } else source.setAtRange(maxRange(tool)); recoverEnvStats(); } } public boolean okAffect(Environmental myHost, Affect affect) { if((getMyDeity()!=null)&&(!getMyDeity().okAffect(this,affect))) return false; if(charStats!=null) { if(!charStats().getCurrentClass().okAffect(this,affect)) return false; if(!charStats().getMyRace().okAffect(this, affect)) return false; } for(int i=0;i<numAffects();i++) { Ability aff=(Ability)fetchAffect(i); if((aff!=null)&&(!aff.okAffect(this,affect))) return false; } for(int i=0;i<inventorySize();i++) { Item I=(Item)fetchInventory(i); if((I!=null)&&(!I.okAffect(this,affect))) return false; } for(int b=0;b<numBehaviors();b++) { Behavior B=fetchBehavior(b); if((B!=null)&&(!B.okAffect(this,affect))) return false; } MOB mob=affect.source(); if((affect.sourceCode()!=Affect.NO_EFFECT) &&(affect.amISource(this)) &&(!Util.bset(affect.sourceMajor(),Affect.MASK_GENERAL))) { int srcMajor=affect.sourceMajor(); if(amDead()) { tell("You are DEAD!"); return false; } if(Util.bset(affect.sourceCode(),Affect.MASK_MALICIOUS)) { if((affect.target()!=this)&&(affect.target()!=null)&&(affect.target() instanceof MOB)) { MOB target=(MOB)affect.target(); if((amFollowing()!=null)&&(target==amFollowing())) { tell("You like "+amFollowing().charStats().himher()+" too much."); return false; } if((getLeigeID().length()>0)&&(target.Name().equals(getLeigeID()))) { tell("You are serving '"+getLeigeID()+"'!"); return false; } establishRange(this,(MOB)affect.target(),affect.tool()); } } if(Util.bset(srcMajor,Affect.MASK_EYES)) { if(Sense.isSleeping(this)) { tell("Not while you are sleeping."); return false; } if(!(affect.target() instanceof Room)) if(!Sense.canBeSeenBy(affect.target(),this)) { if(affect.target() instanceof Item) tell("You don't see "+affect.target()+" here."); else tell("You can't see that!"); return false; } } if(Util.bset(srcMajor,Affect.MASK_MOUTH)) { if(!Sense.aliveAwakeMobile(this,false)) return false; if(Util.bset(srcMajor,Affect.MASK_SOUND)) { if((affect.tool()==null) ||(!(affect.tool() instanceof Ability)) ||(!((Ability)affect.tool()).isNowAnAutoEffect())) { if(Sense.isSleeping(this)) { tell("Not while you are sleeping."); return false; } if(!Sense.canSpeak(this)) { tell("You can't make sounds!"); return false; } if(Sense.isAnimalIntelligence(this)) { tell("You aren't smart enough to speak."); return false; } } } else { if((!Sense.canBeSeenBy(affect.target(),this)) &&(!(isMine(affect.target())&&(affect.target() instanceof Item)))) { mob.tell("You don't see '"+affect.target().name()+"' here."); return false; } if(!Sense.canTaste(this)) { tell("You can't eat or drink!"); return false; } } } if(Util.bset(srcMajor,Affect.MASK_HANDS)) { if((!Sense.canBeSeenBy(affect.target(),this)) &&(!(isMine(affect.target())&&(affect.target() instanceof Item))) &&(!(isInCombat()&&(affect.target()==victim)))) { mob.tell("You don't see '"+affect.target().name()+"' here."); return false; } if(!Sense.aliveAwakeMobile(this,false)) return false; if((Sense.isSitting(this)) &&(affect.sourceMinor()!=Affect.TYP_SITMOVE) &&(affect.targetCode()!=Affect.MSG_OK_VISUAL) &&((affect.sourceMessage()!=null)||(affect.othersMessage()!=null)) &&((!CoffeeUtensils.reachableItem(this,affect.target())) ||(!CoffeeUtensils.reachableItem(this,affect.tool())))) { tell("You need to stand up!"); return false; } } if(Util.bset(srcMajor,Affect.MASK_MOVE)) { boolean sitting=Sense.isSitting(this); if((sitting) &&((affect.sourceMinor()==Affect.TYP_LEAVE) ||(affect.sourceMinor()==Affect.TYP_ENTER))) sitting=false; if(((Sense.isSleeping(this))||(sitting)) &&(affect.sourceMinor()!=Affect.TYP_STAND) &&(affect.sourceMinor()!=Affect.TYP_SITMOVE) &&(affect.sourceMinor()!=Affect.TYP_SLEEP)) { tell("You need to stand up!"); return false; } if(!Sense.canMove(this)) { tell("You can't move!"); return false; } } switch(affect.sourceMinor()) { case Affect.TYP_ENTER: movesSinceTick++; break; case Affect.TYP_JUSTICE: if((affect.target()!=null) &&(isInCombat()) &&(affect.target() instanceof Item)) { tell("Not while you are fighting!"); return false; } break; case Affect.TYP_OPEN: case Affect.TYP_CLOSE: if(isInCombat()) { if((affect.target()!=null) &&((affect.target() instanceof Exit)||(affect.source().isMine(affect.target())))) break; tell("Not while you are fighting!"); return false; } break; case Affect.TYP_BUY: case Affect.TYP_DELICATE_HANDS_ACT: case Affect.TYP_LEAVE: case Affect.TYP_FILL: case Affect.TYP_LIST: case Affect.TYP_LOCK: case Affect.TYP_SIT: case Affect.TYP_SLEEP: case Affect.TYP_UNLOCK: case Affect.TYP_VALUE: case Affect.TYP_SELL: case Affect.TYP_VIEW: case Affect.TYP_READSOMETHING: if(isInCombat()) { tell("Not while you are fighting!"); return false; } break; case Affect.TYP_REBUKE: if((affect.target()==null)||(!(affect.target() instanceof Deity))) { if(affect.target()!=null) { if(!Sense.canBeHeardBy(this,affect.target())) { tell(affect.target().name()+" can't hear you!"); return false; } else if((!((affect.target() instanceof MOB) &&(((MOB)affect.target()).getLeigeID().equals(Name())))) &&(!affect.target().Name().equals(getLeigeID()))) { tell(affect.target().name()+" does not serve you, and you do not serve "+affect.target().name()+"."); return false; } } else if(getLeigeID().length()==0) { tell("You aren't serving anyone!"); return false; } } else if(getWorshipCharID().length()==0) { tell("You aren't worshipping anyone!"); return false; } break; case Affect.TYP_SERVE: if(affect.target()==null) return false; if(affect.target()==this) { tell("You can't serve yourself!"); return false; } if(affect.target() instanceof Deity) break; if(!Sense.canBeHeardBy(this,affect.target())) { tell(affect.target().name()+" can't hear you!"); return false; } if(getLeigeID().length()>0) { tell("You are already serving '"+getLeigeID()+"'."); return false; } break; case Affect.TYP_CAST_SPELL: if(charStats().getStat(CharStats.INTELLIGENCE)<5) { tell("You aren't smart enough to do magic."); return false; } break; default: break; } } if((affect.sourceCode()!=Affect.NO_EFFECT) &&(affect.amISource(this)) &&(affect.target()!=null) &&(affect.target()!=this) &&(!Util.bset(affect.sourceCode(),Affect.MASK_GENERAL)) &&(affect.target() instanceof MOB) &&(location()==((MOB)affect.target()).location())) { MOB target=(MOB)affect.target(); // and now, the consequences of range if((location()!=null) &&(affect.targetMinor()==Affect.TYP_WEAPONATTACK) &&(rangeToTarget()>maxRange(affect.tool()))) { String newstr="<S-NAME> advance(s) at "; affect.modify(this,target,null,Affect.MSG_ADVANCE,newstr+target.name(),Affect.MSG_ADVANCE,newstr+"you",Affect.MSG_ADVANCE,newstr+target.name()); boolean ok=location().okAffect(this,affect); if(ok) setAtRange(rangeToTarget()-1); if(victim!=null) { victim.setAtRange(rangeToTarget()); victim.recoverEnvStats(); } recoverEnvStats(); return ok; } else if(affect.targetMinor()==Affect.TYP_RETREAT) { if(curState().getMovement()<25) { tell("You are too tired."); return false; } if((location()!=null) &&(rangeToTarget()>=location().maxRange())) { tell("You cannot retreat any further."); return false; } curState().adjMovement(-25,maxState()); setAtRange(rangeToTarget()+1); if(victim!=null) { victim.setAtRange(rangeToTarget()); victim.recoverEnvStats(); } recoverEnvStats(); } else if(affect.tool()!=null) { int useRange=rangeToTarget(); Environmental tool=affect.tool(); if(getVictim()!=null) { if(getVictim()==target) useRange=rangeToTarget(); else { if(target.getVictim()==this) useRange=target.rangeToTarget(); else useRange=maxRange(tool); } } if((useRange>=0)&&(maxRange(tool)<useRange)) { mob.tell("You are too far away from "+target.name()+" to use "+tool.name()+"."); return false; } else if((useRange>=0)&&(minRange(tool)>useRange)) { mob.tell("You are too close to "+target.name()+" to use "+tool.name()+"."); if((affect.targetMinor()==Affect.TYP_WEAPONATTACK) &&(tool instanceof Weapon) &&(!((Weapon)tool).amWearingAt(Item.INVENTORY))) ExternalPlay.remove(this,(Item)tool,false); return false; } } } if((affect.targetCode()!=Affect.NO_EFFECT)&&(affect.amITarget(this))) { if((amDead())||(location()==null)) return false; if(Util.bset(affect.targetCode(),Affect.MASK_MALICIOUS)) { if((affect.amISource(this)) &&(!Util.bset(affect.sourceMajor(),Affect.MASK_GENERAL)) &&((affect.tool()==null)||(!(affect.tool() instanceof Ability))||(!((Ability)affect.tool()).isNowAnAutoEffect()))) { mob.tell("You like yourself too much."); if(victim==this) victim=null; return false; } if(!mayIFight(mob)) { mob.tell("You are not allowed to attack "+name()+"."); mob.setVictim(null); if(victim==mob) setVictim(null); return false; } if((!isMonster()) &&(!mob.isMonster()) &&(mob.envStats().level()>envStats().level()+CommonStrings.getPKillLevelDiff())) { mob.tell("That is not EVEN a fair fight."); mob.setVictim(null); if(victim==mob) setVictim(null); return false; } if(this.amFollowing()==mob) setFollowing(null); if(isInCombat()) { if((rangeToTarget()>0) &&(getVictim()!=affect.source()) &&(affect.source().getVictim()==this) &&(affect.source().rangeToTarget()==0)) { setVictim(affect.source()); setAtRange(0); } } if(affect.targetMinor()!=Affect.TYP_WEAPONATTACK) { int chanceToFail=Integer.MIN_VALUE; int saveCode=-1; for(int c=0;c<CharStats.affectTypeMap.length;c++) if(affect.targetMinor()==CharStats.affectTypeMap[c]) { saveCode=c; chanceToFail=charStats().getSave(c); break;} if((chanceToFail>Integer.MIN_VALUE)&&(!affect.wasModified())) { chanceToFail+=(envStats().level()-affect.source().envStats().level()); if(chanceToFail<5) chanceToFail=5; else if(chanceToFail>95) chanceToFail=95; if(Dice.rollPercentage()<chanceToFail) { CommonStrings.resistanceMsgs(affect,affect.source(),this); affect.tagModified(true); } } } } if((rangeToTarget()>0)&&(!isInCombat())) setAtRange(-1); switch(affect.targetMinor()) { case Affect.TYP_CLOSE: case Affect.TYP_DRINK: case Affect.TYP_DROP: case Affect.TYP_THROW: case Affect.TYP_EAT: case Affect.TYP_FILL: case Affect.TYP_GET: case Affect.TYP_HOLD: case Affect.TYP_REMOVE: case Affect.TYP_LOCK: case Affect.TYP_OPEN: case Affect.TYP_PULL: case Affect.TYP_PUT: case Affect.TYP_UNLOCK: case Affect.TYP_WEAR: case Affect.TYP_WIELD: case Affect.TYP_MOUNT: case Affect.TYP_DISMOUNT: mob.tell("You can't do that to "+name()+"."); return false; case Affect.TYP_GIVE: if(affect.tool()==null) return false; if(!(affect.tool() instanceof Item)) return false; if(!Sense.canBeSeenBy(affect.tool(),this)) { mob.tell(name()+" can't see what you are giving."); return false; } FullMsg msg=new FullMsg(affect.source(),affect.tool(),null,Affect.MSG_DROP,null); if(!location().okAffect(affect.source(),msg)) return false; if((affect.target()!=null)&&(affect.target() instanceof MOB)) { msg=new FullMsg((MOB)affect.target(),affect.tool(),null,Affect.MSG_GET,null); if(!location().okAffect(affect.target(),msg)) { mob.tell(affect.target().name()+" cannot seem to accept "+affect.tool().name()+"."); return false; } } break; case Affect.TYP_FOLLOW: if(numFollowers()>=maxFollowers()) { mob.tell(name()+" can't accept any more followers."); return false; } break; } } return true; } public void tell(MOB source, Environmental target, Environmental tool, String msg) { if(mySession!=null) mySession.stdPrintln(source,target,tool,msg); } public void tell(String msg) { tell(this,this,null,msg); } public void affect(Environmental myHost, Affect affect) { if(getMyDeity()!=null) getMyDeity().affect(this,affect); if(charStats!=null) { charStats().getCurrentClass().affect(this,affect); charStats().getMyRace().affect(this,affect); } for(int b=0;b<numBehaviors();b++) { Behavior B=fetchBehavior(b); if(B!=null) B.affect(this,affect); } MOB mob=affect.source(); boolean asleep=Sense.isSleeping(this); boolean canseesrc=Sense.canBeSeenBy(affect.source(),this); boolean canhearsrc=Sense.canBeHeardBy(affect.source(),this); if((affect.sourceCode()!=Affect.NO_EFFECT)&&(affect.amISource(this))) { if(Util.bset(affect.sourceCode(),Affect.MASK_MALICIOUS)) if((affect.target() instanceof MOB)&&(getVictim()!=affect.target())) { establishRange(this,(MOB)affect.target(),affect.tool()); setVictim((MOB)affect.target()); } switch(affect.sourceMinor()) { case Affect.TYP_PANIC: ExternalPlay.flee(mob,""); break; case Affect.TYP_DEATH: if((affect.tool()!=null)&&(affect.tool() instanceof MOB)) ExternalPlay.justDie((MOB)affect.tool(),this); else ExternalPlay.justDie(null,this); tell(this,affect.target(),affect.tool(),affect.sourceMessage()); break; case Affect.TYP_REBUKE: if(((affect.target()==null)&&(getLeigeID().length()>0)) ||((affect.target()!=null)&&(affect.target().Name().equals(getLeigeID())))) setLeigeID(""); tell(this,affect.target(),affect.tool(),affect.sourceMessage()); break; case Affect.TYP_SERVE: if((affect.target()!=null)&&(!(affect.target() instanceof Deity))) setLeigeID(affect.target().Name()); tell(this,affect.target(),affect.tool(),affect.sourceMessage()); break; case Affect.TYP_EXAMINESOMETHING: if((Sense.canBeSeenBy(this,mob))&&(affect.amITarget(this))) { StringBuffer myDescription=new StringBuffer(""); if(Util.bset(mob.getBitmap(),MOB.ATT_SYSOPMSGS)) myDescription.append(ID()+"\n\rRejuv:"+baseEnvStats().rejuv()+"\n\rAbile:"+baseEnvStats().ability()+"\n\rLevel:"+baseEnvStats().level()+"\n\rMisc : "+text()+"\n\r"+description()+"\n\rRoom :'"+((getStartRoom()==null)?"null":getStartRoom().roomID())+"\n\r"); if(!isMonster()) { String levelStr=charStats().displayClassLevel(this,false); myDescription.append(name()+" the "+charStats().raceName()+" is a "+levelStr+".\n\r"); } if(envStats().height()>0) myDescription.append(charStats().HeShe()+" is "+envStats().height()+" inches tall and weighs "+baseEnvStats().weight()+" pounds.\n\r"); myDescription.append(healthText()+"\n\r\n\r"); myDescription.append(description()+"\n\r\n\r"); myDescription.append(charStats().HeShe()+" is wearing:\n\r"+ExternalPlay.getEquipment(affect.source(),this)); tell(myDescription.toString()); } break; case Affect.TYP_READSOMETHING: if((Sense.canBeSeenBy(this,mob))&&(affect.amITarget(this))) tell("There is nothing written on "+name()); break; case Affect.TYP_SIT: { int oldDisposition=mob.baseEnvStats().disposition(); oldDisposition=oldDisposition&(Integer.MAX_VALUE-EnvStats.IS_SLEEPING-EnvStats.IS_SNEAKING-EnvStats.IS_SITTING); mob.baseEnvStats().setDisposition(oldDisposition|EnvStats.IS_SITTING); mob.recoverEnvStats(); mob.recoverCharStats(); mob.recoverMaxState(); tell(this,affect.target(),affect.tool(),affect.sourceMessage()); } break; case Affect.TYP_SLEEP: { int oldDisposition=mob.baseEnvStats().disposition(); oldDisposition=oldDisposition&(Integer.MAX_VALUE-EnvStats.IS_SLEEPING-EnvStats.IS_SNEAKING-EnvStats.IS_SITTING); mob.baseEnvStats().setDisposition(oldDisposition|EnvStats.IS_SLEEPING); mob.recoverEnvStats(); mob.recoverCharStats(); mob.recoverMaxState(); tell(this,affect.target(),affect.tool(),affect.sourceMessage()); } break; case Affect.TYP_QUIT: if(mob.isInCombat()) { mob.getVictim().resetToMaxState(); ExternalPlay.flee(mob,"NOWHERE"); mob.makePeace(); } tell(affect.source(),affect.target(),affect.tool(),affect.sourceMessage()); break; case Affect.TYP_STAND: { int oldDisposition=mob.baseEnvStats().disposition(); oldDisposition=oldDisposition&(Integer.MAX_VALUE-EnvStats.IS_SLEEPING-EnvStats.IS_SNEAKING-EnvStats.IS_SITTING); mob.baseEnvStats().setDisposition(oldDisposition); mob.recoverEnvStats(); mob.recoverCharStats(); mob.recoverMaxState(); tell(this,affect.target(),affect.tool(),affect.sourceMessage()); } break; case Affect.TYP_RECALL: if((affect.target()!=null) && (affect.target() instanceof Room) && (location() != affect.target())) { tell(affect.source(),null,affect.tool(),affect.targetMessage()); location().delInhabitant(this); ((Room)affect.target()).addInhabitant(this); ((Room)affect.target()).showOthers(mob,null,Affect.MSG_ENTER,"<S-NAME> appears out of the Java Plain."); setLocation(((Room)affect.target())); recoverEnvStats(); recoverCharStats(); recoverMaxState(); ExternalPlay.look(mob,new Vector(),true); } break; case Affect.TYP_FOLLOW: if((affect.target()!=null)&&(affect.target() instanceof MOB)) { setFollowing((MOB)affect.target()); tell(affect.source(),affect.target(),affect.tool(),affect.sourceMessage()); } break; case Affect.TYP_NOFOLLOW: setFollowing(null); tell(affect.source(),affect.target(),affect.tool(),affect.sourceMessage()); break; default: // you pretty much always know what you are doing, if you can do it. tell(affect.source(),affect.target(),affect.tool(),affect.sourceMessage()); break; } } else if((affect.targetCode()!=Affect.NO_EFFECT)&&(affect.amITarget(this))) { int targetMajor=affect.targetMajor(); // malicious by itself is pure pain if(Util.bset(affect.targetCode(),Affect.MASK_HURT)) { int dmg=affect.targetCode()-Affect.MASK_HURT; if(dmg>0) { if((!curState().adjHitPoints(-dmg,maxState()))&&(location()!=null)) ExternalPlay.postDeath(affect.source(),this,affect); else if((curState().getHitPoints()<getWimpHitPoint())&&(isInCombat())) ExternalPlay.postPanic(this,affect); } } else if(Util.bset(affect.targetCode(),Affect.MASK_MALICIOUS)) { if((!isInCombat()) &&(!amDead) &&(location().isInhabitant((MOB)affect.source()))) { establishRange(this,affect.source(),affect.tool()); setVictim(affect.source()); } if((isInCombat())&&(!amDead)) { if(affect.targetMinor()==Affect.TYP_WEAPONATTACK) { Weapon weapon=affect.source().myNaturalWeapon(); if((affect.tool()!=null)&&(affect.tool() instanceof Weapon)) weapon=(Weapon)affect.tool(); if(weapon!=null) { boolean isHit=(CoffeeUtensils.normalizeAndRollLess(affect.source().adjustedAttackBonus()+adjustedArmor())); ExternalPlay.postWeaponDamage(affect.source(),this,weapon,isHit); affect.tagModified(true); } } else if((affect.tool()!=null) &&(affect.tool() instanceof Weapon)) ExternalPlay.postWeaponDamage(affect.source(),this,(Weapon)affect.tool(),true); } ExternalPlay.standIfNecessary(this); } else if((affect.targetMinor()==Affect.TYP_GIVE) &&(affect.tool()!=null) &&(affect.tool() instanceof Item)) { FullMsg msg=new FullMsg(affect.source(),affect.tool(),null,Affect.MSG_DROP,null); location().send(this,msg); msg=new FullMsg((MOB)affect.target(),affect.tool(),null,Affect.MSG_GET,null); location().send(this,msg); } else if((affect.targetMinor()==Affect.TYP_EXAMINESOMETHING) &&(Sense.canBeSeenBy(this,mob))) { StringBuffer myDescription=new StringBuffer(""); if(Util.bset(mob.getBitmap(),MOB.ATT_SYSOPMSGS)) myDescription.append(Name()+"\n\rRejuv:"+baseEnvStats().rejuv()+"\n\rAbile:"+baseEnvStats().ability()+"\n\rLevel:"+baseEnvStats().level()+"\n\rMisc :'"+text()+"\n\rRoom :'"+((getStartRoom()==null)?"null":getStartRoom().roomID())+"\n\r"+description()+"\n\r"); if(!isMonster()) { String levelStr=charStats().displayClassLevel(this,false); myDescription.append(name()+" the "+charStats().raceName()+" is a "+levelStr+".\n\r"); } if(envStats().height()>0) myDescription.append(charStats().HeShe()+" is "+envStats().height()+" inches tall and weighs "+baseEnvStats().weight()+" pounds.\n\r"); myDescription.append(healthText()+"\n\r\n\r"); myDescription.append(description()+"\n\r\n\r"); myDescription.append(charStats().HeShe()+" is wearing:\n\r"+ExternalPlay.getEquipment(affect.source(),this)); mob.tell(myDescription.toString()); } else if((affect.targetMinor()==Affect.TYP_REBUKE) &&(affect.source().Name().equals(getLeigeID()))) setLeigeID(""); else if(Util.bset(targetMajor,affect.MASK_CHANNEL)) { if((playerStats()!=null) &&(!Util.isSet(playerStats().getChannelMask(),((affect.targetCode()-affect.MASK_CHANNEL)-Affect.TYP_CHANNEL)))) tell(affect.source(),affect.target(),affect.tool(),affect.targetMessage()); } if((Util.bset(targetMajor,Affect.MASK_SOUND)) &&(canhearsrc)&&(!asleep)) { if((affect.targetMinor()==Affect.TYP_SPEAK) &&(affect.source()!=null) &&(playerStats()!=null)) playerStats().setReplyTo(affect.source()); tell(affect.source(),affect.target(),affect.tool(),affect.targetMessage()); } else if(((Util.bset(targetMajor,Affect.MASK_EYES)) ||(Util.bset(affect.targetCode(),Affect.MASK_HURT)) ||(Util.bset(targetMajor,Affect.MASK_GENERAL))) &&(!asleep)&&(canseesrc)) tell(affect.source(),affect.target(),affect.tool(),affect.targetMessage()); else if(Util.bset(affect.targetCode(),Affect.MASK_MALICIOUS)) tell(affect.source(),affect.target(),affect.tool(),affect.targetMessage()); else if(((Util.bset(targetMajor,Affect.MASK_HANDS)) ||(Util.bset(targetMajor,Affect.MASK_MOVE)) ||((Util.bset(targetMajor,Affect.MASK_MOUTH)) &&(!Util.bset(targetMajor,Affect.MASK_SOUND)))) &&(!asleep)&&((canhearsrc)||(canseesrc))) tell(affect.source(),affect.target(),affect.tool(),affect.targetMessage()); } else if((affect.othersCode()!=Affect.NO_EFFECT) &&(!affect.amISource(this)) &&(!affect.amITarget(this))) { int othersMajor=affect.othersMajor(); int othersMinor=affect.othersMinor(); if(Util.bset(affect.othersCode(),Affect.MASK_MALICIOUS)&&(affect.target() instanceof MOB)) fightingFollowers((MOB)affect.target(),affect.source()); if((othersMinor==Affect.TYP_ENTER) // exceptions to movement ||(othersMinor==Affect.TYP_FLEE) ||(othersMinor==Affect.TYP_LEAVE)) { if(((!asleep)||(affect.othersMinor()==Affect.TYP_ENTER)) &&(Sense.canSenseMoving(affect.source(),this))) tell(affect.source(),affect.target(),affect.tool(),affect.othersMessage()); } else if(Util.bset(othersMajor,affect.MASK_CHANNEL)) { if((playerStats()!=null) &&(!Util.isSet(playerStats().getChannelMask(),((affect.othersCode()-affect.MASK_CHANNEL)-Affect.TYP_CHANNEL)))) tell(affect.source(),affect.target(),affect.tool(),affect.othersMessage()); } else if((Util.bset(othersMajor,Affect.MASK_SOUND)) &&(!asleep) &&(canhearsrc)) tell(affect.source(),affect.target(),affect.tool(),affect.othersMessage()); else if(((Util.bset(othersMajor,Affect.MASK_EYES)) ||(Util.bset(othersMajor,Affect.MASK_HANDS)) ||(Util.bset(othersMajor,Affect.MASK_GENERAL))) &&((!asleep)&&(canseesrc))) tell(affect.source(),affect.target(),affect.tool(),affect.othersMessage()); else if(((Util.bset(othersMajor,Affect.MASK_MOVE)) ||((Util.bset(othersMajor,Affect.MASK_MOUTH))&&(!Util.bset(othersMajor,Affect.MASK_SOUND)))) &&(!asleep) &&((canseesrc)||(canhearsrc))) tell(affect.source(),affect.target(),affect.tool(),affect.othersMessage()); if((affect.othersMinor()==Affect.TYP_DEATH)&&(victim!=null)) { if(victim==affect.source()) setVictim(null); else if((victim.getVictim()==null)||(victim.getVictim()==affect.source())) { if((amFollowing()!=null)&&(victim.amFollowing()!=null)&&(amFollowing()==victim.amFollowing())) setVictim(null); else { victim.setAtRange(-1); victim.setVictim(this); } } } } for(int i=0;i<inventorySize();i++) { Item I=(Item)fetchInventory(i); if(I!=null) I.affect(this,affect); } for(int i=0;i<numAffects();i++) { Ability A=(Ability)fetchAffect(i); if(A!=null) A.affect(this,affect); } } public void affectCharStats(MOB affectedMob, CharStats affectableStats){} public int movesSinceLastTick(){return movesSinceTick;} public long getTickStatus(){return tickStatus;} public boolean tick(Tickable ticking, int tickID) { if(pleaseDestroy) return false; tickStatus=Tickable.STATUS_START; if(tickID==Host.MOB_TICK) { movesSinceTick=0; if(amDead) { tickStatus=Tickable.STATUS_DEAD; if(isMonster()) if((envStats().rejuv()<Integer.MAX_VALUE) &&(baseEnvStats().rejuv()>0)) { envStats().setRejuv(envStats().rejuv()-1); if(envStats().rejuv()<0) { bringToLife(getStartRoom(),true); location().showOthers(this,null,Affect.MSG_OK_ACTION,"<S-NAME> appears!"); } } else { tickStatus=Tickable.STATUS_END; destroy(); tickStatus=Tickable.STATUS_NOT; lastTickedDateTime=System.currentTimeMillis(); return false; } tickStatus=Tickable.STATUS_END; } else if(location()!=null) { tickStatus=Tickable.STATUS_ALIVE; curState().recoverTick(this,maxState); curState().expendEnergy(this,maxState,false); if(!Sense.canBreathe(this)) { location().show(this,this,Affect.MSG_OK_VISUAL,("^Z<S-NAME> can't breathe!^.^?")+CommonStrings.msp("choke.wav",10)); ExternalPlay.postDamage(this,this,null,(int)Math.round(Util.mul(Math.random(),baseEnvStats().level()+2)),Affect.NO_EFFECT,-1,null); } if(isInCombat()) { tickStatus=Tickable.STATUS_FIGHT; peaceTime=0; if(Util.bset(getBitmap(),MOB.ATT_AUTODRAW)) ExternalPlay.drawIfNecessary(this,false); Item weapon=this.fetchWieldedItem(); double curSpeed=Math.floor(speeder); speeder+=envStats().speed(); int numAttacks=(int)Math.round(Math.floor(speeder-curSpeed)); if(Sense.aliveAwakeMobile(this,true)) { for(int s=0;s<numAttacks;s++) { if((!amDead()) &&(curState().getHitPoints()>0) &&(isInCombat()) &&((s==0)||(!Sense.isSitting(this)))) { if((weapon!=null)&&(weapon.amWearingAt(Item.INVENTORY))) weapon=this.fetchWieldedItem(); if((!Util.bset(getBitmap(),MOB.ATT_AUTOMELEE))) ExternalPlay.postAttack(this,victim,weapon); else { boolean inminrange=(rangeToTarget()>=minRange(weapon)); boolean inmaxrange=(rangeToTarget()<=maxRange(weapon)); if((!inminrange)&&(curState().getMovement()>=25)) { FullMsg msg=new FullMsg(this,victim,Affect.MSG_RETREAT,"<S-NAME> retreat(s) before <T-NAME>."); if(location().okAffect(this,msg)) location().send(this,msg); } else if((weapon!=null)&&inminrange&&inmaxrange) ExternalPlay.postAttack(this,victim,weapon); } } else break; } if(Dice.rollPercentage()>(charStats().getStat(CharStats.CONSTITUTION)*4)) curState().adjMovement(-1,maxState()); } if(!isMonster()) { MOB target=this.getVictim(); if((target!=null)&&(!target.amDead())&&(Sense.canBeSeenBy(target,this))) session().print(target.healthText()+"\n\r\n\r"); } } else { speeder=0.0; peaceTime+=Host.TICK_TIME; if(Util.bset(getBitmap(),MOB.ATT_AUTODRAW) &&(peaceTime>=SHEATH_TIME) &&(Sense.aliveAwakeMobile(this,true))) ExternalPlay.sheathIfPossible(this); } tickStatus=Tickable.STATUS_OTHER; if(!isMonster()) { if(Sense.isSleeping(this)) curState().adjFatigue(-CharState.REST_PER_TICK,maxState()); else curState().adjFatigue(Host.TICK_TIME,maxState()); } if((riding()!=null)&&(CoffeeUtensils.roomLocation(riding())!=location())) setRiding(null); if((!isMonster())&&(((++minuteCounter)*Host.TICK_TIME)>60000)) { minuteCounter=0; setAgeHours(AgeHours+1); if(AgeHours>60000) { if(((AgeHours%120)==0)&&(Dice.rollPercentage()==1)) { Ability A=CMClass.getAbility("Disease_Cancer"); if((A!=null)&&(fetchAffect(A.ID())==null)) A.invoke(this,this,true); } else if(((AgeHours%1200)==0)&&(Dice.rollPercentage()<25)) { Ability A=CMClass.getAbility("Disease_Arthritis"); if((A!=null)&&(fetchAffect(A.ID())==null)) A.invoke(this,this,true); } } } } int a=0; while(a<numAffects()) { Ability A=fetchAffect(a); if(A!=null) { tickStatus=Tickable.STATUS_AFFECT+a; int s=affects.size(); if(!A.tick(ticking,tickID)) A.unInvoke(); if(affects.size()==s) a++; } else a++; } for(int b=0;b<numBehaviors();b++) { Behavior B=fetchBehavior(b); tickStatus=Tickable.STATUS_BEHAVIOR+b; if(B!=null) B.tick(ticking,tickID); } tickStatus=Tickable.STATUS_CLASS; charStats().getCurrentClass().tick(ticking,tickID); tickStatus=Tickable.STATUS_RACE; charStats().getMyRace().tick(ticking,tickID); tickStatus=Tickable.STATUS_END; } tickStatus=Tickable.STATUS_NOT; lastTickedDateTime=System.currentTimeMillis(); return !pleaseDestroy; } public boolean isMonster(){ return (mySession==null);} public int compareTo(Object o){ return CMClass.classID(this).compareToIgnoreCase(CMClass.classID(o));} public boolean isASysOp(Room of) { if(baseCharStats()==null) return false; if(baseCharStats().getClassLevel("Archon")>=0) return true; if(of==null) return false; if(of.getArea()==null) return false; if(of.getArea().amISubOp(Username)) return true; return false; } public void confirmWearability() { Race R=charStats().getMyRace(); for(int i=0;i<inventorySize();i++) { Item item=fetchInventory(i); if((item!=null)&&(!item.amWearingAt(Item.INVENTORY))) { long oldCode=item.rawWornCode(); item.unWear(); int msgCode=Affect.MSG_WEAR; if((oldCode&Item.WIELD)>0) msgCode=Affect.MSG_WIELD; else if((oldCode&Item.HELD)>0) msgCode=Affect.MSG_HOLD; FullMsg msg=new FullMsg(this,item,null,Affect.NO_EFFECT,null,msgCode,null,Affect.NO_EFFECT,null); if((R.okAffect(this,msg))&&(item.okAffect(item,msg))) item.wearAt(oldCode); } } } public void addInventory(Item item) { item.setOwner(this); inventory.addElement(item); item.recoverEnvStats(); } public void delInventory(Item item) { inventory.removeElement(item); item.recoverEnvStats(); } public int inventorySize() { return inventory.size(); } public Item fetchInventory(int index) { try { return (Item)inventory.elementAt(index); } catch(java.lang.ArrayIndexOutOfBoundsException x){} return null; } public Item fetchInventory(String itemName) { Item item=(Item)CoffeeUtensils.fetchAvailableItem(inventory,itemName,null,Item.WORN_REQ_ANY,true); if(item==null) item=(Item)CoffeeUtensils.fetchAvailableItem(inventory,itemName,null,Item.WORN_REQ_ANY,false); return item; } public Item fetchInventory(Item goodLocation, String itemName) { Item item=(Item)CoffeeUtensils.fetchAvailableItem(inventory,itemName,goodLocation,Item.WORN_REQ_ANY,true); if(item==null) item=(Item)CoffeeUtensils.fetchAvailableItem(inventory,itemName,goodLocation,Item.WORN_REQ_ANY,false); return item; } public Item fetchCarried(Item goodLocation, String itemName) { Item item=(Item)CoffeeUtensils.fetchAvailableItem(inventory,itemName,goodLocation,Item.WORN_REQ_UNWORNONLY,true); if(item==null) item=(Item)CoffeeUtensils.fetchAvailableItem(inventory,itemName,goodLocation,Item.WORN_REQ_UNWORNONLY,false); return item; } public Item fetchWornItem(String itemName) { Item item=(Item)CoffeeUtensils.fetchAvailableItem(inventory,itemName,null,Item.WORN_REQ_WORNONLY,true); if(item==null) item=(Item)CoffeeUtensils.fetchAvailableItem(inventory,itemName,null,Item.WORN_REQ_WORNONLY,false); return item; } public void addFollower(MOB follower) { if((follower!=null)&&(!followers.contains(follower))) { followers.addElement(follower); } } public void delFollower(MOB follower) { if((follower!=null)&&(followers.contains(follower))) { followers.removeElement(follower); } } public int numFollowers() { return followers.size(); } public MOB fetchFollower(int index) { try { return (MOB)followers.elementAt(index); } catch(java.lang.ArrayIndexOutOfBoundsException x){} return null; } public MOB fetchFollower(MOB thisOne) { if(followers.contains(thisOne)) return thisOne; return null; } public MOB fetchFollower(String ID) { MOB mob=(MOB)CoffeeUtensils.fetchEnvironmental(followers,ID,true); if (mob==null) mob=(MOB)CoffeeUtensils.fetchEnvironmental(followers,ID,false); return mob; } public boolean willFollowOrdersOf(MOB mob) { if(mob.isASysOp(mob.location()) ||(amFollowing()==mob) ||(getLeigeID().equals(mob.Name())) ||((getClanID().length()>0) &&(getClanID().equals(mob.getClanID())) &&(mob.getClanRole()!=getClanRole()) &&(getClanRole()!=Clan.POS_BOSS) &&((mob.getClanRole()==Clan.POS_LEADER) ||(mob.getClanRole()==Clan.POS_BOSS))) ||(ExternalPlay.doesOwnThisProperty(mob,getStartRoom()))) return true; return false; } public MOB amFollowing() { if(amFollowing!=null) { if(amFollowing.fetchFollower(this)==null) amFollowing=null; } return amFollowing; } public void setFollowing(MOB mob) { if(mob==null) { if(amFollowing!=null) { if(amFollowing.fetchFollower(this)!=null) amFollowing.delFollower(this); } } else if(mob.fetchFollower(this)==null) mob.addFollower(this); amFollowing=mob; } private void addFollowers(MOB mob, Hashtable toThis) { if(toThis.get(mob)==null) toThis.put(mob,mob); for(int f=0;f<mob.numFollowers();f++) { MOB follower=mob.fetchFollower(f); if((follower!=null)&&(toThis.get(follower)==null)) { toThis.put(follower,follower); addFollowers(follower,toThis); } } } public Hashtable getRideBuddies(Hashtable list) { if(list==null) return list; if(list.get(this)==null) list.put(this,this); if(riding()!=null) riding().getRideBuddies(list); return list; } public Hashtable getGroupMembers(Hashtable list) { if(list==null) return list; if(list.get(this)==null) list.put(this,this); if(amFollowing()!=null) amFollowing().getGroupMembers(list); for(int f=0;f<numFollowers();f++) { MOB follower=fetchFollower(f); if((follower!=null)&&(list.get(follower)==null)) follower.getGroupMembers(list); } return list; } public boolean isEligibleMonster() { if(!isMonster()) return false; MOB followed=amFollowing(); if(followed!=null) if(!followed.isMonster()) return false; return true; } public MOB soulMate() { return soulMate; } public void setSoulMate(MOB mob) { soulMate=mob; } public void addAbility(Ability to) { if(to==null) return; for(int a=0;a<numAbilities();a++) { Ability A=fetchAbility(a); if((A!=null)&&(A.ID().equals(to.ID()))) return; } abilities.addElement(to); } public void delAbility(Ability to) { abilities.removeElement(to); } public int numAbilities() { return abilities.size(); } public boolean hasAbilityEvoker(String word) { try { for(int a=0;a<abilities.size();a++) { Ability A=(Ability)abilities.elementAt(a); for(int s=0;s<A.triggerStrings().length;s++) { if(A.triggerStrings()[s].startsWith(word)) return true; } } } catch(java.lang.ArrayIndexOutOfBoundsException x){} return false; } public Ability fetchAbility(int index) { try { return (Ability)abilities.elementAt(index); } catch(java.lang.ArrayIndexOutOfBoundsException x){} return null; } public Ability fetchAbility(String ID) { for(int a=0;a<numAbilities();a++) { Ability A=fetchAbility(a); if((A!=null) &&((A.ID().equalsIgnoreCase(ID))||(A.Name().equalsIgnoreCase(ID)))) return A; } return (Ability)CoffeeUtensils.fetchEnvironmental(abilities,ID,false); } public void addNonUninvokableAffect(Ability to) { if(to==null) return; if(affects.contains(to)) return; to.makeNonUninvokable(); to.makeLongLasting(); affects.addElement(to); to.setAffectedOne(this); } public void addAffect(Ability to) { if(to==null) return; if(affects.contains(to)) return; affects.addElement(to); to.setAffectedOne(this); } public void delAffect(Ability to) { int size=affects.size(); affects.removeElement(to); if(affects.size()<size) to.setAffectedOne(null); } public int numAffects() { return affects.size(); } public Ability fetchAffect(int index) { try { return (Ability)affects.elementAt(index); } catch(java.lang.ArrayIndexOutOfBoundsException x){} return null; } public Ability fetchAffect(String ID) { for(int a=0;a<numAffects();a++) { Ability A=fetchAffect(a); if((A!=null)&&(A.ID().equals(ID))) return A; } return null; } /** Manipulation of Behavior objects, which includes * movement, speech, spellcasting, etc, etc.*/ public void addBehavior(Behavior to) { if(to==null) return; for(int b=0;b<numBehaviors();b++) { Behavior B=fetchBehavior(b); if((B!=null)&&(B.ID().equals(to.ID()))) return; } to.startBehavior(this); behaviors.addElement(to); } public void delBehavior(Behavior to) { behaviors.removeElement(to); } public int numBehaviors() { return behaviors.size(); } public Behavior fetchBehavior(int index) { try { return (Behavior)behaviors.elementAt(index); } catch(java.lang.ArrayIndexOutOfBoundsException x){} return null; } public Behavior fetchBehavior(String ID) { for(int b=0;b<numBehaviors();b++) { Behavior B=fetchBehavior(b); if((B!=null)&&(B.ID().equalsIgnoreCase(ID))) return B; } return null; } public boolean amWearingSomethingHere(long wornCode) { for(int i=0;i<inventorySize();i++) { Item thisItem=fetchInventory(i); if((thisItem!=null)&&(thisItem.amWearingAt(wornCode))) return true; } return false; } public Item fetchWornItem(long wornCode) { for(int i=0;i<inventorySize();i++) { Item thisItem=fetchInventory(i); if((thisItem!=null)&&(thisItem.amWearingAt(wornCode))) return thisItem; } return null; } public Item fetchWieldedItem() { for(int i=0;i<inventorySize();i++) { Item thisItem=fetchInventory(i); if((thisItem!=null)&&(thisItem.amWearingAt(Item.WIELD))) return thisItem; } return null; } public boolean isMine(Environmental env) { if(env instanceof Item) { if(inventory.contains(env)) return true; return false; } else if(env instanceof MOB) { if(followers.contains(env)) return true; return false; } else if(env instanceof Ability) { if(abilities.contains(env)) return true; if(affects.contains(env)) return true; return false; } return false; } public void giveItem(Item thisContainer) { // caller is responsible for recovering any env // stat changes! if(Sense.isHidden(thisContainer)) thisContainer.baseEnvStats().setDisposition(thisContainer.baseEnvStats().disposition()&((int)EnvStats.ALLMASK-EnvStats.IS_HIDDEN)); // ensure its out of its previous place Environmental owner=location(); if(thisContainer.owner()!=null) { owner=thisContainer.owner(); if(thisContainer.owner() instanceof Room) ((Room)thisContainer.owner()).delItem(thisContainer); else if(thisContainer.owner() instanceof MOB) ((MOB)thisContainer.owner()).delInventory(thisContainer); } location().delItem(thisContainer); thisContainer.unWear(); if(!isMine(thisContainer)) addInventory(thisContainer); thisContainer.recoverEnvStats(); boolean nothingDone=true; do { nothingDone=true; if(owner instanceof Room) { Room R=(Room)owner; for(int i=0;i<R.numItems();i++) { Item thisItem=R.fetchItem(i); if((thisItem!=null)&&(thisItem.container()==thisContainer)) { giveItem(thisItem); nothingDone=false; break; } } } else if(owner instanceof MOB) { MOB M=(MOB)owner; for(int i=0;i<M.inventorySize();i++) { Item thisItem=M.fetchInventory(i); if((thisItem!=null)&&(thisItem.container()==thisContainer)) { giveItem(thisItem); nothingDone=false; break; } } } }while(!nothingDone); } private void fightingFollowers(MOB target, MOB source) { if((source==null)||(target==null)) return; if(source==target) return; if((target==this)||(source==this)) return; if((target.location()!=location())||(target.location()!=source.location())) return; if((Util.bset(getBitmap(),MOB.ATT_AUTOASSIST))) return; if(isInCombat()) return; if((amFollowing()==target) ||(target.amFollowing()==this) ||((target.amFollowing()!=null)&&(target.amFollowing()==this.amFollowing()))) setVictim(source);//ExternalPlay.postAttack(this,source,fetchWieldedItem()); else if((amFollowing()==source) ||(source.amFollowing()==this) ||((source.amFollowing()!=null)&&(source.amFollowing()==this.amFollowing()))) setVictim(target);//ExternalPlay.postAttack(this,target,fetchWieldedItem()); } protected static String[] CODES={"CLASS","LEVEL","ABILITY","TEXT"}; public String getStat(String code){ switch(getCodeNum(code)) { case 0: return ID(); case 1: return ""+baseEnvStats().level(); case 2: return ""+baseEnvStats().ability(); case 3: return text(); } return ""; } public void setStat(String code, String val) { switch(getCodeNum(code)) { case 0: return; case 1: baseEnvStats().setLevel(Util.s_int(val)); break; case 2: baseEnvStats().setAbility(Util.s_int(val)); break; case 3: setMiscText(val); break; } } public String[] getStatCodes(){return CODES;} protected int getCodeNum(String code){ for(int i=0;i<CODES.length;i++) if(code.equalsIgnoreCase(CODES[i])) return i; return -1; } public boolean sameAs(Environmental E) { if(!(E instanceof StdMOB)) return false; for(int i=0;i<CODES.length;i++) if(!E.getStat(CODES[i]).equals(getStat(CODES[i]))) return false; return true; } }
com/planet_ink/coffee_mud/MOBS/StdMOB.java
package com.planet_ink.coffee_mud.MOBS; import java.util.*; import com.planet_ink.coffee_mud.utils.*; import com.planet_ink.coffee_mud.interfaces.*; import com.planet_ink.coffee_mud.common.*; public class StdMOB implements MOB { public String ID(){return "StdMOB";} protected String Username=""; private String clanID=null; private int clanRole=0; protected CharStats baseCharStats=new DefaultCharStats(); protected CharStats charStats=new DefaultCharStats(); protected EnvStats envStats=new DefaultEnvStats(); protected EnvStats baseEnvStats=new DefaultEnvStats(); protected PlayerStats playerStats=null; protected boolean amDead=false; protected Room location=null; protected Room lastLocation=null; protected Rideable riding=null; protected Session mySession=null; protected boolean pleaseDestroy=false; protected byte[] description=null; protected String displayText=""; protected byte[] miscText=null; protected long tickStatus=Tickable.STATUS_NOT; /* instantiated item types word, contained, owned*/ protected Vector inventory=new Vector(); /* instantiated creature types listed as followers*/ protected Vector followers=new Vector(); /* All Ability codes, including languages*/ protected Vector abilities=new Vector(); /* instantiated affects on this user*/ protected Vector affects=new Vector(); protected Vector behaviors=new Vector(); // gained attributes protected int Experience=0; protected int ExpNextLevel=1000; protected int Practices=0; protected int Trains=0; protected long AgeHours=0; protected int Money=0; protected int attributesBitmap=0; public long getAgeHours(){return AgeHours;} public int getPractices(){return Practices;} public int getExperience(){return Experience;} public int getExpNextLevel(){return ExpNextLevel;} public int getExpNeededLevel() { if(ExpNextLevel<=getExperience()) ExpNextLevel=getExperience()+1000; return ExpNextLevel-getExperience(); } public int getTrains(){return Trains;} public int getMoney(){return Money;} public int getBitmap(){return attributesBitmap;} public void setAgeHours(long newVal){ AgeHours=newVal;} public void setExperience(int newVal){ Experience=newVal; } public void setExpNextLevel(int newVal){ ExpNextLevel=newVal;} public void setPractices(int newVal){ Practices=newVal;} public void setTrains(int newVal){ Trains=newVal;} public void setMoney(int newVal){ Money=newVal;} public void setBitmap(int newVal) { attributesBitmap=newVal; if(mySession!=null) mySession.setTermID(((Util.bset(attributesBitmap,MOB.ATT_ANSI))?1:0)+((Util.bset(attributesBitmap,MOB.ATT_SOUND))?2:0)); } protected int minuteCounter=0; private int movesSinceTick=0; // the core state values public CharState curState=new DefaultCharState(); public CharState maxState=new DefaultCharState(); public CharState baseState=new DefaultCharState(); private long lastTickedDateTime=System.currentTimeMillis(); public long lastTickedDateTime(){return lastTickedDateTime;} // mental characteristics protected int Alignment=0; protected String WorshipCharID=""; protected String LeigeID=""; protected int WimpHitPoint=0; protected int QuestPoint=0; protected int DeityIndex=-1; public String getLeigeID(){return LeigeID;} public String getWorshipCharID(){return WorshipCharID;} public int getAlignment(){return Alignment;} public int getWimpHitPoint(){return WimpHitPoint;} public int getQuestPoint(){return QuestPoint;} public void setLeigeID(String newVal){LeigeID=newVal;} public void setAlignment(int newVal) { if(newVal<0) newVal=0; if(newVal>1000) newVal=1000; Alignment=newVal; } public void setWorshipCharID(String newVal){ WorshipCharID=newVal;} public void setWimpHitPoint(int newVal){ WimpHitPoint=newVal;} public void setQuestPoint(int newVal){ QuestPoint=newVal;} public Deity getMyDeity() { if(getWorshipCharID().length()==0) return null; Deity bob=CMMap.getDeity(getWorshipCharID()); if(bob==null) setWorshipCharID(""); return bob; } // location! protected Room StartRoom=null; public Room getStartRoom(){return StartRoom;} public void setStartRoom(Room newVal){StartRoom=newVal;} protected MOB victim=null; protected MOB amFollowing=null; protected MOB soulMate=null; private double speeder=0.0; protected int atRange=-1; private long peaceTime=0; public long peaceTime(){return peaceTime;} public String Name() { return Username; } public void setName(String newName){Username=newName;} public String name() { if(envStats().newName()!=null) return envStats().newName(); return Username; } public Environmental newInstance() { return new StdMOB(); } public StdMOB(){} protected void cloneFix(MOB E) { affects=new Vector(); baseEnvStats=E.baseEnvStats().cloneStats(); envStats=E.envStats().cloneStats(); baseCharStats=E.baseCharStats().cloneCharStats(); charStats=E.charStats().cloneCharStats(); baseState=E.baseState().cloneCharState(); curState=E.curState().cloneCharState(); maxState=E.maxState().cloneCharState(); pleaseDestroy=false; inventory=new Vector(); followers=new Vector(); abilities=new Vector(); affects=new Vector(); behaviors=new Vector(); for(int i=0;i<E.inventorySize();i++) { Item I2=E.fetchInventory(i); if(I2!=null) { Item I=(Item)I2.copyOf(); I.setOwner(this); inventory.addElement(I); } } for(int i=0;i<inventorySize();i++) { Item I2=fetchInventory(i); if((I2!=null) &&(I2.container()!=null) &&(!isMine(I2.container()))) for(int ii=0;ii<E.inventorySize();ii++) if((E.fetchInventory(ii)==I2.container())&&(ii<inventorySize())) { I2.setContainer(fetchInventory(ii)); break;} } for(int i=0;i<E.numAbilities();i++) { Ability A2=E.fetchAbility(i); if(A2!=null) abilities.addElement(A2.copyOf()); } for(int i=0;i<E.numAffects();i++) { Ability A=(Ability)E.fetchAffect(i); if((A!=null)&&(!A.canBeUninvoked())) addAffect((Ability)A.copyOf()); } for(int i=0;i<E.numBehaviors();i++) { Behavior B=E.fetchBehavior(i); if(B!=null) behaviors.addElement((Behavior)B.copyOf()); } } public Environmental copyOf() { try { StdMOB E=(StdMOB)this.clone(); E.cloneFix(this); return E; } catch(CloneNotSupportedException e) { return this.newInstance(); } } public boolean isGeneric(){return false;} public EnvStats envStats() { return envStats; } public EnvStats baseEnvStats() { return baseEnvStats; } public void recoverEnvStats() { envStats=baseEnvStats.cloneStats(); if(location()!=null) location().affectEnvStats(this,envStats); envStats().setWeight(envStats().weight()+(int)Math.round(Util.div(getMoney(),100.0))); if(riding()!=null) riding().affectEnvStats(this,envStats); if(getMyDeity()!=null) getMyDeity().affectEnvStats(this,envStats); if(charStats!=null) { charStats().getCurrentClass().affectEnvStats(this,envStats); charStats().getMyRace().affectEnvStats(this,envStats); } for(int i=0;i<inventorySize();i++) { Item item=fetchInventory(i); if(item!=null) { item.recoverEnvStats(); item.affectEnvStats(this,envStats); } } for(int a=0;a<numAffects();a++) { Ability affect=fetchAffect(a); if(affect!=null) affect.affectEnvStats(this,envStats); } /* the follower light exception*/ if(!Sense.isLightSource(this)) for(int f=0;f<numFollowers();f++) if(Sense.isLightSource(fetchFollower(f))) envStats.setDisposition(envStats().disposition()|EnvStats.IS_LIGHTSOURCE); } public void setBaseEnvStats(EnvStats newBaseEnvStats) { baseEnvStats=newBaseEnvStats.cloneStats(); } public int maxCarry() { double str=new Integer(charStats().getStat(CharStats.STRENGTH)).doubleValue(); double bodyWeight=0.0; if(charStats().getMyRace()==baseCharStats().getMyRace()) bodyWeight=new Integer(baseEnvStats().weight()).doubleValue(); else bodyWeight=new Integer(charStats().getMyRace().getMaxWeight()).doubleValue(); return (int)Math.round(bodyWeight + ((str+10.0)*str*bodyWeight/150.0) + (str*5.0)); } public int maxFollowers() { return ((int)Math.round(Util.div(charStats().getStat(CharStats.CHARISMA),4.0))+1); } public CharStats baseCharStats(){return baseCharStats;} public CharStats charStats(){return charStats;} public void recoverCharStats() { baseCharStats.setClassLevel(baseCharStats.getCurrentClass(),baseEnvStats().level()-baseCharStats().combinedSubLevels()); charStats=baseCharStats().cloneCharStats(); if(riding()!=null) riding().affectCharStats(this,charStats); if(getMyDeity()!=null) getMyDeity().affectCharStats(this,charStats); for(int a=0;a<numAffects();a++) { Ability affect=fetchAffect(a); if(affect!=null) affect.affectCharStats(this,charStats); } for(int i=0;i<inventorySize();i++) { Item item=fetchInventory(i); if(item!=null) item.affectCharStats(this,charStats); } if(location()!=null) location().affectCharStats(this,charStats); charStats.getCurrentClass().affectCharStats(this,charStats); charStats.getMyRace().affectCharStats(this,charStats); } public void setBaseCharStats(CharStats newBaseCharStats) { baseCharStats=newBaseCharStats.cloneCharStats(); } public void affectEnvStats(Environmental affected, EnvStats affectableStats) { if((Sense.isLightSource(this))&&(affected instanceof Room)) { if(Sense.isInDark(affected)) affectableStats.setDisposition(affectableStats.disposition()-EnvStats.IS_DARK); affectableStats.setDisposition(affectableStats.disposition()|EnvStats.IS_LIGHTSOURCE); } } public void affectCharState(MOB affectedMob, CharState affectableMaxState) {} public CharState curState(){return curState;} public CharState maxState(){return maxState;} public CharState baseState(){return baseState;} public PlayerStats playerStats() { if((playerStats==null)&&(soulMate!=null)) return soulMate.playerStats(); return playerStats; } public void setPlayerStats(PlayerStats newStats){playerStats=newStats;} public void setBaseState(CharState newState) { baseState=newState.cloneCharState(); maxState=newState.cloneCharState(); } public void resetToMaxState() { recoverMaxState(); curState=maxState.cloneCharState(); } public void recoverMaxState() { maxState=baseState.cloneCharState(); if(charStats.getMyRace()!=null) charStats.getMyRace().affectCharState(this,maxState); if(riding()!=null) riding().affectCharState(this,maxState); for(int a=0;a<numAffects();a++) { Ability affect=fetchAffect(a); if(affect!=null) affect.affectCharState(this,maxState); } for(int i=0;i<inventorySize();i++) { Item item=fetchInventory(i); if(item!=null) item.affectCharState(this,maxState); } if(location()!=null) location().affectCharState(this,maxState); } public boolean amDead() { return amDead||pleaseDestroy; } public void destroy() { removeFromGame(); while(numBehaviors()>0) delBehavior(fetchBehavior(0)); while(numAffects()>0) delAffect(fetchAffect(0)); while(numAbilities()>0) delAbility(fetchAbility(0)); while(inventorySize()>0) { Item I=fetchInventory(0); I.destroy(); delInventory(I); } } public void removeFromGame() { pleaseDestroy=true; if(location!=null) { location().delInhabitant(this); if(mySession!=null) location().show(this,null,Affect.MSG_OK_ACTION,"<S-NAME> vanish(es) in a puff of smoke."); } setFollowing(null); Vector oldFollowers=new Vector(); while(numFollowers()>0) { MOB follower=fetchFollower(0); if(follower!=null) { if(follower.isMonster()) oldFollowers.addElement(follower); follower.setFollowing(null); delFollower(follower); } } if(!isMonster()) { for(int f=0;f<oldFollowers.size();f++) { MOB follower=(MOB)oldFollowers.elementAt(f); if(follower.location()!=null) { MOB newFol=(MOB)follower.copyOf(); newFol.baseEnvStats().setRejuv(0); newFol.text(); follower.killMeDead(false); addFollower(newFol); } } session().setKillFlag(true); } } public String getClanID(){return ((clanID==null)?"":clanID);} public void setClanID(String clan){clanID=clan;} public int getClanRole(){return clanRole;} public void setClanRole(int role){clanRole=role;} public void bringToLife(Room newLocation, boolean resetStats) { amDead=false; if((miscText!=null)&&(resetStats)) { if(CommonStrings.getBoolVar(CommonStrings.SYSTEMB_MOBCOMPRESS)) setMiscText(Util.decompressString(miscText)); else setMiscText(new String(miscText)); } if(getStartRoom()==null) setStartRoom(isMonster()?newLocation:CMMap.getStartRoom(this)); setLocation(newLocation); if(location()==null) { setLocation(getStartRoom()); if(location()==null) { Log.errOut("StdMOB",Username+" cannot get a location."); return; } } if(!location().isInhabitant(this)) location().addInhabitant(this); pleaseDestroy=false; // will ensure no duplicate ticks, this obj, this id ExternalPlay.startTickDown(this,Host.MOB_TICK,1); tick(this,Host.MOB_TICK); // slap on the butt for(int a=0;a<numAbilities();a++) { Ability A=fetchAbility(a); if(A!=null) A.autoInvocation(this); } location().recoverRoomStats(); if((!isGeneric())&&(resetStats)) resetToMaxState(); if(Sense.isSleeping(this)) tell("(You are asleep)"); else ExternalPlay.look(this,null,true); } public boolean isInCombat() { if(victim==null) return false; if((victim.location()==null) ||(location()==null) ||(victim.location()!=location()) ||(victim.amDead())) { if((victim instanceof StdMOB) &&(((StdMOB)victim).victim==this)) victim.setVictim(null); setVictim(null); return false; } return true; } public boolean mayIFight(MOB mob) { if(mob==null) return false; if(location()==null) return false; if(mob.location()==null) return false; if(mob.amDead()) return false; if(mob.curState().getHitPoints()<=0) return false; if(amDead()) return false; if(curState().getHitPoints()<=0) return false; if(mob.isMonster()) return true; if(isMonster()){ MOB fol=amFollowing(); if((fol!=null)&&(!fol.isMonster())) return fol.mayIFight(mob); return true; } if(mob==this) return true; if(CommonStrings.getVar(CommonStrings.SYSTEM_PKILL).startsWith("ALWAYS")) return true; if(CommonStrings.getVar(CommonStrings.SYSTEM_PKILL).startsWith("NEVER")) return false; if(!Util.bset(getBitmap(),MOB.ATT_PLAYERKILL)) return false; if(!Util.bset(mob.getBitmap(),MOB.ATT_PLAYERKILL)) return false; return true; } public boolean mayPhysicallyAttack(MOB mob) { if((!mayIFight(mob)) ||(location()!=mob.location()) ||(!location().isInhabitant(this)) ||(!mob.location().isInhabitant(mob))) return false; return true; } public int adjustedAttackBonus() { double att=new Integer( envStats().attackAdjustment() +((charStats().getStat(CharStats.STRENGTH)-9)*3)).doubleValue(); if(curState().getHunger()<1) att=att*.9; if(curState().getThirst()<1) att=att*.9; if(curState().getFatigue()>CharState.FATIGUED_MILLIS) att=att*.8; return (int)Math.round(att); } public int adjustedArmor() { double arm=new Integer(((charStats().getStat(CharStats.DEXTERITY)-9)*3) +50).doubleValue(); if((envStats().disposition()&EnvStats.IS_SLEEPING)>0) arm=0.0; if(arm>0.0) { if(curState().getHunger()<1) arm=arm*.85; if(curState().getThirst()<1) arm=arm*.85; if(curState().getFatigue()>CharState.FATIGUED_MILLIS) arm=arm*.85; if((envStats().disposition()&EnvStats.IS_SITTING)>0) arm=arm*.75; } return (int)Math.round(envStats().armor()-arm); } public int adjustedDamage(Weapon weapon, MOB target) { double damageAmount=0.0; if(target!=null) { if((weapon!=null)&&((weapon.weaponClassification()==Weapon.CLASS_RANGED)||(weapon.weaponClassification()==Weapon.CLASS_THROWN))) damageAmount = new Integer(Dice.roll(1, weapon.envStats().damage(),1)).doubleValue(); else damageAmount = new Integer(Dice.roll(1, envStats().damage(), (charStats().getStat(CharStats.STRENGTH) / 3)-2)).doubleValue(); if(!Sense.canBeSeenBy(target,this)) damageAmount *=.5; if(Sense.isSleeping(target)) damageAmount *=1.5; else if(Sense.isSitting(target)) damageAmount *=1.2; } else if((weapon!=null)&&((weapon.weaponClassification()==Weapon.CLASS_RANGED)||(weapon.weaponClassification()==Weapon.CLASS_THROWN))) damageAmount = new Integer(weapon.envStats().damage()+1).doubleValue(); else damageAmount = new Integer(envStats().damage()+(charStats().getStat(CharStats.STRENGTH) / 3)-2).doubleValue(); if(curState().getHunger() < 1) damageAmount *= .8; if(curState().getFatigue()>CharState.FATIGUED_MILLIS) damageAmount *=.8; if(curState().getThirst() < 1) damageAmount *= .9; if(damageAmount<1.0) damageAmount=1.0; return (int)Math.round(damageAmount); } public void setAtRange(int newRange){atRange=newRange;} public int rangeToTarget(){return atRange;} public int maxRange(){return maxRange(null);} public int minRange(){return maxRange(null);} public int maxRange(Environmental tool) { int max=0; if(tool!=null) max=tool.maxRange(); if((location()!=null)&&(location().maxRange()<max)) max=location().maxRange(); return max; } public int minRange(Environmental tool) { if(tool!=null) return tool.minRange(); return 0; } public void makePeace() { MOB myVictim=victim; setVictim(null); if(myVictim!=null) { MOB oldVictim=myVictim.getVictim(); if(oldVictim==this) myVictim.makePeace(); } } public MOB getVictim() { if(!isInCombat()) return null; return victim; } public void setVictim(MOB mob) { if(mob==null) setAtRange(-1); if(victim==mob) return; if(mob==this) return; victim=mob; recoverEnvStats(); recoverCharStats(); recoverMaxState(); if(mob!=null) { if((mob.location()==null) ||(location()==null) ||(mob.amDead()) ||(amDead()) ||(mob.location()!=location()) ||(!location().isInhabitant(this)) ||(!location().isInhabitant(mob))) { if(victim!=null) victim.setVictim(null); victim=null; } else { mob.recoverCharStats(); mob.recoverEnvStats(); mob.recoverMaxState(); } } } public DeadBody killMeDead(boolean createBody) { Room deathRoom=null; if(isMonster()) deathRoom=location(); else deathRoom=CMMap.getBodyRoom(this); if(location()!=null) location().delInhabitant(this); DeadBody Body=null; if(createBody) Body=charStats().getMyRace().getCorpse(this,deathRoom); amDead=true; makePeace(); setRiding(null); for(int a=numAffects()-1;a>=0;a--) { Ability A=fetchAffect(a); if(A!=null) A.unInvoke(); } setLocation(null); while(numFollowers()>0) { MOB follower=fetchFollower(0); if(follower!=null) { follower.setFollowing(null); delFollower(follower); } } setFollowing(null); if((!isMonster())&&(soulMate()==null)) bringToLife(CMMap.getDeathRoom(this),true); if(Body!=null) Body.startTicker(deathRoom); deathRoom.recoverRoomStats(); return Body; } public Room location() { if(location==null) return lastLocation; return location; } public void setLocation(Room newRoom) { lastLocation=location; location=newRoom; } public Rideable riding(){return riding;} public void setRiding(Rideable ride) { if((ride!=null)&&(riding()!=null)&&(riding()==ride)&&(riding().amRiding(this))) return; if((riding()!=null)&&(riding().amRiding(this))) riding().delRider(this); riding=ride; if((riding()!=null)&&(!riding().amRiding(this))) riding().addRider(this); } public Session session() { return mySession; } public void setSession(Session newSession) { mySession=newSession; setBitmap(getBitmap()); } public Weapon myNaturalWeapon() { if((charStats()!=null)&&(charStats().getMyRace()!=null)) return charStats().getMyRace().myNaturalWeapon(); return (Weapon)CMClass.getWeapon("Natural"); } public String displayText(MOB viewer) { if((displayText.length()==0) ||(!name().equals(name())) ||(Sense.isSleeping(this)) ||(Sense.isSitting(this)) ||(riding()!=null) ||((this instanceof Rideable)&&(((Rideable)this).numRiders()>0)) ||(isInCombat())) { StringBuffer sendBack=null; sendBack=new StringBuffer(name()); sendBack.append(" "); sendBack.append(Sense.dispositionString(this,Sense.flag_is)); sendBack.append(" here"); if(riding()!=null) { sendBack.append(" "+riding().stateString(this)+" "); if(riding()==viewer) sendBack.append("YOU"); else sendBack.append(riding().name()); } else if((this instanceof Rideable) &&(((Rideable)this).numRiders()>0) &&(((Rideable)this).stateStringSubject(((Rideable)this).fetchRider(0)).length()>0)) { Rideable me=(Rideable)this; String first=me.stateStringSubject(me.fetchRider(0)); sendBack.append(" "+first+" "); for(int r=0;r<me.numRiders();r++) { Rider rider=me.fetchRider(r); if((rider!=null)&&(me.stateStringSubject(rider).equals(first))) { if(r>0) { sendBack.append(", "); if(r==me.numRiders()-1) sendBack.append("and "); } if(rider==viewer) sendBack.append("you"); else sendBack.append(rider.name()); } } } if((isInCombat())&&(Sense.canMove(this))&&(!Sense.isSleeping(this))) { sendBack.append(" fighting "); if(getVictim()==viewer) sendBack.append("YOU"); else sendBack.append(getVictim().name()); } sendBack.append("."); return sendBack.toString(); } else return displayText; } public String displayText() { return displayText; } public void setDisplayText(String newDisplayText) { displayText=newDisplayText; } public String description() { if((description==null)||(description.length==0)) return ""; else if(CommonStrings.getBoolVar(CommonStrings.SYSTEMB_MOBDCOMPRESS)) return Util.decompressString(description); else return new String(description); } public void setDescription(String newDescription) { if(newDescription.length()==0) description=null; else if(CommonStrings.getBoolVar(CommonStrings.SYSTEMB_MOBDCOMPRESS)) description=Util.compressString(newDescription); else description=newDescription.getBytes(); } public void setMiscText(String newText) { if(newText.length()==0) miscText=null; else if(CommonStrings.getBoolVar(CommonStrings.SYSTEMB_MOBCOMPRESS)) miscText=Util.compressString(newText); else miscText=newText.getBytes(); } public String text() { if((miscText==null)||(miscText.length==0)) return ""; else if(CommonStrings.getBoolVar(CommonStrings.SYSTEMB_MOBCOMPRESS)) return Util.decompressString(miscText); else return new String(miscText); } public String healthText() { if((charStats()!=null)&&(charStats().getMyRace()!=null)) return charStats().getMyRace().healthText(this); return CommonStrings.standardMobCondition(this); } public void establishRange(MOB source, MOB target, Environmental tool) { // establish and enforce range if((source.rangeToTarget()<0)) { if(source.riding()!=null) { if((target==riding())||(source.riding().amRiding(target))) source.setAtRange(0); else if((source.riding() instanceof MOB) &&(((MOB)source.riding()).isInCombat()) &&(((MOB)source.riding()).getVictim()==target) &&(((MOB)source.riding()).rangeToTarget()>=0) &&(((MOB)source.riding()).rangeToTarget()<rangeToTarget())) { source.setAtRange(((MOB)source.riding()).rangeToTarget()); recoverEnvStats(); return; } else for(int r=0;r<source.riding().numRiders();r++) { Rider rider=source.riding().fetchRider(r); if(!(rider instanceof MOB)) continue; MOB otherMOB=(MOB)rider; if((otherMOB!=null) &&(otherMOB!=this) &&(otherMOB.isInCombat()) &&(otherMOB.getVictim()==target) &&(otherMOB.rangeToTarget()>=0) &&(otherMOB.rangeToTarget()<rangeToTarget())) { source.setAtRange(otherMOB.rangeToTarget()); source.recoverEnvStats(); return; } } } if(target.getVictim()==source) { if(target.rangeToTarget()>=0) source.setAtRange(target.rangeToTarget()); else source.setAtRange(maxRange(tool)); } else source.setAtRange(maxRange(tool)); recoverEnvStats(); } } public boolean okAffect(Environmental myHost, Affect affect) { if((getMyDeity()!=null)&&(!getMyDeity().okAffect(this,affect))) return false; if(charStats!=null) { if(!charStats().getCurrentClass().okAffect(this,affect)) return false; if(!charStats().getMyRace().okAffect(this, affect)) return false; } for(int i=0;i<numAffects();i++) { Ability aff=(Ability)fetchAffect(i); if((aff!=null)&&(!aff.okAffect(this,affect))) return false; } for(int i=0;i<inventorySize();i++) { Item I=(Item)fetchInventory(i); if((I!=null)&&(!I.okAffect(this,affect))) return false; } for(int b=0;b<numBehaviors();b++) { Behavior B=fetchBehavior(b); if((B!=null)&&(!B.okAffect(this,affect))) return false; } MOB mob=affect.source(); if((affect.sourceCode()!=Affect.NO_EFFECT) &&(affect.amISource(this)) &&(!Util.bset(affect.sourceMajor(),Affect.MASK_GENERAL))) { int srcMajor=affect.sourceMajor(); if(amDead()) { tell("You are DEAD!"); return false; } if(Util.bset(affect.sourceCode(),Affect.MASK_MALICIOUS)) { if((affect.target()!=this)&&(affect.target()!=null)&&(affect.target() instanceof MOB)) { MOB target=(MOB)affect.target(); if((amFollowing()!=null)&&(target==amFollowing())) { tell("You like "+amFollowing().charStats().himher()+" too much."); return false; } if((getLeigeID().length()>0)&&(target.Name().equals(getLeigeID()))) { tell("You are serving '"+getLeigeID()+"'!"); return false; } establishRange(this,(MOB)affect.target(),affect.tool()); } } if(Util.bset(srcMajor,Affect.MASK_EYES)) { if(Sense.isSleeping(this)) { tell("Not while you are sleeping."); return false; } if(!(affect.target() instanceof Room)) if(!Sense.canBeSeenBy(affect.target(),this)) { if(affect.target() instanceof Item) tell("You don't see "+affect.target()+" here."); else tell("You can't see that!"); return false; } } if(Util.bset(srcMajor,Affect.MASK_MOUTH)) { if(!Sense.aliveAwakeMobile(this,false)) return false; if(Util.bset(srcMajor,Affect.MASK_SOUND)) { if((affect.tool()==null) ||(!(affect.tool() instanceof Ability)) ||(!((Ability)affect.tool()).isNowAnAutoEffect())) { if(Sense.isSleeping(this)) { tell("Not while you are sleeping."); return false; } if(!Sense.canSpeak(this)) { tell("You can't make sounds!"); return false; } if(Sense.isAnimalIntelligence(this)) { tell("You aren't smart enough to speak."); return false; } } } else { if((!Sense.canBeSeenBy(affect.target(),this)) &&(!(isMine(affect.target())&&(affect.target() instanceof Item)))) { mob.tell("You don't see '"+affect.target().name()+"' here."); return false; } if(!Sense.canTaste(this)) { tell("You can't eat or drink!"); return false; } } } if(Util.bset(srcMajor,Affect.MASK_HANDS)) { if((!Sense.canBeSeenBy(affect.target(),this)) &&(!(isMine(affect.target())&&(affect.target() instanceof Item))) &&(!(isInCombat()&&(affect.target()==victim)))) { mob.tell("You don't see '"+affect.target().name()+"' here."); return false; } if(!Sense.aliveAwakeMobile(this,false)) return false; if((Sense.isSitting(this)) &&(affect.sourceMinor()!=Affect.TYP_SITMOVE) &&(affect.targetCode()!=Affect.MSG_OK_VISUAL) &&((affect.sourceMessage()!=null)||(affect.othersMessage()!=null)) &&((!CoffeeUtensils.reachableItem(this,affect.target())) ||(!CoffeeUtensils.reachableItem(this,affect.tool())))) { tell("You need to stand up!"); return false; } } if(Util.bset(srcMajor,Affect.MASK_MOVE)) { boolean sitting=Sense.isSitting(this); if((sitting) &&((affect.sourceMinor()==Affect.TYP_LEAVE) ||(affect.sourceMinor()==Affect.TYP_ENTER))) sitting=false; if(((Sense.isSleeping(this))||(sitting)) &&(affect.sourceMinor()!=Affect.TYP_STAND) &&(affect.sourceMinor()!=Affect.TYP_SITMOVE) &&(affect.sourceMinor()!=Affect.TYP_SLEEP)) { tell("You need to stand up!"); return false; } if(!Sense.canMove(this)) { tell("You can't move!"); return false; } } switch(affect.sourceMinor()) { case Affect.TYP_ENTER: movesSinceTick++; break; case Affect.TYP_JUSTICE: if((affect.target()!=null) &&(isInCombat()) &&(affect.target() instanceof Item)) { tell("Not while you are fighting!"); return false; } break; case Affect.TYP_OPEN: case Affect.TYP_CLOSE: if(isInCombat()) { if((affect.target()!=null) &&((affect.target() instanceof Exit)||(affect.source().isMine(affect.target())))) break; tell("Not while you are fighting!"); return false; } break; case Affect.TYP_BUY: case Affect.TYP_DELICATE_HANDS_ACT: case Affect.TYP_LEAVE: case Affect.TYP_FILL: case Affect.TYP_LIST: case Affect.TYP_LOCK: case Affect.TYP_SIT: case Affect.TYP_SLEEP: case Affect.TYP_UNLOCK: case Affect.TYP_VALUE: case Affect.TYP_SELL: case Affect.TYP_VIEW: case Affect.TYP_READSOMETHING: if(isInCombat()) { tell("Not while you are fighting!"); return false; } break; case Affect.TYP_REBUKE: if((affect.target()==null)||(!(affect.target() instanceof Deity))) { if(affect.target()!=null) { if(!Sense.canBeHeardBy(this,affect.target())) { tell(affect.target().name()+" can't hear you!"); return false; } else if((!((affect.target() instanceof MOB) &&(((MOB)affect.target()).getLeigeID().equals(Name())))) &&(!affect.target().Name().equals(getLeigeID()))) { tell(affect.target().name()+" does not serve you, and you do not serve "+affect.target().name()+"."); return false; } } else if(getLeigeID().length()==0) { tell("You aren't serving anyone!"); return false; } } else if(getWorshipCharID().length()==0) { tell("You aren't worshipping anyone!"); return false; } break; case Affect.TYP_SERVE: if(affect.target()==null) return false; if(affect.target()==this) { tell("You can't serve yourself!"); return false; } if(affect.target() instanceof Deity) break; if(!Sense.canBeHeardBy(this,affect.target())) { tell(affect.target().name()+" can't hear you!"); return false; } if(getLeigeID().length()>0) { tell("You are already serving '"+getLeigeID()+"'."); return false; } break; case Affect.TYP_CAST_SPELL: if(charStats().getStat(CharStats.INTELLIGENCE)<5) { tell("You aren't smart enough to do magic."); return false; } break; default: break; } } if((affect.sourceCode()!=Affect.NO_EFFECT) &&(affect.amISource(this)) &&(affect.target()!=null) &&(affect.target()!=this) &&(!Util.bset(affect.sourceCode(),Affect.MASK_GENERAL)) &&(affect.target() instanceof MOB) &&(location()==((MOB)affect.target()).location())) { MOB target=(MOB)affect.target(); // and now, the consequences of range if((location()!=null) &&(affect.targetMinor()==Affect.TYP_WEAPONATTACK) &&(rangeToTarget()>maxRange(affect.tool()))) { String newstr="<S-NAME> advance(s) at "; affect.modify(this,target,null,Affect.MSG_ADVANCE,newstr+target.name(),Affect.MSG_ADVANCE,newstr+"you",Affect.MSG_ADVANCE,newstr+target.name()); boolean ok=location().okAffect(this,affect); if(ok) setAtRange(rangeToTarget()-1); if(victim!=null) { victim.setAtRange(rangeToTarget()); victim.recoverEnvStats(); } recoverEnvStats(); return ok; } else if(affect.targetMinor()==Affect.TYP_RETREAT) { if(curState().getMovement()<25) { tell("You are too tired."); return false; } if((location()!=null) &&(rangeToTarget()>=location().maxRange())) { tell("You cannot retreat any further."); return false; } curState().adjMovement(-25,maxState()); setAtRange(rangeToTarget()+1); if(victim!=null) { victim.setAtRange(rangeToTarget()); victim.recoverEnvStats(); } recoverEnvStats(); } else if(affect.tool()!=null) { int useRange=rangeToTarget(); Environmental tool=affect.tool(); if(getVictim()!=null) { if(getVictim()==target) useRange=rangeToTarget(); else { if(target.getVictim()==this) useRange=target.rangeToTarget(); else useRange=maxRange(tool); } } if((useRange>=0)&&(maxRange(tool)<useRange)) { mob.tell("You are too far away from "+target.name()+" to use "+tool.name()+"."); return false; } else if((useRange>=0)&&(minRange(tool)>useRange)) { mob.tell("You are too close to "+target.name()+" to use "+tool.name()+"."); if((affect.targetMinor()==Affect.TYP_WEAPONATTACK) &&(tool instanceof Weapon) &&(!((Weapon)tool).amWearingAt(Item.INVENTORY))) ExternalPlay.remove(this,(Item)tool,false); return false; } } } if((affect.targetCode()!=Affect.NO_EFFECT)&&(affect.amITarget(this))) { if((amDead())||(location()==null)) return false; if(Util.bset(affect.targetCode(),Affect.MASK_MALICIOUS)) { if((affect.amISource(this)) &&(!Util.bset(affect.sourceMajor(),Affect.MASK_GENERAL)) &&((affect.tool()==null)||(!(affect.tool() instanceof Ability))||(!((Ability)affect.tool()).isNowAnAutoEffect()))) { mob.tell("You like yourself too much."); if(victim==this) victim=null; return false; } if(!mayIFight(mob)) { mob.tell("You are not allowed to attack "+name()+"."); mob.setVictim(null); if(victim==mob) setVictim(null); return false; } if((!isMonster()) &&(!mob.isMonster()) &&(mob.envStats().level()>envStats().level()+CommonStrings.getPKillLevelDiff())) { mob.tell("That is not EVEN a fair fight."); mob.setVictim(null); if(victim==mob) setVictim(null); return false; } if(this.amFollowing()==mob) setFollowing(null); if(isInCombat()) { if((rangeToTarget()>0) &&(getVictim()!=affect.source()) &&(affect.source().getVictim()==this) &&(affect.source().rangeToTarget()==0)) { setVictim(affect.source()); setAtRange(0); } } if(affect.targetMinor()!=Affect.TYP_WEAPONATTACK) { int chanceToFail=Integer.MIN_VALUE; int saveCode=-1; for(int c=0;c<CharStats.affectTypeMap.length;c++) if(affect.targetMinor()==CharStats.affectTypeMap[c]) { saveCode=c; chanceToFail=charStats().getSave(c); break;} if((chanceToFail>Integer.MIN_VALUE)&&(!affect.wasModified())) { chanceToFail+=(envStats().level()-affect.source().envStats().level()); if(chanceToFail<5) chanceToFail=5; else if(chanceToFail>95) chanceToFail=95; if(Dice.rollPercentage()<chanceToFail) { CommonStrings.resistanceMsgs(affect,affect.source(),this); affect.tagModified(true); } } } } if((rangeToTarget()>0)&&(!isInCombat())) setAtRange(-1); switch(affect.targetMinor()) { case Affect.TYP_CLOSE: case Affect.TYP_DRINK: case Affect.TYP_DROP: case Affect.TYP_THROW: case Affect.TYP_EAT: case Affect.TYP_FILL: case Affect.TYP_GET: case Affect.TYP_HOLD: case Affect.TYP_REMOVE: case Affect.TYP_LOCK: case Affect.TYP_OPEN: case Affect.TYP_PULL: case Affect.TYP_PUT: case Affect.TYP_UNLOCK: case Affect.TYP_WEAR: case Affect.TYP_WIELD: case Affect.TYP_MOUNT: case Affect.TYP_DISMOUNT: mob.tell("You can't do that to "+name()+"."); return false; case Affect.TYP_GIVE: if(affect.tool()==null) return false; if(!(affect.tool() instanceof Item)) return false; if(!Sense.canBeSeenBy(affect.tool(),this)) { mob.tell(name()+" can't see what you are giving."); return false; } FullMsg msg=new FullMsg(affect.source(),affect.tool(),null,Affect.MSG_DROP,null); if(!location().okAffect(affect.source(),msg)) return false; if((affect.target()!=null)&&(affect.target() instanceof MOB)) { msg=new FullMsg((MOB)affect.target(),affect.tool(),null,Affect.MSG_GET,null); if(!location().okAffect(affect.target(),msg)) { mob.tell(affect.target().name()+" cannot seem to accept "+affect.tool().name()+"."); return false; } } break; case Affect.TYP_FOLLOW: if(numFollowers()>=maxFollowers()) { mob.tell(name()+" can't accept any more followers."); return false; } break; } } return true; } public void tell(MOB source, Environmental target, Environmental tool, String msg) { if(mySession!=null) mySession.stdPrintln(source,target,tool,msg); } public void tell(String msg) { tell(this,this,null,msg); } public void affect(Environmental myHost, Affect affect) { if(getMyDeity()!=null) getMyDeity().affect(this,affect); if(charStats!=null) { charStats().getCurrentClass().affect(this,affect); charStats().getMyRace().affect(this,affect); } for(int b=0;b<numBehaviors();b++) { Behavior B=fetchBehavior(b); if(B!=null) B.affect(this,affect); } MOB mob=affect.source(); boolean asleep=Sense.isSleeping(this); boolean canseesrc=Sense.canBeSeenBy(affect.source(),this); boolean canhearsrc=Sense.canBeHeardBy(affect.source(),this); if((affect.sourceCode()!=Affect.NO_EFFECT)&&(affect.amISource(this))) { if(Util.bset(affect.sourceCode(),Affect.MASK_MALICIOUS)) if((affect.target() instanceof MOB)&&(getVictim()!=affect.target())) { establishRange(this,(MOB)affect.target(),affect.tool()); setVictim((MOB)affect.target()); } switch(affect.sourceMinor()) { case Affect.TYP_PANIC: ExternalPlay.flee(mob,""); break; case Affect.TYP_DEATH: if((affect.tool()!=null)&&(affect.tool() instanceof MOB)) ExternalPlay.justDie((MOB)affect.tool(),this); else ExternalPlay.justDie(null,this); tell(this,affect.target(),affect.tool(),affect.sourceMessage()); break; case Affect.TYP_REBUKE: if(((affect.target()==null)&&(getLeigeID().length()>0)) ||((affect.target()!=null)&&(affect.target().Name().equals(getLeigeID())))) setLeigeID(""); tell(this,affect.target(),affect.tool(),affect.sourceMessage()); break; case Affect.TYP_SERVE: if((affect.target()!=null)&&(!(affect.target() instanceof Deity))) setLeigeID(affect.target().Name()); tell(this,affect.target(),affect.tool(),affect.sourceMessage()); break; case Affect.TYP_EXAMINESOMETHING: if((Sense.canBeSeenBy(this,mob))&&(affect.amITarget(this))) { StringBuffer myDescription=new StringBuffer(""); if(Util.bset(mob.getBitmap(),MOB.ATT_SYSOPMSGS)) myDescription.append(ID()+"\n\rRejuv:"+baseEnvStats().rejuv()+"\n\rAbile:"+baseEnvStats().ability()+"\n\rLevel:"+baseEnvStats().level()+"\n\rMisc : "+text()+"\n\r"+description()+"\n\rRoom :'"+((getStartRoom()==null)?"null":getStartRoom().roomID())+"\n\r"); if(!isMonster()) { String levelStr=charStats().displayClassLevel(this,false); myDescription.append(name()+" the "+charStats().raceName()+" is a "+levelStr+".\n\r"); } if(envStats().height()>0) myDescription.append(charStats().HeShe()+" is "+envStats().height()+" inches tall and weighs "+baseEnvStats().weight()+" pounds.\n\r"); myDescription.append(healthText()+"\n\r\n\r"); myDescription.append(description()+"\n\r\n\r"); myDescription.append(charStats().HeShe()+" is wearing:\n\r"+ExternalPlay.getEquipment(affect.source(),this)); tell(myDescription.toString()); } break; case Affect.TYP_READSOMETHING: if((Sense.canBeSeenBy(this,mob))&&(affect.amITarget(this))) tell("There is nothing written on "+name()); break; case Affect.TYP_SIT: { int oldDisposition=mob.baseEnvStats().disposition(); oldDisposition=oldDisposition&(Integer.MAX_VALUE-EnvStats.IS_SLEEPING-EnvStats.IS_SNEAKING-EnvStats.IS_SITTING); mob.baseEnvStats().setDisposition(oldDisposition|EnvStats.IS_SITTING); mob.recoverEnvStats(); mob.recoverCharStats(); mob.recoverMaxState(); tell(this,affect.target(),affect.tool(),affect.sourceMessage()); } break; case Affect.TYP_SLEEP: { int oldDisposition=mob.baseEnvStats().disposition(); oldDisposition=oldDisposition&(Integer.MAX_VALUE-EnvStats.IS_SLEEPING-EnvStats.IS_SNEAKING-EnvStats.IS_SITTING); mob.baseEnvStats().setDisposition(oldDisposition|EnvStats.IS_SLEEPING); mob.recoverEnvStats(); mob.recoverCharStats(); mob.recoverMaxState(); tell(this,affect.target(),affect.tool(),affect.sourceMessage()); } break; case Affect.TYP_QUIT: if(mob.isInCombat()) { mob.getVictim().resetToMaxState(); ExternalPlay.flee(mob,"NOWHERE"); mob.makePeace(); } tell(affect.source(),affect.target(),affect.tool(),affect.sourceMessage()); break; case Affect.TYP_STAND: { int oldDisposition=mob.baseEnvStats().disposition(); oldDisposition=oldDisposition&(Integer.MAX_VALUE-EnvStats.IS_SLEEPING-EnvStats.IS_SNEAKING-EnvStats.IS_SITTING); mob.baseEnvStats().setDisposition(oldDisposition); mob.recoverEnvStats(); mob.recoverCharStats(); mob.recoverMaxState(); tell(this,affect.target(),affect.tool(),affect.sourceMessage()); } break; case Affect.TYP_RECALL: if((affect.target()!=null) && (affect.target() instanceof Room) && (location() != affect.target())) { tell(affect.source(),null,affect.tool(),affect.targetMessage()); location().delInhabitant(this); ((Room)affect.target()).addInhabitant(this); ((Room)affect.target()).showOthers(mob,null,Affect.MSG_ENTER,"<S-NAME> appears out of the Java Plain."); setLocation(((Room)affect.target())); recoverEnvStats(); recoverCharStats(); recoverMaxState(); ExternalPlay.look(mob,new Vector(),true); } break; case Affect.TYP_FOLLOW: if((affect.target()!=null)&&(affect.target() instanceof MOB)) { setFollowing((MOB)affect.target()); tell(affect.source(),affect.target(),affect.tool(),affect.sourceMessage()); } break; case Affect.TYP_NOFOLLOW: setFollowing(null); tell(affect.source(),affect.target(),affect.tool(),affect.sourceMessage()); break; default: // you pretty much always know what you are doing, if you can do it. tell(affect.source(),affect.target(),affect.tool(),affect.sourceMessage()); break; } } else if((affect.targetCode()!=Affect.NO_EFFECT)&&(affect.amITarget(this))) { int targetMajor=affect.targetMajor(); // malicious by itself is pure pain if(Util.bset(affect.targetCode(),Affect.MASK_HURT)) { int dmg=affect.targetCode()-Affect.MASK_HURT; if(dmg>0) { if((!curState().adjHitPoints(-dmg,maxState()))&&(location()!=null)) ExternalPlay.postDeath(affect.source(),this,affect); else if((curState().getHitPoints()<getWimpHitPoint())&&(isInCombat())) ExternalPlay.postPanic(this,affect); } } else if(Util.bset(affect.targetCode(),Affect.MASK_MALICIOUS)) { if((!isInCombat()) &&(!amDead) &&(location().isInhabitant((MOB)affect.source()))) { establishRange(this,affect.source(),affect.tool()); setVictim(affect.source()); } if((isInCombat())&&(!amDead)) { if(affect.targetMinor()==Affect.TYP_WEAPONATTACK) { Weapon weapon=affect.source().myNaturalWeapon(); if((affect.tool()!=null)&&(affect.tool() instanceof Weapon)) weapon=(Weapon)affect.tool(); if(weapon!=null) { boolean isHit=(CoffeeUtensils.normalizeAndRollLess(affect.source().adjustedAttackBonus()+adjustedArmor())); ExternalPlay.postWeaponDamage(affect.source(),this,weapon,isHit); affect.tagModified(true); } } else if((affect.tool()!=null) &&(affect.tool() instanceof Weapon)) ExternalPlay.postWeaponDamage(affect.source(),this,(Weapon)affect.tool(),true); } ExternalPlay.standIfNecessary(this); } else if((affect.targetMinor()==Affect.TYP_GIVE) &&(affect.tool()!=null) &&(affect.tool() instanceof Item)) { FullMsg msg=new FullMsg(affect.source(),affect.tool(),null,Affect.MSG_DROP,null); location().send(this,msg); msg=new FullMsg((MOB)affect.target(),affect.tool(),null,Affect.MSG_GET,null); location().send(this,msg); } else if((affect.targetMinor()==Affect.TYP_EXAMINESOMETHING) &&(Sense.canBeSeenBy(this,mob))) { StringBuffer myDescription=new StringBuffer(""); if(Util.bset(mob.getBitmap(),MOB.ATT_SYSOPMSGS)) myDescription.append(Name()+"\n\rRejuv:"+baseEnvStats().rejuv()+"\n\rAbile:"+baseEnvStats().ability()+"\n\rLevel:"+baseEnvStats().level()+"\n\rMisc :'"+text()+"\n\rRoom :'"+((getStartRoom()==null)?"null":getStartRoom().roomID())+"\n\r"+description()+"\n\r"); if(!isMonster()) { String levelStr=charStats().displayClassLevel(this,false); myDescription.append(name()+" the "+charStats().raceName()+" is a "+levelStr+".\n\r"); } if(envStats().height()>0) myDescription.append(charStats().HeShe()+" is "+envStats().height()+" inches tall and weighs "+baseEnvStats().weight()+" pounds.\n\r"); myDescription.append(healthText()+"\n\r\n\r"); myDescription.append(description()+"\n\r\n\r"); myDescription.append(charStats().HeShe()+" is wearing:\n\r"+ExternalPlay.getEquipment(affect.source(),this)); mob.tell(myDescription.toString()); } else if((affect.targetMinor()==Affect.TYP_REBUKE) &&(affect.source().Name().equals(getLeigeID()))) setLeigeID(""); else if(Util.bset(targetMajor,affect.MASK_CHANNEL)) { if((playerStats()!=null) &&(!Util.isSet(playerStats().getChannelMask(),((affect.targetCode()-affect.MASK_CHANNEL)-Affect.TYP_CHANNEL)))) tell(affect.source(),affect.target(),affect.tool(),affect.targetMessage()); } if((Util.bset(targetMajor,Affect.MASK_SOUND)) &&(canhearsrc)&&(!asleep)) { if((affect.targetMinor()==Affect.TYP_SPEAK) &&(affect.source()!=null) &&(playerStats()!=null)) playerStats().setReplyTo(affect.source()); tell(affect.source(),affect.target(),affect.tool(),affect.targetMessage()); } else if(((Util.bset(targetMajor,Affect.MASK_EYES)) ||(Util.bset(affect.targetCode(),Affect.MASK_HURT)) ||(Util.bset(targetMajor,Affect.MASK_GENERAL))) &&(!asleep)&&(canseesrc)) tell(affect.source(),affect.target(),affect.tool(),affect.targetMessage()); else if(Util.bset(affect.targetCode(),Affect.MASK_MALICIOUS)) tell(affect.source(),affect.target(),affect.tool(),affect.targetMessage()); else if(((Util.bset(targetMajor,Affect.MASK_HANDS)) ||(Util.bset(targetMajor,Affect.MASK_MOVE)) ||((Util.bset(targetMajor,Affect.MASK_MOUTH)) &&(!Util.bset(targetMajor,Affect.MASK_SOUND)))) &&(!asleep)&&((canhearsrc)||(canseesrc))) tell(affect.source(),affect.target(),affect.tool(),affect.targetMessage()); } else if((affect.othersCode()!=Affect.NO_EFFECT) &&(!affect.amISource(this)) &&(!affect.amITarget(this))) { int othersMajor=affect.othersMajor(); int othersMinor=affect.othersMinor(); if(Util.bset(affect.othersCode(),Affect.MASK_MALICIOUS)&&(affect.target() instanceof MOB)) fightingFollowers((MOB)affect.target(),affect.source()); if((othersMinor==Affect.TYP_ENTER) // exceptions to movement ||(othersMinor==Affect.TYP_FLEE) ||(othersMinor==Affect.TYP_LEAVE)) { if(((!asleep)||(affect.othersMinor()==Affect.TYP_ENTER)) &&(Sense.canSenseMoving(affect.source(),this))) tell(affect.source(),affect.target(),affect.tool(),affect.othersMessage()); } else if(Util.bset(othersMajor,affect.MASK_CHANNEL)) { if((playerStats()!=null) &&(!Util.isSet(playerStats().getChannelMask(),((affect.othersCode()-affect.MASK_CHANNEL)-Affect.TYP_CHANNEL)))) tell(affect.source(),affect.target(),affect.tool(),affect.othersMessage()); } else if((Util.bset(othersMajor,Affect.MASK_SOUND)) &&(!asleep) &&(canhearsrc)) tell(affect.source(),affect.target(),affect.tool(),affect.othersMessage()); else if(((Util.bset(othersMajor,Affect.MASK_EYES)) ||(Util.bset(othersMajor,Affect.MASK_HANDS)) ||(Util.bset(othersMajor,Affect.MASK_GENERAL))) &&((!asleep)&&(canseesrc))) tell(affect.source(),affect.target(),affect.tool(),affect.othersMessage()); else if(((Util.bset(othersMajor,Affect.MASK_MOVE)) ||((Util.bset(othersMajor,Affect.MASK_MOUTH))&&(!Util.bset(othersMajor,Affect.MASK_SOUND)))) &&(!asleep) &&((canseesrc)||(canhearsrc))) tell(affect.source(),affect.target(),affect.tool(),affect.othersMessage()); if((affect.othersMinor()==Affect.TYP_DEATH)&&(victim!=null)) { if(victim==affect.source()) setVictim(null); else if((victim.getVictim()==null)||(victim.getVictim()==affect.source())) { if((amFollowing()!=null)&&(victim.amFollowing()!=null)&&(amFollowing()==victim.amFollowing())) setVictim(null); else { victim.setAtRange(-1); victim.setVictim(this); } } } } for(int i=0;i<inventorySize();i++) { Item I=(Item)fetchInventory(i); if(I!=null) I.affect(this,affect); } for(int i=0;i<numAffects();i++) { Ability A=(Ability)fetchAffect(i); if(A!=null) A.affect(this,affect); } } public void affectCharStats(MOB affectedMob, CharStats affectableStats){} public int movesSinceLastTick(){return movesSinceTick;} public long getTickStatus(){return tickStatus;} public boolean tick(Tickable ticking, int tickID) { if(pleaseDestroy) return false; tickStatus=Tickable.STATUS_START; if(tickID==Host.MOB_TICK) { movesSinceTick=0; if(amDead) { tickStatus=Tickable.STATUS_DEAD; if(isMonster()) if((envStats().rejuv()<Integer.MAX_VALUE) &&(baseEnvStats().rejuv()>0)) { envStats().setRejuv(envStats().rejuv()-1); if(envStats().rejuv()<0) { bringToLife(getStartRoom(),true); location().showOthers(this,null,Affect.MSG_OK_ACTION,"<S-NAME> appears!"); } } else { tickStatus=Tickable.STATUS_END; destroy(); tickStatus=Tickable.STATUS_NOT; lastTickedDateTime=System.currentTimeMillis(); return false; } tickStatus=Tickable.STATUS_END; } else if(location()!=null) { tickStatus=Tickable.STATUS_ALIVE; curState().recoverTick(this,maxState); curState().expendEnergy(this,maxState,false); if(!Sense.canBreathe(this)) { location().show(this,this,Affect.MSG_OK_VISUAL,("^Z<S-NAME> can't breathe!^.^?")+CommonStrings.msp("choke.wav",10)); ExternalPlay.postDamage(this,this,null,(int)Math.round(Util.mul(Math.random(),baseEnvStats().level()+2)),Affect.NO_EFFECT,-1,null); } if(isInCombat()) { tickStatus=Tickable.STATUS_FIGHT; peaceTime=0; if(Util.bset(getBitmap(),MOB.ATT_AUTODRAW)) ExternalPlay.drawIfNecessary(this,false); Item weapon=this.fetchWieldedItem(); double curSpeed=Math.floor(speeder); speeder+=envStats().speed(); int numAttacks=(int)Math.round(Math.floor(speeder-curSpeed)); if(Sense.aliveAwakeMobile(this,true)) { for(int s=0;s<numAttacks;s++) { if((!amDead()) &&(curState().getHitPoints()>0) &&(isInCombat()) &&((s==0)||(!Sense.isSitting(this)))) { if((weapon!=null)&&(weapon.amWearingAt(Item.INVENTORY))) weapon=this.fetchWieldedItem(); if((!Util.bset(getBitmap(),MOB.ATT_AUTOMELEE))) ExternalPlay.postAttack(this,victim,weapon); else { boolean inminrange=(rangeToTarget()>=minRange(weapon)); boolean inmaxrange=(rangeToTarget()<=maxRange(weapon)); if((!inminrange)&&(curState().getMovement()>=25)) { FullMsg msg=new FullMsg(this,victim,Affect.MSG_RETREAT,"<S-NAME> retreat(s) before <T-NAME>."); if(location().okAffect(this,msg)) location().send(this,msg); } else if((weapon!=null)&&inminrange&&inmaxrange) ExternalPlay.postAttack(this,victim,weapon); } } else break; } if(Dice.rollPercentage()>(charStats().getStat(CharStats.CONSTITUTION)*4)) curState().adjMovement(-1,maxState()); } if(!isMonster()) { MOB target=this.getVictim(); if((target!=null)&&(!target.amDead())&&(Sense.canBeSeenBy(target,this))) session().print(target.healthText()+"\n\r\n\r"); } } else { speeder=0.0; peaceTime+=Host.TICK_TIME; if(Util.bset(getBitmap(),MOB.ATT_AUTODRAW) &&(peaceTime>=SHEATH_TIME) &&(Sense.aliveAwakeMobile(this,true))) ExternalPlay.sheathIfPossible(this); } tickStatus=Tickable.STATUS_OTHER; if(!isMonster()) { if(Sense.isSleeping(this)) curState().adjFatigue(-CharState.REST_PER_TICK,maxState()); else curState().adjFatigue(Host.TICK_TIME,maxState()); } if((riding()!=null)&&(CoffeeUtensils.roomLocation(riding())!=location())) setRiding(null); if((!isMonster())&&(((++minuteCounter)*Host.TICK_TIME)>60000)) { minuteCounter=0; setAgeHours(AgeHours+1); if(AgeHours>60000) { if(((AgeHours%120)==0)&&(Dice.rollPercentage()==1)) { Ability A=CMClass.getAbility("Disease_Cancer"); if((A!=null)&&(fetchAffect(A.ID())==null)) A.invoke(this,this,true); } else if(((AgeHours%1200)==0)&&(Dice.rollPercentage()<25)) { Ability A=CMClass.getAbility("Disease_Arthritis"); if((A!=null)&&(fetchAffect(A.ID())==null)) A.invoke(this,this,true); } } } } int a=0; while(a<numAffects()) { Ability A=fetchAffect(a); if(A!=null) { tickStatus=Tickable.STATUS_AFFECT+a; int s=affects.size(); if(!A.tick(ticking,tickID)) A.unInvoke(); if(affects.size()==s) a++; } else a++; } for(int b=0;b<numBehaviors();b++) { Behavior B=fetchBehavior(b); tickStatus=Tickable.STATUS_BEHAVIOR+b; if(B!=null) B.tick(ticking,tickID); } tickStatus=Tickable.STATUS_CLASS; charStats().getCurrentClass().tick(ticking,tickID); tickStatus=Tickable.STATUS_RACE; charStats().getMyRace().tick(ticking,tickID); tickStatus=Tickable.STATUS_END; } tickStatus=Tickable.STATUS_NOT; lastTickedDateTime=System.currentTimeMillis(); return !pleaseDestroy; } public boolean isMonster(){ return (mySession==null);} public int compareTo(Object o){ return CMClass.classID(this).compareToIgnoreCase(CMClass.classID(o));} public boolean isASysOp(Room of) { if(baseCharStats()==null) return false; if(baseCharStats().getClassLevel("Archon")>=0) return true; if(of==null) return false; if(of.getArea()==null) return false; if(of.getArea().amISubOp(Username)) return true; return false; } public void confirmWearability() { Race R=charStats().getMyRace(); for(int i=0;i<inventorySize();i++) { Item item=fetchInventory(i); if((item!=null)&&(!item.amWearingAt(Item.INVENTORY))) { long oldCode=item.rawWornCode(); item.unWear(); int msgCode=Affect.MSG_WEAR; if((oldCode&Item.WIELD)>0) msgCode=Affect.MSG_WIELD; else if((oldCode&Item.HELD)>0) msgCode=Affect.MSG_HOLD; FullMsg msg=new FullMsg(this,item,null,Affect.NO_EFFECT,null,msgCode,null,Affect.NO_EFFECT,null); if((R.okAffect(this,msg))&&(item.okAffect(item,msg))) item.wearAt(oldCode); } } } public void addInventory(Item item) { item.setOwner(this); inventory.addElement(item); item.recoverEnvStats(); } public void delInventory(Item item) { inventory.removeElement(item); item.recoverEnvStats(); } public int inventorySize() { return inventory.size(); } public Item fetchInventory(int index) { try { return (Item)inventory.elementAt(index); } catch(java.lang.ArrayIndexOutOfBoundsException x){} return null; } public Item fetchInventory(String itemName) { Item item=(Item)CoffeeUtensils.fetchAvailableItem(inventory,itemName,null,Item.WORN_REQ_ANY,true); if(item==null) item=(Item)CoffeeUtensils.fetchAvailableItem(inventory,itemName,null,Item.WORN_REQ_ANY,false); return item; } public Item fetchInventory(Item goodLocation, String itemName) { Item item=(Item)CoffeeUtensils.fetchAvailableItem(inventory,itemName,goodLocation,Item.WORN_REQ_ANY,true); if(item==null) item=(Item)CoffeeUtensils.fetchAvailableItem(inventory,itemName,goodLocation,Item.WORN_REQ_ANY,false); return item; } public Item fetchCarried(Item goodLocation, String itemName) { Item item=(Item)CoffeeUtensils.fetchAvailableItem(inventory,itemName,goodLocation,Item.WORN_REQ_UNWORNONLY,true); if(item==null) item=(Item)CoffeeUtensils.fetchAvailableItem(inventory,itemName,goodLocation,Item.WORN_REQ_UNWORNONLY,false); return item; } public Item fetchWornItem(String itemName) { Item item=(Item)CoffeeUtensils.fetchAvailableItem(inventory,itemName,null,Item.WORN_REQ_WORNONLY,true); if(item==null) item=(Item)CoffeeUtensils.fetchAvailableItem(inventory,itemName,null,Item.WORN_REQ_WORNONLY,false); return item; } public void addFollower(MOB follower) { if((follower!=null)&&(!followers.contains(follower))) { followers.addElement(follower); } } public void delFollower(MOB follower) { if((follower!=null)&&(followers.contains(follower))) { followers.removeElement(follower); } } public int numFollowers() { return followers.size(); } public MOB fetchFollower(int index) { try { return (MOB)followers.elementAt(index); } catch(java.lang.ArrayIndexOutOfBoundsException x){} return null; } public MOB fetchFollower(MOB thisOne) { if(followers.contains(thisOne)) return thisOne; return null; } public MOB fetchFollower(String ID) { MOB mob=(MOB)CoffeeUtensils.fetchEnvironmental(followers,ID,true); if (mob==null) mob=(MOB)CoffeeUtensils.fetchEnvironmental(followers,ID,false); return mob; } public boolean willFollowOrdersOf(MOB mob) { if(mob.isASysOp(mob.location()) ||(amFollowing()==mob) ||(getLeigeID().equals(mob.Name())) ||((getClanID().length()>0) &&(getClanID().equals(mob.getClanID())) &&(mob.getClanRole()!=getClanRole()) &&((mob.getClanRole()==Clan.POS_LEADER) ||(mob.getClanRole()==Clan.POS_BOSS))) ||(ExternalPlay.doesOwnThisProperty(mob,getStartRoom()))) return true; return false; } public MOB amFollowing() { if(amFollowing!=null) { if(amFollowing.fetchFollower(this)==null) amFollowing=null; } return amFollowing; } public void setFollowing(MOB mob) { if(mob==null) { if(amFollowing!=null) { if(amFollowing.fetchFollower(this)!=null) amFollowing.delFollower(this); } } else if(mob.fetchFollower(this)==null) mob.addFollower(this); amFollowing=mob; } private void addFollowers(MOB mob, Hashtable toThis) { if(toThis.get(mob)==null) toThis.put(mob,mob); for(int f=0;f<mob.numFollowers();f++) { MOB follower=mob.fetchFollower(f); if((follower!=null)&&(toThis.get(follower)==null)) { toThis.put(follower,follower); addFollowers(follower,toThis); } } } public Hashtable getRideBuddies(Hashtable list) { if(list==null) return list; if(list.get(this)==null) list.put(this,this); if(riding()!=null) riding().getRideBuddies(list); return list; } public Hashtable getGroupMembers(Hashtable list) { if(list==null) return list; if(list.get(this)==null) list.put(this,this); if(amFollowing()!=null) amFollowing().getGroupMembers(list); for(int f=0;f<numFollowers();f++) { MOB follower=fetchFollower(f); if((follower!=null)&&(list.get(follower)==null)) follower.getGroupMembers(list); } return list; } public boolean isEligibleMonster() { if(!isMonster()) return false; MOB followed=amFollowing(); if(followed!=null) if(!followed.isMonster()) return false; return true; } public MOB soulMate() { return soulMate; } public void setSoulMate(MOB mob) { soulMate=mob; } public void addAbility(Ability to) { if(to==null) return; for(int a=0;a<numAbilities();a++) { Ability A=fetchAbility(a); if((A!=null)&&(A.ID().equals(to.ID()))) return; } abilities.addElement(to); } public void delAbility(Ability to) { abilities.removeElement(to); } public int numAbilities() { return abilities.size(); } public boolean hasAbilityEvoker(String word) { try { for(int a=0;a<abilities.size();a++) { Ability A=(Ability)abilities.elementAt(a); for(int s=0;s<A.triggerStrings().length;s++) { if(A.triggerStrings()[s].startsWith(word)) return true; } } } catch(java.lang.ArrayIndexOutOfBoundsException x){} return false; } public Ability fetchAbility(int index) { try { return (Ability)abilities.elementAt(index); } catch(java.lang.ArrayIndexOutOfBoundsException x){} return null; } public Ability fetchAbility(String ID) { for(int a=0;a<numAbilities();a++) { Ability A=fetchAbility(a); if((A!=null) &&((A.ID().equalsIgnoreCase(ID))||(A.Name().equalsIgnoreCase(ID)))) return A; } return (Ability)CoffeeUtensils.fetchEnvironmental(abilities,ID,false); } public void addNonUninvokableAffect(Ability to) { if(to==null) return; if(affects.contains(to)) return; to.makeNonUninvokable(); to.makeLongLasting(); affects.addElement(to); to.setAffectedOne(this); } public void addAffect(Ability to) { if(to==null) return; if(affects.contains(to)) return; affects.addElement(to); to.setAffectedOne(this); } public void delAffect(Ability to) { int size=affects.size(); affects.removeElement(to); if(affects.size()<size) to.setAffectedOne(null); } public int numAffects() { return affects.size(); } public Ability fetchAffect(int index) { try { return (Ability)affects.elementAt(index); } catch(java.lang.ArrayIndexOutOfBoundsException x){} return null; } public Ability fetchAffect(String ID) { for(int a=0;a<numAffects();a++) { Ability A=fetchAffect(a); if((A!=null)&&(A.ID().equals(ID))) return A; } return null; } /** Manipulation of Behavior objects, which includes * movement, speech, spellcasting, etc, etc.*/ public void addBehavior(Behavior to) { if(to==null) return; for(int b=0;b<numBehaviors();b++) { Behavior B=fetchBehavior(b); if((B!=null)&&(B.ID().equals(to.ID()))) return; } to.startBehavior(this); behaviors.addElement(to); } public void delBehavior(Behavior to) { behaviors.removeElement(to); } public int numBehaviors() { return behaviors.size(); } public Behavior fetchBehavior(int index) { try { return (Behavior)behaviors.elementAt(index); } catch(java.lang.ArrayIndexOutOfBoundsException x){} return null; } public Behavior fetchBehavior(String ID) { for(int b=0;b<numBehaviors();b++) { Behavior B=fetchBehavior(b); if((B!=null)&&(B.ID().equalsIgnoreCase(ID))) return B; } return null; } public boolean amWearingSomethingHere(long wornCode) { for(int i=0;i<inventorySize();i++) { Item thisItem=fetchInventory(i); if((thisItem!=null)&&(thisItem.amWearingAt(wornCode))) return true; } return false; } public Item fetchWornItem(long wornCode) { for(int i=0;i<inventorySize();i++) { Item thisItem=fetchInventory(i); if((thisItem!=null)&&(thisItem.amWearingAt(wornCode))) return thisItem; } return null; } public Item fetchWieldedItem() { for(int i=0;i<inventorySize();i++) { Item thisItem=fetchInventory(i); if((thisItem!=null)&&(thisItem.amWearingAt(Item.WIELD))) return thisItem; } return null; } public boolean isMine(Environmental env) { if(env instanceof Item) { if(inventory.contains(env)) return true; return false; } else if(env instanceof MOB) { if(followers.contains(env)) return true; return false; } else if(env instanceof Ability) { if(abilities.contains(env)) return true; if(affects.contains(env)) return true; return false; } return false; } public void giveItem(Item thisContainer) { // caller is responsible for recovering any env // stat changes! if(Sense.isHidden(thisContainer)) thisContainer.baseEnvStats().setDisposition(thisContainer.baseEnvStats().disposition()&((int)EnvStats.ALLMASK-EnvStats.IS_HIDDEN)); // ensure its out of its previous place Environmental owner=location(); if(thisContainer.owner()!=null) { owner=thisContainer.owner(); if(thisContainer.owner() instanceof Room) ((Room)thisContainer.owner()).delItem(thisContainer); else if(thisContainer.owner() instanceof MOB) ((MOB)thisContainer.owner()).delInventory(thisContainer); } location().delItem(thisContainer); thisContainer.unWear(); if(!isMine(thisContainer)) addInventory(thisContainer); thisContainer.recoverEnvStats(); boolean nothingDone=true; do { nothingDone=true; if(owner instanceof Room) { Room R=(Room)owner; for(int i=0;i<R.numItems();i++) { Item thisItem=R.fetchItem(i); if((thisItem!=null)&&(thisItem.container()==thisContainer)) { giveItem(thisItem); nothingDone=false; break; } } } else if(owner instanceof MOB) { MOB M=(MOB)owner; for(int i=0;i<M.inventorySize();i++) { Item thisItem=M.fetchInventory(i); if((thisItem!=null)&&(thisItem.container()==thisContainer)) { giveItem(thisItem); nothingDone=false; break; } } } }while(!nothingDone); } private void fightingFollowers(MOB target, MOB source) { if((source==null)||(target==null)) return; if(source==target) return; if((target==this)||(source==this)) return; if((target.location()!=location())||(target.location()!=source.location())) return; if((Util.bset(getBitmap(),MOB.ATT_AUTOASSIST))) return; if(isInCombat()) return; if((amFollowing()==target) ||(target.amFollowing()==this) ||((target.amFollowing()!=null)&&(target.amFollowing()==this.amFollowing()))) setVictim(source);//ExternalPlay.postAttack(this,source,fetchWieldedItem()); else if((amFollowing()==source) ||(source.amFollowing()==this) ||((source.amFollowing()!=null)&&(source.amFollowing()==this.amFollowing()))) setVictim(target);//ExternalPlay.postAttack(this,target,fetchWieldedItem()); } protected static String[] CODES={"CLASS","LEVEL","ABILITY","TEXT"}; public String getStat(String code){ switch(getCodeNum(code)) { case 0: return ID(); case 1: return ""+baseEnvStats().level(); case 2: return ""+baseEnvStats().ability(); case 3: return text(); } return ""; } public void setStat(String code, String val) { switch(getCodeNum(code)) { case 0: return; case 1: baseEnvStats().setLevel(Util.s_int(val)); break; case 2: baseEnvStats().setAbility(Util.s_int(val)); break; case 3: setMiscText(val); break; } } public String[] getStatCodes(){return CODES;} protected int getCodeNum(String code){ for(int i=0;i<CODES.length;i++) if(code.equalsIgnoreCase(CODES[i])) return i; return -1; } public boolean sameAs(Environmental E) { if(!(E instanceof StdMOB)) return false; for(int i=0;i<CODES.length;i++) if(!E.getStat(CODES[i]).equals(getStat(CODES[i]))) return false; return true; } }
git-svn-id: svn://192.168.1.10/public/CoffeeMud@2971 0d6f1817-ed0e-0410-87c9-987e46238f29
com/planet_ink/coffee_mud/MOBS/StdMOB.java
Java
apache-2.0
4107dd8925e3db44509ccd9b2869c9d83c179ea4
0
UnitedID/YubiHSM-java-api
/* * Copyright (c) 2011 United ID. 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. * * @author Stefan Wold <[email protected]> */ package org.unitedid.yhsm.internal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.unitedid.yhsm.utility.Utils; public class CommandHandler { private static final Logger log = LoggerFactory.getLogger(CommandHandler.class); private CommandHandler() {} protected static synchronized byte[] execute(DeviceHandler device, byte command, byte[] data, boolean readResponse) { byte[] cmdBuffer; if (command != Defines.YSM_NULL) { cmdBuffer = new byte[]{(byte) (((data.length + 1) << 24) >> 24), command}; } else { cmdBuffer = new byte[]{command}; } log.info("CMD BUFFER: {}", Utils.byteArrayToHex(Utils.concatAllArrays(cmdBuffer, data))); device.write(Utils.concatAllArrays(cmdBuffer, data)); try { Thread.sleep(20); //TODO: Implement event listener } catch (InterruptedException e) { e.printStackTrace(); } if (!readResponse) { return null; } return readDevice(device, command); } private static byte[] readDevice(DeviceHandler device, byte command) { byte[] result = new byte[0]; try { if (device.available() > 0) { result = device.read(2); } if (result.length == 0) { reset(device); throw new Exception("No data recieved from the YubiHSM!"); } if ((result[1] & Defines.YSM_RESPONSE) != 0) { log.info("Got response from ({}) {}", result[1], Defines.getCommandString((byte) (result[1] - Defines.YSM_RESPONSE))); } if (result[1] == (command | Defines.YSM_RESPONSE)) { int len = (int)result[0] - 1; return device.read(len); } else { reset(device); throw new Exception("YubiHSM responded to the wrong command!"); } } catch (Exception e) { e.printStackTrace(); } return null; } public static void reset(DeviceHandler device) { byte[] reset = new byte[Defines.YSM_MAX_PKT_SIZE - 1]; for (int i=0; i < Defines.YSM_MAX_PKT_SIZE - 1; i++) { reset[i] = 0x00; } execute(device, Defines.YSM_NULL, reset, false); } }
src/main/java/org/unitedid/yhsm/internal/CommandHandler.java
/* * Copyright (c) 2011 United ID. 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. * * @author Stefan Wold <[email protected]> */ package org.unitedid.yhsm.internal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.unitedid.yhsm.utility.Utils; public class CommandHandler { private static final Logger log = LoggerFactory.getLogger(CommandHandler.class); private CommandHandler() {} protected static synchronized byte[] execute(DeviceHandler device, byte command, byte[] data, boolean readResponse) { byte[] cmdBuffer; if (command != Defines.YSM_NULL) { cmdBuffer = new byte[]{(byte) (((data.length + 1) << 24) >> 24), command}; } else { cmdBuffer = new byte[]{command}; } log.debug("CMD BUFFER: {}", Utils.byteArrayToHexString(Utils.concatAllArrays(cmdBuffer, data))); device.write(Utils.concatAllArrays(cmdBuffer, data)); try { Thread.sleep(100); //TODO: Implement event listener } catch (InterruptedException e) { e.printStackTrace(); } if (!readResponse) { return null; } return readDevice(device, command); } private static byte[] readDevice(DeviceHandler device, byte command) { byte[] result = new byte[0]; try { if (device.available() > 0) { result = device.read(2); } if (result.length == 0 || result == null) { reset(device); throw new Exception("No data recieved from the YubiHSM!"); } if ((result[1] & Defines.YSM_RESPONSE) != 0) { log.info("Got response from ({}) {}", result[1], Defines.getCommandString((byte) (result[1] - Defines.YSM_RESPONSE))); } if (result[1] == (command | Defines.YSM_RESPONSE)) { int len = (int)result[0] - 1; return device.read(len); } else { reset(device); throw new Exception("YubiHSM responded to the wrong command!"); } } catch (Exception e) { e.printStackTrace(); } return null; } public static void reset(DeviceHandler device) { byte[] reset = new byte[Defines.YSM_MAX_PKT_SIZE - 1]; for (int i=0; i < Defines.YSM_MAX_PKT_SIZE - 1; i++) { reset[i] = 0x00; } execute(device, Defines.YSM_NULL, reset, false); } }
Use the correct utility method. Lowered read timeout to 20ms.
src/main/java/org/unitedid/yhsm/internal/CommandHandler.java
Use the correct utility method. Lowered read timeout to 20ms.
Java
apache-2.0
059b8daed51a73e35caf8d57de57b559a57ff733
0
fkeglevich/Raw-Dumper,fkeglevich/Raw-Dumper,fkeglevich/Raw-Dumper
/* * Copyright 2017, Flávio Keglevich * * 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.fkeglevich.rawdumper.io; import java.io.File; import static android.os.Environment.DIRECTORY_DCIM; import static android.os.Environment.getExternalStoragePublicDirectory; /** * TODO: Add class header * <p> * Created by Flávio Keglevich on 06/11/17. */ public class Directories { private static final String RAW_DUMPER_DIR_NAME = "RawDumper"; private static final File RAW_DUMPER_DIR = new File(getExternalStoragePublicDirectory(DIRECTORY_DCIM), RAW_DUMPER_DIR_NAME); public static File getPicturesDirectory() { return RAW_DUMPER_DIR; } public static File getVideosDirectory() { return getPicturesDirectory(); } }
app/src/main/java/com/fkeglevich/rawdumper/io/Directories.java
/* * Copyright 2017, Flávio Keglevich * * 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.fkeglevich.rawdumper.io; import android.os.Environment; import java.io.File; import static android.os.Environment.DIRECTORY_DCIM; /** * TODO: Add class header * <p> * Created by Flávio Keglevich on 06/11/17. */ public class Directories { private static final String RAW_DUMPER_DIR = "RawDumper"; public static File getPicturesDirectory() { return new File(Environment.getExternalStoragePublicDirectory(DIRECTORY_DCIM), RAW_DUMPER_DIR); } public static File getVideosDirectory() { return getPicturesDirectory(); } }
More organized code and cached picture dir as a constant
app/src/main/java/com/fkeglevich/rawdumper/io/Directories.java
More organized code and cached picture dir as a constant
Java
apache-2.0
c324a39c514cbad09c7e9ce74cec1b85325df8b8
0
pantsbuild/ivy,pantsbuild/ivy
/* * 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.ivy.osgi.util; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; import org.apache.ivy.util.Message; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.DTDHandler; import org.xml.sax.ErrorHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; public class DelegetingHandler extends DefaultHandler implements DTDHandler, ContentHandler, ErrorHandler { private DelegetingHandler/* <?> */delegate = null; private DelegetingHandler/* <?> */parent; private final Map/* <String, DelegetingHandler<?>> */saxHandlerMapping = new HashMap(); private final Map/* <String, ChildElementHandler<?>> */childHandlerMapping = new HashMap(); private final String tagName; private boolean started = false; private boolean skip = false; private boolean skipOnError = false; private StringBuffer charBuffer = new StringBuffer(); private boolean bufferingChar = false; private Locator locator; public DelegetingHandler(String name) { this.tagName = name; charBuffer.setLength(0); } protected void addChild(DelegetingHandler saxHandler, ChildElementHandler elementHandler) { saxHandlerMapping.put(saxHandler.getName(), saxHandler); childHandlerMapping.put(saxHandler.getName(), elementHandler); saxHandler.parent = this; } public String getName() { return tagName; } public DelegetingHandler getParent() { return parent; } public void setBufferingChar(boolean bufferingChar) { this.bufferingChar = bufferingChar; } public void setSkipOnError(boolean skipOnError) { this.skipOnError = skipOnError; } public boolean isBufferingChar() { return bufferingChar; } public String getBufferedChars() { return charBuffer.toString(); } public void setDocumentLocator(Locator locator) { this.locator = locator; Iterator itHandler = saxHandlerMapping.values().iterator(); while (itHandler.hasNext()) { DelegetingHandler/* <?> */subHandler = (DelegetingHandler) itHandler.next(); subHandler.setDocumentLocator(locator); } } public Locator getLocator() { return locator; } /** * Return an sort of identifier of the current element being parsed. It will only be used for * logging purpose. * * @return an empty string by default */ protected String getCurrentElementIdentifier() { return ""; } public void skip() { skip = true; Iterator itHandler = saxHandlerMapping.values().iterator(); while (itHandler.hasNext()) { DelegetingHandler/* <?> */subHandler = (DelegetingHandler) itHandler.next(); subHandler.stopDelegating(); } } protected void stopDelegating() { parent.delegate = null; skip = false; started = false; charBuffer.setLength(0); Iterator itHandler = saxHandlerMapping.values().iterator(); while (itHandler.hasNext()) { DelegetingHandler/* <?> */subHandler = (DelegetingHandler) itHandler.next(); subHandler.stopDelegating(); } } private interface SkipOnErrorCallback { public void call() throws SAXException; } private void skipOnError(SkipOnErrorCallback callback) throws SAXException { try { callback.call(); } catch (SAXException e) { if (skipOnError) { skip(); log(Message.MSG_ERR, e.getMessage()); } else { throw e; } } } public final void startDocument() throws SAXException { if (skip) { return; } if (delegate != null) { delegate.startDocument(); } else { doStartDocument(); } } /** * @throws SAXException */ protected void doStartDocument() throws SAXException { // by default do nothing } public final void endDocument() throws SAXException { if (skip) { return; } if (delegate != null) { delegate.endDocument(); } else { doEndDocument(); } } /** * @throws SAXException */ protected void doEndDocument() throws SAXException { // by default do nothing } public final void startElement(final String uri, final String localName, final String n, final Attributes atts) throws SAXException { if (delegate != null) { // we are already delegating, let's continue skipOnError(new SkipOnErrorCallback() { public void call() throws SAXException { delegate.startElement(uri, localName, n, atts); } }); } else { if (!started) { // first time called ? // just for the root, check the expected element name // not need to check the delegated as the mapping is already taking care of it if (parent == null && !localName.equals(tagName)) { // we are at the root and the saxed element doesn't match throw new SAXException("The root element of the parsed document '" + localName + "' didn't matched the expected one: '" + tagName + "'"); } skipOnError(new SkipOnErrorCallback() { public void call() throws SAXException { handleAttributes(atts); } }); started = true; } else { if (skip) { // we con't care anymore about that part of the xml tree return; } // time now to delegate for a new element delegate = (DelegetingHandler) saxHandlerMapping.get(localName); if (delegate != null) { skipOnError(new SkipOnErrorCallback() { public void call() throws SAXException { delegate.startElement(uri, localName, n, atts); } }); } } } } /** * Called when the expected node is achieved * * @param atts * the xml attributes attached to the expected node * @exception SAXException * in case the parsing should be completely stopped */ protected void handleAttributes(Attributes atts) throws SAXException { // nothing to do by default } /** * @throws SAXException */ protected void doStartElement(String uri, String localName, String name, Attributes atts) throws SAXException { // by default do nothing } public final void endElement(final String uri, final String localName, final String n) throws SAXException { if (delegate != null) { final DelegetingHandler savedDelegate = delegate; // we are already delegating, let's continue skipOnError(new SkipOnErrorCallback() { public void call() throws SAXException { delegate.endElement(uri, localName, n); } }); if (delegate == null) { // we just stopped delegating, it means that the child has ended final ChildElementHandler childHandler = (ChildElementHandler) childHandlerMapping .get(localName); if (childHandler != null) { skipOnError(new SkipOnErrorCallback() { public void call() throws SAXException { childHandler.childHanlded(savedDelegate); } }); } } } else { if (!skip) { doEndElement(uri, localName, n); } if (parent != null && tagName.equals(localName)) { // the current element is closed, let's tell the parent to stop delegating stopDelegating(); } } } /** * @throws SAXException */ protected void doEndElement(String uri, String localName, String name) throws SAXException { // by default do nothing } public static interface ChildElementHandler/* <DH extends DelegatingHandler> */{ public void childHanlded(/* DH */DelegetingHandler child) throws SAXParseException; } public final void characters(char[] ch, int start, int length) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.characters(ch, start, length); } else { doCharacters(ch, start, length); } } /** * @throws SAXException */ protected void doCharacters(char[] ch, int start, int length) throws SAXException { if (bufferingChar) { charBuffer.append(ch, start, length); } } public final void startPrefixMapping(String prefix, String uri) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.startPrefixMapping(prefix, uri); } else { doStartPrefixMapping(prefix, uri); } } /** * @throws SAXException */ protected void doStartPrefixMapping(String prefix, String uri) throws SAXException { // by default do nothing } public final void endPrefixMapping(String prefix) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.endPrefixMapping(prefix); } else { doEndPrefixMapping(prefix); } } /** * @throws SAXException */ protected void doEndPrefixMapping(String prefix) throws SAXException { // by default do nothing } public final void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.ignorableWhitespace(ch, start, length); } else { doIgnorableWhitespace(ch, start, length); } } /** * @throws SAXException */ protected void doIgnorableWhitespace(char[] ch, int start, int length) throws SAXException { // by default do nothing } public final void notationDecl(String name, String publicId, String systemId) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.notationDecl(name, publicId, systemId); } else { doNotationDecl(name, publicId, systemId); } } /** * @throws SAXException */ protected void doNotationDecl(String name, String publicId, String systemId) throws SAXException { // by default do nothing } public final void processingInstruction(String target, String data) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.processingInstruction(target, data); } else { doProcessingInstruction(target, data); } } /** * @throws SAXException */ protected void doProcessingInstruction(String target, String data) throws SAXException { // by default do nothing } public final void skippedEntity(String name) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.skippedEntity(name); } else { doSkippedEntity(name); } } /** * @throws SAXException */ protected void doSkippedEntity(String name) throws SAXException { // by default do nothing } /** * @throws SAXException */ public final void unparsedEntityDecl(String name, String publicId, String systemId, String notationName) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.unparsedEntityDecl(name, publicId, systemId, notationName); } else { doUnparsedEntityDecl(name, publicId, systemId, notationName); } } /** * @throws SAXException */ protected void doUnparsedEntityDecl(String name, String publicId, String systemId, String notationName) throws SAXException { // by default do nothing } // ERROR HANDLING public final void warning(SAXParseException exception) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.warning(exception); } else { doWarning(exception); } } /** * @throws SAXException */ protected void doWarning(SAXParseException exception) throws SAXException { // by default do nothing } public final void error(SAXParseException exception) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.error(exception); } else { doError(exception); } } /** * @throws SAXException */ protected void doError(SAXParseException exception) throws SAXException { // by default do nothing } public final void fatalError(SAXParseException exception) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.fatalError(exception); } else { doFatalError(exception); } } /** * @throws SAXException */ protected void doFatalError(SAXParseException exception) throws SAXException { // by default do nothing } // ////////////////////// // Functions related to error handling // ////////////////////// protected void log(int logLevel, String message) { Message.log(logLevel, getLocation(getLocator()) + message); } protected static String getLocation(Locator locator) { if (locator == null) { return ""; } return "[line " + locator.getLineNumber() + " col. " + locator.getColumnNumber() + "] "; } private void skipOnError(DelegetingHandler/* <?> */currentHandler, Class/* * <? extends * delegatingHandler> */handlerClassToSkip, String message) { DelegetingHandler/* <?> */handlerToSkip = currentHandler; while (!(handlerClassToSkip.isAssignableFrom(handlerToSkip.getClass()))) { handlerToSkip = handlerToSkip.getParent(); } log(Message.MSG_ERR, message + ". The '" + handlerToSkip.getName() + "' element " + getCurrentElementIdentifier() + " is then ignored."); handlerToSkip.skip(); } // ////////////////////// // Helpers to parse the attributes // ////////////////////// protected String getRequiredAttribute(Attributes atts, String name) throws SAXParseException { String value = atts.getValue(name); if (value == null) { throw new SAXParseException("Required attribute '" + name + "' not found", getLocator()); } return value; } protected String getOptionalAttribute(Attributes atts, String name, String defaultValue) { String value = atts.getValue(name); if (value == null) { return defaultValue; } return value; } protected int getRequiredIntAttribute(Attributes atts, String name, Integer logLevel) throws SAXParseException { return parseInt(name, getRequiredAttribute(atts, name)); } protected Integer getOptionalIntAttribute(Attributes atts, String name, Integer defaultValue) throws SAXParseException { String value = atts.getValue(name); if (value == null) { return defaultValue; } return new Integer(parseInt(name, value)); } private int parseInt(String name, String value) throws SAXParseException { try { return Integer.parseInt(value); } catch (NumberFormatException e) { throw new SAXParseException("Attribute '" + name + "' is expected to be an integer but was '" + value + "' (" + e.getMessage() + ")", getLocator()); } } protected long getRequiredLongAttribute(Attributes atts, String name) throws SAXParseException { return parseLong(name, getRequiredAttribute(atts, name)); } protected Long getOptionalLongAttribute(Attributes atts, String name, Long defaultValue) throws SAXParseException { String value = atts.getValue(name); if (value == null) { return defaultValue; } return new Long(parseLong(name, value)); } private long parseLong(String name, String value) throws SAXParseException { try { return Long.parseLong(value); } catch (NumberFormatException e) { throw new SAXParseException("Attribute '" + name + "' is expected to be an long but was '" + value + "' (" + e.getMessage() + ")", getLocator()); } } protected boolean getRequiredBooleanAttribute(Attributes atts, String name) throws SAXParseException { return parseBoolean(name, getRequiredAttribute(atts, name)); } protected Boolean getOptionalBooleanAttribute(Attributes atts, String name, Boolean defaultValue) throws SAXParseException { String value = atts.getValue(name); if (value == null) { return defaultValue; } return Boolean.valueOf(parseBoolean(name, value)); } static final String TRUE = Boolean.TRUE.toString().toLowerCase(Locale.US); static final String FALSE = Boolean.FALSE.toString().toLowerCase(Locale.US); private boolean parseBoolean(String name, String value) throws SAXParseException { String lowerValue = value.toLowerCase(Locale.US); if (lowerValue.equals(TRUE)) { return true; } if (lowerValue.equals(FALSE)) { return false; } throw new SAXParseException("Attribute '" + name + "' is expected to be a boolean but was '" + value + "'", getLocator()); } }
src/java/org/apache/ivy/osgi/util/DelegetingHandler.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.ivy.osgi.util; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; import org.apache.ivy.util.Message; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.DTDHandler; import org.xml.sax.ErrorHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; import com.sun.xml.internal.rngom.ast.util.LocatorImpl; public class DelegetingHandler implements DTDHandler, ContentHandler, ErrorHandler { private DelegetingHandler/* <?> */delegate = null; private DelegetingHandler/* <?> */parent; private final Map/* <String, DelegetingHandler<?>> */saxHandlerMapping = new HashMap(); private final Map/* <String, ChildElementHandler<?>> */childHandlerMapping = new HashMap(); private final String tagName; private boolean started = false; private boolean skip = false; private boolean skipOnError = false; private StringBuffer charBuffer = new StringBuffer(); private boolean bufferingChar = false; private Locator locator; public DelegetingHandler(String name) { this.tagName = name; charBuffer.setLength(0); } protected void addChild(DelegetingHandler saxHandler, ChildElementHandler elementHandler) { saxHandlerMapping.put(saxHandler.getName(), saxHandler); childHandlerMapping.put(saxHandler.getName(), elementHandler); saxHandler.parent = this; } public String getName() { return tagName; } public DelegetingHandler getParent() { return parent; } public void setBufferingChar(boolean bufferingChar) { this.bufferingChar = bufferingChar; } public void setSkipOnError(boolean skipOnError) { this.skipOnError = skipOnError; } public boolean isBufferingChar() { return bufferingChar; } public String getBufferedChars() { return charBuffer.toString(); } public void setDocumentLocator(Locator locator) { this.locator = locator; Iterator itHandler = saxHandlerMapping.values().iterator(); while (itHandler.hasNext()) { DelegetingHandler/* <?> */subHandler = (DelegetingHandler) itHandler.next(); subHandler.setDocumentLocator(locator); } } public Locator getLocator() { return locator; } /** * Return an sort of identifier of the current element being parsed. It will only be used for * logging purpose. * * @return an empty string by default */ protected String getCurrentElementIdentifier() { return ""; } public void skip() { skip = true; Iterator itHandler = saxHandlerMapping.values().iterator(); while (itHandler.hasNext()) { DelegetingHandler/* <?> */subHandler = (DelegetingHandler) itHandler.next(); subHandler.stopDelegating(); } } protected void stopDelegating() { parent.delegate = null; skip = false; started = false; charBuffer.setLength(0); Iterator itHandler = saxHandlerMapping.values().iterator(); while (itHandler.hasNext()) { DelegetingHandler/* <?> */subHandler = (DelegetingHandler) itHandler.next(); subHandler.stopDelegating(); } } private interface SkipOnErrorCallback { public void call() throws SAXException; } private void skipOnError(SkipOnErrorCallback callback) throws SAXException { try { callback.call(); } catch (SAXException e) { if (skipOnError) { skip(); Locator locator; if (e instanceof SAXParseException) { locator = new LocatorImpl(null, ((SAXParseException) e).getLineNumber(), ((SAXParseException) e).getColumnNumber()); } else { locator = getLocator(); } log(Message.MSG_ERR, locator, e.getMessage()); } else { throw e; } } } public final void startDocument() throws SAXException { if (skip) { return; } if (delegate != null) { delegate.startDocument(); } else { doStartDocument(); } } /** * @throws SAXException */ protected void doStartDocument() throws SAXException { // by default do nothing } public final void endDocument() throws SAXException { if (skip) { return; } if (delegate != null) { delegate.endDocument(); } else { doEndDocument(); } } /** * @throws SAXException */ protected void doEndDocument() throws SAXException { // by default do nothing } public final void startElement(final String uri, final String localName, final String n, final Attributes atts) throws SAXException { if (delegate != null) { // we are already delegating, let's continue skipOnError(new SkipOnErrorCallback() { public void call() throws SAXException { delegate.startElement(uri, localName, n, atts); } }); } else { if (!started) { // first time called ? // just for the root, check the expected element name // not need to check the delegated as the mapping is already taking care of it if (parent == null && !localName.equals(tagName)) { // we are at the root and the saxed element doesn't match throw new SAXException("The root element of the parsed document '" + localName + "' didn't matched the expected one: '" + tagName + "'"); } skipOnError(new SkipOnErrorCallback() { public void call() throws SAXException { handleAttributes(atts); } }); started = true; } else { if (skip) { // we con't care anymore about that part of the xml tree return; } // time now to delegate for a new element delegate = (DelegetingHandler) saxHandlerMapping.get(localName); if (delegate != null) { skipOnError(new SkipOnErrorCallback() { public void call() throws SAXException { delegate.startElement(uri, localName, n, atts); } }); } } } } /** * Called when the expected node is achieved * * @param atts * the xml attributes attached to the expected node * @exception SAXException * in case the parsing should be completely stopped */ protected void handleAttributes(Attributes atts) throws SAXException { // nothing to do by default } /** * @throws SAXException */ protected void doStartElement(String uri, String localName, String name, Attributes atts) throws SAXException { // by default do nothing } public final void endElement(final String uri, final String localName, final String n) throws SAXException { if (delegate != null) { final DelegetingHandler savedDelegate = delegate; // we are already delegating, let's continue skipOnError(new SkipOnErrorCallback() { public void call() throws SAXException { delegate.endElement(uri, localName, n); } }); if (delegate == null) { // we just stopped delegating, it means that the child has ended final ChildElementHandler childHandler = (ChildElementHandler) childHandlerMapping .get(localName); if (childHandler != null) { skipOnError(new SkipOnErrorCallback() { public void call() throws SAXException { childHandler.childHanlded(savedDelegate); } }); } } } else { if (!skip) { doEndElement(uri, localName, n); } if (parent != null && tagName.equals(localName)) { // the current element is closed, let's tell the parent to stop delegating stopDelegating(); } } } /** * @throws SAXException */ protected void doEndElement(String uri, String localName, String name) throws SAXException { // by default do nothing } public static interface ChildElementHandler/* <DH extends DelegatingHandler> */{ public void childHanlded(/* DH */DelegetingHandler child) throws SAXParseException; } public final void characters(char[] ch, int start, int length) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.characters(ch, start, length); } else { doCharacters(ch, start, length); } } /** * @throws SAXException */ protected void doCharacters(char[] ch, int start, int length) throws SAXException { if (bufferingChar) { charBuffer.append(ch, start, length); } } public final void startPrefixMapping(String prefix, String uri) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.startPrefixMapping(prefix, uri); } else { doStartPrefixMapping(prefix, uri); } } /** * @throws SAXException */ protected void doStartPrefixMapping(String prefix, String uri) throws SAXException { // by default do nothing } public final void endPrefixMapping(String prefix) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.endPrefixMapping(prefix); } else { doEndPrefixMapping(prefix); } } /** * @throws SAXException */ protected void doEndPrefixMapping(String prefix) throws SAXException { // by default do nothing } public final void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.ignorableWhitespace(ch, start, length); } else { doIgnorableWhitespace(ch, start, length); } } /** * @throws SAXException */ protected void doIgnorableWhitespace(char[] ch, int start, int length) throws SAXException { // by default do nothing } public final void notationDecl(String name, String publicId, String systemId) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.notationDecl(name, publicId, systemId); } else { doNotationDecl(name, publicId, systemId); } } /** * @throws SAXException */ protected void doNotationDecl(String name, String publicId, String systemId) throws SAXException { // by default do nothing } public final void processingInstruction(String target, String data) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.processingInstruction(target, data); } else { doProcessingInstruction(target, data); } } /** * @throws SAXException */ protected void doProcessingInstruction(String target, String data) throws SAXException { // by default do nothing } public final void skippedEntity(String name) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.skippedEntity(name); } else { doSkippedEntity(name); } } /** * @throws SAXException */ protected void doSkippedEntity(String name) throws SAXException { // by default do nothing } /** * @throws SAXException */ public final void unparsedEntityDecl(String name, String publicId, String systemId, String notationName) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.unparsedEntityDecl(name, publicId, systemId, notationName); } else { doUnparsedEntityDecl(name, publicId, systemId, notationName); } } /** * @throws SAXException */ protected void doUnparsedEntityDecl(String name, String publicId, String systemId, String notationName) throws SAXException { // by default do nothing } // ERROR HANDLING public final void warning(SAXParseException exception) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.warning(exception); } else { doWarning(exception); } } /** * @throws SAXException */ protected void doWarning(SAXParseException exception) throws SAXException { // by default do nothing } public final void error(SAXParseException exception) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.error(exception); } else { doError(exception); } } /** * @throws SAXException */ protected void doError(SAXParseException exception) throws SAXException { // by default do nothing } public final void fatalError(SAXParseException exception) throws SAXException { if (skip) { return; } if (delegate != null) { delegate.fatalError(exception); } else { doFatalError(exception); } } /** * @throws SAXException */ protected void doFatalError(SAXParseException exception) throws SAXException { // by default do nothing } // ////////////////////// // Functions related to error handling // ////////////////////// protected void log(int logLevel, String message) { log(logLevel, getLocator(), message); } protected void log(int logLevel, Locator/* <?> */locator, String message) { Message.log(logLevel, getLocation(locator) + message); } protected static String getLocation(Locator locator) { if (locator == null) { return ""; } return "[line " + locator.getLineNumber() + " col. " + locator.getColumnNumber() + "] "; } private void skipOnError(DelegetingHandler/* <?> */currentHandler, Class/* * <? extends * delegatingHandler> */handlerClassToSkip, String message) { DelegetingHandler/* <?> */handlerToSkip = currentHandler; while (!(handlerClassToSkip.isAssignableFrom(handlerToSkip.getClass()))) { handlerToSkip = handlerToSkip.getParent(); } log(Message.MSG_ERR, getLocator(), message + ". The '" + handlerToSkip.getName() + "' element " + getCurrentElementIdentifier() + " is then ignored."); handlerToSkip.skip(); } // ////////////////////// // Helpers to parse the attributes // ////////////////////// protected String getRequiredAttribute(Attributes atts, String name) throws SAXParseException { String value = atts.getValue(name); if (value == null) { throw new SAXParseException("Required attribute '" + name + "' not found", getLocator()); } return value; } protected String getOptionalAttribute(Attributes atts, String name, String defaultValue) { String value = atts.getValue(name); if (value == null) { return defaultValue; } return value; } protected int getRequiredIntAttribute(Attributes atts, String name, Integer logLevel) throws SAXParseException { return parseInt(name, getRequiredAttribute(atts, name)); } protected Integer getOptionalIntAttribute(Attributes atts, String name, Integer defaultValue) throws SAXParseException { String value = atts.getValue(name); if (value == null) { return defaultValue; } return Integer.valueOf(parseInt(name, value)); } private int parseInt(String name, String value) throws SAXParseException { try { return Integer.parseInt(value); } catch (NumberFormatException e) { throw new SAXParseException("Attribute '" + name + "' is expected to be an integer but was '" + value + "' (" + e.getMessage() + ")", getLocator()); } } protected long getRequiredLongAttribute(Attributes atts, String name) throws SAXParseException { return parseLong(name, getRequiredAttribute(atts, name)); } protected Long getOptionalLongAttribute(Attributes atts, String name, Long defaultValue) throws SAXParseException { String value = atts.getValue(name); if (value == null) { return defaultValue; } return Long.valueOf(parseLong(name, value)); } private long parseLong(String name, String value) throws SAXParseException { try { return Long.parseLong(value); } catch (NumberFormatException e) { throw new SAXParseException("Attribute '" + name + "' is expected to be an long but was '" + value + "' (" + e.getMessage() + ")", getLocator()); } } protected boolean getRequiredBooleanAttribute(Attributes atts, String name) throws SAXParseException { return parseBoolean(name, getRequiredAttribute(atts, name)); } protected Boolean getOptionalBooleanAttribute(Attributes atts, String name, Boolean defaultValue) throws SAXParseException { String value = atts.getValue(name); if (value == null) { return defaultValue; } return Boolean.valueOf(parseBoolean(name, value)); } static final String TRUE = Boolean.TRUE.toString().toLowerCase(Locale.US); static final String FALSE = Boolean.FALSE.toString().toLowerCase(Locale.US); private boolean parseBoolean(String name, String value) throws SAXParseException { String lowerValue = value.toLowerCase(Locale.US); if (lowerValue.equals(TRUE)) { return true; } if (lowerValue.equals(FALSE)) { return false; } throw new SAXParseException("Attribute '" + name + "' is expected to be a boolean but was '" + value + "'", getLocator()); } }
cleanup git-svn-id: bddd0b838a5b7898c5897d85c562f956f46262e5@1056065 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/ivy/osgi/util/DelegetingHandler.java
cleanup
Java
apache-2.0
fe1a1412478d4fac3f2c1cc9b51f93bf21a30438
0
trivago/triava
/********************************************************************************* * Copyright 2015-present trivago GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **********************************************************************************/ package com.trivago.triava.tcache.core; import java.util.ArrayList; import java.util.Collection; import java.util.Properties; import java.util.concurrent.atomic.AtomicInteger; import javax.cache.configuration.CacheEntryListenerConfiguration; import javax.cache.configuration.CompleteConfiguration; import javax.cache.configuration.Configuration; import javax.cache.configuration.Factory; import javax.cache.expiry.EternalExpiryPolicy; import javax.cache.expiry.ExpiryPolicy; import javax.cache.integration.CacheWriter; import com.trivago.triava.annotations.Beta; import com.trivago.triava.tcache.CacheWriteMode; import com.trivago.triava.tcache.EvictionPolicy; import com.trivago.triava.tcache.HashImplementation; import com.trivago.triava.tcache.JamPolicy; import com.trivago.triava.tcache.TCacheFactory; import com.trivago.triava.tcache.eviction.Cache; import com.trivago.triava.tcache.eviction.CacheLimit; import com.trivago.triava.tcache.eviction.LFUEviction; import com.trivago.triava.tcache.eviction.LRUEviction; import com.trivago.triava.tcache.storage.HighscalelibNonBlockingHashMap; import com.trivago.triava.tcache.storage.JavaConcurrentHashMap; /** * A Builder to create Cache instances. A Builder instance must be retrieved via a TCacheFactory, * to guarantee each created Cache will be registered in a CacheManager (Hint: The TCacheFactory * implements CacheManager). * * @author cesken * * @param <K> Key type * @param <V> Value type */ public class Builder<K,V> implements CompleteConfiguration<K, V> { private static final long serialVersionUID = -4430382287782891844L; static final AtomicInteger anonymousCacheId = new AtomicInteger(); static long MAX_IDLE_TIME = 1800; // DEFAULT: 30 minutes private String id; private boolean strictJSR107 = true; private long maxIdleTime = MAX_IDLE_TIME; // 30 minutes private long maxCacheTime = 3600; // 60 minutes private int maxCacheTimeSpread = 0; // 0 seconds private int expectedMapSize = 10000; private int concurrencyLevel = 14; private int mapConcurrencyLevel = 16; private EvictionPolicy evictionPolicy = EvictionPolicy.LFU; private EvictionInterface<K, V> evictionClass = null; private HashImplementation hashImplementation = HashImplementation.ConcurrentHashMap; private TCacheFactory factory = null; private JamPolicy jamPolicy = JamPolicy.WAIT; private boolean statistics = false; // off by JSR107 default private boolean management = false; // off by JSR107 default private CacheWriteMode writeMode = CacheWriteMode.Identity; private Class<K> keyType = objectKeyType(); private Class<V> valueType = objectValueType(); private Collection<CacheEntryListenerConfiguration<K, V>> listenerConfigurations = new ArrayList<>(0); private Factory<CacheWriter<? super K, ? super V>> writerFactory = null; private Factory<ExpiryPolicy> expiryPolicyFactory = EternalExpiryPolicy.factoryOf(); // TODO Evaluate this in the Cache constructor private CacheLoader<K, V> loader = null; private Factory<javax.cache.integration.CacheLoader<K, V>> loaderFactory = null; private boolean writeThrough = false; private boolean readThrough = false; /** * Native Builder for creating Cache instances. The returned object is initialized with default values. * The native Builder by default uses a STORE_BY_REFERENCE model instead of the JSR107 default of STORE_BY_VALUE. * <p> * Any Cache created by {@link #build()} is registered in the given factory/CacheManager. * * @param factory The associated managing TCacheFactory/CacheManager */ public Builder(TCacheFactory factory) { this.factory = factory; management = true; statistics = true; strictJSR107 = false; } /** * A Builder that is target for usage in JSR107 scenarios. * It takes a JSR107 Configuration object to define defaults, and its isStoreByValue() value * is converted to a CacheWriteMode using {@link CacheWriteMode#fromStoreByValue(boolean)}. * <p> * Defaults for this Builder are taken from the given * configuration, which can be a plain JSR107 Configuration or a Builder itself. The * given configuration is copied in both cases, so subsequent changes to the original object will have * no effect on this Builder or any Cache created from it. * <p> * Any Cache created by {@link #build()} is registered in the given factory/CacheManager. * * @param factory The associated managing TCacheFactory/CacheManager * @param configuration Cache Configuration, which can also be a Builder */ public Builder(TCacheFactory factory, Configuration<K,V> configuration) { this.factory = factory; copyBuilder(configuration, this); } /** * Builds a Cache from the parameters that were set. evictionType defines the eviction policy. Any not * explicitly set parameters will get a default values, which are: * * <pre> * private long maxIdleTime = 1800; * private long maxCacheTime = 3600; * private int expectedMapSize = 10000; * private int concurrencyLevel = 16; * private TCacheEvictionType evictionType = TCacheEvictionType.LFU; * * </pre> * * Any Cache created by {@link #build()} is registered in the associated factory/CacheManager. * * @return The Cache */ public Cache<K, V> build() { if (factory == null) { factory = TCacheFactory.standardFactory(); } if (id == null) { id = "tcache-" + anonymousCacheId.incrementAndGet(); } final Cache<K, V> cache; if (evictionClass != null) { cache = new CacheLimit<>(this); } else { switch (evictionPolicy) { case LFU: cache = new CacheLimit<>(this.setEvictionClass(new LFUEviction<K,V>())); break; case LRU: cache = new CacheLimit<>(this.setEvictionClass(new LRUEviction<K,V>())); break; // case CLOCK: // throw new UnsupportedOperationException("Experimental option is not activated: eviciton.CLOCK"); // break; // // ClockEviction requires a TimeSource, but it may not be active yet (or even worse will change) // // => either we need to activate the TimeSource here, or introduce an "Expiration Context" that provides the TimeSource // cache = new CacheLimit<>(this.setEvictionClass(new ClockEviction<K,V>())); case CUSTOM: cache = new CacheLimit<>(this); break; case NONE: cache = new Cache<>(this); break; default: throw new IllegalArgumentException("Invalid evictionPolicy=" + evictionPolicy); } } return cache; } public Builder<K,V> setId(String id) { this.id = id; return this; } /** * Sets the maximum time of an unused (idle) cache entry. * * @param maxIdleTime The maximum time * @return c */ public Builder<K,V> setMaxIdleTime(long maxIdleTime) { if (maxIdleTime == 0) this.maxIdleTime = MAX_IDLE_TIME; else this.maxIdleTime = maxIdleTime; return this; } /** * Sets the interval within a cache entry expires. The value in the interval [maxCacheTime, maxCacheTime+interval] * is selected pseudo-randomly for each individual entry put in the cache, unless an explicit expiration time is set in the put() operation. * <p> * This method is useful for mass-inserts in the Cache, that * should not expire at the same time (e.g. for resource reasons). * * @param maxCacheTime The minimum time to keep in seconds * @param interval The size of the interval in seconds * @return This Builder */ public Builder<K,V> setMaxCacheTime(long maxCacheTime, int interval) { this.maxCacheTime = maxCacheTime; this.maxCacheTimeSpread = interval; return this; } /** * Sets the default expiration time for entries in this cache. All entries use this time, unless it is * added using a put method that allows overriding the expiration time, like * {@link Cache#put(Object, Object, long, long)}. * * @param maxCacheTime * The time to keep the value in seconds * @return This Builder */ public Builder<K, V> setMaxCacheTime(long maxCacheTime) { this.maxCacheTime = maxCacheTime; return this; } /** * Sets the expected number of elements to be stored. Cache instances with eviction policy will start evicting * after reaching {@link #expectedMapSize}. Cache instances of unlimited size * {@link EvictionPolicy}.NONE will use this value only as a hint * for initially sizing the underlying storage structures. * * @param expectedMapSize The expected number of elements to be stored * @return This Builder */ public Builder<K,V> setExpectedMapSize(int expectedMapSize) { this.expectedMapSize = expectedMapSize; return this; } /** * Sets the expected concurrency level. In other words, the number of application Threads that concurrently write to the Cache. * The underlying ConcurrentMap will use the concurrencyLevel to tune its internal data structures for concurrent * usage. For example, the Java ConcurrentHashMap uses this value as-is. * Default is 14, and the minimum is 8. * <p> * If not set, the default concurrencyLevel is 16, which should usually rarely create thread contention. * If running with 12 cores (24 with hyperthreading) chances are not too high for contention. * A note from the Java 6 API docs: "overestimates and underestimates within an order * of magnitude do not usually have much noticeable impact." * <p> * For example, in a scenario where 150 Threads write concurrently via putIfAbsent(), only 12 Threads will * actually run. As concurrencyLevel is 16, threads will usually rarely block. But in case of unlucky hash * bucket distribution or if too many Threads get suspended during holding a lock, issues could arise. If the * underlying ConcurrentMap uses unfair locks, it might even lead to thread starvation. * * @param concurrencyLevel The excpected number of application Threads that concurrently write to the Cache * @return This Builder */ public Builder<K,V> setConcurrencyLevel(int concurrencyLevel) { this.concurrencyLevel = concurrencyLevel; this.mapConcurrencyLevel = Math.max(concurrencyLevel + 2, 8); return this; } /** * Sets the eviction policy, for example LFU or LRU. * <p> * If you want to use a custom eviction strategy, * use {@link #setEvictionClass(EvictionInterface)} instead. * * @param evictionPolicy The EvictionPolicy * @return This Builder */ public Builder<K,V> setEvictionPolicy(EvictionPolicy evictionPolicy) { this.evictionPolicy = evictionPolicy; this.evictionClass = null; return this; } /** * Sets a custom eviction policy. This is useful if the value V holds sensible information that can be used for * eviction. For example if V is a Session class, it could hold information about the user: Guest users may be evicted * before registered users, and the last chosen should be premium users. * <p> * If you want to use a standard eviction strategy like LFU or LRU, * use {@link #setEvictionPolicy(EvictionPolicy)} instead. * * @param clazz The instance that implements the eviction policy * @return This Builder */ public Builder<K,V> setEvictionClass(EvictionInterface<K, V> clazz) { this.evictionPolicy = EvictionPolicy.CUSTOM; this.evictionClass = clazz; return this; } /** * @return the evictionClass. null if there is no custom class */ public EvictionInterface<K, V> getEvictionClass() { return evictionClass; } /** * Set the StorageBackend for the underlying ConcurrentMap. If this method is not called, * ConcurrentHashMap will be used. * * @param hashImplementation The {@link HashImplementation} * @return This Builder * */ @Beta(comment="To be replaced by a method to set a StorageBackend") public Builder<K,V> setHashImplementation(HashImplementation hashImplementation) { this.hashImplementation = hashImplementation; return this; } /** * Sets the policy, how a Thread that calls put() will behave the cache is full. * Either the Thread will WAIT or DROP the element and not put it in the cache. * The default is WAIT. The {@link JamPolicy} has no effect on caches of unlimited size * {@link EvictionPolicy}}.NONE. * * @param jamPolicy The {@link JamPolicy} * @return This Builder */ public Builder<K,V> setJamPolicy(JamPolicy jamPolicy) { this.jamPolicy = jamPolicy; return this; } /** * @return the factory */ public TCacheFactory getFactory() { return factory; } /** * @param factory the factory to set */ public void setFactory(TCacheFactory factory) { this.factory = factory; } public boolean getStatistics() { return statistics; } /** * Sets whether statistics should be gathered. The performance impact on creating statistics is very low, * so it is safe to activate statistics. If this method is not called, the default is to collect statistics. * * @param statistics true, if you want to switch on statistics * @return This Builder */ public Builder<K,V> setStatistics(boolean statistics) { this.statistics = statistics; return this; } /** * @return the id */ public String getId() { return id; } /** * @return the maxIdleTime */ public long getMaxIdleTime() { return maxIdleTime; } /** * @return The lower bound of the "maximum cache time interval" [maxCacheTime, maxCacheTime+maxCacheTimeSpread] */ public long getMaxCacheTime() { return maxCacheTime; } /** * * @return The interval size of the cache time interval */ public int getMaxCacheTimeSpread() { return maxCacheTimeSpread; } /** * @return the expectedMapSize */ public int getExpectedMapSize() { return expectedMapSize; } /** * @return the concurrencyLevel */ public int getConcurrencyLevel() { return concurrencyLevel; } public int getMapConcurrencyLevel() { return mapConcurrencyLevel; } /** * @return the evictionPolicy */ public EvictionPolicy getEvictionPolicy() { return evictionPolicy; } /** * @return the hashImplementation */ public HashImplementation getHashImplementation() { return hashImplementation; } public StorageBackend<K, V> storageFactory() { switch (hashImplementation) { case ConcurrentHashMap: return new JavaConcurrentHashMap<K, V>(); // case PerfTestGuavaLocalCache: // return new GuavaLocalCache<K, V>(); case HighscalelibNonBlockingHashMap: return new HighscalelibNonBlockingHashMap<K, V>(); default: return null; } } public JamPolicy getJamPolicy() { return jamPolicy; } public CacheLoader<K, V> getLoader() { return (CacheLoader<K, V>) loader; } public Builder<K, V> setLoader(CacheLoader<K, V> loader) { this.loader = loader; return this; } @Override public Factory<javax.cache.integration.CacheLoader<K, V>> getCacheLoaderFactory() { return loaderFactory; } @SuppressWarnings("unchecked") @Override // JSR107 public Class<K> getKeyType() { return keyType == null ? (Class<K>)Object.class : keyType; } @Override // JSR107 public Class<V> getValueType() { return valueType; } public void setKeyType(Class<K> keyType) { this.keyType = keyType; } public void setValueType(Class<V> valueType) { this.valueType = valueType; } @Override // JSR107 public boolean isStoreByValue() { return writeMode.isStoreByValue(); } public enum PropsType { CacheManager, Cache }; // should be package-private /** * Returns a representation of the Configuration as Properties. * The returned properties are a private copy for the caller and thus not shared amongst different callers. * Changes to the returned Properties have no effect on the Cache. * * @param propsType If PropsType.CacheManager, the Cache specific properties (cacheName, cacheLoaderClass) are excluded * @return The current configuration */ public Properties asProperties(PropsType propsType) { boolean propsForCache = propsType == PropsType.Cache; Properties props = new Properties(); if (propsForCache) props.setProperty("cacheName", id); props.setProperty("maxIdleTime", Long.toString(maxIdleTime)); props.setProperty("maxCacheTime", Long.toString(maxCacheTime)); props.setProperty("maxCacheTimeSpread", Long.toString(maxCacheTimeSpread)); props.setProperty("expectedMapSize", Integer.toString(expectedMapSize)); props.setProperty("concurrencyLevel", Integer.toString(concurrencyLevel)); props.setProperty("evictionPolicy", evictionPolicy.toString()); props.setProperty("hashMapClass", hashImplementation.toString()); props.setProperty("jamPolicy", jamPolicy.toString()); props.setProperty("statistics", Boolean.toString(statistics)); if (propsForCache) props.setProperty("cacheLoaderClass", loader == null ? "null" : loader.getClass().getName()); props.setProperty("writeMode", writeMode.toString()); return props; } /** * Copies the configuration to the target Builder. If the source (configuration) * is also a Builder, its fields also get copied. Any null-value in the * configuration is ignored in the copying process, leaving the corresponding * target value unchanged. The CacheWriteMode can be * defined in two ways: If configuration is a Builder it is copied plainly, * otherwise it is derived from configuration.isStoreByValue(). * * @param configuration The source builder * @param target The target builder */ private void copyBuilder(Configuration<K, V> configuration, Builder<K, V> target) { CacheWriteMode tcacheWriteMode = null; if (configuration instanceof Builder) { Builder<K, V> sourceB = (Builder<K, V>)configuration; // tCache native configuration if (sourceB.id != null) target.id = sourceB.id; target.strictJSR107 = sourceB.strictJSR107; target.maxIdleTime = sourceB.maxIdleTime; target.maxCacheTime = sourceB.maxCacheTime; target.maxCacheTimeSpread = sourceB.maxCacheTimeSpread; target.expectedMapSize = sourceB.expectedMapSize; target.concurrencyLevel = sourceB.concurrencyLevel; if (sourceB.evictionPolicy != null) target.evictionPolicy = sourceB.evictionPolicy; if (sourceB.evictionClass != null) target.evictionClass = sourceB.evictionClass; if (sourceB.hashImplementation != null) target.hashImplementation = sourceB.hashImplementation; if (sourceB.jamPolicy != null) target.jamPolicy = sourceB.jamPolicy; if (sourceB.loader != null) target.loader = sourceB.loader; // loader vs loaderFactory tcacheWriteMode = sourceB.writeMode; } if (configuration instanceof CompleteConfiguration) { CompleteConfiguration<K,V> cc = (CompleteConfiguration<K,V>)configuration; target.statistics = cc.isStatisticsEnabled(); target.management = cc.isManagementEnabled(); target.expiryPolicyFactory = cc.getExpiryPolicyFactory(); target.writerFactory = cc.getCacheWriterFactory(); Factory<javax.cache.integration.CacheLoader<K, V>> lf = cc.getCacheLoaderFactory(); if (lf != null) { target.loader = null; // loader vs loaderFactory target.loaderFactory = lf; } Collection<CacheEntryListenerConfiguration<K, V>> listenerConfsCopy = new ArrayList<>(0); for (CacheEntryListenerConfiguration<K, V> entry : cc.getCacheEntryListenerConfigurations()) { listenerConfsCopy.add(entry); } target.listenerConfigurations = listenerConfsCopy; target.writeThrough = cc.isWriteThrough(); target.readThrough = cc.isReadThrough(); } // JSR107 configuration follows if (tcacheWriteMode != null) target.writeMode = tcacheWriteMode; else target.writeMode = CacheWriteMode.fromStoreByValue(configuration.isStoreByValue()); target.keyType = configuration.getKeyType(); target.valueType = configuration.getValueType(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + concurrencyLevel; result = prime * result + ((evictionClass == null) ? 0 : evictionClass.hashCode()); result = prime * result + ((evictionPolicy == null) ? 0 : evictionPolicy.hashCode()); result = prime * result + expectedMapSize; result = prime * result + ((factory == null) ? 0 : factory.hashCode()); result = prime * result + ((hashImplementation == null) ? 0 : hashImplementation.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((jamPolicy == null) ? 0 : jamPolicy.hashCode()); result = prime * result + ((keyType == null) ? 0 : keyType.hashCode()); result = prime * result + ((loader == null) ? 0 : loader.hashCode()); result = prime * result + mapConcurrencyLevel; result = prime * result + (int) (maxCacheTime ^ (maxCacheTime >>> 32)); result = prime * result + maxCacheTimeSpread; result = prime * result + (int) (maxIdleTime ^ (maxIdleTime >>> 32)); result = prime * result + (statistics ? 1231 : 1237); result = prime * result + ((valueType == null) ? 0 : valueType.hashCode()); result = prime * result + ((writeMode == null) ? 0 : writeMode.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; if (! (obj instanceof Builder)) return false; Builder<?,?> other = (Builder<?,?>) obj; if (concurrencyLevel != other.concurrencyLevel) return false; if (evictionClass == null) { if (other.evictionClass != null) return false; } else if (!evictionClass.equals(other.evictionClass)) return false; if (evictionPolicy != other.evictionPolicy) return false; if (expectedMapSize != other.expectedMapSize) return false; if (factory == null) { if (other.factory != null) return false; } else if (!factory.equals(other.factory)) return false; if (hashImplementation != other.hashImplementation) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (jamPolicy != other.jamPolicy) return false; if (keyType == null) { if (other.keyType != null) return false; } else if (!keyType.equals(other.keyType)) return false; if (loader == null) { if (other.loader != null) return false; } else if (!loader.equals(other.loader)) return false; if (mapConcurrencyLevel != other.mapConcurrencyLevel) return false; if (maxCacheTime != other.maxCacheTime) return false; if (maxCacheTimeSpread != other.maxCacheTimeSpread) return false; if (maxIdleTime != other.maxIdleTime) return false; if (statistics != other.statistics) return false; if (valueType == null) { if (other.valueType != null) return false; } else if (!valueType.equals(other.valueType)) return false; if (writeMode != other.writeMode) return false; return true; } @Override public boolean isReadThrough() { return readThrough; } public Builder<K, V> setCacheLoaderFactory(Factory<javax.cache.integration.CacheLoader<K, V>> loaderFactory) { this.loaderFactory = loaderFactory; return this; } @SuppressWarnings("unchecked") public Builder<K, V> setCacheWriterFactory( Factory<? extends CacheWriter<? super K, ? super V>> factory) { this.writerFactory = (Factory<CacheWriter<? super K, ? super V>>) factory; return this; } public Builder<K, V> setReadThrough(boolean isReadThrough) { this.readThrough = isReadThrough; return this; } public Builder<K, V> setWriteThrough(boolean isWriteThrough) { this.writeThrough = isWriteThrough; return this; } @Override public boolean isWriteThrough() { return writeThrough; } @Override public boolean isStatisticsEnabled() { return statistics; } @Override public boolean isManagementEnabled() { return management; } /** * Returns whether the Cache behaves strictly JSR107 compliant * * @return true if the Cache behaves strictly JSR107 compliant */ public boolean isStrictJSR107() { return strictJSR107; } public void setStrictJSR107(boolean strictJSR107) { this.strictJSR107 = strictJSR107; } @Override public Iterable<CacheEntryListenerConfiguration<K, V>> getCacheEntryListenerConfigurations() { return listenerConfigurations; } @Override public Factory<CacheWriter<? super K, ? super V>> getCacheWriterFactory() { return writerFactory; } @Override public Factory<ExpiryPolicy> getExpiryPolicyFactory() { return expiryPolicyFactory; } void setExpiryPolicyFactory(Factory<ExpiryPolicy> expiryPolicyFactory) { this.expiryPolicyFactory = expiryPolicyFactory; } /** * Return Object.class casted suitably for {@link #getValueType()} * @return Object.class */ @SuppressWarnings("unchecked") private Class<V> objectValueType() { return (Class<V>)Object.class; } /** * Return Object.class casted suitably for {@link #getKeyType()} * @return Object.class */ @SuppressWarnings("unchecked") private Class<K> objectKeyType() { return (Class<K>)Object.class; } public void addCacheEntryListenerConfiguration(CacheEntryListenerConfiguration<K, V> listenerConfiguration) { listenerConfigurations.add(listenerConfiguration); } public void removeCacheEntryListenerConfiguration(CacheEntryListenerConfiguration<K, V> listenerConfiguration) { listenerConfigurations.remove(listenerConfiguration); } }
src/main/java/com/trivago/triava/tcache/core/Builder.java
/********************************************************************************* * Copyright 2015-present trivago GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **********************************************************************************/ package com.trivago.triava.tcache.core; import java.util.ArrayList; import java.util.Collection; import java.util.Properties; import java.util.concurrent.atomic.AtomicInteger; import javax.cache.configuration.CacheEntryListenerConfiguration; import javax.cache.configuration.CompleteConfiguration; import javax.cache.configuration.Configuration; import javax.cache.configuration.Factory; import javax.cache.expiry.EternalExpiryPolicy; import javax.cache.expiry.ExpiryPolicy; import javax.cache.integration.CacheWriter; import com.trivago.triava.annotations.Beta; import com.trivago.triava.tcache.CacheWriteMode; import com.trivago.triava.tcache.EvictionPolicy; import com.trivago.triava.tcache.HashImplementation; import com.trivago.triava.tcache.JamPolicy; import com.trivago.triava.tcache.TCacheFactory; import com.trivago.triava.tcache.eviction.Cache; import com.trivago.triava.tcache.eviction.CacheLimit; import com.trivago.triava.tcache.eviction.LFUEviction; import com.trivago.triava.tcache.eviction.LRUEviction; import com.trivago.triava.tcache.storage.HighscalelibNonBlockingHashMap; import com.trivago.triava.tcache.storage.JavaConcurrentHashMap; /** * A Builder to create Cache instances. A Builder instance must be retrieved via a TCacheFactory, * to guarantee each created Cache will be registered in a CacheManager (Hint: The TCacheFactory * implements CacheManager). * * @author cesken * * @param <K> Key type * @param <V> Value type */ public class Builder<K,V> implements CompleteConfiguration<K, V> { private static final long serialVersionUID = -4430382287782891844L; static final AtomicInteger anonymousCacheId = new AtomicInteger(); static long MAX_IDLE_TIME = 1800; // DEFAULT: 30 minutes private String id; private boolean strictJSR107 = true; private long maxIdleTime = MAX_IDLE_TIME; // 30 minutes private long maxCacheTime = 3600; // 60 minutes private int maxCacheTimeSpread = 0; // 0 seconds private int expectedMapSize = 10000; private int concurrencyLevel = 14; private int mapConcurrencyLevel = 16; private EvictionPolicy evictionPolicy = EvictionPolicy.LFU; private EvictionInterface<K, V> evictionClass = null; private HashImplementation hashImplementation = HashImplementation.ConcurrentHashMap; private TCacheFactory factory = null; private JamPolicy jamPolicy = JamPolicy.WAIT; private boolean statistics = false; // off by JSR107 default private boolean management = false; // off by JSR107 default private CacheWriteMode writeMode = CacheWriteMode.Identity; private Class<K> keyType = objectKeyType(); private Class<V> valueType = objectValueType(); private Collection<CacheEntryListenerConfiguration<K, V>> listenerConfigurations = new ArrayList<>(0); private Factory<CacheWriter<? super K, ? super V>> writerFactory = null; private Factory<ExpiryPolicy> expiryPolicyFactory = EternalExpiryPolicy.factoryOf(); // TODO Evaluate this in the Cache constructor private CacheLoader<K, V> loader = null; private Factory<javax.cache.integration.CacheLoader<K, V>> loaderFactory = null; private boolean writeThrough = false; private boolean readThrough = false; /** * Native Builder for creating Cache instances. The returned object is initialized with default values. * The native Builder by default uses a STORE_BY_REFERENCE model instead of the JSR107 default of STORE_BY_VALUE. * <p> * Any Cache created by {@link #build()} is registered in the given factory/CacheManager. * * @param factory The associated managing TCacheFactory/CacheManager */ public Builder(TCacheFactory factory) { this.factory = factory; management = true; statistics = true; strictJSR107 = false; } /** * A Builder that is target for usage in JSR107 scenarios. * It takes a JSR107 Configuration object to define defaults, and its isStoreByValue() value * is converted to a CacheWriteMode using {@link CacheWriteMode#fromStoreByValue(boolean)}. * <p> * Defaults for this Builder are taken from the given * configuration, which can be a plain JSR107 Configuration or a Builder itself. The * given configuration is copied in both cases, so subsequent changes to the original object will have * no effect on this Builder or any Cache created from it. * <p> * Any Cache created by {@link #build()} is registered in the given factory/CacheManager. * * @param factory The associated managing TCacheFactory/CacheManager * @param configuration Cache Configuration, which can also be a Builder */ public Builder(TCacheFactory factory, Configuration<K,V> configuration) { this.factory = factory; copyBuilder(configuration, this); } /** * Builds a Cache from the parameters that were set. evictionType defines the eviction policy. Any not * explicitly set parameters will get a default values, which are: * * <pre> * private long maxIdleTime = 1800; * private long maxCacheTime = 3600; * private int expectedMapSize = 10000; * private int concurrencyLevel = 16; * private TCacheEvictionType evictionType = TCacheEvictionType.LFU; * * </pre> * * Any Cache created by {@link #build()} is registered in the associated factory/CacheManager. * * @return The Cache */ public Cache<K, V> build() { if (factory == null) { factory = TCacheFactory.standardFactory(); } if (id == null) { id = "tcache-" + anonymousCacheId.incrementAndGet(); } final Cache<K, V> cache; if (evictionClass != null) { cache = new CacheLimit<>(this); } else { switch (evictionPolicy) { case LFU: cache = new CacheLimit<>(this.setEvictionClass(new LFUEviction<K,V>())); break; case LRU: cache = new CacheLimit<>(this.setEvictionClass(new LRUEviction<K,V>())); break; // case CLOCK: // throw new UnsupportedOperationException("Experimental option is not activated: eviciton.CLOCK"); // break; // // ClockEviction requires a TimeSource, but it may not be active yet (or even worse will change) // // => either we need to activate the TimeSource here, or introduce an "Expiration Context" that provides the TimeSource // cache = new CacheLimit<>(this.setEvictionClass(new ClockEviction<K,V>())); case CUSTOM: cache = new CacheLimit<>(this); break; case NONE: cache = new Cache<>(this); break; default: throw new IllegalArgumentException("Invalid evictionPolicy=" + evictionPolicy); } } return cache; } public Builder<K,V> setId(String id) { this.id = id; return this; } /** * Sets the maximum time of an unused (idle) cache entry. * * @param maxIdleTime The maximum time * @return c */ public Builder<K,V> setMaxIdleTime(long maxIdleTime) { if (maxIdleTime == 0) this.maxIdleTime = MAX_IDLE_TIME; else this.maxIdleTime = maxIdleTime; return this; } /** * Sets the interval within a cache entry expires. The value in the interval [maxCacheTime, maxCacheTime+interval] * is selected pseudo-randomly for each individual entry put in the cache, unless an explicit expiration time is set in the put() operation. * <p> * This method is useful for mass-inserts in the Cache, that * should not expire at the same time (e.g. for resource reasons). * * @param maxCacheTime The minimum time to keep in seconds * @param interval The size of the interval in seconds * @return This Builder */ public Builder<K,V> setMaxCacheTime(long maxCacheTime, int interval) { this.maxCacheTime = maxCacheTime; this.maxCacheTimeSpread = interval; return this; } /** * Sets the default expiration time for entries in this cache. All entries use this time, unless it is * added using a put method that allows overriding the expiration time, like * {@link Cache#put(Object, Object, long, long)}. * * @param maxCacheTime * The time to keep the value in seconds * @return This Builder */ public Builder<K, V> setMaxCacheTime(long maxCacheTime) { this.maxCacheTime = maxCacheTime; return this; } /** * Sets the expected number of elements to be stored. Cache instances with eviction policy will start evicting * after reaching {@link #expectedMapSize}. Cache instances of unlimited size * {@link EvictionPolicy}.NONE will use this value only as a hint * for initially sizing the underlying storage structures. * * @param expectedMapSize The expected number of elements to be stored * @return This Builder */ public Builder<K,V> setExpectedMapSize(int expectedMapSize) { this.expectedMapSize = expectedMapSize; return this; } /** * Sets the expected concurrency level. In other words, the number of application Threads that concurrently write to the Cache. * The underlying ConcurrentMap will use the concurrencyLevel to tune its internal data structures for concurrent * usage. For example, the Java ConcurrentHashMap uses this value as-is. * Default is 14, and the minimum is 8. * <p> * If not set, the default concurrencyLevel is 16, which should usually rarely create thread contention. * If running with 12 cores (24 with hyperthreading) chances are not too high for contention. * A note from the Java 6 API docs: "overestimates and underestimates within an order * of magnitude do not usually have much noticeable impact." * <p> * For example, in a scenario where 150 Threads write concurrently via putIfAbsent(), only 12 Threads will * actually run. As concurrencyLevel is 16, threads will usually rarely block. But in case of unlucky hash * bucket distribution or if too many Threads get suspended during holding a lock, issues could arise. If the * underlying ConcurrentMap uses unfair locks, it might even lead to thread starvation. * * @param concurrencyLevel The excpected number of application Threads that concurrently write to the Cache * @return This Builder */ public Builder<K,V> setConcurrencyLevel(int concurrencyLevel) { this.concurrencyLevel = concurrencyLevel; this.mapConcurrencyLevel = Math.max(concurrencyLevel + 2, 8); return this; } /** * Sets the eviction policy, for example LFU or LRU. * <p> * If you want to use a custom eviction strategy, * use {@link #setEvictionClass(EvictionInterface)} instead. * * @param evictionPolicy The EvictionPolicy * @return This Builder */ public Builder<K,V> setEvictionPolicy(EvictionPolicy evictionPolicy) { this.evictionPolicy = evictionPolicy; this.evictionClass = null; return this; } /** * Sets a custom eviction policy. This is useful if the value V holds sensible information that can be used for * eviction. For example if V is a Session class, it could hold information about the user: Guest users may be evicted * before registered users, and the last chosen should be premium users. * <p> * If you want to use a standard eviction strategy like LFU or LRU, * use {@link #setEvictionPolicy(EvictionPolicy)} instead. * * @param clazz The instance that implements the eviction policy * @return This Builder */ public Builder<K,V> setEvictionClass(EvictionInterface<K, V> clazz) { this.evictionPolicy = EvictionPolicy.CUSTOM; this.evictionClass = clazz; return this; } /** * @return the evictionClass. null if there is no custom class */ public EvictionInterface<K, V> getEvictionClass() { return evictionClass; } /** * Set the StorageBackend for the underlying ConcurrentMap. If this method is not called, * ConcurrentHashMap will be used. * * @param hashImplementation The {@link HashImplementation} * @return This Builder * */ @Beta(comment="To be replaced by a method to set a StorageBackend") public Builder<K,V> setHashImplementation(HashImplementation hashImplementation) { this.hashImplementation = hashImplementation; return this; } /** * Sets the policy, how a Thread that calls put() will behave the cache is full. * Either the Thread will WAIT or DROP the element and not put it in the cache. * The default is WAIT. The {@link JamPolicy} has no effect on caches of unlimited size * {@link EvictionPolicy}}.NONE. * * @param jamPolicy The {@link JamPolicy} * @return This Builder */ public Builder<K,V> setJamPolicy(JamPolicy jamPolicy) { this.jamPolicy = jamPolicy; return this; } /** * @return the factory */ public TCacheFactory getFactory() { return factory; } /** * @param factory the factory to set */ public void setFactory(TCacheFactory factory) { this.factory = factory; } public boolean getStatistics() { return statistics; } /** * Sets whether statistics should be gathered. The performance impact on creating statistics is very low, * so it is safe to activate statistics. If this method is not called, the default is to collect statistics. * * @param statistics true, if you want to switch on statistics * @return This Builder */ public Builder<K,V> setStatistics(boolean statistics) { this.statistics = statistics; return this; } /** * @return the id */ public String getId() { return id; } /** * @return the maxIdleTime */ public long getMaxIdleTime() { return maxIdleTime; } /** * @return The lower bound of the "maximum cache time interval" [maxCacheTime, maxCacheTime+maxCacheTimeSpread] */ public long getMaxCacheTime() { return maxCacheTime; } /** * * @return The interval size of the cache time interval */ public int getMaxCacheTimeSpread() { return maxCacheTimeSpread; } /** * @return the expectedMapSize */ public int getExpectedMapSize() { return expectedMapSize; } /** * @return the concurrencyLevel */ public int getConcurrencyLevel() { return concurrencyLevel; } public int getMapConcurrencyLevel() { return mapConcurrencyLevel; } /** * @return the evictionPolicy */ public EvictionPolicy getEvictionPolicy() { return evictionPolicy; } /** * @return the hashImplementation */ public HashImplementation getHashImplementation() { return hashImplementation; } public StorageBackend<K, V> storageFactory() { switch (hashImplementation) { case ConcurrentHashMap: return new JavaConcurrentHashMap<K, V>(); // case PerfTestGuavaLocalCache: // return new GuavaLocalCache<K, V>(); case HighscalelibNonBlockingHashMap: return new HighscalelibNonBlockingHashMap<K, V>(); default: return null; } } public JamPolicy getJamPolicy() { return jamPolicy; } public CacheLoader<K, V> getLoader() { return (CacheLoader<K, V>) loader; } public Builder<K, V> setLoader(CacheLoader<K, V> loader) { this.loader = loader; return this; } @Override public Factory<javax.cache.integration.CacheLoader<K, V>> getCacheLoaderFactory() { return loaderFactory; } @SuppressWarnings("unchecked") @Override // JSR107 public Class<K> getKeyType() { return keyType == null ? (Class<K>)Object.class : keyType; } @Override // JSR107 public Class<V> getValueType() { return valueType; } public void setKeyType(Class<K> keyType) { this.keyType = keyType; } public void setValueType(Class<V> valueType) { this.valueType = valueType; } @Override // JSR107 public boolean isStoreByValue() { return writeMode.isStoreByValue(); } public enum PropsType { CacheManager, Cache }; // should be package-private /** * Returns a representation of the Configuration as Properties. * The returned properties are a private copy for the caller and thus not shared amongst different callers. * Changes to the returned Properties have no effect on the Cache. * * @param propsType If PropsType.CacheManager, the Cache specific properties (cacheName, cacheLoaderClass) are excluded * @return The current configuration */ public Properties asProperties(PropsType propsType) { boolean propsForCache = propsType == PropsType.Cache; Properties props = new Properties(); if (propsForCache) props.setProperty("cacheName", id); props.setProperty("maxIdleTime", Long.toString(maxIdleTime)); props.setProperty("maxCacheTime", Long.toString(maxCacheTime)); props.setProperty("maxCacheTimeSpread", Long.toString(maxCacheTimeSpread)); props.setProperty("expectedMapSize", Integer.toString(expectedMapSize)); props.setProperty("concurrencyLevel", Integer.toString(concurrencyLevel)); props.setProperty("evictionPolicy", evictionPolicy.toString()); props.setProperty("hashMapClass", hashImplementation.toString()); props.setProperty("jamPolicy", jamPolicy.toString()); props.setProperty("statistics", Boolean.toString(statistics)); if (propsForCache) props.setProperty("cacheLoaderClass", loader == null ? "null" : loader.getClass().getName()); props.setProperty("writeMode", writeMode.toString()); return props; } /** * Copies the configuration to the target Builder. If the source (configuration) * is also a Builder, its fields also get copied. Any null-value in the * configuration is ignored in the copying process, leaving the corresponding * target value unchanged. The CacheWriteMode can be * defined in two ways: If configuration is a Builder it is copied plainly, * otherwise it is derived from configuration.isStoreByValue(). * * @param configuration The source builder * @param target The target builder */ private void copyBuilder(Configuration<K, V> configuration, Builder<K, V> target) { CacheWriteMode tcacheWriteMode = null; if (configuration instanceof Builder) { Builder<K, V> sourceB = (Builder<K, V>)configuration; // tCache native configuration if (sourceB.id != null) target.id = sourceB.id; target.strictJSR107 = sourceB.strictJSR107; target.maxIdleTime = sourceB.maxIdleTime; target.maxCacheTime = sourceB.maxCacheTime; target.maxCacheTimeSpread = sourceB.maxCacheTimeSpread; target.expectedMapSize = sourceB.expectedMapSize; target.concurrencyLevel = sourceB.concurrencyLevel; if (sourceB.evictionPolicy != null) target.evictionPolicy = sourceB.evictionPolicy; if (sourceB.evictionClass != null) target.evictionClass = sourceB.evictionClass; if (sourceB.hashImplementation != null) target.hashImplementation = sourceB.hashImplementation; if (sourceB.jamPolicy != null) target.jamPolicy = sourceB.jamPolicy; if (sourceB.loader != null) target.loader = sourceB.loader; // loader vs loaderFactory tcacheWriteMode = sourceB.writeMode; } if (configuration instanceof CompleteConfiguration) { CompleteConfiguration<K,V> cc = (CompleteConfiguration<K,V>)configuration; target.statistics = cc.isStatisticsEnabled(); target.management = cc.isManagementEnabled(); target.expiryPolicyFactory = cc.getExpiryPolicyFactory(); target.writerFactory = cc.getCacheWriterFactory(); Factory<javax.cache.integration.CacheLoader<K, V>> lf = cc.getCacheLoaderFactory(); if (lf != null) { target.loader = null; // loader vs loaderFactory target.loaderFactory = lf; } Collection<CacheEntryListenerConfiguration<K, V>> listenerConfsCopy = new ArrayList<>(0); for (CacheEntryListenerConfiguration<K, V> entry : cc.getCacheEntryListenerConfigurations()) { listenerConfsCopy.add(entry); } target.listenerConfigurations = listenerConfsCopy; target.writeThrough = cc.isWriteThrough(); target.readThrough = cc.isReadThrough(); } // JSR107 configuration follows if (tcacheWriteMode != null) target.writeMode = tcacheWriteMode; else target.writeMode = CacheWriteMode.fromStoreByValue(configuration.isStoreByValue()); target.keyType = configuration.getKeyType(); target.valueType = configuration.getValueType(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + concurrencyLevel; result = prime * result + ((evictionClass == null) ? 0 : evictionClass.hashCode()); result = prime * result + ((evictionPolicy == null) ? 0 : evictionPolicy.hashCode()); result = prime * result + expectedMapSize; result = prime * result + ((factory == null) ? 0 : factory.hashCode()); result = prime * result + ((hashImplementation == null) ? 0 : hashImplementation.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((jamPolicy == null) ? 0 : jamPolicy.hashCode()); result = prime * result + ((keyType == null) ? 0 : keyType.hashCode()); result = prime * result + ((loader == null) ? 0 : loader.hashCode()); result = prime * result + mapConcurrencyLevel; result = prime * result + (int) (maxCacheTime ^ (maxCacheTime >>> 32)); result = prime * result + maxCacheTimeSpread; result = prime * result + (int) (maxIdleTime ^ (maxIdleTime >>> 32)); result = prime * result + (statistics ? 1231 : 1237); result = prime * result + ((valueType == null) ? 0 : valueType.hashCode()); result = prime * result + ((writeMode == null) ? 0 : writeMode.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; if (! (obj instanceof Builder)) return false; Builder<?,?> other = (Builder<?,?>) obj; if (concurrencyLevel != other.concurrencyLevel) return false; if (evictionClass == null) { if (other.evictionClass != null) return false; } else if (!evictionClass.equals(other.evictionClass)) return false; if (evictionPolicy != other.evictionPolicy) return false; if (expectedMapSize != other.expectedMapSize) return false; if (factory == null) { if (other.factory != null) return false; } else if (!factory.equals(other.factory)) return false; if (hashImplementation != other.hashImplementation) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (jamPolicy != other.jamPolicy) return false; if (keyType == null) { if (other.keyType != null) return false; } else if (!keyType.equals(other.keyType)) return false; if (loader == null) { if (other.loader != null) return false; } else if (!loader.equals(other.loader)) return false; if (mapConcurrencyLevel != other.mapConcurrencyLevel) return false; if (maxCacheTime != other.maxCacheTime) return false; if (maxCacheTimeSpread != other.maxCacheTimeSpread) return false; if (maxIdleTime != other.maxIdleTime) return false; if (statistics != other.statistics) return false; if (valueType == null) { if (other.valueType != null) return false; } else if (!valueType.equals(other.valueType)) return false; if (writeMode != other.writeMode) return false; return true; } @Override public boolean isReadThrough() { return readThrough; } public Builder<K, V> setCacheLoaderFactory(Factory<javax.cache.integration.CacheLoader<K, V>> loaderFactory) { this.loaderFactory = loaderFactory; return this; } @SuppressWarnings("unchecked") public Builder<K, V> setCacheWriterFactory( Factory<? extends CacheWriter<? super K, ? super V>> factory) { this.writerFactory = (Factory<CacheWriter<? super K, ? super V>>) factory; return this; } public Builder<K, V> setReadThrough(boolean isReadThrough) { this.readThrough = isReadThrough; return this; } public Builder<K, V> setWriteThrough(boolean isWriteThrough) { this.writeThrough = isWriteThrough; return this; } @Override public boolean isWriteThrough() { return writeThrough; } @Override public boolean isStatisticsEnabled() { return statistics; } @Override public boolean isManagementEnabled() { return management; } /** * Returns whether the Cache behaves strictly JSR107 compliant * * @return true if the Cache behaves strictly JSR107 compliant */ public boolean isStrictJSR107() { return strictJSR107; } public void setStrictJSR107(boolean strictJSR107) { this.strictJSR107 = strictJSR107; } @Override public Iterable<CacheEntryListenerConfiguration<K, V>> getCacheEntryListenerConfigurations() { return listenerConfigurations; } @Override public Factory<CacheWriter<? super K, ? super V>> getCacheWriterFactory() { return writerFactory; } @Override public Factory<ExpiryPolicy> getExpiryPolicyFactory() { return expiryPolicyFactory; } /** * Return Object.class casted suitably for {@link #getValueType()} * @return Object.class */ @SuppressWarnings("unchecked") private Class<V> objectValueType() { return (Class<V>)Object.class; } /** * Return Object.class casted suitably for {@link #getKeyType()} * @return Object.class */ @SuppressWarnings("unchecked") private Class<K> objectKeyType() { return (Class<K>)Object.class; } public void addCacheEntryListenerConfiguration(CacheEntryListenerConfiguration<K, V> listenerConfiguration) { listenerConfigurations.add(listenerConfiguration); } public void removeCacheEntryListenerConfiguration(CacheEntryListenerConfiguration<K, V> listenerConfiguration) { listenerConfigurations.remove(listenerConfiguration); } }
SAE-94 Prepare JSR107 expiration support Expiration support in JSR107 is pretty well, with expiration based on adding and accessing the entry, and also with automatic spreading. And it can be even better when supporting JSR107, so lets start with adding a setter.
src/main/java/com/trivago/triava/tcache/core/Builder.java
SAE-94 Prepare JSR107 expiration support
Java
apache-2.0
f4f6e81b711d62f7059b401dd22e2bfa6e561eb4
0
mureinik/commons-lang,rikles/commons-lang,anzhdanov/seeding-realistic-concurrency-bugs,mureinik/commons-lang,mureinik/commons-lang,anzhdanov/seeding-realistic-concurrency-bugs,rikles/commons-lang,anzhdanov/seeding-realistic-concurrency-bugs,rikles/commons-lang
/* * 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.lang3; /** * Immutable concrete manifestation of the {@link Pair} type. * * <p>#ThreadSafe# if the objects are threadsafe</p> * @since Lang 3.0 * @author Matt Benson * @version $Id$ * * @param <L> left generic type * @param <R> right generic type */ public class ImmutablePair<L, R> extends Pair<L, R> { /** Serialization version */ private static final long serialVersionUID = 4954918890077093841L; /** Left object */ public final L left; /** Right object */ public final R right; /** * Create a new ImmutablePair instance. * * @param left the left value * @param right the right value */ public ImmutablePair(L left, R right) { super(); this.left = left; this.right = right; } /** * {@inheritDoc} */ @Override public L getLeftElement() { return left; } /** * {@inheritDoc} */ @Override public R getRightElement() { return right; } /** * {@link java.util.Map.Entry#setValue(Object)} implementation. Because this * class is immutable the {@code setValue()} operation is not supported. * Therefore always an exception is thrown. * * @param value the value to set * @return the old right value * @throws UnsupportedOperationException as this operation is not supported */ public R setValue(R value) { throw new UnsupportedOperationException(); } /** * Static fluent creation method for an {@link ImmutablePair}<L, R>: * <code>ImmutablePair.of(left, right)</code> * * @param <L> the left generic type * @param <R> the right generic type * @param left the let value * @param right the right value * @return ImmutablePair<L, R>(left, right) */ public static <L, R> ImmutablePair<L, R> of(L left, R right) { return new ImmutablePair<L, R>(left, right); } }
src/main/java/org/apache/commons/lang3/ImmutablePair.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.lang3; /** * Immutable concrete manifestation of the {@link Pair} type. * * <p>#ThreadSafe# if the objects are threadsafe</p> * @since Lang 3.0 * @author Matt Benson * @version $Id$ * * @param <L> left generic type * @param <R> right generic type */ public class ImmutablePair<L, R> extends Pair<L, R> { /** Serialization version */ private static final long serialVersionUID = 4954918890077093841L; /** Left object */ public final L left; /** Right object */ public final R right; /** * Create a new ImmutablePair instance. * * @param left the left value * @param right the right value */ public ImmutablePair(L left, R right) { super(); this.left = left; this.right = right; } /** * {@inheritDoc} */ @Override public L getLeftElement() { return left; } /** * {@inheritDoc} */ @Override public R getRightElement() { return right; } /** * {@link java.util.Map.Entry#setValue(Object)} implementation. Because this * class is immutable the {@code setValue()} operation is not supported. * Therefore always an exception is thrown. * * @param value the value to set * @throws UnsupportedOperationException as this operation is not supported */ public R setValue(R value) { throw new UnsupportedOperationException(); } /** * Static fluent creation method for an {@link ImmutablePair}<L, R>: * <code>ImmutablePair.of(left, right)</code> * * @param <L> the left generic type * @param <R> the right generic type * @param left the let value * @param right the right value * @return ImmutablePair<L, R>(left, right) */ public static <L, R> ImmutablePair<L, R> of(L left, R right) { return new ImmutablePair<L, R>(left, right); } }
git-svn-id: https://svn.apache.org/repos/asf/commons/proper/lang/trunk@1083232 13f79535-47bb-0310-9956-ffa450edef68
src/main/java/org/apache/commons/lang3/ImmutablePair.java
Java
apache-2.0
83dd4af040fcca6c8b2225889d718b7a1c04d338
0
OpenHFT/Chronicle-Wire,OpenHFT/Chronicle-Wire
/* * Copyright 2016-2020 chronicle.software * * https://chronicle.software * * 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.openhft.chronicle.wire; import net.openhft.chronicle.bytes.Bytes; import net.openhft.chronicle.core.Jvm; import net.openhft.chronicle.core.Maths; import net.openhft.chronicle.core.OS; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.yaml.snakeyaml.Yaml; import java.io.*; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.Future; import static org.junit.Assert.assertEquals; @RunWith(value = Parameterized.class) public class JSON222Test extends WireTestCommon { @NotNull final String file; private final Future future; public JSON222Test(@NotNull String file, Future future) { this.file = file; this.future = future; } @NotNull @Parameterized.Parameters(name = "{0}") public static Collection<Object[]> combinations() { @NotNull List<Object[]> list = new ArrayList<>(); for (@NotNull final File file : OS.findFile("OpenHFT", "Chronicle-Wire", "src/test/resources/nst_files").listFiles()) { if (file.getName().contains("_")) { Future task = ForkJoinPool.commonPool().submit(() -> { try { testJSON(file); } catch (IOException ioe) { throw Jvm.rethrow(ioe); } }); @NotNull Object[] args = {file.getName(), task}; list.add(args); } } list.sort(Comparator.comparingInt(f -> Integer.parseInt(((String) f[0]).split("[_.]")[1]))); return list; } static void testJSON(File file) throws IOException { int len = Maths.toUInt31(file.length()); @NotNull byte[] bytes = new byte[len]; try (@NotNull InputStream in = new FileInputStream(file)) { in.read(bytes); } // System.out.println(file + " " + new String(bytes, "UTF-8")); Bytes b = Bytes.wrapForRead(bytes); @NotNull Wire wire = new JSONWire(b); Bytes bytes2 = Bytes.elasticByteBuffer(); @NotNull TextWire out = new TextWire(bytes2); boolean fail = file.getName().startsWith("n"); Bytes bytes3 = Bytes.elasticByteBuffer(); try { @NotNull List list = new ArrayList(); do { @Nullable final Object object = wire.getValueIn() .object(); @NotNull TextWire out3 = new TextWire(bytes3); out3.getValueOut() .object(object); // System.out.println("As YAML " + bytes3); parseWithSnakeYaml(bytes3.toString()); @Nullable Object object3 = out3.getValueIn() .object(); assertEquals(object, object3); list.add(object); out.getValueOut().object(object); } while (wire.isNotEmptyAfterPadding()); if (fail) { @NotNull String path = file.getPath(); @NotNull final File file2 = new File(path.replaceAll("\\b._", "e-").replaceAll("\\.json", ".yaml")); /* // System.out.println(file2 + "\n" + new String(bytes, "UTF-8") + "\n" + bytes2); try (OutputStream out2 = new FileOutputStream(file2)) { out2.write(bytes2.toByteArray()); } */ if (!file2.exists()) throw new AssertionError("Expected to fail\n" + bytes2); @NotNull byte[] bytes4 = new byte[(int) file2.length()]; try (@NotNull InputStream in = new FileInputStream(file2)) { in.read(bytes4); } String expected = new String(bytes4, "UTF-8"); if (expected.contains("\r\n")) expected = expected.replaceAll("\r\n", "\n"); String actual = bytes2.toString(); assertEquals(expected, actual); } // if (fail) // throw new AssertionError("Expected to fail, was " + list); } catch (Exception e) { if (!fail) throw new AssertionError(e); } finally { bytes2.releaseLast(); bytes3.releaseLast(); } } static void parseWithSnakeYaml(@NotNull String s) { try { @NotNull Yaml yaml = new Yaml(); yaml.load(new StringReader(s)); } catch (Exception e) { throw e; } } @SuppressWarnings({"rawtypes", "unchecked"}) @Test public void testJSON() throws IOException, ExecutionException, InterruptedException { future.get(); } }
src/test/java/net/openhft/chronicle/wire/JSON222Test.java
/* * Copyright 2016-2020 chronicle.software * * https://chronicle.software * * 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.openhft.chronicle.wire; import net.openhft.chronicle.bytes.Bytes; import net.openhft.chronicle.core.Maths; import net.openhft.chronicle.core.OS; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.yaml.snakeyaml.Yaml; import java.io.*; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.List; import static org.junit.Assert.assertEquals; @RunWith(value = Parameterized.class) public class JSON222Test extends WireTestCommon { @NotNull final File file; public JSON222Test(@NotNull File file) { this.file = file; } @NotNull @Parameterized.Parameters public static Collection<File[]> combinations() { @NotNull List<File[]> list = new ArrayList<>(); for (@NotNull File file : OS.findFile("OpenHFT", "Chronicle-Wire", "src/test/resources/nst_files").listFiles()) { if (file.getName().contains("_")) { @NotNull File[] args = {file}; list.add(args); } } list.sort(Comparator.comparingInt(f -> Integer.parseInt(f[0].getName().split("[_.]")[1]))); return list; } @SuppressWarnings({"rawtypes", "unchecked"}) @Test//(timeout = 500) public void testJSON() throws IOException { int len = Maths.toUInt31(file.length()); @NotNull byte[] bytes = new byte[len]; try (@NotNull InputStream in = new FileInputStream(file)) { in.read(bytes); } // System.out.println(file + " " + new String(bytes, "UTF-8")); Bytes b = Bytes.wrapForRead(bytes); @NotNull Wire wire = new JSONWire(b); Bytes bytes2 = Bytes.elasticByteBuffer(); @NotNull TextWire out = new TextWire(bytes2); boolean fail = file.getName().startsWith("n"); Bytes bytes3 = Bytes.elasticByteBuffer(); try { @NotNull List list = new ArrayList(); do { @Nullable final Object object = wire.getValueIn() .object(); @NotNull TextWire out3 = new TextWire(bytes3); out3.getValueOut() .object(object); // System.out.println("As YAML " + bytes3); parseWithSnakeYaml(bytes3.toString()); @Nullable Object object3 = out3.getValueIn() .object(); assertEquals(object, object3); list.add(object); out.getValueOut().object(object); } while (wire.isNotEmptyAfterPadding()); if (fail) { @NotNull String path = this.file.getPath(); @NotNull final File file2 = new File(path.replaceAll("\\b._", "e-").replaceAll("\\.json", ".yaml")); /* // System.out.println(file2 + "\n" + new String(bytes, "UTF-8") + "\n" + bytes2); try (OutputStream out2 = new FileOutputStream(file2)) { out2.write(bytes2.toByteArray()); } */ if (!file2.exists()) throw new AssertionError("Expected to fail\n" + bytes2); @NotNull byte[] bytes4 = new byte[(int) file2.length()]; try (@NotNull InputStream in = new FileInputStream(file2)) { in.read(bytes4); } String expected = new String(bytes4, "UTF-8"); if (expected.contains("\r\n")) expected = expected.replaceAll("\r\n", "\n"); String actual = bytes2.toString(); assertEquals(expected, actual); } // if (fail) // throw new AssertionError("Expected to fail, was " + list); } catch (Exception e) { if (!fail) throw new AssertionError(e); } finally { bytes2.releaseLast(); bytes3.releaseLast(); } } private void parseWithSnakeYaml(@NotNull String s) { try { @NotNull Yaml yaml = new Yaml(); yaml.load(new StringReader(s)); } catch (Exception e) { throw e; } } }
Make concurrent
src/test/java/net/openhft/chronicle/wire/JSON222Test.java
Make concurrent
Java
bsd-2-clause
7eb98905a4482a482f6463789876cd7bff0528ad
0
ratan12/Atarashii,AnimeNeko/Atarashii,ratan12/Atarashii,AnimeNeko/Atarashii
package net.somethingdreadful.MAL; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.webkit.CookieManager; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.ViewFlipper; import net.somethingdreadful.MAL.account.AccountService; import net.somethingdreadful.MAL.api.ALApi; import net.somethingdreadful.MAL.api.MALApi; import net.somethingdreadful.MAL.tasks.AuthenticationCheckTask; import butterknife.Bind; import butterknife.ButterKnife; public class FirstTimeInit extends AppCompatActivity implements AuthenticationCheckTask.AuthenticationCheckListener, OnClickListener { String MalUser; String MalPass; Context context; ProgressDialog dialog; @Bind(R.id.edittext_malUser) EditText malUser; @Bind(R.id.edittext_malPass) EditText malPass; @Bind(R.id.viewFlipper) ViewFlipper viewFlipper; @Bind(R.id.button_connectToMal) Button connectButton; @Bind(R.id.registerButton) Button registerButton; @Bind(R.id.webview) WebView webview; @Bind(R.id.myanimelist) TextView myanimelist; @Bind(R.id.anilist) TextView anilist; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_firstrun); Theme.setActionBar(this); ButterKnife.bind(this); context = getApplicationContext(); if (getIntent().getBooleanExtra("updatePassword", false)) Theme.Snackbar(this, R.string.toast_info_password); connectButton.setOnClickListener(this); registerButton.setOnClickListener(this); myanimelist.setOnClickListener(this); anilist.setOnClickListener(this); CookieManager.getInstance().removeAllCookie(); webview.getSettings().setJavaScriptEnabled(true); webview.getSettings().setDomStorageEnabled(true); webview.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { String code = ALApi.getCode(url); if (code != null) { MalUser = code; tryConnection(); return true; } else { return false; } } }); webview.loadUrl(ALApi.getAnilistURL()); PrefManager.deleteAccount(); NfcHelper.disableBeam(this); } private void tryConnection() { if (MALApi.isNetworkAvailable(this)) { dialog = new ProgressDialog(this); dialog.setIndeterminate(true); dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); dialog.setTitle(getString(R.string.dialog_title_Verifying)); dialog.setMessage(getString(R.string.dialog_message_Verifying)); dialog.show(); if (MalPass != null) new AuthenticationCheckTask(this, this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, MalUser, MalPass); else new AuthenticationCheckTask(this, this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, MalUser); } else { Theme.Snackbar(this, R.string.toast_error_noConnectivity); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); break; } return super.onOptionsItemSelected(item); } @Override public void onAuthenticationCheckFinished(boolean result) { if (result) { Theme.setCrashData("site", AccountService.accountType.toString()); PrefManager.setForceSync(true); PrefManager.commitChanges(); dialog.dismiss(); Intent goHome = new Intent(context, Home.class); startActivity(goHome); finish(); } else if (!isDestroyed()) { dialog.dismiss(); if (MALApi.isNetworkAvailable(this)) Theme.Snackbar(this, R.string.toast_error_VerifyProblem); else Theme.Snackbar(this, R.string.toast_error_noConnectivity); } } @Override protected void onDestroy() { dialog.dismiss(); super.onDestroy(); } @Override public void onBackPressed() { if (viewFlipper.getDisplayedChild() == 1 || viewFlipper.getDisplayedChild() == 2) viewFlipper.setDisplayedChild(0); else finish(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button_connectToMal: MalUser = malUser.getText().toString().trim(); MalPass = malPass.getText().toString().trim(); tryConnection(); break; case R.id.registerButton: Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://myanimelist.net/register.php")); startActivity(browserIntent); break; case R.id.myanimelist: viewFlipper.setDisplayedChild(1); break; case R.id.anilist: if (MALApi.isNetworkAvailable(this)) viewFlipper.setDisplayedChild(2); else Theme.Snackbar(this, R.string.toast_error_noConnectivity); break; } } }
Atarashii/src/net/somethingdreadful/MAL/FirstTimeInit.java
package net.somethingdreadful.MAL; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.webkit.CookieManager; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.ViewFlipper; import net.somethingdreadful.MAL.account.AccountService; import net.somethingdreadful.MAL.api.ALApi; import net.somethingdreadful.MAL.api.MALApi; import net.somethingdreadful.MAL.tasks.AuthenticationCheckTask; import butterknife.Bind; import butterknife.ButterKnife; public class FirstTimeInit extends AppCompatActivity implements AuthenticationCheckTask.AuthenticationCheckListener, OnClickListener { String MalUser; String MalPass; Context context; ProgressDialog dialog; @Bind(R.id.edittext_malUser) EditText malUser; @Bind(R.id.edittext_malPass) EditText malPass; @Bind(R.id.viewFlipper) ViewFlipper viewFlipper; @Bind(R.id.button_connectToMal) Button connectButton; @Bind(R.id.registerButton) Button registerButton; @Bind(R.id.webview) WebView webview; @Bind(R.id.myanimelist) TextView myanimelist; @Bind(R.id.anilist) TextView anilist; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_firstrun); Theme.setActionBar(this); ButterKnife.bind(this); context = getApplicationContext(); if (getIntent().getBooleanExtra("updatePassword", false)) Theme.Snackbar(this, R.string.toast_info_password); connectButton.setOnClickListener(this); registerButton.setOnClickListener(this); myanimelist.setOnClickListener(this); anilist.setOnClickListener(this); CookieManager.getInstance().removeAllCookie(); webview.getSettings().setJavaScriptEnabled(true); webview.getSettings().setDomStorageEnabled(true); webview.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { String code = ALApi.getCode(url); if (code != null) { MalUser = code; tryConnection(); return true; } else { return false; } } }); webview.loadUrl(ALApi.getAnilistURL()); PrefManager.deleteAccount(); NfcHelper.disableBeam(this); } private void tryConnection() { if (MALApi.isNetworkAvailable(this)) { dialog = new ProgressDialog(this); dialog.setIndeterminate(true); dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); dialog.setTitle(getString(R.string.dialog_title_Verifying)); dialog.setMessage(getString(R.string.dialog_message_Verifying)); dialog.show(); if (MalPass != null) new AuthenticationCheckTask(this, this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, MalUser, MalPass); else new AuthenticationCheckTask(this, this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, MalUser); } else { Theme.Snackbar(this, R.string.toast_error_noConnectivity); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); break; } return super.onOptionsItemSelected(item); } @Override public void onAuthenticationCheckFinished(boolean result) { if (result) { Theme.setCrashData("site", AccountService.accountType.toString()); PrefManager.setForceSync(true); PrefManager.commitChanges(); dialog.dismiss(); Intent goHome = new Intent(context, Home.class); startActivity(goHome); finish(); } else { dialog.dismiss(); if (MALApi.isNetworkAvailable(this)) Theme.Snackbar(this, R.string.toast_error_VerifyProblem); else Theme.Snackbar(this, R.string.toast_error_noConnectivity); } } @Override public void onBackPressed() { if (viewFlipper.getDisplayedChild() == 1 || viewFlipper.getDisplayedChild() == 2) viewFlipper.setDisplayedChild(0); else finish(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button_connectToMal: MalUser = malUser.getText().toString().trim(); MalPass = malPass.getText().toString().trim(); tryConnection(); break; case R.id.registerButton: Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://myanimelist.net/register.php")); startActivity(browserIntent); break; case R.id.myanimelist: viewFlipper.setDisplayedChild(1); break; case R.id.anilist: if (MALApi.isNetworkAvailable(this)) viewFlipper.setDisplayedChild(2); else Theme.Snackbar(this, R.string.toast_error_noConnectivity); break; } } }
Fix windowstate crash by checking if activity still exists
Atarashii/src/net/somethingdreadful/MAL/FirstTimeInit.java
Fix windowstate crash by checking if activity still exists
Java
mit
acf5fdd0dbefe34486e11e7107cacd4679c06840
0
KodyJKing/RandomToolKit
package rtk.common; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; public class CWorld { public static boolean shouldReplace(World world, BlockPos pos){ IBlockState bs = world.getBlockState(pos); return bs.getBlock().isReplaceable(world, pos) || !bs.isOpaqueCube() && bs.getBlockHardness(world, pos) < 0.01F || bs.getMaterial() == Material.AIR; } // Still avoids calls to breakBlock and onBlockAdded, but fixes lighting, elevation and does updates. // This is a modified version of World.setBlockState. public static void silentSetBlockStateAndUpdate(World world, BlockPos pos, IBlockState newState, int flags){ if (world.isOutsideBuildHeight(pos)) { return; } else { Chunk chunk = world.getChunkFromBlockCoords(pos); pos = pos.toImmutable(); // Forge - prevent mutable BlockPos leaks net.minecraftforge.common.util.BlockSnapshot blockSnapshot = null; if (world.captureBlockSnapshots && !world.isRemote) { blockSnapshot = net.minecraftforge.common.util.BlockSnapshot.getBlockSnapshot(world, pos, flags); world.capturedBlockSnapshots.add(blockSnapshot); } IBlockState oldState = world.getBlockState(pos); int oldLight = oldState.getLightValue(world, pos); int oldOpacity = oldState.getLightOpacity(world, pos); IBlockState iblockstate = chunk.getBlockState(pos); silentSetBlockState(world, pos, newState); // RandomToolKit - silently set the block state before calling into chunk.setBlockState so breakBlock and onBlockAdded won't get called. chunk.setBlockState(pos, newState); if (iblockstate == null) { if (blockSnapshot != null) world.capturedBlockSnapshots.remove(blockSnapshot); return; } else { if (newState.getLightOpacity(world, pos) != oldOpacity || newState.getLightValue(world, pos) != oldLight) { world.profiler.startSection("checkLight"); world.checkLight(pos); world.profiler.endSection(); } if (blockSnapshot == null) // Don't notify clients or update physics while capturing blockstates { world.markAndNotifyBlock(pos, chunk, iblockstate, newState, flags); } } } } // To Avoid calls to breakBlock and onBlockAdded. // Also avoids updating lighting, and elevation information and updates. // See Chunk.setBlockState. public static void silentSetBlockState(World world, BlockPos pos, IBlockState state){ world.removeTileEntity(pos); int dx = pos.getX() & 15; int dz = pos.getZ() & 15; int y = pos.getY(); Chunk chunk = world.getChunkFromBlockCoords(pos); ExtendedBlockStorage extendedblockstorage = chunk.getBlockStorageArray()[y >> 4]; if (extendedblockstorage == Chunk.NULL_BLOCK_STORAGE) return; extendedblockstorage.set(dx, y & 15, dz, state); chunk.setModified(true); } public BlockPos pickSpawnPoint(World world, BlockPos pos, int radius, int tries, int scanHeight){ for (int i = 0; i < tries; i++){ BlockPos scanPos = pos.add(new BlockPos(CMath.randomVector(radius))); for (int j = 0; j < scanHeight; j++){ if (world.isSideSolid(scanPos.down(), EnumFacing.UP) && world.isAirBlock(scanPos) && world.isAirBlock(scanPos.up())) return scanPos; scanPos = scanPos.up(); } } return null; } }
src/main/java/rtk/common/CWorld.java
package rtk.common; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; public class CWorld { public static boolean shouldReplace(World world, BlockPos pos){ IBlockState bs = world.getBlockState(pos); return bs.getBlock().isReplaceable(world, pos) || !bs.isOpaqueCube() && bs.getBlockHardness(world, pos) < 0.01F || bs.getMaterial() == Material.AIR; } // Still avoids calls to breakBlock and onBlockAdded, but fixes lighting, elevation and does updates. // This is a modified version of World.setBlockState. public static void silentSetBlockStateAndUpdate(World world, BlockPos pos, IBlockState newState, int flags){ if (world.isOutsideBuildHeight(pos)) { return; } else { Chunk chunk = world.getChunkFromBlockCoords(pos); pos = pos.toImmutable(); // Forge - prevent mutable BlockPos leaks net.minecraftforge.common.util.BlockSnapshot blockSnapshot = null; if (world.captureBlockSnapshots && !world.isRemote) { blockSnapshot = net.minecraftforge.common.util.BlockSnapshot.getBlockSnapshot(world, pos, flags); world.capturedBlockSnapshots.add(blockSnapshot); } IBlockState oldState = world.getBlockState(pos); int oldLight = oldState.getLightValue(world, pos); int oldOpacity = oldState.getLightOpacity(world, pos); IBlockState iblockstate = chunk.getBlockState(pos); silentSetBlockState(world, pos, newState); // RandomTookKit - silently set the block state before calling into chunk.setBlockState so breakBlock and onBlockAdded won't get called. chunk.setBlockState(pos, newState); if (iblockstate == null) { if (blockSnapshot != null) world.capturedBlockSnapshots.remove(blockSnapshot); return; } else { if (newState.getLightOpacity(world, pos) != oldOpacity || newState.getLightValue(world, pos) != oldLight) { world.profiler.startSection("checkLight"); world.checkLight(pos); world.profiler.endSection(); } if (blockSnapshot == null) // Don't notify clients or update physics while capturing blockstates { world.markAndNotifyBlock(pos, chunk, iblockstate, newState, flags); } } } } // To Avoid calls to breakBlock and onBlockAdded. // Also avoids updating lighting, and elevation information and updates. // See Chunk.setBlockState. public static void silentSetBlockState(World world, BlockPos pos, IBlockState state){ world.removeTileEntity(pos); int dx = pos.getX() & 15; int dz = pos.getZ() & 15; int y = pos.getY(); Chunk chunk = world.getChunkFromBlockCoords(pos); ExtendedBlockStorage extendedblockstorage = chunk.getBlockStorageArray()[y >> 4]; if (extendedblockstorage == Chunk.NULL_BLOCK_STORAGE) return; extendedblockstorage.set(dx, y & 15, dz, state); chunk.setModified(true); } public BlockPos pickSpawnPoint(World world, BlockPos pos, int radius, int tries, int scanHeight){ for (int i = 0; i < tries; i++){ BlockPos scanPos = pos.add(new BlockPos(CMath.randomVector(radius))); for (int j = 0; j < scanHeight; j++){ if (world.isSideSolid(scanPos.down(), EnumFacing.UP) && world.isAirBlock(scanPos) && world.isAirBlock(scanPos.up())) return scanPos; scanPos = scanPos.up(); } } return null; } }
Update CWorld.java
src/main/java/rtk/common/CWorld.java
Update CWorld.java
Java
mit
6e231dc140d40ccccc3cc00258cf63e964b41caa
0
frc868/2016-Vizzini
package com.techhounds.commands.auton; import com.techhounds.commands.gyro.SetGyro; import edu.wpi.first.wpilibj.command.CommandGroup; import edu.wpi.first.wpilibj.networktables.NetworkTable; /** * */ public class VisionAlignToTarget extends CommandGroup { private double offAngle = 0; private NetworkTable netTable; public VisionAlignToTarget() { NetworkTable.setServerMode(); NetworkTable.initialize(); netTable = NetworkTable.getTable("SmartDashboard"); if(netTable != null) { offAngle = netTable.getNumber("OffCenterDegreesX", 0); } else { offAngle = 0; } addSequential(new SetGyro(offAngle)); } }
src/com/techhounds/commands/auton/VisionAlignToTarget.java
package com.techhounds.commands.auton; import com.techhounds.subsystems.DriveSubsystem; import edu.wpi.first.wpilibj.PIDController; import edu.wpi.first.wpilibj.PIDOutput; import edu.wpi.first.wpilibj.PIDSource; import edu.wpi.first.wpilibj.PIDSourceType; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.networktables.NetworkTable; /** * */ public class VisionAlignToTarget extends Command implements PIDSource, PIDOutput { private DriveSubsystem drive; private double offAngle = 0; private PIDController pid; private NetworkTable netTable; public VisionAlignToTarget() { drive = DriveSubsystem.getInstance(); requires(drive); pid = new PIDController(0, 0, 0, this, this); pid.setOutputRange(-1, 1); } // Called just before this Command runs the first time protected void initialize() { NetworkTable.setServerMode(); NetworkTable.initialize(); netTable = NetworkTable.getTable("SmartDashboard"); if(netTable != null) { offAngle = netTable.getNumber("OffCenterDegreesX", 0); } pid.setSetpoint(offAngle); pid.enable(); } // Called repeatedly when this Command is scheduled to run protected void execute() { } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return pid.onTarget(); } // Called once after isFinished returns true protected void end() { pid.disable(); } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } @Override public void pidWrite(double output) { drive.setLeftPower(-output); drive.setRightPower(output); } @Override public void setPIDSourceType(PIDSourceType pidSource) { // TODO Auto-generated method stub } @Override public PIDSourceType getPIDSourceType() { // TODO Auto-generated method stub return null; } @Override public double pidGet() { return offAngle; } /* * if angle is positive, * we need to rotate to the left (counterclockwise) * thus left power should be negative, right power should be positive */ }
Convert VisionAlign Command to CommandGroup Now relies on SetGyro command.
src/com/techhounds/commands/auton/VisionAlignToTarget.java
Convert VisionAlign Command to CommandGroup
Java
mit
40fd8b5c803936d49c5e21bc44d93d489c1d67ae
0
betato/GameDisplay
package com.betato.gamedisplay; /** * A game loop to run a GameWindow at the specified frame and update rate. */ public class GameLoop { private int targetFps = 60; private int nanoFps = 1000000000 / targetFps; private int targetUps = 60; private int nanoUps = 1000000000 / targetUps; public boolean running = true; public long deltaUps = 0; /** * Creates a new GameLoop with the specified frame rate and update rate. * * @param targetFps * The frame rate for the GameWindow in frames per second * @param targetUps * The update rate for the GameWindow in updates per second */ public GameLoop(int targetFps, int targetUps) { this.targetFps = targetFps; this.targetUps = targetUps; nanoFps = 1000000000 / targetFps; nanoUps = 1000000000 / targetUps; } void run(GameWindow game) { long startTime = System.nanoTime(); long deltaFps = 0; long deltaDisplay = 0; int framecount = 0; int updatecount = 0; while (running) { // Get current time long currentTime = System.nanoTime(); // Get time since last loop deltaFps += currentTime - startTime; deltaUps += currentTime - startTime; deltaDisplay += currentTime - startTime; // Set start time of this loop for use in next cycle startTime = currentTime; // Render if target time has been reached if (deltaFps >= nanoFps) { // Render game.render(); framecount++; deltaFps = 0; } // Update if target time has been reached if (deltaUps >= nanoUps) { // Update game.update(); updatecount++; deltaUps = 0; } // Update fps and ups if one second has passed if (deltaDisplay >= 1000000000) { game.updateFps(framecount, updatecount); framecount = 0; updatecount = 0; deltaDisplay = 0; } } } }
src/com/betato/gamedisplay/GameLoop.java
package com.betato.gamedisplay; public class GameLoop { private int targetFps = 60; private int nanoFps = 1000000000 / targetFps; private int targetUps = 60; private int nanoUps = 1000000000 / targetUps; public boolean running = true; public long deltaUps = 0; public GameLoop(int targetFps, int targetUps) { this.targetFps = targetFps; this.targetUps = targetUps; nanoFps = 1000000000 / targetFps; nanoUps = 1000000000 / targetUps; } // Runs the GameLoop public void run(GameWindow game) { long startTime = System.nanoTime(); long deltaFps = 0; long deltaDisplay = 0; int framecount = 0; int updatecount = 0; while (running) { // Get current time long currentTime = System.nanoTime(); // Get time since last loop deltaFps += currentTime - startTime; deltaUps += currentTime - startTime; deltaDisplay += currentTime - startTime; // Set start time of this loop for use in next cycle startTime = currentTime; // Render if target time has been reached if (deltaFps >= nanoFps) { // Render game.render(); framecount++; deltaFps = 0; } // Update if target time has been reached if (deltaUps >= nanoUps) { // Update game.update(); updatecount++; deltaUps = 0; } // Update fps and ups if one second has passed if (deltaDisplay >= 1000000000) { game.updateFps(framecount, updatecount); framecount = 0; updatecount = 0; deltaDisplay = 0; } } } }
Add Javadoc comments for GameLoop
src/com/betato/gamedisplay/GameLoop.java
Add Javadoc comments for GameLoop
Java
mit
de3775e81d07dcf4c9f755f108b126501a9fc9e3
0
DMDirc/DMDirc,DMDirc/DMDirc,ShaneMcC/DMDirc-Client,greboid/DMDirc,greboid/DMDirc,ShaneMcC/DMDirc-Client,ShaneMcC/DMDirc-Client,greboid/DMDirc,DMDirc/DMDirc,DMDirc/DMDirc,greboid/DMDirc,csmith/DMDirc,ShaneMcC/DMDirc-Client,csmith/DMDirc,csmith/DMDirc,csmith/DMDirc
/* * Copyright (c) 2006-2011 Chris Smith, Shane Mc Cormack, Gregory Holmes * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dmdirc; import com.dmdirc.config.Identity; import com.dmdirc.config.IdentityManager; import com.dmdirc.logger.ErrorLevel; import com.dmdirc.logger.Logger; import com.dmdirc.parser.common.ChannelJoinRequest; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; /** * The ServerManager maintains a list of all servers, and provides methods to * search or iterate over them. * * @author chris */ public final class ServerManager { /** Singleton instance of ServerManager. */ private static ServerManager me; /** All servers that currently exist. */ private final Set<Server> servers = new CopyOnWriteArraySet<Server>(); /** * Creates a new instance of ServerManager. */ private ServerManager() { } /** * Returns the singleton instance of ServerManager. * * @return Instance of ServerManager */ public static synchronized ServerManager getServerManager() { if (me == null) { me = new ServerManager(); } return me; } /** * Registers a new server with the manager. * * @param server The server to be registered */ public void registerServer(final Server server) { servers.add(server); } /** * Unregisters a server from the manager. The request is ignored if the * ServerManager is in the process of closing all servers. * * @param server The server to be unregistered */ public void unregisterServer(final Server server) { servers.remove(server); } /** * Returns a list of all servers. * * @return A list of all servers */ public List<Server> getServers() { return new ArrayList<Server>(servers); } /** * Makes all servers disconnected with the specified quit message. * * @param message The quit message to send to the IRC servers */ public void disconnectAll(final String message) { for (Server server : servers) { server.disconnect(message); } } /** * Closes all servers with a default quit message. */ public void closeAll() { for (Server server : servers) { server.disconnect(); server.close(); } } /** * Closes all servers with the specified quit message. * * @param message The quit message to send to the IRC servers */ public void closeAll(final String message) { for (Server server : servers) { server.disconnect(message); server.close(); } } /** * Returns the number of servers that are registered with the manager. * * @return number of registered servers */ public int numServers() { return servers.size(); } /** * Retrieves a list of servers connected to the specified network. * * @param network The network to search for * @return A list of servers connected to the network */ public List<Server> getServersByNetwork(final String network) { final List<Server> res = new ArrayList<Server>(); for (Server server : servers) { if (server.isNetwork(network)) { res.add(server); } } return res; } /** * Retrieves a list of servers connected to the specified address. * * @param address The address to search for * @return A list of servers connected to the network */ public List<Server> getServersByAddress(final String address) { final List<Server> res = new ArrayList<Server>(); for (Server server : servers) { if (server.getAddress().equalsIgnoreCase(address)) { res.add(server); } } return res; } /** * Creates a new server which will connect to the specified URI with the * default profile. * * @param uri The URI to connect to * @return The server which will be connecting * @since 0.6.3 */ public Server connectToAddress(final URI uri) { return connectToAddress(uri, IdentityManager.getCustomIdentities( "profile").get(0)); } /** * Creates a new server which will connect to the specified URI with the * specified profile. * * @param uri The URI to connect to * @param profile The profile to use * @return The server which will be connecting * @since 0.6.3 */ public Server connectToAddress(final URI uri, final Identity profile) { Logger.assertTrue(profile.isProfile()); Server server = null; for (Server loopServer : servers) { if (loopServer.compareURI(uri)) { server = loopServer; break; } } if (server == null) { server = new Server(uri, profile); server.connect(); return server; } if (server.getState().isDisconnected()) { server.connect(uri, profile); } else { server.join(server.getParser().extractChannels(uri) .toArray(new ChannelJoinRequest[0])); } return server; } /** * Connects the user to Quakenet if neccessary and joins #DMDirc. */ public void joinDevChat() { final List<Server> qnetServers = getServersByNetwork("Quakenet"); Server connectedServer = null; for (Server server : qnetServers) { if (server.getState() == ServerState.CONNECTED) { connectedServer = server; if (server.hasChannel("#DMDirc")) { server.join(new ChannelJoinRequest("#DMDirc")); return; } } } if (connectedServer == null) { try { final Server server = new Server(new URI("irc://irc.quakenet.org/DMDirc"), IdentityManager.getCustomIdentities("profile").get(0)); server.connect(); } catch (URISyntaxException ex) { Logger.appError(ErrorLevel.MEDIUM, "Unable to construct new server", ex); } } else { connectedServer.join(new ChannelJoinRequest("#DMDirc")); } } }
src/com/dmdirc/ServerManager.java
/* * Copyright (c) 2006-2011 Chris Smith, Shane Mc Cormack, Gregory Holmes * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dmdirc; import com.dmdirc.config.Identity; import com.dmdirc.config.IdentityManager; import com.dmdirc.logger.ErrorLevel; import com.dmdirc.logger.Logger; import com.dmdirc.parser.common.ChannelJoinRequest; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; /** * The ServerManager maintains a list of all servers, and provides methods to * search or iterate over them. * * @author chris */ public final class ServerManager { /** Singleton instance of ServerManager. */ private static ServerManager me; /** All servers that currently exist. */ private final List<Server> servers = new ArrayList<Server>(); /** * Creates a new instance of ServerManager. */ private ServerManager() { } /** * Returns the singleton instance of ServerManager. * * @return Instance of ServerManager */ public static synchronized ServerManager getServerManager() { if (me == null) { me = new ServerManager(); } return me; } /** * Registers a new server with the manager. * * @param server The server to be registered */ public void registerServer(final Server server) { synchronized (servers) { servers.add(server); } } /** * Unregisters a server from the manager. The request is ignored if the * ServerManager is in the process of closing all servers. * * @param server The server to be unregistered */ public void unregisterServer(final Server server) { synchronized (servers) { servers.remove(server); } } /** * Returns a list of all servers. * * @return A list of all servers */ public List<Server> getServers() { return new ArrayList<Server>(servers); } /** * Makes all servers disconnected with the specified quit message. * * @param message The quit message to send to the IRC servers */ public void disconnectAll(final String message) { synchronized (servers) { for (Server server : servers) { server.disconnect(message); } } } /** * Closes all servers with a default quit message. */ public void closeAll() { synchronized (servers) { for (Server server : servers) { server.disconnect(); server.close(); } } } /** * Closes all servers with the specified quit message. * * @param message The quit message to send to the IRC servers */ public void closeAll(final String message) { synchronized (servers) { for (Server server : servers) { server.disconnect(message); server.close(); } } } /** * Returns the number of servers that are registered with the manager. * * @return number of registered servers */ public int numServers() { return servers.size(); } /** * Retrieves a list of servers connected to the specified network. * * @param network The network to search for * @return A list of servers connected to the network */ public List<Server> getServersByNetwork(final String network) { final List<Server> res = new ArrayList<Server>(); synchronized (servers) { for (Server server : servers) { if (server.isNetwork(network)) { res.add(server); } } } return res; } /** * Retrieves a list of servers connected to the specified address. * * @param address The address to search for * @return A list of servers connected to the network */ public List<Server> getServersByAddress(final String address) { final List<Server> res = new ArrayList<Server>(); synchronized (servers) { for (Server server : servers) { if (server.getAddress().equalsIgnoreCase(address)) { res.add(server); } } } return res; } /** * Creates a new server which will connect to the specified URI with the * default profile. * * @param uri The URI to connect to * @return The server which will be connecting * @since 0.6.3 */ public Server connectToAddress(final URI uri) { return connectToAddress(uri, IdentityManager.getCustomIdentities( "profile").get(0)); } /** * Creates a new server which will connect to the specified URI with the * specified profile. * * @param uri The URI to connect to * @param profile The profile to use * @return The server which will be connecting * @since 0.6.3 */ public Server connectToAddress(final URI uri, final Identity profile) { Logger.assertTrue(profile.isProfile()); Server server = null; synchronized (servers) { for (Server loopServer : servers) { if (loopServer.compareURI(uri)) { server = loopServer; break; } } } if (server == null) { server = new Server(uri, profile); server.connect(); return server; } if (server.getState().isDisconnected()) { server.connect(uri, profile); } else { server.join(server.getParser().extractChannels(uri) .toArray(new ChannelJoinRequest[0])); } return server; } /** * Connects the user to Quakenet if neccessary and joins #DMDirc. */ public void joinDevChat() { final List<Server> qnetServers = getServersByNetwork("Quakenet"); Server connectedServer = null; for (Server server : qnetServers) { if (server.getState() == ServerState.CONNECTED) { connectedServer = server; if (server.hasChannel("#DMDirc")) { server.join(new ChannelJoinRequest("#DMDirc")); return; } } } if (connectedServer == null) { try { final Server server = new Server(new URI("irc://irc.quakenet.org/DMDirc"), IdentityManager.getCustomIdentities("profile").get(0)); server.connect(); } catch (URISyntaxException ex) { Logger.appError(ErrorLevel.MEDIUM, "Unable to construct new server", ex); } } else { connectedServer.join(new ChannelJoinRequest("#DMDirc")); } } }
Fix concurrency problems in ServerManager Fixes CLIENT-250 Change-Id: Ic571a757be828d77dda0b3aa439ec06cde061e3c Reviewed-on: http://gerrit.dmdirc.com/1976 Automatic-Compile: DMDirc Build Manager Reviewed-by: Greg Holmes <[email protected]>
src/com/dmdirc/ServerManager.java
Fix concurrency problems in ServerManager
Java
mit
9e405446a66ad6c9038b108ed400b22f17b112f1
0
ThomasGaubert/ble-locator-android,TexasGamer/ble-locator-android
package com.tgaubert.blefinder; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.RemoteException; import android.support.v4.app.NotificationCompat; import android.util.Log; import org.altbeacon.beacon.Beacon; import org.altbeacon.beacon.BeaconConsumer; import org.altbeacon.beacon.BeaconManager; import org.altbeacon.beacon.BeaconParser; import org.altbeacon.beacon.RangeNotifier; import org.altbeacon.beacon.Region; import java.util.ArrayList; import java.util.Collection; public class BLEDataTracker implements BeaconConsumer { private BeaconManager beaconManager; private Collection<Beacon> beacons; private BeaconListAdapter listAdapter; private boolean isTracking = false; private Context context; private String TAG = "BLEDataTracker"; private NotificationManager notifyMgr; public BLEDataTracker(final Context context) { this.context = context; notifyMgr = (NotificationManager) context.getSystemService(Service.NOTIFICATION_SERVICE); BeaconIO.loadBeacons(context); beaconManager = BeaconManager.getInstanceForApplication(context); beaconManager.getBeaconParsers().add(new BeaconParser(). setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24")); beaconManager.bind(this); } public void setBeacons(Collection<Beacon> beacons) { this.beacons = beacons; } public Collection<Beacon> getBeacons() { return beacons; } public void setTracking(boolean isTracking) { this.isTracking = isTracking; try { if (isTracking) { beaconManager.startRangingBeaconsInRegion(new Region("BLEFinder", null, null, null)); } else { beaconManager.stopRangingBeaconsInRegion(new Region("BLEFinder", null, null, null)); BeaconIO.saveBeacons(context); notifyMgr.cancel(1); } } catch (RemoteException e) { e.printStackTrace(); } } public boolean isTracking() { return isTracking; } public void setListAdapter(BeaconListAdapter listAdapter) { this.listAdapter = listAdapter; } @Override public void onBeaconServiceConnect() { Log.i(TAG, "Connected to service"); beaconManager.setRangeNotifier(new RangeNotifier() { @Override public void didRangeBeaconsInRegion(final Collection<Beacon> beacons, Region region) { setBeacons(beacons); final ArrayList<Beacon> visibleBeacons = new ArrayList<>(); ((MainActivity) context).runOnUiThread(new Runnable() { @Override public void run() { for (Beacon b : beacons) { SeenBeacon seenBeacon = BeaconIO.getSeenBeacon(b.getBluetoothAddress()); if (seenBeacon != null && !seenBeacon.isIgnore()) visibleBeacons.add(b); } listAdapter.set(visibleBeacons); } }); int notificationId = 1; int beaconCount = 0; NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext()) .setSmallIcon(R.mipmap.ic_launcher) .setColor(context.getResources().getColor(R.color.primary)) .setGroup("BLE_FINDER_ALERT") .setOngoing(true) .setContentTitle("Beacon Alert"); NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); final Intent notificationIntent = new Intent(context, MainActivity.class); notificationIntent.setAction(Intent.ACTION_MAIN); notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER); builder.setContentIntent(PendingIntent.getActivity(context, 0, notificationIntent, 0)); for (Beacon b : beacons) { if (BeaconIO.getSeenBeacons().containsKey(b.getBluetoothAddress())) { Log.i(TAG, "Beacon " + b.getBluetoothAddress() + " has been seen before."); SeenBeacon seenBeacon = BeaconIO.getSeenBeacon(b.getBluetoothAddress()); if(!seenBeacon.isIgnore() && Double.parseDouble(seenBeacon.getDistance()) >= b.getDistance()) { beaconCount++; String savedName = seenBeacon.getUserName(); if(savedName.contains("BLEFinder\u2063")) savedName = b.getBluetoothName(); if(beaconCount == 1) { builder.setContentText(savedName + " is within " + seenBeacon.getDistance() + "m."); } else { inboxStyle.setBigContentTitle(beaconCount + " beacons nearby"); if(beaconCount < 6) { if(beaconCount == 2) { inboxStyle.addLine(builder.mContentText.toString().replace(" is within ", " ").replace(".", "")); } inboxStyle.addLine(savedName + " " + seenBeacon.getDistance() + "m"); } else { inboxStyle.setSummaryText("+" + (beaconCount - 5) + " more"); } builder.setContentText(beaconCount + " beacons nearby"); builder.setStyle(inboxStyle); } } } else { Log.i(TAG, "Just saw a beacon " + b.getBluetoothAddress() + " for the first time."); BeaconIO.getSeenBeacons().put(b.getBluetoothAddress(), new SeenBeacon(b.getBluetoothAddress(), b.getBluetoothName())); } } if(beaconCount == 0) { notifyMgr.cancel(1); } else { notifyMgr.notify(notificationId, builder.build()); } } }); try { if (isTracking) { beaconManager.startRangingBeaconsInRegion(new Region("BLEFinder", null, null, null)); } } catch (RemoteException e) { e.printStackTrace(); } } @Override public Context getApplicationContext() { return context; } @Override public void unbindService(ServiceConnection serviceConnection) { context.unbindService(serviceConnection); notifyMgr.cancel(1); } @Override public boolean bindService(Intent intent, ServiceConnection serviceConnection, int i) { context.bindService(intent, serviceConnection, i); return true; } }
mobile/src/main/java/com/tgaubert/blefinder/BLEDataTracker.java
package com.tgaubert.blefinder; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.RemoteException; import android.support.v4.app.NotificationCompat; import android.util.Log; import org.altbeacon.beacon.Beacon; import org.altbeacon.beacon.BeaconConsumer; import org.altbeacon.beacon.BeaconManager; import org.altbeacon.beacon.BeaconParser; import org.altbeacon.beacon.RangeNotifier; import org.altbeacon.beacon.Region; import java.util.ArrayList; import java.util.Collection; public class BLEDataTracker implements BeaconConsumer { private BeaconManager beaconManager; private Collection<Beacon> beacons; private BeaconListAdapter listAdapter; private boolean isTracking = false; private Context context; private String TAG = "BLEDataTracker"; private NotificationManager notifyMgr; public BLEDataTracker(final Context context) { this.context = context; notifyMgr = (NotificationManager) context.getSystemService(Service.NOTIFICATION_SERVICE); BeaconIO.loadBeacons(context); beaconManager = BeaconManager.getInstanceForApplication(context); beaconManager.getBeaconParsers().add(new BeaconParser(). setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24")); beaconManager.bind(this); } public void setBeacons(Collection<Beacon> beacons) { this.beacons = beacons; } public Collection<Beacon> getBeacons() { return beacons; } public void setTracking(boolean isTracking) { this.isTracking = isTracking; try { if (isTracking) { beaconManager.startRangingBeaconsInRegion(new Region("BLEFinder", null, null, null)); } else { beaconManager.stopRangingBeaconsInRegion(new Region("BLEFinder", null, null, null)); BeaconIO.saveBeacons(context); notifyMgr.cancel(1); } } catch (RemoteException e) { e.printStackTrace(); } } public boolean isTracking() { return isTracking; } public void setListAdapter(BeaconListAdapter listAdapter) { this.listAdapter = listAdapter; } @Override public void onBeaconServiceConnect() { Log.i(TAG, "Connected to service"); beaconManager.setRangeNotifier(new RangeNotifier() { @Override public void didRangeBeaconsInRegion(final Collection<Beacon> beacons, Region region) { setBeacons(beacons); final ArrayList<Beacon> visibleBeacons = new ArrayList<>(); ((MainActivity) context).runOnUiThread(new Runnable() { @Override public void run() { for (Beacon b : beacons) { SeenBeacon seenBeacon = BeaconIO.getSeenBeacon(b.getBluetoothAddress()); if (seenBeacon != null && !seenBeacon.isIgnore()) visibleBeacons.add(b); } listAdapter.set(visibleBeacons); } }); int notificationId = 1; int beaconCount = 0; NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext()) .setSmallIcon(R.mipmap.ic_launcher) .setColor(context.getResources().getColor(R.color.primary)) .setGroup("BLE_FINDER_ALERT") .setContentTitle("Beacon Alert"); NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); final Intent notificationIntent = new Intent(context, MainActivity.class); notificationIntent.setAction(Intent.ACTION_MAIN); notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER); builder.setContentIntent(PendingIntent.getActivity(context, 0, notificationIntent, 0)); for (Beacon b : beacons) { if (BeaconIO.getSeenBeacons().containsKey(b.getBluetoothAddress())) { Log.i(TAG, "Beacon " + b.getBluetoothAddress() + " has been seen before."); SeenBeacon seenBeacon = BeaconIO.getSeenBeacon(b.getBluetoothAddress()); if(!seenBeacon.isIgnore() && Double.parseDouble(seenBeacon.getDistance()) >= b.getDistance()) { beaconCount++; String savedName = seenBeacon.getUserName(); if(savedName.contains("BLEFinder\u2063")) savedName = b.getBluetoothName(); if(beaconCount == 1) { builder.setContentText(savedName + " is within " + seenBeacon.getDistance() + "m."); } else { inboxStyle.setBigContentTitle(beaconCount + " beacons nearby"); if(beaconCount < 6) { if(beaconCount == 2) { inboxStyle.addLine(builder.mContentText.toString().replace(" is within ", " ").replace(".", "")); } inboxStyle.addLine(savedName + " " + seenBeacon.getDistance() + "m"); } else { inboxStyle.setSummaryText("+" + (beaconCount - 5) + " more"); } builder.setContentText(beaconCount + " beacons nearby"); builder.setStyle(inboxStyle); } } } else { Log.i(TAG, "Just saw a beacon " + b.getBluetoothAddress() + " for the first time."); BeaconIO.getSeenBeacons().put(b.getBluetoothAddress(), new SeenBeacon(b.getBluetoothAddress(), b.getBluetoothName())); } } if(beaconCount == 0) { notifyMgr.cancel(1); } else { notifyMgr.notify(notificationId, builder.build()); } } }); try { if (isTracking) { beaconManager.startRangingBeaconsInRegion(new Region("BLEFinder", null, null, null)); } } catch (RemoteException e) { e.printStackTrace(); } } @Override public Context getApplicationContext() { return context; } @Override public void unbindService(ServiceConnection serviceConnection) { context.unbindService(serviceConnection); notifyMgr.cancel(1); } @Override public boolean bindService(Intent intent, ServiceConnection serviceConnection, int i) { context.bindService(intent, serviceConnection, i); return true; } }
Notification is now ongoing
mobile/src/main/java/com/tgaubert/blefinder/BLEDataTracker.java
Notification is now ongoing
Java
agpl-3.0
4b5346350f60628e9e7c2ab86fadff5fff4354fc
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
538ffb0e-2e62-11e5-9284-b827eb9e62be
hello.java
538a75ee-2e62-11e5-9284-b827eb9e62be
538ffb0e-2e62-11e5-9284-b827eb9e62be
hello.java
538ffb0e-2e62-11e5-9284-b827eb9e62be
Java
agpl-3.0
d65d12ae00ac9073b1747ecc67b3828ae91016e0
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
aee6d890-2e5f-11e5-9284-b827eb9e62be
hello.java
aee15a46-2e5f-11e5-9284-b827eb9e62be
aee6d890-2e5f-11e5-9284-b827eb9e62be
hello.java
aee6d890-2e5f-11e5-9284-b827eb9e62be
Java
lgpl-2.1
ceb326e1de9db09c2649d528a775d178f664a01a
0
exedio/copernica,exedio/copernica,exedio/copernica
/* * Copyright (C) 2004-2006 exedio GmbH (www.exedio.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.exedio.cope; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import com.exedio.cope.Field.Option; import com.exedio.cope.ItemField.DeletePolicy; import com.exedio.cope.util.ReactivationConstructorDummy; /** * This is the super class for all classes, * that want to store their data persistently with COPE. * <p> * To enable serialization for subclasses of <tt>Item</tt>, * see {@link #Item()}. * * @author Ralf Wiebicke */ public abstract class Item extends Cope { final transient Type<? extends Item> type; /** * The primary key of the item, * that is unique within the {@link #type} of this item. */ final int pk; /** * Returns a string unique for this item in all other items of the model. * For any item <tt>a</tt> in its model <tt>m</tt> * the following holds true: * <tt>a.equals(m.findByID(a.getCopeID()).</tt> * Does not activate this item, if it's not already active. * Never returns null. * @see Model#findByID(String) */ public final String getCopeID() { return type.id + '.' + type.getPkSource().pk2id(pk); } /** * Returns the type of this item. * Never returns null. */ public final Type<? extends Item> getCopeType() { assert type!=null; return type; } /** * Returns true, if <tt>o</tt> represents the same item as this item. * Is equivalent to * <pre>(o != null) && (o instanceof Item) && getCopeID().equals(((Item)o).getCopeID())</pre> * Does not activate this item, if it's not already active. */ @Override public final boolean equals(final Object o) { if(o==null || !(o instanceof Item)) return false; final Item i = (Item)o; return type==i.type && pk==i.pk; } /** * Returns a hash code, that is consistent with {@link #equals(Object)}. * Note, that this is not neccessarily equivalent to <tt>getCopeID().hashCode()</tt>. * Does not activate this item, if it's not already active. */ @Override public final int hashCode() { return type.hashCode() ^ pk; } @Override public String toString() { return getCopeID(); } /** * Returns, whether this item is active. */ public final boolean isActiveCopeItem() { final Entity entity = getEntityIfActive(); return (entity!=null) && (entity.getItem() == this); } /** * Returns the active item object representing the same item as this item object. * For any two item objects <tt>a</tt>, <tt>b</tt> the following holds true: * <p> * If and only if <tt>a.equals(b)</tt> then <tt>a.activeCopeItem() == b.activeCopeItem()</tt>. * <p> * So it does for items, what {@link String#intern} does for strings. * Does activate this item, if it's not already active. * Is guaranteed to be very cheap, if this item object is already active, which means * this method returns <tt>this</tt>. * Never returns null. */ public final Item activeCopeItem() { return getEntity().getItem(); } /** * @throws MandatoryViolationException * if <tt>value</tt> is null and <tt>attribute</tt> * is {@link Field#isMandatory() mandatory}. * @throws ClassCastException * if <tt>value</tt> is not compatible to <tt>attribute</tt>. */ protected Item(final SetValue[] setValues) { this(setValues, null); } /** * To be used from {@link ItemWithoutJavaClass} only. */ Item(final SetValue[] setValues, final Type<? extends Item> typeWithoutJavaClass) { this.type = typeWithoutJavaClass==null ? Type.findByJavaClass(getClass()) : typeWithoutJavaClass; this.pk = type.getPkSource().nextPK(type.getModel().getCurrentTransaction().getConnection()); if(pk==Type.NOT_A_PK) throw new RuntimeException(); //System.out.println("create item "+type+" "+pk); final Map<Field, Object> attributeValues = executeSetValues(setValues, null); Date now = null; for(final Field attribute : type.getFields()) { if(attribute instanceof FunctionField && !attributeValues.containsKey(attribute)) { final FunctionField fa = (FunctionField)attribute; Object defaultValue = fa.defaultConstant; if(defaultValue==null && fa instanceof DateField && ((DateField)fa).defaultNow) { if(now==null) now = new Date(); defaultValue = now; } if(defaultValue!=null) attributeValues.put(attribute, defaultValue); } } for(final Field attribute : attributeValues.keySet()) { if(!attribute.getType().isAssignableFrom(type)) throw new RuntimeException("field " + attribute + " does not belong to type " + type.toString()); } for(final Field attribute : type.getFields()) { attribute.checkValue(attributeValues.get(attribute), null); } final Entity entity = getEntity(false); entity.put(attributeValues); entity.write(toBlobs(attributeValues)); postCreate(); } /** * Is called after every item creation. Override this method when needed. * The default implementation does nothing. */ protected void postCreate() { // empty default implementation } /** * Reactivation constructor. * Is used for internal purposes only. * Does not actually create a new item, but a passive item object for * an already existing item. */ protected Item( final ReactivationConstructorDummy reactivationDummy, final int pk) { this(pk, null); if(reactivationDummy!=Type.REACTIVATION_DUMMY) throw new RuntimeException("reactivation constructor is for internal purposes only, don't use it in your application!"); } protected Item(final int pk, final Type<? extends Item> typeWithoutJavaClass) { this.type = typeWithoutJavaClass==null ? Type.findByJavaClass(getClass()) : typeWithoutJavaClass; this.pk = pk; //System.out.println("reactivate item:"+type+" "+pk); if(pk==Type.NOT_A_PK) throw new RuntimeException(); } /** * Empty constructor for deserialization. * <p> * To enable serialization for subclasses of <tt>Item</tt>, * let these classes implement {@link java.io.Serializable} * and make sure, there is a no-arg constructor * calling this deserialization constructor. * <p> * Serialization of instances of <tt>Item</tt> * is guaranteed to be light-weight - * there are no non-static, non-transient object reference * fields in this class or its supertypes. */ protected Item() { type = Type.findByJavaClass(getClass()); pk = suppressWarning(this.pk); } private static final int suppressWarning(final int pk) { return pk; } public final <E> E get(final Function<E> function) { return function.get(this); } /** * @throws MandatoryViolationException * if <tt>value</tt> is null and <tt>attribute</tt> * is {@link Field#isMandatory() mandatory}. * @throws FinalViolationException * if <tt>attribute</tt> is {@link Field#isFinal() final}. * @throws ClassCastException * if <tt>value</tt> is not compatible to <tt>attribute</tt>. */ public final <E> void set(final FunctionField<E> attribute, final E value) throws UniqueViolationException, MandatoryViolationException, LengthViolationException, FinalViolationException, ClassCastException { if(!attribute.getType().isAssignableFrom(type)) throw new RuntimeException("field " + attribute + " does not belong to type " + type.toString()); if(attribute.isfinal) throw new FinalViolationException(attribute, this); attribute.checkValue(value, this); final Entity entity = getEntity(); entity.put(attribute, value); entity.write(Collections.<BlobColumn, byte[]>emptyMap()); } /** * @throws MandatoryViolationException * if <tt>value</tt> is null and <tt>attribute</tt> * is {@link Field#isMandatory() mandatory}. * @throws FinalViolationException * if <tt>attribute</tt> is {@link Field#isFinal() final}. * @throws ClassCastException * if <tt>value</tt> is not compatible to <tt>attribute</tt>. */ public final void set(final SetValue[] setValues) throws UniqueViolationException, MandatoryViolationException, LengthViolationException, FinalViolationException, ClassCastException { final Map<Field, Object> attributeValues = executeSetValues(setValues, this); for(final Field attribute : attributeValues.keySet()) { if(!attribute.getType().isAssignableFrom(type)) throw new RuntimeException("field " + attribute + " does not belong to type " + type.toString()); if(attribute.isfinal) throw new FinalViolationException(attribute, this); attribute.checkValue(attributeValues.get(attribute), this); } final Entity entity = getEntity(); entity.put(attributeValues); entity.write(toBlobs(attributeValues)); } public final void deleteCopeItem() throws IntegrityViolationException { checkDeleteCopeItem(new HashSet<Item>()); deleteCopeItem(new HashSet<Item>()); } private final void checkDeleteCopeItem(final HashSet<Item> toDelete) throws IntegrityViolationException { toDelete.add(this); for(final ItemField<Item> attribute : castReferences(type.getReferences())) { switch(attribute.getDeletePolicy()) { case FORBID: { final Collection s = attribute.getType().search(attribute.equal(this)); if(!s.isEmpty()) throw new IntegrityViolationException(attribute, this); break; } case CASCADE: { for(final Item item : attribute.getType().search(attribute.equal(this))) { //System.out.println("------------check:"+item.toString()); if(!toDelete.contains(item)) item.checkDeleteCopeItem(toDelete); } break; } case NULLIFY: // avoid warnings break; } } } private final void deleteCopeItem(final HashSet<Item> toDelete) { toDelete.add(this); //final String tostring = toString(); //System.out.println("------------delete:"+tostring); // TODO make sure, no item is deleted twice for(final ItemField<Item> attribute : castReferences(type.getReferences())) { switch(attribute.getDeletePolicy()) { case NULLIFY: { final Query<? extends Item> q = attribute.getType().newQuery(attribute.equal(this)); for(final Item item : q.search()) { //System.out.println("------------nullify:"+item.toString()); item.set(attribute, null); } break; } case CASCADE: { final Query<?> q = attribute.getType().newQuery(attribute.equal(this)); for(Iterator j = q.search().iterator(); j.hasNext(); ) { final Item item = (Item)j.next(); //System.out.println("------------check:"+item.toString()); if(!toDelete.contains(item)) item.deleteCopeItem(toDelete); } break; } case FORBID: // avoid warnings break; } } Entity entity = getEntity(); entity.delete(); entity.write(null); } @SuppressWarnings("unchecked") private final List<ItemField<Item>> castReferences(final List l) { return (List<ItemField<Item>>)l; } /** * Returns, whether the item does exist. * There are two possibilities, why an item could not exist: * <ol> * <li>the item has been deleted by {@link #deleteCopeItem()}. * <li>the item has been created in a transaction, * that was subsequently rolled back by {@link Model#rollback()}. * </ol> */ public final boolean existsCopeItem() { try { return getEntity().exists(); } catch ( NoSuchItemException e ) { return false; } } // convenience for subclasses -------------------------------------------------- public static final Field.Option MANDATORY = Field.Option.MANDATORY; public static final Field.Option OPTIONAL = Field.Option.OPTIONAL; public static final Field.Option UNIQUE = Field.Option.UNIQUE; public static final Field.Option UNIQUE_OPTIONAL = Field.Option.UNIQUE_OPTIONAL; public static final Field.Option FINAL = Field.Option.FINAL; public static final Field.Option FINAL_OPTIONAL = Field.Option.FINAL_OPTIONAL; public static final Field.Option FINAL_UNIQUE = Field.Option.FINAL_UNIQUE; public static final Field.Option FINAL_UNIQUE_OPTIONAL = Field.Option.FINAL_UNIQUE_OPTIONAL; /** * @deprecated Has been renamed to {@link #FINAL}. */ @Deprecated public static final Field.Option READ_ONLY = FINAL; /** * @deprecated Has been renamed to {@link #FINAL_OPTIONAL}. */ @Deprecated public static final Field.Option READ_ONLY_OPTIONAL = FINAL_OPTIONAL; /** * @deprecated Has been renamed to {@link #FINAL_UNIQUE}. */ @Deprecated public static final Field.Option READ_ONLY_UNIQUE = FINAL_UNIQUE; /** * @deprecated Has been renamed to {@link #FINAL_UNIQUE_OPTIONAL}. */ @Deprecated public static final Field.Option READ_ONLY_UNIQUE_OPTIONAL = FINAL_UNIQUE_OPTIONAL; public static final ItemField.DeletePolicy FORBID = ItemField.DeletePolicy.FORBID; public static final ItemField.DeletePolicy NULLIFY = ItemField.DeletePolicy.NULLIFY; public static final ItemField.DeletePolicy CASCADE = ItemField.DeletePolicy.CASCADE; protected static final <C extends Item> Type<C> newType(final Class<C> javaClass) { return new Type<C>(javaClass); } protected static final <C extends Item> Type<C> newType(final Class<C> javaClass, final String id) { return new Type<C>(javaClass, id); } /** * @deprecated Renamed to {@link #newEnumField(Class)}. */ @Deprecated public static final <E extends Enum<E>> EnumField<E> newEnumAttribute(final Class<E> valueClass) { return newEnumField(valueClass); } @SuppressWarnings("deprecation") // OK: constructor is deprecated for public use only public static final <E extends Enum<E>> EnumField<E> newEnumField(final Class<E> valueClass) { return new EnumField<E>(valueClass); } /** * @deprecated Renamed to {@link #newEnumField(com.exedio.cope.Field.Option, Class)}. */ @Deprecated public static final <E extends Enum<E>> EnumField<E> newEnumAttribute(final Option option, final Class<E> valueClass) { return newEnumField(option, valueClass); } @SuppressWarnings("deprecation") // OK: constructor is deprecated for public use only public static final <E extends Enum<E>> EnumField<E> newEnumField(final Option option, final Class<E> valueClass) { return new EnumField<E>(option, valueClass); } /** * @deprecated Renamed to {@link #newItemField(Class)}. */ @Deprecated public static final <E extends Item> ItemField<E> newItemAttribute(final Class<E> valueClass) { return newItemField(valueClass); } @SuppressWarnings("deprecation") // OK: constructor is deprecated for public use only public static final <E extends Item> ItemField<E> newItemField(final Class<E> valueClass) { return new ItemField<E>(valueClass); } /** * @deprecated Renamed to {@link #newItemField(com.exedio.cope.Field.Option, Class)}. */ @Deprecated public static final <E extends Item> ItemField<E> newItemAttribute(final Option option, final Class<E> valueClass) { return newItemField(option, valueClass); } @SuppressWarnings("deprecation") // OK: constructor is deprecated for public use only public static final <E extends Item> ItemField<E> newItemField(final Option option, final Class<E> valueClass) { return new ItemField<E>(option, valueClass); } /** * @deprecated Renamed to {@link #newItemField(Class, com.exedio.cope.ItemField.DeletePolicy)}. */ @Deprecated public static final <E extends Item> ItemField<E> newItemAttribute(final Class<E> valueClass, final DeletePolicy policy) { return newItemField(valueClass, policy); } @SuppressWarnings("deprecation") // OK: constructor is deprecated for public use only public static final <E extends Item> ItemField<E> newItemField(final Class<E> valueClass, final DeletePolicy policy) { return new ItemField<E>(valueClass, policy); } /** * @deprecated Renamed to {@link #newItemField(com.exedio.cope.Field.Option, Class, com.exedio.cope.ItemField.DeletePolicy)}. */ @Deprecated public static final <E extends Item> ItemField<E> newItemAttribute(final Option option, final Class<E> valueClass, final DeletePolicy policy) { return newItemField(option, valueClass, policy); } @SuppressWarnings("deprecation") // OK: constructor is deprecated for public use only public static final <E extends Item> ItemField<E> newItemField(final Option option, final Class<E> valueClass, final DeletePolicy policy) { return new ItemField<E>(option, valueClass, policy); } // activation/deactivation ----------------------------------------------------- private final Entity getEntity() { return getEntity(true); } private final Entity getEntity(final boolean present) { return type.getModel().getCurrentTransaction().getEntity(this, present); } private final Entity getEntityIfActive() { return type.getModel().getCurrentTransaction().getEntityIfActive(type, pk); } private static final Map<Field, Object> executeSetValues(final SetValue<?>[] sources, final Item exceptionItem) { final HashMap<Field, Object> result = new HashMap<Field, Object>(); for(final SetValue<?> source : sources) { if(source.settable instanceof Field) { putAttribute(result, source); } else { for(final SetValue part : execute(source, exceptionItem)) putAttribute(result, part); } } return result; } private static final void putAttribute(final HashMap<Field, Object> result, final SetValue<?> setValue) { if(result.put((Field)setValue.settable, setValue.value)!=null) throw new RuntimeException("duplicate function attribute " + setValue.settable.toString()); } private static final <X extends Object> SetValue[] execute(final SetValue<X> sv, final Item exceptionItem) { return sv.settable.execute(sv.value, exceptionItem); } private final HashMap<BlobColumn, byte[]> toBlobs(final Map<Field, Object> fieldValues) { final HashMap<BlobColumn, byte[]> result = new HashMap<BlobColumn, byte[]>(); for(final Field field : fieldValues.keySet()) { if(!(field instanceof DataField)) continue; final DataField da = (DataField)field; da.impl.fillBlob((byte[])fieldValues.get(field), result, this); } return result; } }
runtime/src/com/exedio/cope/Item.java
/* * Copyright (C) 2004-2006 exedio GmbH (www.exedio.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.exedio.cope; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import com.exedio.cope.Field.Option; import com.exedio.cope.ItemField.DeletePolicy; import com.exedio.cope.util.ReactivationConstructorDummy; /** * This is the super class for all classes, * that want to store their data persistently with COPE. * <p> * To enable serialization for subclasses of <tt>Item</tt>, * see {@link #Item()}. * * @author Ralf Wiebicke */ public abstract class Item extends Cope { final transient Type<? extends Item> type; /** * The primary key of the item, * that is unique within the {@link #type} of this item. */ final int pk; /** * Returns a string unique for this item in all other items of the model. * For any item <tt>a</tt> in its model <tt>m</tt> * the following holds true: * <tt>a.equals(m.findByID(a.getCopeID()).</tt> * Does not activate this item, if it's not already active. * Never returns null. * @see Model#findByID(String) */ public final String getCopeID() { return type.id + '.' + type.getPkSource().pk2id(pk); } /** * Returns the type of this item. * Never returns null. */ public final Type<? extends Item> getCopeType() { assert type!=null; return type; } /** * Returns true, if <tt>o</tt> represents the same item as this item. * Is equivalent to * <pre>(o != null) && (o instanceof Item) && getCopeID().equals(((Item)o).getCopeID())</pre> * Does not activate this item, if it's not already active. */ @Override public final boolean equals(final Object o) { if(o==null || !(o instanceof Item)) return false; final Item i = (Item)o; return type==i.type && pk==i.pk; } /** * Returns a hash code, that is consistent with {@link #equals(Object)}. * Note, that this is not neccessarily equivalent to <tt>getCopeID().hashCode()</tt>. * Does not activate this item, if it's not already active. */ @Override public final int hashCode() { return type.hashCode() ^ pk; } @Override public String toString() { return getCopeID(); } /** * Returns, whether this item is active. */ public final boolean isActiveCopeItem() { final Entity entity = getEntityIfActive(); return (entity!=null) && (entity.getItem() == this); } /** * Returns the active item object representing the same item as this item object. * For any two item objects <tt>a</tt>, <tt>b</tt> the following holds true: * <p> * If and only if <tt>a.equals(b)</tt> then <tt>a.activeCopeItem() == b.activeCopeItem()</tt>. * <p> * So it does for items, what {@link String#intern} does for strings. * Does activate this item, if it's not already active. * Is guaranteed to be very cheap, if this item object is already active, which means * this method returns <tt>this</tt>. * Never returns null. */ public final Item activeCopeItem() { return getEntity().getItem(); } /** * @throws MandatoryViolationException * if <tt>value</tt> is null and <tt>attribute</tt> * is {@link Field#isMandatory() mandatory}. * @throws ClassCastException * if <tt>value</tt> is not compatible to <tt>attribute</tt>. */ protected Item(final SetValue[] setValues) { this(setValues, null); } /** * To be used from {@link ItemWithoutJavaClass} only. */ Item(final SetValue[] setValues, final Type<? extends Item> typeWithoutJavaClass) { this.type = typeWithoutJavaClass==null ? Type.findByJavaClass(getClass()) : typeWithoutJavaClass; this.pk = type.getPkSource().nextPK(type.getModel().getCurrentTransaction().getConnection()); if(pk==Type.NOT_A_PK) throw new RuntimeException(); //System.out.println("create item "+type+" "+pk); final Map<Field, Object> attributeValues = executeSetValues(setValues, null); Date now = null; for(final Field attribute : type.getFields()) { if(attribute instanceof FunctionField && !attributeValues.containsKey(attribute)) { final FunctionField fa = (FunctionField)attribute; Object defaultValue = fa.defaultConstant; if(defaultValue==null && fa instanceof DateField && ((DateField)fa).defaultNow) { if(now==null) now = new Date(); defaultValue = now; } if(defaultValue!=null) attributeValues.put(attribute, defaultValue); } } for(final Field attribute : attributeValues.keySet()) { if(!attribute.getType().isAssignableFrom(type)) throw new RuntimeException("field " + attribute + " does not belong to type " + type.toString()); } for(final Field attribute : type.getFields()) { attribute.checkValue(attributeValues.get(attribute), null); } final Entity entity = getEntity(false); entity.put(attributeValues); entity.write(toBlobs(attributeValues)); postCreate(); } /** * Is called after every item creation. Override this method when needed. * The default implementation does nothing. */ protected void postCreate() { // empty default implementation } /** * Reactivation constructor. * Is used for internal purposes only. * Does not actually create a new item, but a passive item object for * an already existing item. */ protected Item( final ReactivationConstructorDummy reactivationDummy, final int pk) { this(pk, null); if(reactivationDummy!=Type.REACTIVATION_DUMMY) throw new RuntimeException("reactivation constructor is for internal purposes only, don't use it in your application!"); } protected Item(final int pk, final Type<? extends Item> typeWithoutJavaClass) { this.type = typeWithoutJavaClass==null ? Type.findByJavaClass(getClass()) : typeWithoutJavaClass; this.pk = pk; //System.out.println("reactivate item:"+type+" "+pk); if(pk==Type.NOT_A_PK) throw new RuntimeException(); } /** * Empty constructor for deserialization. * <p> * To enable serialization for subclasses of <tt>Item</tt>, * let these classes implement {@link java.io.Serializable} * and make sure, there is a no-arg constructor * calling this deserialization constructor. * <p> * Serialization of instances of <tt>Item</tt> * is guaranteed to be light-weight - * there are no non-static, non-transient object reference * fields in this class or its supertypes. */ protected Item() { type = Type.findByJavaClass(getClass()); pk = suppressWarning(this.pk); } private static final int suppressWarning(final int pk) { return pk; } public final <E> E get(final Function<E> function) { return function.get(this); } /** * @throws MandatoryViolationException * if <tt>value</tt> is null and <tt>attribute</tt> * is {@link Field#isMandatory() mandatory}. * @throws FinalViolationException * if <tt>attribute</tt> is {@link Field#isFinal() final}. * @throws ClassCastException * if <tt>value</tt> is not compatible to <tt>attribute</tt>. */ public final <E> void set(final FunctionField<E> attribute, final E value) throws UniqueViolationException, MandatoryViolationException, LengthViolationException, FinalViolationException, ClassCastException { if(!attribute.getType().isAssignableFrom(type)) throw new RuntimeException("field " + attribute + " does not belong to type " + type.toString()); if(attribute.isfinal) throw new FinalViolationException(attribute, this); attribute.checkValue(value, this); final Entity entity = getEntity(); entity.put(attribute, value); entity.write(Collections.<BlobColumn, byte[]>emptyMap()); } /** * @throws MandatoryViolationException * if <tt>value</tt> is null and <tt>attribute</tt> * is {@link Field#isMandatory() mandatory}. * @throws FinalViolationException * if <tt>attribute</tt> is {@link Field#isFinal() final}. * @throws ClassCastException * if <tt>value</tt> is not compatible to <tt>attribute</tt>. */ public final void set(final SetValue[] setValues) throws UniqueViolationException, MandatoryViolationException, LengthViolationException, FinalViolationException, ClassCastException { final Map<Field, Object> attributeValues = executeSetValues(setValues, this); for(final Field attribute : attributeValues.keySet()) { if(!attribute.getType().isAssignableFrom(type)) throw new RuntimeException("field " + attribute + " does not belong to type " + type.toString()); if(attribute.isfinal) throw new FinalViolationException(attribute, this); attribute.checkValue(attributeValues.get(attribute), this); } final Entity entity = getEntity(); entity.put(attributeValues); entity.write(toBlobs(attributeValues)); } public final void deleteCopeItem() throws IntegrityViolationException { checkDeleteCopeItem(new HashSet<Item>()); deleteCopeItem(new HashSet<Item>()); } private final void checkDeleteCopeItem(final HashSet<Item> toDelete) throws IntegrityViolationException { toDelete.add(this); for(final ItemField<Item> attribute : castReferences(type.getReferences())) { switch(attribute.getDeletePolicy()) { case FORBID: { final Collection s = attribute.getType().search(attribute.equal(this)); if(!s.isEmpty()) throw new IntegrityViolationException(attribute, this); break; } case CASCADE: { for(final Item item : attribute.getType().search(attribute.equal(this))) { //System.out.println("------------check:"+item.toString()); if(!toDelete.contains(item)) item.checkDeleteCopeItem(toDelete); } break; } case NULLIFY: // avoid warnings break; } } } private final void deleteCopeItem(final HashSet<Item> toDelete) { toDelete.add(this); //final String tostring = toString(); //System.out.println("------------delete:"+tostring); // TODO make sure, no item is deleted twice for(final ItemField<Item> attribute : castReferences(type.getReferences())) { switch(attribute.getDeletePolicy()) { case NULLIFY: { final Query<? extends Item> q = attribute.getType().newQuery(attribute.equal(this)); for(final Item item : q.search()) { //System.out.println("------------nullify:"+item.toString()); item.set(attribute, null); } break; } case CASCADE: { final Query<?> q = attribute.getType().newQuery(attribute.equal(this)); for(Iterator j = q.search().iterator(); j.hasNext(); ) { final Item item = (Item)j.next(); //System.out.println("------------check:"+item.toString()); if(!toDelete.contains(item)) item.deleteCopeItem(toDelete); } break; } case FORBID: // avoid warnings break; } } Entity entity = getEntity(); entity.delete(); entity.write(null); } @SuppressWarnings("unchecked") private final List<ItemField<Item>> castReferences(final List l) { return (List<ItemField<Item>>)l; } /** * Returns, whether the item does exist. * There are two possibilities, why an item could not exist: * <ol> * <li>the item has been deleted by {@link #deleteCopeItem()}. * <li>the item has been created in a transaction, * that was subsequently rolled back by {@link Model#rollback()}. * </ol> */ public final boolean existsCopeItem() { try { return getEntity().exists(); } catch ( NoSuchItemException e ) { return false; } } // convenience for subclasses -------------------------------------------------- public static final Field.Option MANDATORY = Field.Option.MANDATORY; public static final Field.Option OPTIONAL = Field.Option.OPTIONAL; public static final Field.Option UNIQUE = Field.Option.UNIQUE; public static final Field.Option UNIQUE_OPTIONAL = Field.Option.UNIQUE_OPTIONAL; public static final Field.Option FINAL = Field.Option.FINAL; public static final Field.Option FINAL_OPTIONAL = Field.Option.FINAL_OPTIONAL; public static final Field.Option FINAL_UNIQUE = Field.Option.FINAL_UNIQUE; public static final Field.Option FINAL_UNIQUE_OPTIONAL = Field.Option.FINAL_UNIQUE_OPTIONAL; /** * @deprecated Has been renamed to {@link #FINAL}. */ @Deprecated public static final Field.Option READ_ONLY = FINAL; /** * @deprecated Has been renamed to {@link #FINAL_OPTIONAL}. */ @Deprecated public static final Field.Option READ_ONLY_OPTIONAL = FINAL_OPTIONAL; /** * @deprecated Has been renamed to {@link #FINAL_UNIQUE}. */ @Deprecated public static final Field.Option READ_ONLY_UNIQUE = FINAL_UNIQUE; /** * @deprecated Has been renamed to {@link #FINAL_UNIQUE_OPTIONAL}. */ @Deprecated public static final Field.Option READ_ONLY_UNIQUE_OPTIONAL = FINAL_UNIQUE_OPTIONAL; public static final ItemField.DeletePolicy FORBID = ItemField.DeletePolicy.FORBID; public static final ItemField.DeletePolicy NULLIFY = ItemField.DeletePolicy.NULLIFY; public static final ItemField.DeletePolicy CASCADE = ItemField.DeletePolicy.CASCADE; protected static final <C extends Item> Type<C> newType(final Class<C> javaClass) { return new Type<C>(javaClass); } protected static final <C extends Item> Type<C> newType(final Class<C> javaClass, final String id) { return new Type<C>(javaClass, id); } /** * @deprecated Renamed to {@link #newEnumField(Class)}. */ @Deprecated public static final <E extends Enum<E>> EnumField<E> newEnumAttribute(final Class<E> valueClass) { return newEnumField(valueClass); } @SuppressWarnings("deprecation") // OK: constructor is deprecated for public use only public static final <E extends Enum<E>> EnumField<E> newEnumField(final Class<E> valueClass) { return new EnumField<E>(valueClass); } /** * @deprecated Renamed to {@link #newEnumField(com.exedio.cope.Field.Option, Class)}. */ @Deprecated public static final <E extends Enum<E>> EnumField<E> newEnumAttribute(final Option option, final Class<E> valueClass) { return newEnumField(option, valueClass); } @SuppressWarnings("deprecation") // OK: constructor is deprecated for public use only public static final <E extends Enum<E>> EnumField<E> newEnumField(final Option option, final Class<E> valueClass) { return new EnumField<E>(option, valueClass); } /** * @deprecated Renamed to {@link #newItemField(Class)}. */ @Deprecated public static final <E extends Item> ItemField<E> newItemAttribute(final Class<E> valueClass) { return newItemField(valueClass); } @SuppressWarnings("deprecation") // OK: constructor is deprecated for public use only public static final <E extends Item> ItemField<E> newItemField(final Class<E> valueClass) { return new ItemField<E>(valueClass); } /** * @deprecated Renamed to {@link #newItemField(com.exedio.cope.Field.Option, Class)}. */ @Deprecated public static final <E extends Item> ItemField<E> newItemAttribute(final Option option, final Class<E> valueClass) { return newItemField(option, valueClass); } @SuppressWarnings("deprecation") // OK: constructor is deprecated for public use only public static final <E extends Item> ItemField<E> newItemField(final Option option, final Class<E> valueClass) { return new ItemField<E>(option, valueClass); } /** * @deprecated Renamed to {@link #newItemField(Class, com.exedio.cope.ItemField.DeletePolicy)}. */ @Deprecated public static final <E extends Item> ItemField<E> newItemAttribute(final Class<E> valueClass, final DeletePolicy policy) { return newItemField(valueClass, policy); } @SuppressWarnings("deprecation") // OK: constructor is deprecated for public use only public static final <E extends Item> ItemField<E> newItemField(final Class<E> valueClass, final DeletePolicy policy) { return new ItemField<E>(valueClass, policy); } /** * @deprecated Renamed to {@link #newItemField(com.exedio.cope.Field.Option, Class, com.exedio.cope.ItemField.DeletePolicy)}. */ @Deprecated public static final <E extends Item> ItemField<E> newItemAttribute(final Option option, final Class<E> valueClass, final DeletePolicy policy) { return newItemField(option, valueClass, policy); } @SuppressWarnings("deprecation") // OK: constructor is deprecated for public use only public static final <E extends Item> ItemField<E> newItemField(final Option option, final Class<E> valueClass, final DeletePolicy policy) { return new ItemField<E>(option, valueClass, policy); } // activation/deactivation ----------------------------------------------------- private final Entity getEntity() { return getEntity(true); } private final Entity getEntity(final boolean present) { return type.getModel().getCurrentTransaction().getEntity(this, present); } private final Entity getEntityIfActive() { return type.getModel().getCurrentTransaction().getEntityIfActive(type, pk); } private static final Map<Field, Object> executeSetValues(final SetValue<?>[] sources, final Item exceptionItem) { final HashMap<Field, Object> result = new HashMap<Field, Object>(); for(final SetValue<?> source : sources) { if(source.settable instanceof Field) { putAttribute(result, source); } else { for(final SetValue part : execute(source, exceptionItem)) putAttribute(result, part); } } return result; } private static final void putAttribute(final HashMap<Field, Object> result, final SetValue<?> setValue) { if(result.put((Field)setValue.settable, setValue.value)!=null) throw new RuntimeException("duplicate function attribute " + setValue.settable.toString()); } private static final <X extends Object> SetValue[] execute(final SetValue<X> sv, final Item exceptionItem) { return sv.settable.execute(sv.value, exceptionItem); } private final HashMap<BlobColumn, byte[]> toBlobs(final Map<Field, Object> fieldValues) { final HashMap<BlobColumn, byte[]> result = new HashMap<BlobColumn, byte[]>(); for(final Field attribute : fieldValues.keySet()) { if(!(attribute instanceof DataField)) continue; final DataField da = (DataField)attribute; da.impl.fillBlob((byte[])fieldValues.get(attribute), result, this); } return result; } }
rename attribute to field git-svn-id: 9dbc6da3594b32e13bcf3b3752e372ea5bc7c2cc@6518 e7d4fc99-c606-0410-b9bf-843393a9eab7
runtime/src/com/exedio/cope/Item.java
rename attribute to field
Java
lgpl-2.1
8ff1b4456845201377b78a9c88f7e3662d68ed48
0
kaffe/kaffe,kaffe/kaffe,kaffe/kaffe,kaffe/kaffe,kaffe/kaffe
/** * check some more class loading etc, this time with superclasses * * test written by Edouard Parmelan <[email protected]> */ public class ProcessClassTest { public static void test(final String tag, final String class_name) { Thread thread = new Thread() { public void run() { setName(tag); try { Class c = Class.forName(class_name); Object o = c.newInstance(); System.out.println(getName() + " " + class_name + " " + o); } catch (Throwable t) { System.out.println(getName() + " " + class_name + " " + t); //t.printStackTrace(); } } }; thread.start(); try { thread.join(); } catch (InterruptedException t) { System.out.println(thread.getName() + " " + class_name + " " + t); } } public static void main(String args[]) { new java.io.File("DontExist.class").delete(); test("A", "Segv"); test("B", "First"); test("C", "Second"); test("D", "Third"); test("E", "Segv"); test("F", "First"); test("G", "Second"); test("H", "Third"); } } class Segv { public Segv() { Object segv = null; segv.hashCode(); } } class First { static boolean inited; static { inited = false; new Segv(); inited = true; } public String toString() { if (inited) return new String("pass"); else return new String("fail"); } } class DontExist { } class Second extends DontExist { static boolean inited; static { inited = false; inited = true; } public String toString() { if (inited) return new String("pass"); else return new String("fail"); } } class Third { static boolean inited; static { inited = false; new DontExist(); inited = true; } public String toString() { if (inited) return new String("pass"); else return new String("fail"); } } /* Expected Output: A Segv java.lang.NullPointerException B First java.lang.ExceptionInInitializerError: [exception was java.lang.NullPointerException] C Second java.lang.NoClassDefFoundError: DontExist D Third java.lang.ExceptionInInitializerError: [exception was java.lang.NoClassDefFoundError: DontExist] E Segv java.lang.NullPointerException F First java.lang.NoClassDefFoundError: First G Second java.lang.NoClassDefFoundError: Second H Third java.lang.NoClassDefFoundError: Third */
test/regression/ProcessClassTest.java
/** * check some more class loading etc, this time with superclasses * * test written by Edouard Parmelan <[email protected]> */ public class ProcessClassTest { public static void test(final String tag, final String class_name) { Thread thread = new Thread() { public void run() { setName(tag); try { Class c = Class.forName(class_name); Object o = c.newInstance(); System.out.println(getName() + " " + class_name + " " + o); } catch (Throwable t) { System.out.println(getName() + " " + class_name + " " + t); //t.printStackTrace(); } } }; thread.start(); try { thread.join(); } catch (InterruptedException t) { System.out.println(thread.getName() + " " + class_name + " " + t); } } public static void main(String args[]) { new java.io.File("DontExist.class").delete(); test("A", "Segv"); test("B", "First"); test("C", "Second"); test("D", "Third"); test("E", "Segv"); test("F", "First"); test("G", "Second"); test("H", "Third"); } } class Segv { public Segv() { Object segv = null; segv.hashCode(); } } class First { static boolean inited; static { inited = false; new Segv(); inited = true; } public String toString() { if (inited) return new String("pass"); else return new String("fail"); } } class DontExist { } class Second extends DontExist { static boolean inited; static { inited = false; inited = true; } public String toString() { if (inited) return new String("pass"); else return new String("fail"); } } class Third { static boolean inited; static { inited = false; new DontExist(); inited = true; } public String toString() { if (inited) return new String("pass"); else return new String("fail"); } } /* Expected Output: A Segv java.lang.NullPointerException B First java.lang.ExceptionInInitializerError: [exception was java.lang.NullPointerException: null] C Second java.lang.NoClassDefFoundError: DontExist D Third java.lang.ExceptionInInitializerError: [exception was java.lang.NoClassDefFoundError: DontExist] E Segv java.lang.NullPointerException F First java.lang.NoClassDefFoundError: First G Second java.lang.NoClassDefFoundError: Second H Third java.lang.NoClassDefFoundError: Third */
Adjust expected output as a result of change to ExceptionInInitializer.java
test/regression/ProcessClassTest.java
Adjust expected output as a result of change to ExceptionInInitializer.java
Java
apache-2.0
fd52106cb1781f720403b322794464e3b84f05dc
0
barterli/barterli_android,siddharth-shah/barterli_android
/******************************************************************************* * Copyright 2014, barter.li * * 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 li.barter.fragments; import com.android.volley.Request.Method; import com.google.android.gms.analytics.HitBuilders.EventBuilder; import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh; import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout; import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.Loader; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MenuItem.OnActionExpandListener; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import android.widget.SearchView; import android.widget.SearchView.OnCloseListener; import java.util.HashMap; import java.util.Map; import li.barter.R; import li.barter.activities.AbstractBarterLiActivity.AlertStyle; import li.barter.activities.ScanIsbnActivity; import li.barter.adapters.BooksGridAdapter; import li.barter.analytics.AnalyticsConstants.Actions; import li.barter.analytics.AnalyticsConstants.Categories; import li.barter.analytics.AnalyticsConstants.ParamKeys; import li.barter.analytics.AnalyticsConstants.ParamValues; import li.barter.analytics.AnalyticsConstants.Screens; import li.barter.analytics.GoogleAnalyticsManager; import li.barter.data.DBInterface; import li.barter.data.DBInterface.AsyncDbQueryCallback; import li.barter.data.DatabaseColumns; import li.barter.data.SQLiteLoader; import li.barter.data.TableSearchBooks; import li.barter.data.ViewSearchBooksWithLocations; import li.barter.fragments.dialogs.EnableLocationDialogFragment; import li.barter.fragments.dialogs.SingleChoiceDialogFragment; import li.barter.http.BlRequest; import li.barter.http.HttpConstants; import li.barter.http.HttpConstants.ApiEndpoints; import li.barter.http.HttpConstants.RequestId; import li.barter.http.IBlRequestContract; import li.barter.http.ResponseInfo; import li.barter.utils.AppConstants; import li.barter.utils.AppConstants.DeviceInfo; import li.barter.utils.AppConstants.FragmentTags; import li.barter.utils.AppConstants.Keys; import li.barter.utils.AppConstants.Loaders; import li.barter.utils.AppConstants.QueryTokens; import li.barter.utils.AppConstants.RequestCodes; import li.barter.utils.AppConstants.ResultCodes; import li.barter.utils.LoadMoreHelper; import li.barter.utils.LoadMoreHelper.LoadMoreCallbacks; import li.barter.utils.Logger; import li.barter.utils.SearchViewNetworkQueryHelper; import li.barter.utils.SearchViewNetworkQueryHelper.NetworkCallbacks; import li.barter.utils.SharedPreferenceHelper; import li.barter.utils.Utils; /** * @author Vinay S Shenoy Fragment for displaying Books Around Me. Also contains * a Map that the user can use to easily switch locations */ public class BooksAroundMeFragment extends AbstractBarterLiFragment implements LoaderCallbacks<Cursor>, AsyncDbQueryCallback, OnItemClickListener, LoadMoreCallbacks, NetworkCallbacks, OnRefreshListener, OnCloseListener, OnActionExpandListener, OnClickListener { private static final String TAG = "BooksAroundMeFragment"; /** * Helper class for performing network search queries from Action Bar easily */ private SearchViewNetworkQueryHelper mSearchNetworkQueryHelper; /** * GridView into which the book content will be placed */ private GridView mBooksAroundMeGridView; /** * {@link BooksGridAdapter} instance for the Books */ private BooksGridAdapter mBooksAroundMeAdapter; /** * Current page used for load more */ private int mCurPage; /** * Used to remember the last location so that we can avoid fetching the * books again if the last fetched locations, and current fetched locations * are close by */ private Location mLastFetchedLocation; /** * Flag to indicate whether a load operation is in progress */ private boolean mIsLoading; /** * Flag to indicate whether all items have been fetched */ private boolean mHasLoadedAllItems; /** * Reference to the Dialog Fragment for selecting the book add options */ private SingleChoiceDialogFragment mAddBookDialogFragment; /** * Action Bar SearchView */ private SearchView mSearchView; private View mEmptyView; /** * {@link PullToRefreshLayout} reference */ private PullToRefreshLayout mPullToRefreshLayout; private EnableLocationDialogFragment mEnableLocationDialogFragment; @Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { init(container, savedInstanceState); setHasOptionsMenu(true); final View contentView = inflater .inflate(R.layout.fragment_books_around_me, container, false); setActionBarTitle(R.string.app_name); mPullToRefreshLayout = (PullToRefreshLayout) contentView .findViewById(R.id.ptr_layout); mBooksAroundMeGridView = (GridView) contentView .findViewById(R.id.grid_books_around_me); ActionBarPullToRefresh.from(getActivity()).allChildrenArePullable() .listener(this).setup(mPullToRefreshLayout); LoadMoreHelper.init(this).on(mBooksAroundMeGridView); mBooksAroundMeAdapter = new BooksGridAdapter(getActivity()); mBooksAroundMeGridView.setAdapter(mBooksAroundMeAdapter); mBooksAroundMeGridView.setOnItemClickListener(this); mBooksAroundMeGridView.setVerticalScrollBarEnabled(false); mEmptyView = contentView.findViewById(R.id.empty_view); mEmptyView.findViewById(R.id.text_try_again).setOnClickListener(this); mEmptyView.findViewById(R.id.text_add_your_own) .setOnClickListener(this); mEmptyView.findViewById(R.id.image_add_graphic) .setOnClickListener(this); mCurPage = SharedPreferenceHelper .getInt(getActivity(), R.string.pref_last_fetched_page, 0); if (savedInstanceState != null) { mLastFetchedLocation = savedInstanceState .getParcelable(Keys.LAST_FETCHED_LOCATION); mHasLoadedAllItems = savedInstanceState .getBoolean(Keys.HAS_LOADED_ALL_ITEMS); } mAddBookDialogFragment = (SingleChoiceDialogFragment) getFragmentManager() .findFragmentByTag(FragmentTags.DIALOG_ADD_BOOK); mEnableLocationDialogFragment = (EnableLocationDialogFragment) getFragmentManager() .findFragmentByTag(FragmentTags.DIALOG_ENABLE_LOCATION); loadBookSearchResults(); setActionBarDrawerToggleEnabled(true); return contentView; } @Override public void onSaveInstanceState(final Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(Keys.LAST_FETCHED_LOCATION, mLastFetchedLocation); outState.putBoolean(Keys.HAS_LOADED_ALL_ITEMS, mHasLoadedAllItems); } /** * Starts the loader for book search results */ private void loadBookSearchResults() { getLoaderManager().restartLoader(Loaders.SEARCH_BOOKS, null, this); } /** * Method to fetch books around me from the server centered at a location, * and in a search radius * * @param center The {@link Location} representing the center */ private void fetchBooksAroundMe(final Location center) { if (center != null) { mIsLoading = true; final BlRequest request = new BlRequest(Method.GET, HttpConstants.getApiBaseUrl() + ApiEndpoints.SEARCH, null, mVolleyCallbacks); request.setRequestId(RequestId.SEARCH_BOOKS); final Map<String, String> params = new HashMap<String, String>(2); params.put(HttpConstants.LATITUDE, String.valueOf(center .getLatitude())); params.put(HttpConstants.LONGITUDE, String.valueOf(center .getLongitude())); Logger.d(TAG, center.getLatitude() + " " + center.getLongitude()); final int pageToFetch = mCurPage + 1; params.put(HttpConstants.PAGE, String.valueOf(pageToFetch)); params.put(HttpConstants.PERLIMIT, String .valueOf(AppConstants.DEFAULT_ITEM_COUNT)); request.addExtra(Keys.LOCATION, center); request.setParams(params); addRequestToQueue(request, true, 0, true); } } /** * Method to fetch books around me from the server centered at a location, * and in a search radius and the search field * * @param center The {@link Location} representing the center * @param radius The radius(in kilometers) to search in * @param bookname The book name to search for */ private void fetchBooksAroundMeForSearch(final Location center, final int radius, final String bookname) { if (center != null) { final BlRequest request = new BlRequest(Method.GET, HttpConstants.getApiBaseUrl() + ApiEndpoints.SEARCH, null, mVolleyCallbacks); request.setRequestId(RequestId.SEARCH_BOOKS); final Map<String, String> params = new HashMap<String, String>(2); params.put(HttpConstants.LATITUDE, String.valueOf(center .getLatitude())); params.put(HttpConstants.LONGITUDE, String.valueOf(center .getLongitude())); params.put(HttpConstants.SEARCH, bookname); params.put(HttpConstants.PERLIMIT, String .valueOf(AppConstants.DEFAULT_ITEM_COUNT)); request.addExtra(Keys.LOCATION, center); if (radius >= 1) { params.put(HttpConstants.RADIUS, String.valueOf(radius)); } request.setParams(params); addRequestToQueue(request, true, 0, true); } } @Override public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) { inflater.inflate(R.menu.menu_books_around_me, menu); final MenuItem menuItem = menu.findItem(R.id.action_search); menuItem.setOnActionExpandListener(this); mSearchView = (SearchView) menuItem.getActionView(); mSearchNetworkQueryHelper = new SearchViewNetworkQueryHelper(mSearchView, this); mSearchNetworkQueryHelper.setSuggestCountThreshold(3); mSearchNetworkQueryHelper.setSuggestWaitThreshold(400); } @Override public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.action_add_book: { showAddBookOptions(); return true; } default: { return super.onOptionsItemSelected(item); } } } /** * Show dialog for adding books */ private void showAddBookOptions() { mAddBookDialogFragment = new SingleChoiceDialogFragment(); mAddBookDialogFragment .show(AlertDialog.THEME_HOLO_LIGHT, R.array.add_book_choices, 0, R.string.add_book_dialog_head, getFragmentManager(), true, FragmentTags.DIALOG_ADD_BOOK); } @Override public void onActivityResult(final int requestCode, final int resultCode, final Intent data) { if ((requestCode == RequestCodes.SCAN_ISBN) && (resultCode == ResultCodes.SUCCESS)) { Bundle args = null; if (data != null) { args = data.getExtras(); } loadAddOrEditBookFragment(args); } else { super.onActivityResult(requestCode, resultCode, data); } } @Override protected Object getVolleyTag() { return hashCode(); } public void updateLocation(final Location location) { if ((location.getLatitude() == 0.0) && (location.getLongitude() == 0.0)) { return; } fetchBooksOnLocationUpdate(location); } /** * When the location is updated, check to see if books need to be refreshed, * and refresh them * * @param location The location at which books should be fetched */ private void fetchBooksOnLocationUpdate(Location location) { if (shouldRefetchBooks(location)) { final Bundle cookie = new Bundle(1); cookie.putParcelable(Keys.LOCATION, location); // Delete the current search results before parsing the old ones DBInterface.deleteAsync(AppConstants.QueryTokens.DELETE_BOOKS_SEARCH_RESULTS, cookie, TableSearchBooks.NAME, null, null, true, this); } else { mCurPage = 0; mHasLoadedAllItems = false; fetchBooksAroundMe(location); } } @Override public void onPause() { super.onPause(); saveLastFetchedInfoToPref(); } /** * Saves the last fetched info to shared preferences. This will be read * again in onResume so as to prevent refetching of the books */ private void saveLastFetchedInfoToPref() { SharedPreferenceHelper .set(getActivity(), R.string.pref_last_fetched_page, mCurPage); if (mLastFetchedLocation != null) { SharedPreferenceHelper .set(getActivity(), R.string.pref_last_fetched_latitude, mLastFetchedLocation .getLatitude()); SharedPreferenceHelper .set(getActivity(), R.string.pref_last_fetched_longitude, mLastFetchedLocation .getLongitude()); } } @Override public void onResume() { super.onResume(); //done to force refresh! just change the value accordingly, default value is false if (!SharedPreferenceHelper .getBoolean(getActivity(), R.string.pref_dont_refresh_books)) { SharedPreferenceHelper .set(getActivity(), R.string.pref_last_fetched_latitude, 0.0); SharedPreferenceHelper .set(getActivity(), R.string.pref_last_fetched_longitude, 0.0); SharedPreferenceHelper .set(getActivity(), R.string.pref_dont_refresh_books, true); } if (isLocationServiceEnabled()) { readLastFetchedInfoFromPref(); final Location latestLocation = DeviceInfo.INSTANCE .getLatestLocation(); if ((latestLocation.getLatitude() != 0.0) && (latestLocation.getLongitude() != 0.0)) { updateLocation(latestLocation); } } else { showEnableLocationDialog(); } } /** * Show the dialog for the user to add his name, in case it's not already * added */ protected void showEnableLocationDialog() { mEnableLocationDialogFragment = new EnableLocationDialogFragment(); mEnableLocationDialogFragment .show(AlertDialog.THEME_HOLO_LIGHT, 0, R.string.enable_location, R.string.enable_location_message, R.string.enable, R.string.cancel, 0, getFragmentManager(), true, FragmentTags.DIALOG_ENABLE_LOCATION); } /** * Reads the latest fetched locations from shared preferences */ private void readLastFetchedInfoFromPref() { // Don't read from pref if already has fetched if (mLastFetchedLocation == null) { mLastFetchedLocation = new Location(LocationManager.PASSIVE_PROVIDER); Logger.d(TAG, mLastFetchedLocation.getLatitude() + ""); if (mLastFetchedLocation == null) { mLastFetchedLocation = new Location(LocationManager.NETWORK_PROVIDER); Logger.d(TAG, mLastFetchedLocation.getLatitude() + ""); } mLastFetchedLocation .setLatitude(SharedPreferenceHelper .getDouble(getActivity(), R.string.pref_last_fetched_latitude)); mLastFetchedLocation .setLongitude(SharedPreferenceHelper .getDouble(getActivity(), R.string.pref_last_fetched_longitude)); } } /** * Loads the Fragment to Add Or Edit Books * * @param bookInfo The book info to load. Can be <code>null</code>, in which * case, it treats it as Add a new book flow */ private void loadAddOrEditBookFragment(final Bundle bookInfo) { loadFragment(mContainerViewId, (AbstractBarterLiFragment) Fragment .instantiate(getActivity(), AddOrEditBookFragment.class .getName(), bookInfo), FragmentTags.ADD_OR_EDIT_BOOK, true, FragmentTags.BS_BOOKS_AROUND_ME); } @Override public void onSuccess(final int requestId, final IBlRequestContract request, final ResponseInfo response) { if (requestId == RequestId.SEARCH_BOOKS) { mLastFetchedLocation = (Location) request.getExtras() .get(Keys.LOCATION); mCurPage++; if (response.responseBundle.getBoolean(Keys.NO_BOOKS_FLAG_KEY)) { mHasLoadedAllItems = true; mCurPage--; } /* * Do nothing because the loader will take care of reloading the * data */ } } @Override public void onPostExecute(final IBlRequestContract request) { super.onPostExecute(request); if (request.getRequestId() == RequestId.SEARCH_BOOKS) { mIsLoading = false; mPullToRefreshLayout.setRefreshComplete(); } } @Override public void onBadRequestError(final int requestId, final IBlRequestContract request, final int errorCode, final String errorMessage, final Bundle errorResponseBundle) { if (requestId == RequestId.SEARCH_BOOKS) { showCrouton(R.string.unable_to_fetch_books, AlertStyle.ERROR); } if (requestId == RequestId.SEARCH_BOOKS_FROM_EDITTEXT) { showCrouton(R.string.unable_to_fetch_books, AlertStyle.ERROR); } } @Override public void onOtherError(int requestId, IBlRequestContract request, int errorCode) { if (requestId == RequestId.SEARCH_BOOKS) { showCrouton(R.string.unable_to_fetch_books, AlertStyle.ERROR); } if (requestId == RequestId.SEARCH_BOOKS_FROM_EDITTEXT) { showCrouton(R.string.unable_to_fetch_books, AlertStyle.ERROR); } } @Override public Loader<Cursor> onCreateLoader(final int loaderId, final Bundle args) { if (loaderId == Loaders.SEARCH_BOOKS) { return new SQLiteLoader(getActivity(), false, ViewSearchBooksWithLocations.NAME, null, null, null, null, null, null, null); } else { return null; } } @Override public void onLoadFinished(final Loader<Cursor> loader, final Cursor cursor) { if (loader.getId() == Loaders.SEARCH_BOOKS) { if(cursor.getCount()==0) { mBooksAroundMeGridView.setEmptyView(mEmptyView); } Logger.d(TAG, "Cursor Loaded with count: %d", cursor.getCount()); { mBooksAroundMeAdapter.swapCursor(cursor); } } } @Override public void onLoaderReset(final Loader<Cursor> loader) { if (loader.getId() == Loaders.SEARCH_BOOKS) { mBooksAroundMeAdapter.swapCursor(null); } } /** * Checks if a new set of books should be fetched * * @param center The new center point at which the books should be fetched * @return <code>true</code> if a new set should be fetched, * <code>false</code> otherwise */ private boolean shouldRefetchBooks(final Location center) { if (mLastFetchedLocation != null) { final float distanceBetweenCurAndLastFetchedLocations = Utils .distanceBetween(center, mLastFetchedLocation) / 1000; /* * If there's less than 25 km distance between the current location * and the location where we last fetched the books we don't need to * fetch the books again since the current set will include * those(The server uses 50 km as the search radius) */ if (distanceBetweenCurAndLastFetchedLocations <= 25.0f) { Logger.v(TAG, "Points are really close. Don't fetch"); return false; } } return true; } @Override public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) { if (parent.getId() == R.id.grid_books_around_me) { if (position == mBooksAroundMeAdapter.getCount() - 1) { showAddBookOptions(); } else { final Cursor cursor = (Cursor) mBooksAroundMeAdapter .getItem(position); final String idBook = cursor.getString(cursor .getColumnIndex(DatabaseColumns.ID)); Logger.d(TAG, "ID:" + idBook); final String userId = cursor.getString(cursor .getColumnIndex(DatabaseColumns.USER_ID)); final Bundle showBooksArgs = new Bundle(); showBooksArgs.putString(Keys.ID, idBook); showBooksArgs.putString(Keys.USER_ID, userId); showBooksArgs.putInt(Keys.BOOK_POSITION, position); loadFragment(mContainerViewId, (AbstractBarterLiFragment) Fragment .instantiate(getActivity(), BooksPagerFragment.class .getName(), showBooksArgs), FragmentTags.BOOKS_AROUND_ME, true, FragmentTags.BS_BOOK_DETAIL); } } } @Override public void onInsertComplete(final int token, final Object cookie, final long insertRowId) { // TODO Auto-generated method stub } @Override public void onDeleteComplete(final int token, final Object cookie, final int deleteCount) { if (token == QueryTokens.DELETE_BOOKS_SEARCH_RESULTS) { assert (cookie != null); mCurPage = 0; mHasLoadedAllItems = false; final Bundle args = (Bundle) cookie; fetchBooksAroundMe((Location) args.getParcelable(Keys.LOCATION)); } if (token == QueryTokens.DELETE_BOOKS_SEARCH_RESULTS_FROM_EDITTEXT) { assert (cookie != null); final Bundle args = (Bundle) cookie; fetchBooksAroundMeForSearch((Location) args.getParcelable(Keys.LOCATION), 50, args .getString(Keys.SEARCH)); } } @Override public void onUpdateComplete(final int token, final Object cookie, final int updateCount) { // TODO Auto-generated method stub } @Override public void onQueryComplete(final int token, final Object cookie, final Cursor cursor) { // TODO Auto-generated method stub } @Override public void onLoadMore() { fetchBooksAroundMe(mLastFetchedLocation); } @Override public boolean isLoading() { return mIsLoading; } @Override public boolean hasLoadedAllItems() { return mHasLoadedAllItems; } @Override public boolean willHandleDialog(final DialogInterface dialog) { if ((mAddBookDialogFragment != null) && mAddBookDialogFragment.getDialog().equals(dialog)) { return true; } else if ((mEnableLocationDialogFragment != null) && mEnableLocationDialogFragment.getDialog() .equals(dialog)) { return true; } return super.willHandleDialog(dialog); } @Override public void onDialogClick(final DialogInterface dialog, final int which) { if ((mAddBookDialogFragment != null) && mAddBookDialogFragment.getDialog().equals(dialog)) { if (which == 0) { // scan book startActivityForResult(new Intent(getActivity(), ScanIsbnActivity.class), RequestCodes.SCAN_ISBN); GoogleAnalyticsManager .getInstance() .sendEvent(new EventBuilder(Categories.USAGE, Actions.ADD_BOOK) .set(ParamKeys.TYPE, ParamValues.SCAN)); } else if (which == 1) { // add book manually loadAddOrEditBookFragment(null); GoogleAnalyticsManager .getInstance() .sendEvent(new EventBuilder(Categories.USAGE, Actions.ADD_BOOK) .set(ParamKeys.TYPE, ParamValues.MANUAL)); } } else if ((mEnableLocationDialogFragment != null) && mEnableLocationDialogFragment.getDialog() .equals(dialog)) { if (which == DialogInterface.BUTTON_POSITIVE) { // enable location Intent locationOptionsIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(locationOptionsIntent); } else if (which == DialogInterface.BUTTON_NEGATIVE) { // cancel dialog.cancel(); } } else { super.onDialogClick(dialog, which); } } @Override public void performQuery(SearchView searchView, String query) { final Bundle cookie = new Bundle(2); cookie.putParcelable(Keys.LOCATION, mLastFetchedLocation); cookie.putString(Keys.SEARCH, query); // Delete the current search results before parsing the old ones DBInterface.deleteAsync(AppConstants.QueryTokens.DELETE_BOOKS_SEARCH_RESULTS_FROM_EDITTEXT, cookie, TableSearchBooks.NAME, null, null, true, BooksAroundMeFragment.this); } @Override public void onRefreshStarted(View view) { if (view.getId() == R.id.grid_books_around_me) { reloadNearbyBooks(); } } /** * Reloads nearby books */ private void reloadNearbyBooks() { mSearchView.setQuery(null, false); final Bundle cookie = new Bundle(2); cookie.putParcelable(Keys.LOCATION, mLastFetchedLocation); DBInterface.deleteAsync(AppConstants.QueryTokens.DELETE_BOOKS_SEARCH_RESULTS, cookie, TableSearchBooks.NAME, null, null, true, this); } @Override public boolean onMenuItemActionCollapse(MenuItem item) { reloadNearbyBooks(); return true; } @Override public boolean onMenuItemActionExpand(MenuItem item) { return true; } @Override public boolean onClose() { return false; } @Override protected String getAnalyticsScreenName() { return Screens.BOOKS_AROUND_ME; } @Override public void onClick(View v) { final int id = v.getId(); switch (id) { case R.id.text_try_again: { reloadNearbyBooks(); break; } case R.id.image_add_graphic: case R.id.text_add_your_own: { showAddBookOptions(); break; } } } }
barter.li/src/li/barter/fragments/BooksAroundMeFragment.java
/******************************************************************************* * Copyright 2014, barter.li * * 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 li.barter.fragments; import com.android.volley.Request.Method; import com.google.android.gms.analytics.HitBuilders.EventBuilder; import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh; import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout; import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.Loader; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MenuItem.OnActionExpandListener; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import android.widget.SearchView; import android.widget.SearchView.OnCloseListener; import java.util.HashMap; import java.util.Map; import li.barter.R; import li.barter.activities.AbstractBarterLiActivity.AlertStyle; import li.barter.activities.ScanIsbnActivity; import li.barter.adapters.BooksGridAdapter; import li.barter.analytics.AnalyticsConstants.Actions; import li.barter.analytics.AnalyticsConstants.Categories; import li.barter.analytics.AnalyticsConstants.ParamKeys; import li.barter.analytics.AnalyticsConstants.ParamValues; import li.barter.analytics.AnalyticsConstants.Screens; import li.barter.analytics.GoogleAnalyticsManager; import li.barter.data.DBInterface; import li.barter.data.DBInterface.AsyncDbQueryCallback; import li.barter.data.DatabaseColumns; import li.barter.data.SQLiteLoader; import li.barter.data.TableSearchBooks; import li.barter.data.ViewSearchBooksWithLocations; import li.barter.fragments.dialogs.EnableLocationDialogFragment; import li.barter.fragments.dialogs.SingleChoiceDialogFragment; import li.barter.http.BlRequest; import li.barter.http.HttpConstants; import li.barter.http.HttpConstants.ApiEndpoints; import li.barter.http.HttpConstants.RequestId; import li.barter.http.IBlRequestContract; import li.barter.http.ResponseInfo; import li.barter.utils.AppConstants; import li.barter.utils.AppConstants.DeviceInfo; import li.barter.utils.AppConstants.FragmentTags; import li.barter.utils.AppConstants.Keys; import li.barter.utils.AppConstants.Loaders; import li.barter.utils.AppConstants.QueryTokens; import li.barter.utils.AppConstants.RequestCodes; import li.barter.utils.AppConstants.ResultCodes; import li.barter.utils.LoadMoreHelper; import li.barter.utils.LoadMoreHelper.LoadMoreCallbacks; import li.barter.utils.Logger; import li.barter.utils.SearchViewNetworkQueryHelper; import li.barter.utils.SearchViewNetworkQueryHelper.NetworkCallbacks; import li.barter.utils.SharedPreferenceHelper; import li.barter.utils.Utils; /** * @author Vinay S Shenoy Fragment for displaying Books Around Me. Also contains * a Map that the user can use to easily switch locations */ public class BooksAroundMeFragment extends AbstractBarterLiFragment implements LoaderCallbacks<Cursor>, AsyncDbQueryCallback, OnItemClickListener, LoadMoreCallbacks, NetworkCallbacks, OnRefreshListener, OnCloseListener, OnActionExpandListener, OnClickListener { private static final String TAG = "BooksAroundMeFragment"; /** * Helper class for performing network search queries from Action Bar easily */ private SearchViewNetworkQueryHelper mSearchNetworkQueryHelper; /** * GridView into which the book content will be placed */ private GridView mBooksAroundMeGridView; /** * {@link BooksGridAdapter} instance for the Books */ private BooksGridAdapter mBooksAroundMeAdapter; /** * Current page used for load more */ private int mCurPage; /** * Used to remember the last location so that we can avoid fetching the * books again if the last fetched locations, and current fetched locations * are close by */ private Location mLastFetchedLocation; /** * Flag to indicate whether a load operation is in progress */ private boolean mIsLoading; /** * Flag to indicate whether all items have been fetched */ private boolean mHasLoadedAllItems; /** * Reference to the Dialog Fragment for selecting the book add options */ private SingleChoiceDialogFragment mAddBookDialogFragment; /** * Action Bar SearchView */ private SearchView mSearchView; private View mEmptyView; /** * {@link PullToRefreshLayout} reference */ private PullToRefreshLayout mPullToRefreshLayout; private EnableLocationDialogFragment mEnableLocationDialogFragment; @Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { init(container, savedInstanceState); setHasOptionsMenu(true); final View contentView = inflater .inflate(R.layout.fragment_books_around_me, container, false); setActionBarTitle(R.string.app_name); mPullToRefreshLayout = (PullToRefreshLayout) contentView .findViewById(R.id.ptr_layout); mBooksAroundMeGridView = (GridView) contentView .findViewById(R.id.grid_books_around_me); ActionBarPullToRefresh.from(getActivity()).allChildrenArePullable() .listener(this).setup(mPullToRefreshLayout); LoadMoreHelper.init(this).on(mBooksAroundMeGridView); mBooksAroundMeAdapter = new BooksGridAdapter(getActivity()); mBooksAroundMeGridView.setAdapter(mBooksAroundMeAdapter); mBooksAroundMeGridView.setOnItemClickListener(this); mBooksAroundMeGridView.setVerticalScrollBarEnabled(false); mEmptyView = contentView.findViewById(R.id.empty_view); mEmptyView.findViewById(R.id.text_try_again).setOnClickListener(this); mEmptyView.findViewById(R.id.text_add_your_own) .setOnClickListener(this); mEmptyView.findViewById(R.id.image_add_graphic) .setOnClickListener(this); mBooksAroundMeGridView.setEmptyView(mEmptyView); mCurPage = SharedPreferenceHelper .getInt(getActivity(), R.string.pref_last_fetched_page, 0); if (savedInstanceState != null) { mLastFetchedLocation = savedInstanceState .getParcelable(Keys.LAST_FETCHED_LOCATION); mHasLoadedAllItems = savedInstanceState .getBoolean(Keys.HAS_LOADED_ALL_ITEMS); } mAddBookDialogFragment = (SingleChoiceDialogFragment) getFragmentManager() .findFragmentByTag(FragmentTags.DIALOG_ADD_BOOK); mEnableLocationDialogFragment = (EnableLocationDialogFragment) getFragmentManager() .findFragmentByTag(FragmentTags.DIALOG_ENABLE_LOCATION); loadBookSearchResults(); setActionBarDrawerToggleEnabled(true); return contentView; } @Override public void onSaveInstanceState(final Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(Keys.LAST_FETCHED_LOCATION, mLastFetchedLocation); outState.putBoolean(Keys.HAS_LOADED_ALL_ITEMS, mHasLoadedAllItems); } /** * Starts the loader for book search results */ private void loadBookSearchResults() { getLoaderManager().restartLoader(Loaders.SEARCH_BOOKS, null, this); } /** * Method to fetch books around me from the server centered at a location, * and in a search radius * * @param center The {@link Location} representing the center */ private void fetchBooksAroundMe(final Location center) { if (center != null) { mIsLoading = true; final BlRequest request = new BlRequest(Method.GET, HttpConstants.getApiBaseUrl() + ApiEndpoints.SEARCH, null, mVolleyCallbacks); request.setRequestId(RequestId.SEARCH_BOOKS); final Map<String, String> params = new HashMap<String, String>(2); params.put(HttpConstants.LATITUDE, String.valueOf(center .getLatitude())); params.put(HttpConstants.LONGITUDE, String.valueOf(center .getLongitude())); Logger.d(TAG, center.getLatitude() + " " + center.getLongitude()); final int pageToFetch = mCurPage + 1; params.put(HttpConstants.PAGE, String.valueOf(pageToFetch)); params.put(HttpConstants.PERLIMIT, String .valueOf(AppConstants.DEFAULT_ITEM_COUNT)); request.addExtra(Keys.LOCATION, center); request.setParams(params); addRequestToQueue(request, true, 0, true); } } /** * Method to fetch books around me from the server centered at a location, * and in a search radius and the search field * * @param center The {@link Location} representing the center * @param radius The radius(in kilometers) to search in * @param bookname The book name to search for */ private void fetchBooksAroundMeForSearch(final Location center, final int radius, final String bookname) { if (center != null) { final BlRequest request = new BlRequest(Method.GET, HttpConstants.getApiBaseUrl() + ApiEndpoints.SEARCH, null, mVolleyCallbacks); request.setRequestId(RequestId.SEARCH_BOOKS); final Map<String, String> params = new HashMap<String, String>(2); params.put(HttpConstants.LATITUDE, String.valueOf(center .getLatitude())); params.put(HttpConstants.LONGITUDE, String.valueOf(center .getLongitude())); params.put(HttpConstants.SEARCH, bookname); params.put(HttpConstants.PERLIMIT, String .valueOf(AppConstants.DEFAULT_ITEM_COUNT)); request.addExtra(Keys.LOCATION, center); if (radius >= 1) { params.put(HttpConstants.RADIUS, String.valueOf(radius)); } request.setParams(params); addRequestToQueue(request, true, 0, true); } } @Override public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) { inflater.inflate(R.menu.menu_books_around_me, menu); final MenuItem menuItem = menu.findItem(R.id.action_search); menuItem.setOnActionExpandListener(this); mSearchView = (SearchView) menuItem.getActionView(); mSearchNetworkQueryHelper = new SearchViewNetworkQueryHelper(mSearchView, this); mSearchNetworkQueryHelper.setSuggestCountThreshold(3); mSearchNetworkQueryHelper.setSuggestWaitThreshold(400); } @Override public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.action_add_book: { showAddBookOptions(); return true; } default: { return super.onOptionsItemSelected(item); } } } /** * Show dialog for adding books */ private void showAddBookOptions() { mAddBookDialogFragment = new SingleChoiceDialogFragment(); mAddBookDialogFragment .show(AlertDialog.THEME_HOLO_LIGHT, R.array.add_book_choices, 0, R.string.add_book_dialog_head, getFragmentManager(), true, FragmentTags.DIALOG_ADD_BOOK); } @Override public void onActivityResult(final int requestCode, final int resultCode, final Intent data) { if ((requestCode == RequestCodes.SCAN_ISBN) && (resultCode == ResultCodes.SUCCESS)) { Bundle args = null; if (data != null) { args = data.getExtras(); } loadAddOrEditBookFragment(args); } else { super.onActivityResult(requestCode, resultCode, data); } } @Override protected Object getVolleyTag() { return hashCode(); } public void updateLocation(final Location location) { if ((location.getLatitude() == 0.0) && (location.getLongitude() == 0.0)) { return; } fetchBooksOnLocationUpdate(location); } /** * When the location is updated, check to see if books need to be refreshed, * and refresh them * * @param location The location at which books should be fetched */ private void fetchBooksOnLocationUpdate(Location location) { if (shouldRefetchBooks(location)) { final Bundle cookie = new Bundle(1); cookie.putParcelable(Keys.LOCATION, location); // Delete the current search results before parsing the old ones DBInterface.deleteAsync(AppConstants.QueryTokens.DELETE_BOOKS_SEARCH_RESULTS, cookie, TableSearchBooks.NAME, null, null, true, this); } else { mCurPage = 0; mHasLoadedAllItems = false; fetchBooksAroundMe(location); } } @Override public void onPause() { super.onPause(); saveLastFetchedInfoToPref(); } /** * Saves the last fetched info to shared preferences. This will be read * again in onResume so as to prevent refetching of the books */ private void saveLastFetchedInfoToPref() { SharedPreferenceHelper .set(getActivity(), R.string.pref_last_fetched_page, mCurPage); if (mLastFetchedLocation != null) { SharedPreferenceHelper .set(getActivity(), R.string.pref_last_fetched_latitude, mLastFetchedLocation .getLatitude()); SharedPreferenceHelper .set(getActivity(), R.string.pref_last_fetched_longitude, mLastFetchedLocation .getLongitude()); } } @Override public void onResume() { super.onResume(); //done to force refresh! just change the value accordingly, default value is false if (!SharedPreferenceHelper .getBoolean(getActivity(), R.string.pref_dont_refresh_books)) { SharedPreferenceHelper .set(getActivity(), R.string.pref_last_fetched_latitude, 0.0); SharedPreferenceHelper .set(getActivity(), R.string.pref_last_fetched_longitude, 0.0); SharedPreferenceHelper .set(getActivity(), R.string.pref_dont_refresh_books, true); } if (isLocationServiceEnabled()) { readLastFetchedInfoFromPref(); final Location latestLocation = DeviceInfo.INSTANCE .getLatestLocation(); if ((latestLocation.getLatitude() != 0.0) && (latestLocation.getLongitude() != 0.0)) { updateLocation(latestLocation); } } else { showEnableLocationDialog(); } } /** * Show the dialog for the user to add his name, in case it's not already * added */ protected void showEnableLocationDialog() { mEnableLocationDialogFragment = new EnableLocationDialogFragment(); mEnableLocationDialogFragment .show(AlertDialog.THEME_HOLO_LIGHT, 0, R.string.enable_location, R.string.enable_location_message, R.string.enable, R.string.cancel, 0, getFragmentManager(), true, FragmentTags.DIALOG_ENABLE_LOCATION); } /** * Reads the latest fetched locations from shared preferences */ private void readLastFetchedInfoFromPref() { // Don't read from pref if already has fetched if (mLastFetchedLocation == null) { mLastFetchedLocation = new Location(LocationManager.PASSIVE_PROVIDER); Logger.d(TAG, mLastFetchedLocation.getLatitude() + ""); if (mLastFetchedLocation == null) { mLastFetchedLocation = new Location(LocationManager.NETWORK_PROVIDER); Logger.d(TAG, mLastFetchedLocation.getLatitude() + ""); } mLastFetchedLocation .setLatitude(SharedPreferenceHelper .getDouble(getActivity(), R.string.pref_last_fetched_latitude)); mLastFetchedLocation .setLongitude(SharedPreferenceHelper .getDouble(getActivity(), R.string.pref_last_fetched_longitude)); } } /** * Loads the Fragment to Add Or Edit Books * * @param bookInfo The book info to load. Can be <code>null</code>, in which * case, it treats it as Add a new book flow */ private void loadAddOrEditBookFragment(final Bundle bookInfo) { loadFragment(mContainerViewId, (AbstractBarterLiFragment) Fragment .instantiate(getActivity(), AddOrEditBookFragment.class .getName(), bookInfo), FragmentTags.ADD_OR_EDIT_BOOK, true, FragmentTags.BS_BOOKS_AROUND_ME); } @Override public void onSuccess(final int requestId, final IBlRequestContract request, final ResponseInfo response) { if (requestId == RequestId.SEARCH_BOOKS) { mLastFetchedLocation = (Location) request.getExtras() .get(Keys.LOCATION); mCurPage++; if (response.responseBundle.getBoolean(Keys.NO_BOOKS_FLAG_KEY)) { mHasLoadedAllItems = true; mCurPage--; } /* * Do nothing because the loader will take care of reloading the * data */ } } @Override public void onPostExecute(final IBlRequestContract request) { super.onPostExecute(request); if (request.getRequestId() == RequestId.SEARCH_BOOKS) { mIsLoading = false; mPullToRefreshLayout.setRefreshComplete(); } } @Override public void onBadRequestError(final int requestId, final IBlRequestContract request, final int errorCode, final String errorMessage, final Bundle errorResponseBundle) { if (requestId == RequestId.SEARCH_BOOKS) { showCrouton(R.string.unable_to_fetch_books, AlertStyle.ERROR); } if (requestId == RequestId.SEARCH_BOOKS_FROM_EDITTEXT) { showCrouton(R.string.unable_to_fetch_books, AlertStyle.ERROR); } } @Override public void onOtherError(int requestId, IBlRequestContract request, int errorCode) { if (requestId == RequestId.SEARCH_BOOKS) { showCrouton(R.string.unable_to_fetch_books, AlertStyle.ERROR); } if (requestId == RequestId.SEARCH_BOOKS_FROM_EDITTEXT) { showCrouton(R.string.unable_to_fetch_books, AlertStyle.ERROR); } } @Override public Loader<Cursor> onCreateLoader(final int loaderId, final Bundle args) { if (loaderId == Loaders.SEARCH_BOOKS) { return new SQLiteLoader(getActivity(), false, ViewSearchBooksWithLocations.NAME, null, null, null, null, null, null, null); } else { return null; } } @Override public void onLoadFinished(final Loader<Cursor> loader, final Cursor cursor) { if (loader.getId() == Loaders.SEARCH_BOOKS) { Logger.d(TAG, "Cursor Loaded with count: %d", cursor.getCount()); { mBooksAroundMeAdapter.swapCursor(cursor); } } } @Override public void onLoaderReset(final Loader<Cursor> loader) { if (loader.getId() == Loaders.SEARCH_BOOKS) { mBooksAroundMeAdapter.swapCursor(null); } } /** * Checks if a new set of books should be fetched * * @param center The new center point at which the books should be fetched * @return <code>true</code> if a new set should be fetched, * <code>false</code> otherwise */ private boolean shouldRefetchBooks(final Location center) { if (mLastFetchedLocation != null) { final float distanceBetweenCurAndLastFetchedLocations = Utils .distanceBetween(center, mLastFetchedLocation) / 1000; /* * If there's less than 25 km distance between the current location * and the location where we last fetched the books we don't need to * fetch the books again since the current set will include * those(The server uses 50 km as the search radius) */ if (distanceBetweenCurAndLastFetchedLocations <= 25.0f) { Logger.v(TAG, "Points are really close. Don't fetch"); return false; } } return true; } @Override public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) { if (parent.getId() == R.id.grid_books_around_me) { if (position == mBooksAroundMeAdapter.getCount() - 1) { showAddBookOptions(); } else { final Cursor cursor = (Cursor) mBooksAroundMeAdapter .getItem(position); final String idBook = cursor.getString(cursor .getColumnIndex(DatabaseColumns.ID)); Logger.d(TAG, "ID:" + idBook); final String userId = cursor.getString(cursor .getColumnIndex(DatabaseColumns.USER_ID)); final Bundle showBooksArgs = new Bundle(); showBooksArgs.putString(Keys.ID, idBook); showBooksArgs.putString(Keys.USER_ID, userId); showBooksArgs.putInt(Keys.BOOK_POSITION, position); loadFragment(mContainerViewId, (AbstractBarterLiFragment) Fragment .instantiate(getActivity(), BooksPagerFragment.class .getName(), showBooksArgs), FragmentTags.BOOKS_AROUND_ME, true, FragmentTags.BS_BOOK_DETAIL); } } } @Override public void onInsertComplete(final int token, final Object cookie, final long insertRowId) { // TODO Auto-generated method stub } @Override public void onDeleteComplete(final int token, final Object cookie, final int deleteCount) { if (token == QueryTokens.DELETE_BOOKS_SEARCH_RESULTS) { assert (cookie != null); mCurPage = 0; mHasLoadedAllItems = false; final Bundle args = (Bundle) cookie; fetchBooksAroundMe((Location) args.getParcelable(Keys.LOCATION)); } if (token == QueryTokens.DELETE_BOOKS_SEARCH_RESULTS_FROM_EDITTEXT) { assert (cookie != null); final Bundle args = (Bundle) cookie; fetchBooksAroundMeForSearch((Location) args.getParcelable(Keys.LOCATION), 50, args .getString(Keys.SEARCH)); } } @Override public void onUpdateComplete(final int token, final Object cookie, final int updateCount) { // TODO Auto-generated method stub } @Override public void onQueryComplete(final int token, final Object cookie, final Cursor cursor) { // TODO Auto-generated method stub } @Override public void onLoadMore() { fetchBooksAroundMe(mLastFetchedLocation); } @Override public boolean isLoading() { return mIsLoading; } @Override public boolean hasLoadedAllItems() { return mHasLoadedAllItems; } @Override public boolean willHandleDialog(final DialogInterface dialog) { if ((mAddBookDialogFragment != null) && mAddBookDialogFragment.getDialog().equals(dialog)) { return true; } else if ((mEnableLocationDialogFragment != null) && mEnableLocationDialogFragment.getDialog() .equals(dialog)) { return true; } return super.willHandleDialog(dialog); } @Override public void onDialogClick(final DialogInterface dialog, final int which) { if ((mAddBookDialogFragment != null) && mAddBookDialogFragment.getDialog().equals(dialog)) { if (which == 0) { // scan book startActivityForResult(new Intent(getActivity(), ScanIsbnActivity.class), RequestCodes.SCAN_ISBN); GoogleAnalyticsManager .getInstance() .sendEvent(new EventBuilder(Categories.USAGE, Actions.ADD_BOOK) .set(ParamKeys.TYPE, ParamValues.SCAN)); } else if (which == 1) { // add book manually loadAddOrEditBookFragment(null); GoogleAnalyticsManager .getInstance() .sendEvent(new EventBuilder(Categories.USAGE, Actions.ADD_BOOK) .set(ParamKeys.TYPE, ParamValues.MANUAL)); } } else if ((mEnableLocationDialogFragment != null) && mEnableLocationDialogFragment.getDialog() .equals(dialog)) { if (which == DialogInterface.BUTTON_POSITIVE) { // enable location Intent locationOptionsIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(locationOptionsIntent); } else if (which == DialogInterface.BUTTON_NEGATIVE) { // cancel dialog.cancel(); } } else { super.onDialogClick(dialog, which); } } @Override public void performQuery(SearchView searchView, String query) { final Bundle cookie = new Bundle(2); cookie.putParcelable(Keys.LOCATION, mLastFetchedLocation); cookie.putString(Keys.SEARCH, query); // Delete the current search results before parsing the old ones DBInterface.deleteAsync(AppConstants.QueryTokens.DELETE_BOOKS_SEARCH_RESULTS_FROM_EDITTEXT, cookie, TableSearchBooks.NAME, null, null, true, BooksAroundMeFragment.this); } @Override public void onRefreshStarted(View view) { if (view.getId() == R.id.grid_books_around_me) { reloadNearbyBooks(); } } /** * Reloads nearby books */ private void reloadNearbyBooks() { mSearchView.setQuery(null, false); final Bundle cookie = new Bundle(2); cookie.putParcelable(Keys.LOCATION, mLastFetchedLocation); DBInterface.deleteAsync(AppConstants.QueryTokens.DELETE_BOOKS_SEARCH_RESULTS, cookie, TableSearchBooks.NAME, null, null, true, this); } @Override public boolean onMenuItemActionCollapse(MenuItem item) { reloadNearbyBooks(); return true; } @Override public boolean onMenuItemActionExpand(MenuItem item) { return true; } @Override public boolean onClose() { return false; } @Override protected String getAnalyticsScreenName() { return Screens.BOOKS_AROUND_ME; } @Override public void onClick(View v) { final int id = v.getId(); switch (id) { case R.id.text_try_again: { reloadNearbyBooks(); break; } case R.id.image_add_graphic: case R.id.text_add_your_own: { showAddBookOptions(); break; } } } }
resolved issue of reflecting empty view when we navigate from book detail to booksaroundme
barter.li/src/li/barter/fragments/BooksAroundMeFragment.java
resolved issue of reflecting empty view when we navigate from book detail to booksaroundme
Java
apache-2.0
702aa3eb2b46020ca50b06fee3c7d0d559ae7439
0
tateshitah/jspwiki,tateshitah/jspwiki,tateshitah/jspwiki,tateshitah/jspwiki
/* * 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.wiki.search.tika; import net.sf.ehcache.CacheManager; import org.apache.wiki.TestEngine; import org.apache.wiki.attachment.Attachment; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Properties; public class TikaSearchProviderTest { private static final long SLEEP_TIME = 200L; private static final int SLEEP_COUNT = 500; TestEngine engine; Properties props; @BeforeEach void setUp() throws Exception { props = TestEngine.getTestProperties(); TestEngine.emptyWorkDir( props ); CacheManager.getInstance().removeAllCaches(); engine = new TestEngine( props ); } @Test void testGetAttachmentContent() throws Exception { engine.saveText( "Test-tika", "blablablabla" ); byte[] filePdf = Files.readAllBytes( Paths.get( TikaSearchProviderTest.class.getClassLoader().getResource( "aaa-diagram.pdf" ).toURI() ) ); byte[] filePng = Files.readAllBytes( Paths.get( TikaSearchProviderTest.class.getClassLoader().getResource( "favicon.png" ).toURI() ) ); engine.addAttachment( "Test-tika", "aaa-diagram.pdf", filePdf ); engine.addAttachment( "Test-tika", "favicon.png", filePng ); TikaSearchProvider tsp = ( TikaSearchProvider )engine.getSearchManager().getSearchEngine(); Attachment attPdf = engine.getAttachmentManager().getAttachmentInfo( "Test-tika/aaa-diagram.pdf" ); String pdfIndexed = tsp.getAttachmentContent( attPdf ); Assertions.assertTrue( pdfIndexed.contains( "aaa-diagram.pdf" ) ); Assertions.assertTrue( pdfIndexed.contains( "WebContainerAuthorizer" ) ); Attachment attPng = engine.getAttachmentManager().getAttachmentInfo( "Test-tika/favicon.png" ); String pngIndexed = tsp.getAttachmentContent( attPng ); Assertions.assertTrue( pngIndexed.contains( "favicon.png" ) ); } }
jspwiki-tika-searchprovider/src/test/java/org/apache/wiki/search/tika/TikaSearchProviderTest.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.wiki.search.tika; import net.sf.ehcache.CacheManager; import org.apache.wiki.TestEngine; import org.apache.wiki.attachment.Attachment; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Properties; public class TikaSearchProviderTest { private static final long SLEEP_TIME = 200L; private static final int SLEEP_COUNT = 500; TestEngine engine; Properties props; @BeforeEach void setUp() throws Exception { props = TestEngine.getTestProperties(); TestEngine.emptyWorkDir( props ); CacheManager.getInstance().removeAllCaches(); engine = new TestEngine( props ); } @Test void testGetAttachmentContent() throws Exception { engine.saveText( "test-tika", "blablablabla" ); byte[] filePdf = Files.readAllBytes( Paths.get( TikaSearchProviderTest.class.getClassLoader().getResource( "aaa-diagram.pdf" ).toURI() ) ); byte[] filePng = Files.readAllBytes( Paths.get( TikaSearchProviderTest.class.getClassLoader().getResource( "favicon.png" ).toURI() ) ); engine.addAttachment( "test-tika", "aaa-diagram.pdf", filePdf ); engine.addAttachment( "test-tika", "favicon.png", filePng ); TikaSearchProvider tsp = ( TikaSearchProvider )engine.getSearchManager().getSearchEngine(); Attachment attPdf = engine.getAttachmentManager().getAttachmentInfo( "test-tika/aaa-diagram.pdf" ); String pdfIndexed = tsp.getAttachmentContent( attPdf ); Assertions.assertTrue( pdfIndexed.contains( "aaa-diagram.pdf" ) ); Assertions.assertTrue( pdfIndexed.contains( "WebContainerAuthorizer" ) ); Attachment attPng = engine.getAttachmentManager().getAttachmentInfo( "test-tika/favicon.png" ); String pngIndexed = tsp.getAttachmentContent( attPng ); Assertions.assertTrue( pngIndexed.contains( "favicon.png" ) ); } }
finally, fix test - patch provided by Murray Altheim on ML
jspwiki-tika-searchprovider/src/test/java/org/apache/wiki/search/tika/TikaSearchProviderTest.java
finally, fix test - patch provided by Murray Altheim on ML
Java
apache-2.0
41084c016eff5b2bf7c154f0e49d42e9c2a2edd7
0
hongjun117/mpush,hongjun117/mpush,mpusher/mpush,mpusher/mpush,hongjun117/mpush,mpusher/mpush
package com.shinemo.mpush.tools.zk.listener; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.cache.TreeCacheEvent; import org.apache.curator.framework.recipes.cache.TreeCacheListener; import com.shinemo.mpush.log.LogType; import com.shinemo.mpush.log.LoggerManage; public abstract class DataChangeListener implements TreeCacheListener{ @Override public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception { String path = null == event.getData() ? "" : event.getData().getPath(); if (path.isEmpty()) { return; } LoggerManage.log(LogType.ZK, "DataChangeListener:{},{},namespace:{}", path,listenerPath(),client.getNamespace()); if(path.startsWith(listenerPath())){ dataChanged(client, event, path); } } public abstract void initData(); public abstract void dataChanged(CuratorFramework client, TreeCacheEvent event,String path) throws Exception; public abstract String listenerPath(); }
mpush-tools/src/main/java/com/shinemo/mpush/tools/zk/listener/DataChangeListener.java
package com.shinemo.mpush.tools.zk.listener; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.cache.TreeCacheEvent; import org.apache.curator.framework.recipes.cache.TreeCacheListener; import com.shinemo.mpush.log.LogType; import com.shinemo.mpush.log.LoggerManage; public abstract class DataChangeListener implements TreeCacheListener{ @Override public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception { String path = null == event.getData() ? "" : event.getData().getPath(); if (path.isEmpty()) { return; } LoggerManage.log(LogType.ZK, "DataChangeListener:%s,%s,namespace:%s", path,listenerPath(),client.getNamespace()); if(path.startsWith(listenerPath())){ dataChanged(client, event, path); } } public abstract void initData(); public abstract void dataChanged(CuratorFramework client, TreeCacheEvent event,String path) throws Exception; public abstract String listenerPath(); }
add log
mpush-tools/src/main/java/com/shinemo/mpush/tools/zk/listener/DataChangeListener.java
add log
Java
apache-2.0
b9910b60c08ad6fc47bcd9445d5cccf1f67a5249
0
estatio/isis,kidaa/isis,kidaa/isis,kidaa/isis,niv0/isis,estatio/isis,niv0/isis,sanderginn/isis,sanderginn/isis,oscarbou/isis,incodehq/isis,estatio/isis,howepeng/isis,incodehq/isis,oscarbou/isis,incodehq/isis,estatio/isis,peridotperiod/isis,oscarbou/isis,apache/isis,apache/isis,niv0/isis,incodehq/isis,apache/isis,howepeng/isis,apache/isis,kidaa/isis,peridotperiod/isis,howepeng/isis,apache/isis,apache/isis,niv0/isis,sanderginn/isis,howepeng/isis,peridotperiod/isis,sanderginn/isis,peridotperiod/isis,oscarbou/isis
package org.nakedobjects.utility; import java.awt.BorderLayout; import java.awt.Button; import java.awt.Color; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Frame; import java.awt.Panel; import java.awt.TextArea; import java.awt.event.ActionEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Vector; /** * A specialised frame for displaying the details of an object and its display * mechanisms. */ public abstract class DebugFrame extends Frame { private static Vector frames = new Vector(); /** * Calls dispose on all the open debug frames * */ public static void disposeAll() { Frame[] f = new Frame[frames.size()]; for (int i = 0; i < f.length; i++) { f[i] = (Frame) frames.elementAt(i); } for (int i = 0; i < f.length; i++) { f[i].dispose(); } } private TextArea field; public DebugFrame() { frames.addElement(this); setLayout(new BorderLayout(7, 7)); addWindowListener(new WindowAdapter() { DebugFrame frame = DebugFrame.this; public void windowClosing(WindowEvent e) { closeDialog(); } }); TextArea area = new TextArea("", 40, 80, TextArea.SCROLLBARS_BOTH); area.setForeground(Color.black); Font font = new Font("Courier", Font.PLAIN, 11); area.setFont(font); add("Center", area); field = area; Panel buttons = new Panel(); buttons.setLayout(new FlowLayout()); add(buttons, BorderLayout.SOUTH); // add buttons Button b = new java.awt.Button("Refresh"); b.setFont(font); buttons.add(b); b.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { refresh(); } }); b = new java.awt.Button("Print..."); b.setFont(font); b.setEnabled(false); buttons.add(b); b.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { // TODO add print option } }); b = new java.awt.Button("Save..."); b.setFont(font); b.setEnabled(false); buttons.add(b); b.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { // TODO add save option } }); b = new java.awt.Button("Close"); b.setFont(font); buttons.add(b); b.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { closeDialog(); } }); } private void closeDialog() { dialogClosing(); hide(); dispose(); } public void dialogClosing() {} public void dispose() { frames.removeElement(this); super.dispose(); } public TextArea getField() { return field; } public void refresh() { DebugInfo info = getInfo(); if(info != null) { setTitle(info.getDebugTitle()); field.setText(info.getDebugData()); } } protected abstract DebugInfo getInfo(); void setField(java.awt.TextArea newField) { field = newField; } /** * show the frame at the specified coordinates */ public void show(int x, int y) { refresh(); pack(); setLocation(x, y); show(); } } /* * Naked Objects - a framework that exposes behaviourally complete business * objects directly to the user. Copyright (C) 2000 - 2005 Naked Objects Group * Ltd * * 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 * * The authors can be contacted via www.nakedobjects.org (the registered address * of Naked Objects Group is Kingsway House, 123 Goldworth Road, Woking GU21 * 1NR, UK). */
no-core/src/org/nakedobjects/utility/DebugFrame.java
package org.nakedobjects.utility; import java.awt.BorderLayout; import java.awt.Button; import java.awt.Color; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Frame; import java.awt.Panel; import java.awt.TextArea; import java.awt.event.ActionEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Vector; /** * A specialised frame for displaying the details of an object and its display * mechanisms. */ public abstract class DebugFrame extends Frame { private static Vector frames = new Vector(); /** * Calls dispose on all the open debug frames * */ public static void disposeAll() { Frame[] f = new Frame[frames.size()]; for (int i = 0; i < f.length; i++) { f[i] = (Frame) frames.elementAt(i); } for (int i = 0; i < f.length; i++) { f[i].dispose(); } } private TextArea field; public DebugFrame() { frames.addElement(this); setLayout(new BorderLayout(7, 7)); addWindowListener(new WindowAdapter() { DebugFrame frame = DebugFrame.this; public void windowClosing(WindowEvent e) { closeDialog(); } }); TextArea area = new TextArea("", 40, 80, TextArea.SCROLLBARS_BOTH); area.setForeground(Color.black); Font font = new Font("Courier", Font.PLAIN, 11); area.setFont(font); add("Center", area); field = area; Panel buttons = new Panel(); buttons.setLayout(new FlowLayout()); add(buttons, BorderLayout.SOUTH); // add buttons Button b = new java.awt.Button("Refresh"); b.setFont(font); buttons.add(b); b.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { refresh(); } }); b = new java.awt.Button("Print..."); b.setFont(font); b.setEnabled(false); buttons.add(b); b.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { // TODO add print option } }); b = new java.awt.Button("Save..."); b.setFont(font); b.setEnabled(false); buttons.add(b); b.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { // TODO add save option } }); b = new java.awt.Button("Close"); b.setFont(font); buttons.add(b); b.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { closeDialog(); } }); } private void closeDialog() { hide(); dispose(); } public void dispose() { frames.removeElement(this); super.dispose(); } public TextArea getField() { return field; } public void refresh() { DebugInfo info = getInfo(); if(info != null) { setTitle(info.getDebugTitle()); field.setText(info.getDebugData()); } } protected abstract DebugInfo getInfo(); void setField(java.awt.TextArea newField) { field = newField; } /** * show the frame at the specified coordinates */ public void show(int x, int y) { refresh(); pack(); setLocation(x, y); show(); } } /* * Naked Objects - a framework that exposes behaviourally complete business * objects directly to the user. Copyright (C) 2000 - 2005 Naked Objects Group * Ltd * * 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 * * The authors can be contacted via www.nakedobjects.org (the registered address * of Naked Objects Group is Kingsway House, 123 Goldworth Road, Woking GU21 * 1NR, UK). */
Added hook into DebugFrame so subclasses can react to a closing debug window. git-svn-id: 3f09329b2f6451ddff3637e937fd5de689f72c1f@1006772 13f79535-47bb-0310-9956-ffa450edef68
no-core/src/org/nakedobjects/utility/DebugFrame.java
Added hook into DebugFrame so subclasses can react to a closing debug window.
Java
apache-2.0
8b8436eadb945e5d640883dbc722f514d2b1b4cc
0
Ensembl/ensj-healthcheck,thomasmaurel/ensj-healthcheck,Ensembl/ensj-healthcheck,thomasmaurel/ensj-healthcheck,Ensembl/ensj-healthcheck,Ensembl/ensj-healthcheck,thomasmaurel/ensj-healthcheck,thomasmaurel/ensj-healthcheck
/* * Copyright (C) 2004 EBI, GRL * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free * Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.ensembl.healthcheck.util; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.ensembl.healthcheck.DatabaseRegistry; import org.ensembl.healthcheck.DatabaseServer; import org.ensembl.healthcheck.ReportManager; import org.ensembl.healthcheck.testcase.EnsTestCase; /** * Various database utilities. */ public final class DBUtils { private static Logger logger = Logger.getLogger("HealthCheckLogger"); private static List<DatabaseServer> mainDatabaseServers; private static List<DatabaseServer> secondaryDatabaseServers; private static DatabaseRegistry mainDatabaseRegistry; private static DatabaseRegistry secondaryDatabaseRegistry; // hide constructor to stop instantiation private DBUtils() { } // ------------------------------------------------------------------------- /** * Open a connection to the database. * * @param driverClassName * The class name of the driver to load. * @param databaseURL * The URL of the database to connect to. * @param user * The username to connect with. * @param password * Password for user. * @return A connection to the database, or null. */ public static Connection openConnection(String driverClassName, String databaseURL, String user, String password) { return ConnectionPool.getConnection(driverClassName, databaseURL, user, password); } // openConnection // ------------------------------------------------------------------------- /** * Get a list of the database names for a particular connection. * * @param con * The connection to query. * @return An array of Strings containing the database names. */ public static String[] listDatabases(Connection con) { if (con == null) { logger.severe("Database connection is null"); } ArrayList<String> dbNames = new ArrayList<String>(); try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SHOW DATABASES"); while (rs.next()) { dbNames.add(rs.getString(1)); } rs.close(); stmt.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } String[] ret = new String[dbNames.size()]; return (String[]) dbNames.toArray(ret); } // listDatabases // ------------------------------------------------------------------------- /** * Get a list of the database names that match a certain pattern for a particular connection. * * @param conn * The connection to query. * @param regex * A regular expression to match. If null, match all. * @return An array of Strings containing the database names. */ public static String[] listDatabases(Connection con, String regex) { ArrayList<String> dbMatches = new ArrayList<String>(); String[] allDBNames = listDatabases(con); for (String name : allDBNames) { if (regex == null) { dbMatches.add(name); } else if (name.matches(regex)) { dbMatches.add(name); } } String[] ret = new String[dbMatches.size()]; return (String[]) dbMatches.toArray(ret); } // listDatabases // ------------------------------------------------------------------------- /** * Compare a list of ResultSets to see if there are any differences. Note that if the ResultSets are large and/or there are many * of them, this may take a long time! * * @return The number of differences. * @param testCase * The test case that is calling the comparison. Used for ReportManager. * @param resultSetGroup * The list of ResultSets to compare */ public static boolean compareResultSetGroup(List<ResultSet> resultSetGroup, EnsTestCase testCase, boolean comparingSchema) { boolean same = true; // avoid comparing the same two ResultSets more than once // i.e. only need the upper-right triangle of the comparison matrix int size = resultSetGroup.size(); for (int i = 0; i < size; i++) { for (int j = i + 1; j < size; j++) { ResultSet rsi = resultSetGroup.get(i); ResultSet rsj = resultSetGroup.get(j); same &= compareResultSets(rsi, rsj, testCase, "", true, true, "", comparingSchema); } } return same; } // compareResultSetGroup // ------------------------------------------------------------------------- /** * Compare two ResultSets. * * @return True if all the following are true: * <ol> * <li>rs1 and rs2 have the same number of columns</li> * <li>The name and type of each column in rs1 is equivalent to the corresponding column in rs2.</li> * <li>All the rows in rs1 have the same type and value as the corresponding rows in rs2.</li> * </ol> * @param testCase * The test case calling the comparison; used in ReportManager. * @param text * Additional text to put in any error reports. * @param rs1 * The first ResultSet to compare. * @param rs2 * The second ResultSet to compare. * @param reportErrors * If true, error details are stored in ReportManager as they are found. * @param singleTableName * If comparing 2 result sets from a single table (or from a DESCRIBE table) this should be the name of the table, to be * output in any error text. Otherwise "". */ public static boolean compareResultSets(ResultSet rs1, ResultSet rs2, EnsTestCase testCase, String text, boolean reportErrors, boolean warnNull, String singleTableName, boolean comparingSchema) { return compareResultSets(rs1, rs2, testCase, text, reportErrors, warnNull, singleTableName, null, comparingSchema); } public static boolean compareResultSets(ResultSet rs1, ResultSet rs2, EnsTestCase testCase, String text, boolean reportErrors, boolean warnNull, String singleTableName, int[] columns, boolean comparingSchema) { // quick tests first // Check for object equality if (rs1.equals(rs2)) { return true; } try { // get some information about the ResultSets String name1 = getShortDatabaseName(rs1.getStatement().getConnection()); String name2 = getShortDatabaseName(rs2.getStatement().getConnection()); // Check for same column count, names and types ResultSetMetaData rsmd1 = rs1.getMetaData(); ResultSetMetaData rsmd2 = rs2.getMetaData(); if (rsmd1.getColumnCount() != rsmd2.getColumnCount() && columns == null) { ReportManager.problem(testCase, name1, "Column counts differ " + singleTableName + " " + name1 + ": " + rsmd1.getColumnCount() + " " + name2 + ": " + rsmd2.getColumnCount()); return false; // Deliberate early return for performance // reasons } if (columns == null) { columns = new int[rsmd1.getColumnCount()]; for (int i = 0; i < columns.length; i++) { columns[i] = i + 1; } } for (int j = 0; j < columns.length; j++) { int i = columns[j]; // note columns indexed from l if (!((rsmd1.getColumnName(i)).equals(rsmd2.getColumnName(i)))) { ReportManager.problem(testCase, name1, "Column names differ for " + singleTableName + " column " + i + " - " + name1 + ": " + rsmd1.getColumnName(i) + " " + name2 + ": " + rsmd2.getColumnName(i)); // Deliberate early return for performance reasons return false; } if (rsmd1.getColumnType(i) != rsmd2.getColumnType(i)) { ReportManager.problem(testCase, name1, "Column types differ for " + singleTableName + " column " + i + " - " + name1 + ": " + rsmd1.getColumnType(i) + " " + name2 + ": " + rsmd2.getColumnType(i)); return false; // Deliberate early return for performance // reasons } } // for column // make sure both cursors are at the start of the ResultSet // (default is before the start) rs1.beforeFirst(); rs2.beforeFirst(); // if quick checks didn't cause return, try comparing row-wise int row = 1; while (rs1.next()) { if (rs2.next()) { for (int j = 0; j < columns.length; j++) { int i = columns[j]; // note columns indexed from 1 if (!compareColumns(rs1, rs2, i, warnNull)) { String str = name1 + " and " + name2 + text + " " + singleTableName + " differ at row " + row + " column " + i + " (" + rsmd1.getColumnName(i) + ")" + " Values: " + Utils.truncate(rs1.getString(i), 250, true) + ", " + Utils.truncate(rs2.getString(i), 250, true); if (reportErrors) { ReportManager.problem(testCase, name1, str); } return false; } } row++; } else { // rs1 has more rows than rs2 ReportManager.problem(testCase, name1, singleTableName + " (or definition) has more rows in " + name1 + " than in " + name2); return false; } } // while rs1 // if both ResultSets are the same, then we should be at the end of // both, i.e. .next() should return false String extra = comparingSchema ? ". This means that there are missing columns in the table, rectify!" : ""; if (rs1.next()) { if (reportErrors) { ReportManager.problem(testCase, name1, name1 + " " + singleTableName + " has additional rows that are not in " + name2 + extra); } return false; } else if (rs2.next()) { if (reportErrors) { ReportManager.problem(testCase, name2, name2 + " " + singleTableName + " has additional rows that are not in " + name1 + extra); } return false; } } catch (SQLException se) { se.printStackTrace(); } return true; } // compareResultSets // ------------------------------------------------------------------------- /** * Compare a particular column in two ResultSets. * * @param rs1 * The first ResultSet to compare. * @param rs2 * The second ResultSet to compare. * @param i * The index of the column to compare. * @return True if the type and value of the columns match. */ public static boolean compareColumns(ResultSet rs1, ResultSet rs2, int i, boolean warnNull) { try { ResultSetMetaData rsmd = rs1.getMetaData(); Connection con1 = rs1.getStatement().getConnection(); Connection con2 = rs2.getStatement().getConnection(); if (rs1.getObject(i) == null) { if (warnNull) { System.out.println("Column " + rsmd.getColumnName(i) + " is null in table " + rsmd.getTableName(i) + " in " + DBUtils.getShortDatabaseName(con1)); } return (rs2.getObject(i) == null); // true if both are null } if (rs2.getObject(i) == null) { if (warnNull) { System.out.println("Column " + rsmd.getColumnName(i) + " is null in table " + rsmd.getTableName(i) + " in " + DBUtils.getShortDatabaseName(con2)); } return (rs1.getObject(i) == null); // true if both are null } // Note deliberate early returns for performance reasons switch (rsmd.getColumnType(i)) { case Types.INTEGER: return rs1.getInt(i) == rs2.getInt(i); case Types.SMALLINT: return rs1.getInt(i) == rs2.getInt(i); case Types.TINYINT: return rs1.getInt(i) == rs2.getInt(i); case Types.VARCHAR: return rs1.getString(i).equals(rs2.getString(i)); case Types.FLOAT: return rs1.getFloat(i) == rs2.getFloat(i); case Types.DOUBLE: return rs1.getDouble(i) == rs2.getDouble(i); case Types.TIMESTAMP: return rs1.getTimestamp(i).equals(rs2.getTimestamp(i)); default: // treat everything else as a String (should deal with ENUM and // TEXT) if (rs1.getString(i) == null || rs2.getString(i) == null) { return true; // ???? } else { return rs1.getString(i).equals(rs2.getString(i)); } } // switch } catch (SQLException se) { se.printStackTrace(); } return true; } // compareColumns // ------------------------------------------------------------------------- /** * Print a ResultSet to standard out. Optionally limit the number of rows. * * @param maxRows * The maximum number of rows to print. -1 to print all rows. * @param rs * The ResultSet to print. */ public static void printResultSet(ResultSet rs, int maxRows) { int row = 0; try { ResultSetMetaData rsmd = rs.getMetaData(); while (rs.next()) { for (int i = 1; i <= rsmd.getColumnCount(); i++) { System.out.print(rs.getString(i) + "\t"); } System.out.println(""); if (maxRows != -1 && ++row >= maxRows) { break; } } } catch (SQLException se) { se.printStackTrace(); } } // printResultSet // ------------------------------------------------------------------------- /** * Gets the database name, without the jdbc:// prefix. * * @param con * The Connection to query. * @return The name of the database (everything after the last / in the JDBC URL). */ public static String getShortDatabaseName(Connection con) { String url = null; try { url = con.getMetaData().getURL(); } catch (SQLException se) { se.printStackTrace(); } String name = url.substring(url.lastIndexOf('/') + 1); return name; } // getShortDatabaseName // ------------------------------------------------------------------------- /** * Generate a name for a temporary database. Should be fairly unique; name is _temp_{user}_{time} where user is current user and * time is current time in ms. * * @return The temporary name. Will not have any spaces. */ public static String generateTempDatabaseName() { StringBuffer buf = new StringBuffer("_temp_"); buf.append(System.getProperty("user.name")); buf.append("_" + System.currentTimeMillis()); String str = buf.toString(); str = str.replace(' ', '_'); // filter any spaces logger.fine("Generated temporary database name: " + str); return str; } // ------------------------------------------------------------------------- /** * Get a list of all the table names. * * @param con * The database connection to use. * @return An array of Strings representing the names of the tables, obtained from the SHOW TABLES command. */ public static String[] getTableNames(Connection con) { List<String> result = new ArrayList<String>(); if (con == null) { logger.severe("getTableNames(): Database connection is null"); } try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SHOW TABLES"); while (rs.next()) { result.add(rs.getString(1)); } rs.close(); stmt.close(); } catch (SQLException se) { logger.severe(se.getMessage()); } return (String[]) result.toArray(new String[result.size()]); } // ------------------------------------------------------------------------- /** * Get a list of the table names that match a particular SQL pattern. * * @param con * The database connection to use. * @param pattern * The SQL pattern to match the table names against. * @return An array of Strings representing the names of the tables. */ public static String[] getTableNames(Connection con, String pattern) { List<String> result = new ArrayList<String>(); if (con == null) { logger.severe("getTableNames(): Database connection is null"); } try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SHOW TABLES LIKE '" + pattern + "'"); while (rs.next()) { result.add(rs.getString(1)); } rs.close(); stmt.close(); } catch (SQLException se) { logger.severe(se.getMessage()); } return (String[]) result.toArray(new String[result.size()]); } // ------------------------------------------------------------------------- /** * List the columns in a particular table. * * @param table * The name of the table to list. * @param con * The connection to use. * @return A List of Strings representing the column names. */ public static List<String> getColumnsInTable(Connection con, String table) { List<String> result = new ArrayList<String>(); try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("DESCRIBE " + table); while (rs.next()) { result.add(rs.getString(1)); } rs.close(); stmt.close(); } catch (SQLException se) { logger.severe(se.getMessage()); } return result; } // ------------------------------------------------------------------------- /** * List the column information in a table - names, types, defaults etc. * * @param table * The name of the table to list. * @param con * The connection to use. * @param typeFilter * If not null, only return columns whose types start with this string (case insensitive). * @return A List of 6-element String[] arrays representing: 0: Column name 1: Type 2: Null? 3: Key 4: Default 5: Extra */ public static List<String[]> getTableInfo(Connection con, String table, String typeFilter) { List<String[]> result = new ArrayList<String[]>(); if (typeFilter != null) { typeFilter = typeFilter.toLowerCase(); } try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("DESCRIBE " + table); while (rs.next()) { String[] info = new String[6]; for (int i = 0; i < 6; i++) { info[i] = rs.getString(i + 1); } if (typeFilter == null || info[1].toLowerCase().startsWith(typeFilter)) { result.add(info); } } rs.close(); stmt.close(); } catch (SQLException se) { logger.severe(se.getMessage()); } return result; } // ------------------------------------------------------------------------- /** * Execute SQL and writes results to ReportManager.info(). * * @param testCase * testCase which created the sql statement * @param con * connection to execute sql on. * @param sql * sql statement to execute. */ public static void printRows(EnsTestCase testCase, Connection con, String sql) { try { ResultSet rs = con.createStatement().executeQuery(sql); if (rs.next()) { int nCols = rs.getMetaData().getColumnCount(); StringBuffer line = new StringBuffer(); do { line.delete(0, line.length()); for (int i = 1; i <= nCols; ++i) { line.append(rs.getString(i)); if (i < nCols) { line.append("\t"); } } ReportManager.info(testCase, con, line.toString()); } while (rs.next()); } } catch (SQLException e) { e.printStackTrace(); } } // --------------------------------------------------------------------- /** * Get the meta_value for a named key in the meta table. */ public static String getMetaValue(Connection con, String key) { String result = ""; try { ResultSet rs = con.createStatement().executeQuery("SELECT meta_value FROM meta WHERE meta_key='" + key + "'"); if (rs.next()) { result = rs.getString(1); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } return result; } // ------------------------------------------------------------------------- /** * Get main database server list - build if necessary. Assumes properties file already read. */ public static List<DatabaseServer> getMainDatabaseServers() { Utils.readPropertiesFileIntoSystem("database.properties", false); if (mainDatabaseServers == null) { mainDatabaseServers = new ArrayList<DatabaseServer>(); checkAndAddDatabaseServer(mainDatabaseServers, "host", "port", "user", "password", "driver"); checkAndAddDatabaseServer(mainDatabaseServers, "host1", "port1", "user1", "password1", "driver1"); checkAndAddDatabaseServer(mainDatabaseServers, "host2", "port2", "user2", "password2", "driver2"); } logger.fine("Number of main database servers found: " + mainDatabaseServers.size()); return mainDatabaseServers; } // ------------------------------------------------------------------------- /** * Look for secondary database servers. */ public static List<DatabaseServer> getSecondaryDatabaseServers() { Utils.readPropertiesFileIntoSystem("database.properties", false); if (secondaryDatabaseServers == null) { secondaryDatabaseServers = new ArrayList<DatabaseServer>(); checkAndAddDatabaseServer(secondaryDatabaseServers, "secondary.host", "secondary.port", "secondary.user", "secondary.password", "secondary.driver"); checkAndAddDatabaseServer(secondaryDatabaseServers, "secondary.host1", "secondary.port1", "secondary.user1", "secondary.password1", "secondary.driver1"); checkAndAddDatabaseServer(secondaryDatabaseServers, "secondary.host2", "secondary.port2", "secondary.user2", "secondary.password2", "secondary.driver2"); } logger.fine("Number of secondary database servers found: " + secondaryDatabaseServers.size()); return secondaryDatabaseServers; } // ------------------------------------------------------------------------- /** * Check for the existence of a particular database server. Assumes properties file has already been read in. If it exists, add it to the list. */ private static void checkAndAddDatabaseServer(List<DatabaseServer> servers, String hostProp, String portProp, String userProp, String passwordProp, String driverProp) { if (System.getProperty(hostProp) != null && System.getProperty(portProp) != null && System.getProperty(userProp) != null) { DatabaseServer server = new DatabaseServer(System.getProperty(hostProp), System.getProperty(portProp), System.getProperty(userProp), System.getProperty(passwordProp), System.getProperty(driverProp)); servers.add(server); logger.fine("Added server: " + server.toString()); } } // ------------------------------------------------------------------------- public static DatabaseRegistry getSecondaryDatabaseRegistry() { if (secondaryDatabaseRegistry == null) { secondaryDatabaseRegistry = new DatabaseRegistry(null, null, null, true); } return secondaryDatabaseRegistry; } //------------------------------------------------------------------------- public static DatabaseRegistry getMainDatabaseRegistry() { if (mainDatabaseRegistry == null) { mainDatabaseRegistry = new DatabaseRegistry(null, null, null, false); } return mainDatabaseRegistry; } // ------------------------------------------------------------------------- } // DBUtils
src/org/ensembl/healthcheck/util/DBUtils.java
/* * Copyright (C) 2004 EBI, GRL * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free * Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.ensembl.healthcheck.util; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.ensembl.healthcheck.DatabaseRegistry; import org.ensembl.healthcheck.DatabaseServer; import org.ensembl.healthcheck.ReportManager; import org.ensembl.healthcheck.testcase.EnsTestCase; /** * Various database utilities. */ public final class DBUtils { private static Logger logger = Logger.getLogger("HealthCheckLogger"); private static List<DatabaseServer> mainDatabaseServers; private static List<DatabaseServer> secondaryDatabaseServers; private static DatabaseRegistry mainDatabaseRegistry; private static DatabaseRegistry secondaryDatabaseRegistry; // hide constructor to stop instantiation private DBUtils() { } // ------------------------------------------------------------------------- /** * Open a connection to the database. * * @param driverClassName * The class name of the driver to load. * @param databaseURL * The URL of the database to connect to. * @param user * The username to connect with. * @param password * Password for user. * @return A connection to the database, or null. */ public static Connection openConnection(String driverClassName, String databaseURL, String user, String password) { return ConnectionPool.getConnection(driverClassName, databaseURL, user, password); } // openConnection // ------------------------------------------------------------------------- /** * Get a list of the database names for a particular connection. * * @param con * The connection to query. * @return An array of Strings containing the database names. */ public static String[] listDatabases(Connection con) { if (con == null) { logger.severe("Database connection is null"); } ArrayList<String> dbNames = new ArrayList<String>(); try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SHOW DATABASES"); while (rs.next()) { dbNames.add(rs.getString(1)); } rs.close(); stmt.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } String[] ret = new String[dbNames.size()]; return (String[]) dbNames.toArray(ret); } // listDatabases // ------------------------------------------------------------------------- /** * Get a list of the database names that match a certain pattern for a particular connection. * * @param conn * The connection to query. * @param regex * A regular expression to match. If null, match all. * @return An array of Strings containing the database names. */ public static String[] listDatabases(Connection con, String regex) { ArrayList<String> dbMatches = new ArrayList<String>(); String[] allDBNames = listDatabases(con); for (String name : allDBNames) { if (regex == null) { dbMatches.add(name); } else if (name.matches(regex)) { dbMatches.add(name); } } String[] ret = new String[dbMatches.size()]; return (String[]) dbMatches.toArray(ret); } // listDatabases // ------------------------------------------------------------------------- /** * Compare a list of ResultSets to see if there are any differences. Note that if the ResultSets are large and/or there are many * of them, this may take a long time! * * @return The number of differences. * @param testCase * The test case that is calling the comparison. Used for ReportManager. * @param resultSetGroup * The list of ResultSets to compare */ public static boolean compareResultSetGroup(List<ResultSet> resultSetGroup, EnsTestCase testCase, boolean comparingSchema) { boolean same = true; // avoid comparing the same two ResultSets more than once // i.e. only need the upper-right triangle of the comparison matrix int size = resultSetGroup.size(); for (int i = 0; i < size; i++) { for (int j = i + 1; j < size; j++) { ResultSet rsi = resultSetGroup.get(i); ResultSet rsj = resultSetGroup.get(j); same &= compareResultSets(rsi, rsj, testCase, "", true, true, "", comparingSchema); } } return same; } // compareResultSetGroup // ------------------------------------------------------------------------- /** * Compare two ResultSets. * * @return True if all the following are true: * <ol> * <li>rs1 and rs2 have the same number of columns</li> * <li>The name and type of each column in rs1 is equivalent to the corresponding column in rs2.</li> * <li>All the rows in rs1 have the same type and value as the corresponding rows in rs2.</li> * </ol> * @param testCase * The test case calling the comparison; used in ReportManager. * @param text * Additional text to put in any error reports. * @param rs1 * The first ResultSet to compare. * @param rs2 * The second ResultSet to compare. * @param reportErrors * If true, error details are stored in ReportManager as they are found. * @param singleTableName * If comparing 2 result sets from a single table (or from a DESCRIBE table) this should be the name of the table, to be * output in any error text. Otherwise "". */ public static boolean compareResultSets(ResultSet rs1, ResultSet rs2, EnsTestCase testCase, String text, boolean reportErrors, boolean warnNull, String singleTableName, boolean comparingSchema) { return compareResultSets(rs1, rs2, testCase, text, reportErrors, warnNull, singleTableName, null, comparingSchema); } public static boolean compareResultSets(ResultSet rs1, ResultSet rs2, EnsTestCase testCase, String text, boolean reportErrors, boolean warnNull, String singleTableName, int[] columns, boolean comparingSchema) { // quick tests first // Check for object equality if (rs1.equals(rs2)) { return true; } try { // get some information about the ResultSets String name1 = getShortDatabaseName(rs1.getStatement().getConnection()); String name2 = getShortDatabaseName(rs2.getStatement().getConnection()); // Check for same column count, names and types ResultSetMetaData rsmd1 = rs1.getMetaData(); ResultSetMetaData rsmd2 = rs2.getMetaData(); if (rsmd1.getColumnCount() != rsmd2.getColumnCount() && columns == null) { ReportManager.problem(testCase, name1, "Column counts differ " + singleTableName + " " + name1 + ": " + rsmd1.getColumnCount() + " " + name2 + ": " + rsmd2.getColumnCount()); return false; // Deliberate early return for performance // reasons } if (columns == null) { columns = new int[rsmd1.getColumnCount()]; for (int i = 0; i < columns.length; i++) { columns[i] = i + 1; } } for (int j = 0; j < columns.length; j++) { int i = columns[j]; // note columns indexed from l if (!((rsmd1.getColumnName(i)).equals(rsmd2.getColumnName(i)))) { ReportManager.problem(testCase, name1, "Column names differ for " + singleTableName + " column " + i + " - " + name1 + ": " + rsmd1.getColumnName(i) + " " + name2 + ": " + rsmd2.getColumnName(i)); // Deliberate early return for performance reasons return false; } if (rsmd1.getColumnType(i) != rsmd2.getColumnType(i)) { ReportManager.problem(testCase, name1, "Column types differ for " + singleTableName + " column " + i + " - " + name1 + ": " + rsmd1.getColumnType(i) + " " + name2 + ": " + rsmd2.getColumnType(i)); return false; // Deliberate early return for performance // reasons } } // for column // make sure both cursors are at the start of the ResultSet // (default is before the start) rs1.beforeFirst(); rs2.beforeFirst(); // if quick checks didn't cause return, try comparing row-wise int row = 1; while (rs1.next()) { if (rs2.next()) { for (int j = 0; j < columns.length; j++) { int i = columns[j]; // note columns indexed from 1 if (!compareColumns(rs1, rs2, i, warnNull)) { String str = name1 + " and " + name2 + text + " " + singleTableName + " differ at row " + row + " column " + i + " (" + rsmd1.getColumnName(i) + ")" + " Values: " + Utils.truncate(rs1.getString(i), 250, true) + ", " + Utils.truncate(rs2.getString(i), 250, true); if (reportErrors) { ReportManager.problem(testCase, name1, str); } return false; } } row++; } else { // rs1 has more rows than rs2 ReportManager.problem(testCase, name1, singleTableName + " (or definition) has more rows in " + name1 + " than in " + name2); return false; } } // while rs1 // if both ResultSets are the same, then we should be at the end of // both, i.e. .next() should return false String extra = comparingSchema ? ". This means that there are missing columns in the table, rectify!" : ""; if (rs1.next()) { if (reportErrors) { ReportManager.problem(testCase, name1, name1 + " " + singleTableName + " has additional rows that are not in " + name2 + extra); } return false; } else if (rs2.next()) { if (reportErrors) { ReportManager.problem(testCase, name2, name2 + " " + singleTableName + " has additional rows that are not in " + name1 + extra); } return false; } } catch (SQLException se) { se.printStackTrace(); } return true; } // compareResultSets // ------------------------------------------------------------------------- /** * Compare a particular column in two ResultSets. * * @param rs1 * The first ResultSet to compare. * @param rs2 * The second ResultSet to compare. * @param i * The index of the column to compare. * @return True if the type and value of the columns match. */ public static boolean compareColumns(ResultSet rs1, ResultSet rs2, int i, boolean warnNull) { try { ResultSetMetaData rsmd = rs1.getMetaData(); Connection con1 = rs1.getStatement().getConnection(); Connection con2 = rs2.getStatement().getConnection(); if (rs1.getObject(i) == null) { if (warnNull) { System.out.println("Column " + rsmd.getColumnName(i) + " is null in table " + rsmd.getTableName(i) + " in " + DBUtils.getShortDatabaseName(con1)); } return (rs2.getObject(i) == null); // true if both are null } if (rs2.getObject(i) == null) { if (warnNull) { System.out.println("Column " + rsmd.getColumnName(i) + " is null in table " + rsmd.getTableName(i) + " in " + DBUtils.getShortDatabaseName(con2)); } return (rs1.getObject(i) == null); // true if both are null } // Note deliberate early returns for performance reasons switch (rsmd.getColumnType(i)) { case Types.INTEGER: return rs1.getInt(i) == rs2.getInt(i); case Types.SMALLINT: return rs1.getInt(i) == rs2.getInt(i); case Types.TINYINT: return rs1.getInt(i) == rs2.getInt(i); case Types.VARCHAR: return rs1.getString(i).equals(rs2.getString(i)); case Types.FLOAT: return rs1.getFloat(i) == rs2.getFloat(i); case Types.DOUBLE: return rs1.getDouble(i) == rs2.getDouble(i); case Types.TIMESTAMP: return rs1.getTimestamp(i).equals(rs2.getTimestamp(i)); default: // treat everything else as a String (should deal with ENUM and // TEXT) if (rs1.getString(i) == null || rs2.getString(i) == null) { return true; // ???? } else { return rs1.getString(i).equals(rs2.getString(i)); } } // switch } catch (SQLException se) { se.printStackTrace(); } return true; } // compareColumns // ------------------------------------------------------------------------- /** * Print a ResultSet to standard out. Optionally limit the number of rows. * * @param maxRows * The maximum number of rows to print. -1 to print all rows. * @param rs * The ResultSet to print. */ public static void printResultSet(ResultSet rs, int maxRows) { int row = 0; try { ResultSetMetaData rsmd = rs.getMetaData(); while (rs.next()) { for (int i = 1; i <= rsmd.getColumnCount(); i++) { System.out.print(rs.getString(i) + "\t"); } System.out.println(""); if (maxRows != -1 && ++row >= maxRows) { break; } } } catch (SQLException se) { se.printStackTrace(); } } // printResultSet // ------------------------------------------------------------------------- /** * Gets the database name, without the jdbc:// prefix. * * @param con * The Connection to query. * @return The name of the database (everything after the last / in the JDBC URL). */ public static String getShortDatabaseName(Connection con) { String url = null; try { url = con.getMetaData().getURL(); } catch (SQLException se) { se.printStackTrace(); } String name = url.substring(url.lastIndexOf('/') + 1); return name; } // getShortDatabaseName // ------------------------------------------------------------------------- /** * Generate a name for a temporary database. Should be fairly unique; name is _temp_{user}_{time} where user is current user and * time is current time in ms. * * @return The temporary name. Will not have any spaces. */ public static String generateTempDatabaseName() { StringBuffer buf = new StringBuffer("_temp_"); buf.append(System.getProperty("user.name")); buf.append("_" + System.currentTimeMillis()); String str = buf.toString(); str = str.replace(' ', '_'); // filter any spaces logger.fine("Generated temporary database name: " + str); return str; } // ------------------------------------------------------------------------- /** * Get a list of all the table names. * * @param con * The database connection to use. * @return An array of Strings representing the names of the tables, obtained from the SHOW TABLES command. */ public static String[] getTableNames(Connection con) { List<String> result = new ArrayList<String>(); if (con == null) { logger.severe("getTableNames(): Database connection is null"); } try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SHOW TABLES"); while (rs.next()) { result.add(rs.getString(1)); } rs.close(); stmt.close(); } catch (SQLException se) { logger.severe(se.getMessage()); } return (String[]) result.toArray(new String[result.size()]); } // ------------------------------------------------------------------------- /** * Get a list of the table names that match a particular SQL pattern. * * @param con * The database connection to use. * @param pattern * The SQL pattern to match the table names against. * @return An array of Strings representing the names of the tables. */ public static String[] getTableNames(Connection con, String pattern) { List<String> result = new ArrayList<String>(); if (con == null) { logger.severe("getTableNames(): Database connection is null"); } try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SHOW TABLES LIKE '" + pattern + "'"); while (rs.next()) { result.add(rs.getString(1)); } rs.close(); stmt.close(); } catch (SQLException se) { logger.severe(se.getMessage()); } return (String[]) result.toArray(new String[result.size()]); } // ------------------------------------------------------------------------- /** * List the columns in a particular table. * * @param table * The name of the table to list. * @param con * The connection to use. * @return A List of Strings representing the column names. */ public static List<String> getColumnsInTable(Connection con, String table) { List<String> result = new ArrayList<String>(); try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("DESCRIBE " + table); while (rs.next()) { result.add(rs.getString(1)); } rs.close(); stmt.close(); } catch (SQLException se) { logger.severe(se.getMessage()); } return result; } // ------------------------------------------------------------------------- /** * List the column information in a table - names, types, defaults etc. * * @param table * The name of the table to list. * @param con * The connection to use. * @param typeFilter * If not null, only return columns whose types start with this string (case insensitive). * @return A List of 6-element String[] arrays representing: 0: Column name 1: Type 2: Null? 3: Key 4: Default 5: Extra */ public static List<String[]> getTableInfo(Connection con, String table, String typeFilter) { List<String[]> result = new ArrayList<String[]>(); if (typeFilter != null) { typeFilter = typeFilter.toLowerCase(); } try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("DESCRIBE " + table); while (rs.next()) { String[] info = new String[6]; for (int i = 0; i < 6; i++) { info[i] = rs.getString(i + 1); } if (typeFilter == null || info[1].toLowerCase().startsWith(typeFilter)) { result.add(info); } } rs.close(); stmt.close(); } catch (SQLException se) { logger.severe(se.getMessage()); } return result; } // ------------------------------------------------------------------------- /** * Execute SQL and writes results to ReportManager.info(). * * @param testCase * testCase which created the sql statement * @param con * connection to execute sql on. * @param sql * sql statement to execute. */ public static void printRows(EnsTestCase testCase, Connection con, String sql) { try { ResultSet rs = con.createStatement().executeQuery(sql); if (rs.next()) { int nCols = rs.getMetaData().getColumnCount(); StringBuffer line = new StringBuffer(); do { line.delete(0, line.length()); for (int i = 1; i <= nCols; ++i) { line.append(rs.getString(i)); if (i < nCols) { line.append("\t"); } } ReportManager.info(testCase, con, line.toString()); } while (rs.next()); } } catch (SQLException e) { e.printStackTrace(); } } // --------------------------------------------------------------------- /** * Get the meta_value for a named key in the meta table. */ public static String getMetaValue(Connection con, String key) { String result = ""; try { ResultSet rs = con.createStatement().executeQuery("SELECT meta_value FROM meta WHERE meta_key='" + key + "'"); if (rs.next()) { result = rs.getString(1); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } return result; } // ------------------------------------------------------------------------- /** * Get main database server list - build if necessary. Assumes properties file already read. */ public static List<DatabaseServer> getMainDatabaseServers() { Utils.readPropertiesFileIntoSystem("database.properties", false); if (mainDatabaseServers == null) { mainDatabaseServers = new ArrayList<DatabaseServer>(); checkAndAddDatabaseServer(mainDatabaseServers, "host", "port", "user", "password", "driver"); checkAndAddDatabaseServer(mainDatabaseServers, "host1", "port1", "user1", "password1", "driver1"); checkAndAddDatabaseServer(mainDatabaseServers, "host2", "port2", "user2", "password2", "driver2"); } logger.fine("Number of main database servers found: " + mainDatabaseServers.size()); return mainDatabaseServers; } // ------------------------------------------------------------------------- /** * Look for secondary database servers. */ public static List<DatabaseServer> getSecondaryDatabaseServers() { Utils.readPropertiesFileIntoSystem("database.properties", false); if (secondaryDatabaseServers == null) { secondaryDatabaseServers = new ArrayList<DatabaseServer>(); checkAndAddDatabaseServer(secondaryDatabaseServers, "secondary.host", "secondary.port", "secondary.user", "secondary.password", "secondary.driver"); checkAndAddDatabaseServer(secondaryDatabaseServers, "secondary.host1", "secondary.port1", "secondary.user1", "secondary.password1", "secondary.driver1"); checkAndAddDatabaseServer(secondaryDatabaseServers, "secondary.host2", "secondary.port2", "secondary.user2", "secondary.password2", "secondary.driver2"); } logger.fine("Number of secondary database servers found: " + secondaryDatabaseServers.size()); return secondaryDatabaseServers; } // ------------------------------------------------------------------------- /** * Check for the existence of a particular database server. Assumes properties file has already been read in. If it exists, add it to the list. */ private static void checkAndAddDatabaseServer(List<DatabaseServer> servers, String hostProp, String portProp, String userProp, String passwordProp, String driverProp) { if (System.getProperty(hostProp) != null && System.getProperty(portProp) != null && System.getProperty(userProp) != null) { DatabaseServer server = new DatabaseServer(System.getProperty(hostProp), System.getProperty(portProp), System.getProperty(userProp), System.getProperty(passwordProp), System.getProperty(driverProp)); servers.add(server); logger.fine("Added server: " + server.toString()); } } // ------------------------------------------------------------------------- public static DatabaseRegistry getSecondaryDatabaseRegistry() { System.out.println("Getting secondary"); if (secondaryDatabaseRegistry == null) { secondaryDatabaseRegistry = new DatabaseRegistry(null, null, null, true); } return secondaryDatabaseRegistry; } //------------------------------------------------------------------------- public static DatabaseRegistry getMainDatabaseRegistry() { System.out.println("Getting main"); if (mainDatabaseRegistry == null) { mainDatabaseRegistry = new DatabaseRegistry(null, null, null, false); } return mainDatabaseRegistry; } // ------------------------------------------------------------------------- } // DBUtils
Removed debug.
src/org/ensembl/healthcheck/util/DBUtils.java
Removed debug.
Java
apache-2.0
87099a6db1626de04d5fa8732b4b9091dae04f28
0
ywjno/nutz,happyday517/nutz,ywjno/nutz,ansjsun/nutz,ywjno/nutz,ywjno/nutz,ansjsun/nutz,elkan1788/nutz,ansjsun/nutz,happyday517/nutz,ansjsun/nutz,nutzam/nutz,elkan1788/nutz,nutzam/nutz,nutzam/nutz,happyday517/nutz,nutzam/nutz,elkan1788/nutz,ywjno/nutz,elkan1788/nutz,nutzam/nutz,ansjsun/nutz,happyday517/nutz
package org.nutz.lang.util; import java.io.BufferedReader; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.nutz.lang.Encoding; import org.nutz.lang.Strings; /** * 可支持直接书写多行文本的 Properties 文件 * * @author zozoh([email protected]) */ public class MultiLineProperties implements Map<String, String> { public MultiLineProperties(Reader reader) throws IOException { this(); load(reader); } public MultiLineProperties() { maps = new LinkedHashMap<String, String>(); } protected Map<String, String> maps; /** * <b>载入并销毁之前的记录</b> * * @param reader * @throws IOException */ public synchronized void load(Reader reader) throws IOException { load(reader, false); } public synchronized void load(Reader reader, boolean clear) throws IOException { if (clear) this.clear(); BufferedReader tr = null; if (reader instanceof BufferedReader) tr = (BufferedReader) reader; else tr = new BufferedReader(reader); String s; while (null != (s = tr.readLine())) { if (Strings.isBlank(s)) continue; if (s.length() > 0 && s.trim().charAt(0) == '#') // 只要第一个非空白字符是#,就认为是注释 continue; int pos; char c = '0'; for (pos = 0; pos < s.length(); pos++) { c = s.charAt(pos); if (c == '=' || c == ':') break; } if (c == '=') { String name = s.substring(0, pos); String value = s.substring(pos + 1); if (value.endsWith("\\") && !value.endsWith("\\\\")) { StringBuilder sb = new StringBuilder(value.substring(0, value.length() - 1)); while (null != (s = tr.readLine())) { if (Strings.isBlank(s)) break; if (s.endsWith("\\") && !s.endsWith("\\\\")) { sb.append(s.substring(0, s.length() - 1)); } else { sb.append(s); break; } } value = sb.toString(); } // 对value里面的\\uXXXX进行转义? if (value.contains("\\u")) { value = Strings.unicodeDecode(value); } maps.put(Strings.trim(name), value); } else if (c == ':') { String name = s.substring(0, pos); StringBuffer sb = new StringBuffer(); sb.append(s.substring(pos + 1)); String ss; while (null != (ss = tr.readLine())) { if (ss.length() > 0 && ss.charAt(0) == '#') break; sb.append("\r\n" + ss); } maps.put(Strings.trim(name), sb.toString()); if (null == ss) return; } else { maps.put(Strings.trim(s), null); } } } public synchronized void clear() { maps.clear(); } public boolean containsKey(Object key) { return maps.containsKey(key); } public boolean containsValue(Object value) { return maps.containsValue(value); } public Set<Entry<String, String>> entrySet() { return maps.entrySet(); } @Override public boolean equals(Object o) { return maps.equals(o); } @Override public int hashCode() { return maps.hashCode(); } public boolean isEmpty() { return maps.isEmpty(); } public Set<String> keySet() { return maps.keySet(); } public List<String> keys() { return new ArrayList<String>(maps.keySet()); } public synchronized String put(String key, String value) { return maps.put(key, value); } @SuppressWarnings({"unchecked", "rawtypes"}) public synchronized void putAll(Map t) { maps.putAll(t); } public synchronized String remove(Object key) { return maps.remove(key); } public int size() { return maps.size(); } public Collection<String> values() { return maps.values(); } public String get(Object key) { return maps.get(key); } public void print(OutputStream out) throws IOException { print(new OutputStreamWriter(out, Encoding.CHARSET_UTF8)); } public void print(Writer writer) throws IOException { String NL = System.getProperty("line.separator"); for (Map.Entry<String, String> en : entrySet()) { writer.write(en.getKey()); String val = en.getValue(); if (val == null) { writer.write("="); continue; } if (val.contains("\n")) { writer.write(":="); writer.write(val); writer.write(NL); writer.write("#End " + en.getKey()); } else { writer.write('='); writer.write(val); } writer.write(NL); } } }
src/org/nutz/lang/util/MultiLineProperties.java
package org.nutz.lang.util; import java.io.BufferedReader; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.nutz.lang.Encoding; import org.nutz.lang.Strings; /** * 可支持直接书写多行文本的 Properties 文件 * * @author zozoh([email protected]) */ public class MultiLineProperties implements Map<String, String> { public MultiLineProperties(Reader reader) throws IOException { this(); load(reader); } public MultiLineProperties() { maps = new LinkedHashMap<String, String>(); } protected Map<String, String> maps; /** * <b>载入并销毁之前的记录</b> * * @param reader * @throws IOException */ public synchronized void load(Reader reader) throws IOException { load(reader, false); } public synchronized void load(Reader reader, boolean clear) throws IOException { if (clear) this.clear(); BufferedReader tr = null; if (reader instanceof BufferedReader) tr = (BufferedReader) reader; else tr = new BufferedReader(reader); String s; while (null != (s = tr.readLine())) { if (Strings.isBlank(s)) continue; if (s.length() > 0 && s.trim().charAt(0) == '#') // 只要第一个非空白字符是#,就认为是注释 continue; int pos; char c = '0'; for (pos = 0; pos < s.length(); pos++) { c = s.charAt(pos); if (c == '=' || c == ':') break; } if (c == '=') { String name = s.substring(0, pos); String value = s.substring(pos + 1); if (value.endsWith("\\") && !value.endsWith("\\\\")) { StringBuilder sb = new StringBuilder(value.substring(0, value.length() - 1)); while (null != (s = tr.readLine())) { if (Strings.isBlank(s)) break; if (s.endsWith("\\") && !s.endsWith("\\\\")) { sb.append(s.substring(0, s.length() - 1)); } else { sb.append(s); break; } } value = sb.toString(); } // 对value里面的\\uXXXX进行转义? if (value.contains("\\u")) { value = Strings.unicodeDecode(value); } maps.put(Strings.trim(name), value); } else if (c == ':') { String name = s.substring(0, pos); StringBuffer sb = new StringBuffer(); sb.append(s.substring(pos + 1)); String ss; while (null != (ss = tr.readLine())) { if (ss.length() > 0 && ss.charAt(0) == '#') break; sb.append("\r\n" + ss); } maps.put(Strings.trim(name), sb.toString()); if (null == ss) return; } else { maps.put(Strings.trim(s), null); } } } public synchronized void clear() { maps.clear(); } public boolean containsKey(Object key) { return maps.containsKey(key); } public boolean containsValue(Object value) { return maps.containsValue(value); } public Set<Entry<String, String>> entrySet() { return maps.entrySet(); } @Override public boolean equals(Object o) { return maps.equals(o); } @Override public int hashCode() { return maps.hashCode(); } public boolean isEmpty() { return maps.isEmpty(); } public Set<String> keySet() { return maps.keySet(); } public List<String> keys() { return new ArrayList<String>(maps.keySet()); } public synchronized String put(String key, String value) { return maps.put(key, value); } @SuppressWarnings({"unchecked", "rawtypes"}) public synchronized void putAll(Map t) { maps.putAll(t); } public synchronized String remove(Object key) { return maps.remove(key); } public int size() { return maps.size(); } public Collection<String> values() { return maps.values(); } public String get(Object key) { return maps.get(key); } public void print(OutputStream out) throws IOException { print(new OutputStreamWriter(out, Encoding.CHARSET_UTF8)); } public void print(Writer writer) throws IOException { String NL = System.getProperty("line.separator"); for (Map.Entry<String, String> en : entrySet()) { writer.write(en.getKey()); String val = en.getValue(); if (val == null) { writer.write("="); continue; } if (val.contains("\n")) { writer.write(":="); writer.write(val); writer.write(NL); writer.write("#End " + en.getKey()); } else { writer.write('='); writer.write(val); } writer.write(NL); } } }
fix: 移除编译警告
src/org/nutz/lang/util/MultiLineProperties.java
fix: 移除编译警告
Java
apache-2.0
b0ee7dbccaf2304bc20b1199f2790a122e27b7cb
0
psoreide/bnd,magnet/bnd,magnet/bnd,mcculls/bnd,magnet/bnd,lostiniceland/bnd,psoreide/bnd,psoreide/bnd,lostiniceland/bnd,lostiniceland/bnd,mcculls/bnd,mcculls/bnd
package aQute.lib.io; import static java.nio.charset.StandardCharsets.UTF_8; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.DataOutput; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.nio.charset.Charset; import java.nio.file.FileAlreadyExistsException; import java.nio.file.FileVisitOption; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import java.security.MessageDigest; import java.util.Collection; import java.util.EnumSet; import java.util.LinkedHashSet; import java.util.Set; import java.util.regex.Pattern; import aQute.libg.glob.Glob; public class IO { static final int BUFFER_SIZE = IOConstants.PAGE_SIZE * 16; static final public File work = new File(System.getProperty("user.dir")); static final public File home; private static final EnumSet<StandardOpenOption> writeOptions = EnumSet.of(StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); private static final EnumSet<StandardOpenOption> readOptions = EnumSet.of(StandardOpenOption.READ); static { File tmp = null; try { tmp = new File(System.getenv("HOME")); } catch (Exception e) {} if (tmp == null) { tmp = new File(System.getProperty("user.home")); } home = tmp; } public static String getExtension(String fileName, String deflt) { int n = fileName.lastIndexOf('.'); if (n < 0) return deflt; return fileName.substring(n + 1); } public static Collection<File> tree(File current) { Set<File> files = new LinkedHashSet<File>(); traverse(files, current, null); return files; } public static Collection<File> tree(File current, String glob) { Set<File> files = new LinkedHashSet<File>(); traverse(files, current, glob == null ? null : new Glob(glob)); return files; } private static void traverse(Collection<File> files, File current, Glob glob) { if (current.isFile() && (glob == null || glob.matcher(current.getName()).matches())) { files.add(current); } else if (current.isDirectory()) { for (File sub : current.listFiles()) { traverse(files, sub, glob); } } } public static void copy(byte[] data, File file) throws IOException { copy(data, file.toPath()); } public static void copy(byte[] data, Path path) throws IOException { try (FileChannel out = writeChannel(path)) { ByteBuffer buffer = ByteBuffer.wrap(data); while (buffer.hasRemaining()) { out.write(buffer); } } } public static void copy(byte[] r, Writer w) throws IOException { w.write(new String(r, UTF_8)); } public static void copy(byte[] r, OutputStream out) throws IOException { out.write(r); } public static void copy(Reader r, Writer w) throws IOException { try { char buffer[] = new char[BUFFER_SIZE]; for (int size; (size = r.read(buffer)) > 0;) { w.write(buffer, 0, size); } } finally { r.close(); } } public static void copy(Reader r, OutputStream out) throws IOException { copy(r, out, UTF_8); } public static void copy(Reader r, OutputStream out, String charset) throws IOException { copy(r, out, Charset.forName(charset)); } public static void copy(Reader r, OutputStream out, Charset charset) throws IOException { Writer w = writer(out, charset); try { copy(r, w); } finally { w.flush(); } } public static void copy(InputStream in, Writer w) throws IOException { copy(in, w, UTF_8); } public static void copy(InputStream in, Writer w, String charset) throws IOException { copy(in, w, Charset.forName(charset)); } public static void copy(InputStream in, Writer w, Charset charset) throws IOException { copy(reader(in, charset), w); } public static void copy(InputStream in, OutputStream out) throws IOException { try { byte[] buffer = new byte[BUFFER_SIZE]; for (int size; (size = in.read(buffer)) > 0;) { out.write(buffer, 0, size); } } finally { in.close(); } } public static void copy(InputStream in, DataOutput out) throws IOException { try { byte[] buffer = new byte[BUFFER_SIZE]; for (int size; (size = in.read(buffer)) > 0;) { out.write(buffer, 0, size); } } finally { in.close(); } } public static void copy(ReadableByteChannel in, WritableByteChannel out) throws IOException { try { ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER_SIZE); while (in.read(buffer) > 0) { buffer.flip(); out.write(buffer); buffer.compact(); } buffer.flip(); while (buffer.hasRemaining()) { out.write(buffer); } } finally { in.close(); } } public static void copy(InputStream in, ByteBuffer bb) throws IOException { try { if (bb.hasArray()) { byte[] buffer = bb.array(); int offset = bb.arrayOffset(); for (int size; bb.hasRemaining() && (size = in.read(buffer, offset + bb.position(), bb.remaining())) > 0;) { bb.position(bb.position() + size); } } else { int length = Math.min(bb.remaining(), BUFFER_SIZE); byte[] buffer = new byte[length]; for (int size; bb.hasRemaining() && (size = in.read(buffer, 0, length)) > 0;) { bb.put(buffer, 0, size); length = Math.min(bb.remaining(), buffer.length); } } } finally { in.close(); } } public static void copy(URL url, MessageDigest md) throws IOException { copy(stream(url), md); } public static void copy(File file, MessageDigest md) throws IOException { copy(file.toPath(), md); } public static void copy(Path path, MessageDigest md) throws IOException { copy(readChannel(path), md); } public static void copy(URLConnection conn, MessageDigest md) throws IOException { copy(conn.getInputStream(), md); } public static void copy(InputStream in, MessageDigest md) throws IOException { try { byte[] buffer = new byte[BUFFER_SIZE]; for (int size; (size = in.read(buffer)) > 0;) { md.update(buffer, 0, size); } } finally { in.close(); } } public static void copy(ReadableByteChannel in, MessageDigest md) throws IOException { try { ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); while (in.read(buffer) > 0) { buffer.flip(); md.update(buffer); buffer.compact(); } buffer.flip(); while (buffer.hasRemaining()) { md.update(buffer); } } finally { in.close(); } } public static void copy(URL url, File file) throws IOException { copy(stream(url), file); } public static void copy(URLConnection conn, File file) throws IOException { copy(conn.getInputStream(), file); } public static void copy(InputStream in, URL url) throws IOException { copy(in, url, null); } public static void copy(InputStream in, URL url, String method) throws IOException { URLConnection c = url.openConnection(); HttpURLConnection http = (c instanceof HttpURLConnection) ? (HttpURLConnection) c : null; if (http != null && method != null) { http.setRequestMethod(method); } c.setDoOutput(true); try (OutputStream os = c.getOutputStream()) { copy(in, os); } finally { if (http != null) { http.disconnect(); } } } public static void copy(File src, File tgt) throws IOException { copy(src.toPath(), tgt.toPath()); } public static void copy(Path src, Path tgt) throws IOException { final Path source = src.toAbsolutePath(); final Path target = tgt.toAbsolutePath(); if (Files.isRegularFile(source)) { Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); return; } if (Files.isDirectory(source)) { if (Files.notExists(target)) { mkdirs(target); } if (!Files.isDirectory(target)) throw new IllegalArgumentException("target directory for a directory must be a directory: " + target); if (target.startsWith(source)) throw new IllegalArgumentException("target directory can not be child of source directory."); Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new FileVisitor<Path>() { final FileTime now = FileTime.fromMillis(System.currentTimeMillis()); @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { Path targetdir = target.resolve(source.relativize(dir)); try { Files.copy(dir, targetdir); } catch (FileAlreadyExistsException e) { if (!Files.isDirectory(targetdir)) throw e; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Path targetFile = target.resolve(source.relativize(file)); Files.copy(file, targetFile, StandardCopyOption.REPLACE_EXISTING); Files.setLastModifiedTime(targetFile, now); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { if (exc != null) { // directory iteration failed throw exc; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (exc != null) { throw exc; } return FileVisitResult.CONTINUE; } }); return; } throw new FileNotFoundException("During copy: " + source.toString()); } public static void copy(InputStream in, File file) throws IOException { copy(in, file.toPath()); } public static void copy(InputStream in, Path path) throws IOException { try (FileChannel out = writeChannel(path)) { copy(in, out); } } public static void copy(File file, OutputStream out) throws IOException { copy(file.toPath(), out); } public static void copy(Path path, OutputStream out) throws IOException { copy(readChannel(path), out); } public static void copy(InputStream in, WritableByteChannel out) throws IOException { try { ByteBuffer bb = ByteBuffer.allocate(BUFFER_SIZE); byte[] buffer = bb.array(); for (int size; (size = in.read(buffer, bb.position(), bb.remaining())) > 0;) { bb.position(bb.position() + size); bb.flip(); out.write(bb); bb.compact(); } bb.flip(); while (bb.hasRemaining()) { out.write(bb); } } finally { in.close(); } } public static void copy(ReadableByteChannel in, OutputStream out) throws IOException { try { ByteBuffer bb = ByteBuffer.allocate(BUFFER_SIZE); byte[] buffer = bb.array(); while (in.read(bb) > 0) { out.write(buffer, 0, bb.position()); bb.clear(); } } finally { in.close(); } } public static byte[] read(File file) throws IOException { ByteBuffer bb = read(file.toPath()); return bb.array(); } public static ByteBuffer read(Path path) throws IOException { try (FileChannel in = readChannel(path)) { ByteBuffer buffer = ByteBuffer.allocate((int) in.size()); while (in.read(buffer) > 0) {} buffer.flip(); return buffer; } } public static byte[] read(URL url) throws IOException { return read(stream(url)); } public static byte[] read(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); copy(in, out); return out.toByteArray(); } public static void write(byte[] data, OutputStream out) throws Exception { copy(data, out); } public static void write(byte[] data, File file) throws Exception { copy(data, file); } public static String collect(File file) throws IOException { return collect(file.toPath(), UTF_8); } public static String collect(File file, String encoding) throws IOException { return collect(file.toPath(), Charset.forName(encoding)); } public static String collect(File file, Charset encoding) throws IOException { return collect(file.toPath(), encoding); } public static String collect(Path path) throws IOException { return collect(path, UTF_8); } public static String collect(Path path, Charset encoding) throws IOException { return encoding.decode(read(path)).toString(); } public static String collect(URL url, String encoding) throws IOException { return collect(stream(url), Charset.forName(encoding)); } public static String collect(URL url, Charset encoding) throws IOException { return collect(stream(url), encoding); } public static String collect(URL url) throws IOException { return collect(url, UTF_8); } public static String collect(String path) throws IOException { return collect(Paths.get(path), UTF_8); } public static String collect(InputStream in) throws IOException { return collect(in, UTF_8); } public static String collect(InputStream in, String encoding) throws IOException { return collect(in, Charset.forName(encoding)); } public static String collect(InputStream in, Charset encoding) throws IOException { return collect(reader(in, encoding)); } public static String collect(Reader r) throws IOException { StringWriter w = new StringWriter(); copy(r, w); return w.toString(); } /** * Create a temporary file. * * @param directory the directory in which to create the file. Can be null, * in which case the system TMP directory is used * @param pattern the filename prefix pattern. Must be at least 3 characters * long * @param suffix the filename suffix. Can be null, in which case (system) * default suffix is used * @return temp file * @throws IllegalArgumentException when pattern is null or too short * @throws IOException when the specified (non-null) directory is not a * directory */ public static File createTempFile(File directory, String pattern, String suffix) throws IllegalArgumentException, IOException { if ((pattern == null) || (pattern.length() < 3)) { throw new IllegalArgumentException("Pattern must be at least 3 characters long, got " + ((pattern == null) ? "null" : pattern.length())); } if ((directory != null) && !directory.isDirectory()) { throw new FileNotFoundException("Directory " + directory + " is not a directory"); } return File.createTempFile(pattern, suffix, directory); } public static File getFile(String filename) { return getFile(work, filename); } public static File getFile(File base, String file) { if (file.startsWith("~/")) { file = file.substring(2); if (!file.startsWith("~/")) { return getFile(home, file); } } if (file.startsWith("~")) { file = file.substring(1); return getFile(home.getParentFile(), file); } File f = new File(file); if (f.isAbsolute()) return f; if (base == null) base = work; f = base.getAbsoluteFile(); for (int n; (n = file.indexOf('/')) > 0;) { String first = file.substring(0, n); file = file.substring(n + 1); if (first.equals("..")) f = f.getParentFile(); else f = new File(f, first); } if (file.equals("..")) return f.getParentFile(); return new File(f, file).getAbsoluteFile(); } /** * Deletes the specified file. Folders are recursively deleted.<br> * If file(s) cannot be deleted, no feedback is provided (fail silently). * * @param file file to be deleted */ public static void delete(File file) { delete(file.toPath()); } /** * Deletes the specified path. Folders are recursively deleted.<br> * If file(s) cannot be deleted, no feedback is provided (fail silently). * * @param path path to be deleted */ public static void delete(Path path) { try { deleteWithException(path); } catch (IOException e) { // Ignore a failed delete } } /** * Deletes and creates directories */ public static void initialize(File dir) { try { deleteWithException(dir); mkdirs(dir); } catch (IOException e) { throw new RuntimeException(e); } } /** * Deletes the specified file. Folders are recursively deleted.<br> * Throws exception if any of the files could not be deleted. * * @param file file to be deleted * @throws IOException if the file (or contents of a folder) could not be * deleted */ public static void deleteWithException(File file) throws IOException { deleteWithException(file.toPath()); } /** * Deletes the specified path. Folders are recursively deleted.<br> * Throws exception if any of the files could not be deleted. * * @param path path to be deleted * @throws IOException if the path (or contents of a folder) could not be * deleted */ public static void deleteWithException(Path path) throws IOException { path = path.toAbsolutePath(); if (Files.notExists(path) && !isSymbolicLink(path)) { return; } if (path.equals(path.getRoot())) throw new IllegalArgumentException("Cannot recursively delete root for safety reasons"); Files.walkFileTree(path, new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { try { Files.delete(file); } catch (IOException e) { throw exc; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (exc != null) { // directory iteration failed throw exc; } Files.delete(dir); return FileVisitResult.CONTINUE; } }); } /** * Renames <code>from</code> to <code>to</code> replacing the target file if * necessary. * * @param from source file * @param to destination file * @throws IOException if the rename operation fails */ public static void rename(File from, File to) throws IOException { rename(from.toPath(), to.toPath()); } /** * Renames <code>from</code> to <code>to</code> replacing the target file if * necessary. * * @param from source path * @param to destination path * @throws IOException if the rename operation fails */ public static void rename(Path from, Path to) throws IOException { Files.move(from, to, StandardCopyOption.REPLACE_EXISTING); } public static void mkdirs(File dir) throws IOException { mkdirs(dir.toPath()); } public static void mkdirs(Path dir) throws IOException { Files.createDirectories(dir); } public static long drain(InputStream in) throws IOException { try { long result = 0; byte[] buffer = new byte[BUFFER_SIZE]; for (int size; (size = in.read(buffer)) > 0;) { result += size; } return result; } finally { in.close(); } } public static void copy(Collection< ? > c, OutputStream out) throws IOException { PrintWriter pw = writer(out); try { for (Object o : c) { pw.println(o); } } finally { pw.flush(); } } public static Throwable close(Closeable in) { try { if (in != null) in.close(); } catch (Throwable e) { return e; } return null; } public static URL toURL(String s, File base) throws MalformedURLException { int n = s.indexOf(':'); if (n > 0 && n < 10) { // is url return new URL(s); } return getFile(base, s).toURI().toURL(); } public static void store(Object o, File file) throws IOException { store(o, file.toPath(), UTF_8); } public static void store(Object o, File file, String encoding) throws IOException { store(o, file.toPath(), Charset.forName(encoding)); } public static void store(Object o, Path path, Charset encoding) throws IOException { try (FileChannel ch = writeChannel(path)) { if (o != null) { try (Writer w = Channels.newWriter(ch, encoding.newEncoder(), -1)) { w.write(o.toString()); } } } } public static void store(Object o, OutputStream out) throws IOException { store(o, out, UTF_8); } public static void store(Object o, OutputStream out, String encoding) throws IOException { store(o, out, Charset.forName(encoding)); } public static void store(Object o, OutputStream out, Charset encoding) throws IOException { Writer w = writer(out, encoding); try { store(o, w); } finally { w.flush(); } } public static void store(Object o, Writer w) throws IOException { if (o != null) { w.write(o.toString()); } } public static InputStream stream(String s) { return stream(s, UTF_8); } public static InputStream stream(String s, String encoding) throws IOException { return stream(s, Charset.forName(encoding)); } public static InputStream stream(String s, Charset encoding) { return new ByteArrayInputStream(s.getBytes(encoding)); } public static InputStream stream(File file) throws IOException { return stream(file.toPath()); } public static InputStream stream(Path path) throws IOException { return Files.newInputStream(path); } public static InputStream stream(URL url) throws IOException { return url.openStream(); } public static FileChannel readChannel(Path path) throws IOException { return FileChannel.open(path, readOptions); } public static OutputStream outputStream(File file) throws IOException { return outputStream(file.toPath()); } public static OutputStream outputStream(Path path) throws IOException { return Files.newOutputStream(path); } public static FileChannel writeChannel(Path path) throws IOException { return FileChannel.open(path, writeOptions); } public static BufferedReader reader(String s) { return new BufferedReader(new StringReader(s)); } public static BufferedReader reader(File file) throws IOException { return reader(file.toPath(), UTF_8); } public static BufferedReader reader(File file, String encoding) throws IOException { return reader(file.toPath(), Charset.forName(encoding)); } public static BufferedReader reader(File file, Charset encoding) throws IOException { return reader(file.toPath(), encoding); } public static BufferedReader reader(Path path, Charset encoding) throws IOException { return reader(readChannel(path), encoding); } public static BufferedReader reader(ReadableByteChannel in, Charset encoding) throws IOException { return new BufferedReader(Channels.newReader(in, encoding.newDecoder(), -1)); } public static BufferedReader reader(InputStream in) throws IOException { return reader(in, UTF_8); } public static BufferedReader reader(InputStream in, String encoding) throws IOException { return reader(in, Charset.forName(encoding)); } public static BufferedReader reader(InputStream in, Charset encoding) throws IOException { return new BufferedReader(new InputStreamReader(in, encoding)); } public static PrintWriter writer(File file) throws IOException { return writer(file.toPath(), UTF_8); } public static PrintWriter writer(File file, String encoding) throws IOException { return writer(file.toPath(), Charset.forName(encoding)); } public static PrintWriter writer(File file, Charset encoding) throws IOException { return writer(file.toPath(), encoding); } public static PrintWriter writer(Path path, Charset encoding) throws IOException { return writer(writeChannel(path), encoding); } public static PrintWriter writer(WritableByteChannel out, Charset encoding) throws IOException { return new PrintWriter(Channels.newWriter(out, encoding.newEncoder(), -1)); } public static PrintWriter writer(OutputStream out) throws IOException { return writer(out, UTF_8); } public static PrintWriter writer(OutputStream out, String encoding) throws IOException { return writer(out, Charset.forName(encoding)); } public static PrintWriter writer(OutputStream out, Charset encoding) throws IOException { return new PrintWriter(new OutputStreamWriter(out, encoding)); } public static boolean createSymbolicLink(File link, File target) throws Exception { return createSymbolicLink(link.toPath(), target.toPath()); } public static boolean createSymbolicLink(Path link, Path target) throws Exception { if (isSymbolicLink(link)) { Path linkTarget = Files.readSymbolicLink(link); if (target.equals(linkTarget)) { return true; } else { Files.delete(link); } } try { Files.createSymbolicLink(link, target); return true; } catch (Exception e) { // ignore } return false; } public static boolean isSymbolicLink(File link) { return isSymbolicLink(link.toPath()); } public static boolean isSymbolicLink(Path link) { return Files.isSymbolicLink(link); } /** * Creates a symbolic link from {@code link} to the {@code target}, or * copies {@code target} to {@code link} if running on Windows. * <p> * Creating symbolic links on Windows requires administrator permissions, so * copying is a safer fallback. Copy only happens if timestamp and and file * length are different than target * * @param link the location of the symbolic link, or destination of the * copy. * @param target the source of the symbolic link, or source of the copy. * @return {@code true} if the operation succeeds, {@code false} otherwise. */ public static boolean createSymbolicLinkOrCopy(File link, File target) { return createSymbolicLinkOrCopy(link.toPath(), target.toPath()); } /** * Creates a symbolic link from {@code link} to the {@code target}, or * copies {@code target} to {@code link} if running on Windows. * <p> * Creating symbolic links on Windows requires administrator permissions, so * copying is a safer fallback. Copy only happens if timestamp and and file * length are different than target * * @param link the location of the symbolic link, or destination of the * copy. * @param target the source of the symbolic link, or source of the copy. * @return {@code true} if the operation succeeds, {@code false} otherwise. */ public static boolean createSymbolicLinkOrCopy(Path link, Path target) { try { if (isWindows() || !createSymbolicLink(link, target)) { // only copy if target length and timestamp differ BasicFileAttributes targetAttrs = Files.readAttributes(target, BasicFileAttributes.class); try { BasicFileAttributes linkAttrs = Files.readAttributes(link, BasicFileAttributes.class); if (targetAttrs.lastModifiedTime().equals(linkAttrs.lastModifiedTime()) && targetAttrs.size() == linkAttrs.size()) { return true; } } catch (IOException e) { // link does not exist } copy(target, link); Files.setLastModifiedTime(link, targetAttrs.lastModifiedTime()); } return true; } catch (Exception ignore) { // ignore } return false; } static final public OutputStream nullStream = new OutputStream() { @Override public void write(int var0) throws IOException {} @Override public void write(byte[] var0) throws IOException {} @Override public void write(byte[] var0, int from, int l) throws IOException {} }; static final public Writer nullWriter = new Writer() { public java.io.Writer append(char var0) throws java.io.IOException { return null; } public java.io.Writer append(java.lang.CharSequence var0) throws java.io.IOException { return null; } public java.io.Writer append(java.lang.CharSequence var0, int var1, int var2) throws java.io.IOException { return null; } public void write(int var0) throws java.io.IOException {} public void write(java.lang.String var0) throws java.io.IOException {} public void write(java.lang.String var0, int var1, int var2) throws java.io.IOException {} public void write(char[] var0) throws java.io.IOException {} public void write(char[] var0, int var1, int var2) throws java.io.IOException {} public void close() throws IOException {} public void flush() throws IOException {} }; public static String toSafeFileName(String string) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (c < ' ') continue; if (isWindows()) { switch (c) { case '<' : case '>' : case '"' : case '/' : case '\\' : case '|' : case '*' : case ':' : sb.append('%'); break; default : sb.append(c); } } else { switch (c) { case '/' : sb.append('%'); break; default : sb.append(c); } } } if (sb.length() == 0 || (isWindows() && RESERVED_WINDOWS_P.matcher(sb).matches())) sb.append("_"); return sb.toString(); } final static Pattern RESERVED_WINDOWS_P = Pattern.compile( "CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9]"); static boolean isWindows() { return File.separatorChar == '\\'; } }
aQute.libg/src/aQute/lib/io/IO.java
package aQute.lib.io; import static java.nio.charset.StandardCharsets.UTF_8; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.DataOutput; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.nio.charset.Charset; import java.nio.file.FileAlreadyExistsException; import java.nio.file.FileVisitOption; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import java.security.MessageDigest; import java.util.Collection; import java.util.EnumSet; import java.util.LinkedHashSet; import java.util.Set; import java.util.regex.Pattern; import aQute.libg.glob.Glob; public class IO { static final int BUFFER_SIZE = IOConstants.PAGE_SIZE * 16; static final public File work = new File(System.getProperty("user.dir")); static final public File home; private static final EnumSet<StandardOpenOption> writeOptions = EnumSet.of(StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); private static final EnumSet<StandardOpenOption> readOptions = EnumSet.of(StandardOpenOption.READ); static { File tmp = null; try { tmp = new File(System.getenv("HOME")); } catch (Exception e) {} if (tmp == null) { tmp = new File(System.getProperty("user.home")); } home = tmp; } public static String getExtension(String fileName, String deflt) { int n = fileName.lastIndexOf('.'); if (n < 0) return deflt; return fileName.substring(n + 1); } public static Collection<File> tree(File current) { Set<File> files = new LinkedHashSet<File>(); traverse(files, current, null); return files; } public static Collection<File> tree(File current, String glob) { Set<File> files = new LinkedHashSet<File>(); traverse(files, current, glob == null ? null : new Glob(glob)); return files; } private static void traverse(Collection<File> files, File current, Glob glob) { if (current.isFile() && (glob == null || glob.matcher(current.getName()).matches())) { files.add(current); } else if (current.isDirectory()) { for (File sub : current.listFiles()) { traverse(files, sub, glob); } } } public static void copy(byte[] data, File file) throws IOException { copy(data, file.toPath()); } public static void copy(byte[] data, Path path) throws IOException { try (FileChannel out = writeChannel(path)) { ByteBuffer buffer = ByteBuffer.wrap(data); while (buffer.hasRemaining()) { out.write(buffer); } } } public static void copy(byte[] r, Writer w) throws IOException { w.write(new String(r, UTF_8)); } public static void copy(byte[] r, OutputStream out) throws IOException { out.write(r); } public static void copy(Reader r, Writer w) throws IOException { try { char buffer[] = new char[BUFFER_SIZE]; for (int size; (size = r.read(buffer)) > 0;) { w.write(buffer, 0, size); } } finally { r.close(); } } public static void copy(Reader r, OutputStream out) throws IOException { copy(r, out, UTF_8); } public static void copy(Reader r, OutputStream out, String charset) throws IOException { copy(r, out, Charset.forName(charset)); } public static void copy(Reader r, OutputStream out, Charset charset) throws IOException { Writer w = writer(out, charset); try { copy(r, w); } finally { w.flush(); } } public static void copy(InputStream in, Writer w) throws IOException { copy(in, w, UTF_8); } public static void copy(InputStream in, Writer w, String charset) throws IOException { copy(in, w, Charset.forName(charset)); } public static void copy(InputStream in, Writer w, Charset charset) throws IOException { copy(reader(in, charset), w); } public static void copy(InputStream in, OutputStream out) throws IOException { try { byte[] buffer = new byte[BUFFER_SIZE]; for (int size; (size = in.read(buffer)) > 0;) { out.write(buffer, 0, size); } } finally { in.close(); } } public static void copy(InputStream in, DataOutput out) throws IOException { try { byte[] buffer = new byte[BUFFER_SIZE]; for (int size; (size = in.read(buffer)) > 0;) { out.write(buffer, 0, size); } } finally { in.close(); } } public static void copy(ReadableByteChannel in, WritableByteChannel out) throws IOException { try { ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER_SIZE); while (in.read(buffer) > 0) { buffer.flip(); out.write(buffer); buffer.compact(); } buffer.flip(); while (buffer.hasRemaining()) { out.write(buffer); } } finally { in.close(); } } public static void copy(InputStream in, ByteBuffer bb) throws IOException { try { if (bb.hasArray()) { byte[] buffer = bb.array(); int offset = bb.arrayOffset(); for (int size; bb.hasRemaining() && (size = in.read(buffer, offset + bb.position(), bb.remaining())) > 0;) { bb.position(bb.position() + size); } } else { int length = Math.min(bb.remaining(), BUFFER_SIZE); byte[] buffer = new byte[length]; for (int size; bb.hasRemaining() && (size = in.read(buffer, 0, length)) > 0;) { bb.put(buffer, 0, size); length = Math.min(bb.remaining(), buffer.length); } } } finally { in.close(); } } public static void copy(URL url, MessageDigest md) throws IOException { copy(stream(url), md); } public static void copy(File file, MessageDigest md) throws IOException { copy(file.toPath(), md); } public static void copy(Path path, MessageDigest md) throws IOException { copy(readChannel(path), md); } public static void copy(URLConnection conn, MessageDigest md) throws IOException { copy(conn.getInputStream(), md); } public static void copy(InputStream in, MessageDigest md) throws IOException { try { byte[] buffer = new byte[BUFFER_SIZE]; for (int size; (size = in.read(buffer)) > 0;) { md.update(buffer, 0, size); } } finally { in.close(); } } public static void copy(ReadableByteChannel in, MessageDigest md) throws IOException { try { ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); while (in.read(buffer) > 0) { buffer.flip(); md.update(buffer); buffer.compact(); } buffer.flip(); while (buffer.hasRemaining()) { md.update(buffer); } } finally { in.close(); } } public static void copy(URL url, File file) throws IOException { copy(stream(url), file); } public static void copy(URLConnection conn, File file) throws IOException { copy(conn.getInputStream(), file); } public static void copy(InputStream in, URL url) throws IOException { copy(in, url, null); } public static void copy(InputStream in, URL url, String method) throws IOException { URLConnection c = url.openConnection(); HttpURLConnection http = (c instanceof HttpURLConnection) ? (HttpURLConnection) c : null; if (http != null && method != null) { http.setRequestMethod(method); } c.setDoOutput(true); try (OutputStream os = c.getOutputStream()) { copy(in, os); } finally { if (http != null) { http.disconnect(); } } } public static void copy(File src, File tgt) throws IOException { copy(src.toPath(), tgt.toPath()); } public static void copy(Path src, Path tgt) throws IOException { final Path source = src.toAbsolutePath(); final Path target = tgt.toAbsolutePath(); if (Files.isRegularFile(source)) { Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); return; } if (Files.isDirectory(source)) { if (Files.notExists(target)) { mkdirs(target); } if (!Files.isDirectory(target)) throw new IllegalArgumentException("target directory for a directory must be a directory: " + target); if (target.startsWith(source)) throw new IllegalArgumentException("target directory can not be child of source directory."); Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new FileVisitor<Path>() { final FileTime now = FileTime.fromMillis(System.currentTimeMillis()); @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { Path targetdir = target.resolve(source.relativize(dir)); try { Files.copy(dir, targetdir); } catch (FileAlreadyExistsException e) { if (!Files.isDirectory(targetdir)) throw e; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Path targetFile = target.resolve(source.relativize(file)); Files.copy(file, targetFile, StandardCopyOption.REPLACE_EXISTING); Files.setLastModifiedTime(targetFile, now); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { if (exc != null) { // directory iteration failed throw exc; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (exc != null) { throw exc; } return FileVisitResult.CONTINUE; } }); return; } throw new FileNotFoundException("During copy: " + source.toString()); } public static void copy(InputStream in, File file) throws IOException { copy(in, file.toPath()); } public static void copy(InputStream in, Path path) throws IOException { try (FileChannel out = writeChannel(path)) { copy(Channels.newChannel(in), out); } } public static void copy(File file, OutputStream out) throws IOException { copy(file.toPath(), out); } public static void copy(Path path, OutputStream out) throws IOException { copy(readChannel(path), Channels.newChannel(out)); } public static byte[] read(File file) throws IOException { ByteBuffer bb = read(file.toPath()); return bb.array(); } public static ByteBuffer read(Path path) throws IOException { try (FileChannel in = readChannel(path)) { ByteBuffer buffer = ByteBuffer.allocate((int) in.size()); while (in.read(buffer) > 0) {} buffer.flip(); return buffer; } } public static byte[] read(URL url) throws IOException { return read(stream(url)); } public static byte[] read(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); copy(in, out); return out.toByteArray(); } public static void write(byte[] data, OutputStream out) throws Exception { copy(data, out); } public static void write(byte[] data, File file) throws Exception { copy(data, file); } public static String collect(File file) throws IOException { return collect(file.toPath(), UTF_8); } public static String collect(File file, String encoding) throws IOException { return collect(file.toPath(), Charset.forName(encoding)); } public static String collect(File file, Charset encoding) throws IOException { return collect(file.toPath(), encoding); } public static String collect(Path path) throws IOException { return collect(path, UTF_8); } public static String collect(Path path, Charset encoding) throws IOException { return encoding.decode(read(path)).toString(); } public static String collect(URL url, String encoding) throws IOException { return collect(stream(url), Charset.forName(encoding)); } public static String collect(URL url, Charset encoding) throws IOException { return collect(stream(url), encoding); } public static String collect(URL url) throws IOException { return collect(url, UTF_8); } public static String collect(String path) throws IOException { return collect(Paths.get(path), UTF_8); } public static String collect(InputStream in) throws IOException { return collect(in, UTF_8); } public static String collect(InputStream in, String encoding) throws IOException { return collect(in, Charset.forName(encoding)); } public static String collect(InputStream in, Charset encoding) throws IOException { return collect(reader(in, encoding)); } public static String collect(Reader r) throws IOException { StringWriter w = new StringWriter(); copy(r, w); return w.toString(); } /** * Create a temporary file. * * @param directory the directory in which to create the file. Can be null, * in which case the system TMP directory is used * @param pattern the filename prefix pattern. Must be at least 3 characters * long * @param suffix the filename suffix. Can be null, in which case (system) * default suffix is used * @return temp file * @throws IllegalArgumentException when pattern is null or too short * @throws IOException when the specified (non-null) directory is not a * directory */ public static File createTempFile(File directory, String pattern, String suffix) throws IllegalArgumentException, IOException { if ((pattern == null) || (pattern.length() < 3)) { throw new IllegalArgumentException("Pattern must be at least 3 characters long, got " + ((pattern == null) ? "null" : pattern.length())); } if ((directory != null) && !directory.isDirectory()) { throw new FileNotFoundException("Directory " + directory + " is not a directory"); } return File.createTempFile(pattern, suffix, directory); } public static File getFile(String filename) { return getFile(work, filename); } public static File getFile(File base, String file) { if (file.startsWith("~/")) { file = file.substring(2); if (!file.startsWith("~/")) { return getFile(home, file); } } if (file.startsWith("~")) { file = file.substring(1); return getFile(home.getParentFile(), file); } File f = new File(file); if (f.isAbsolute()) return f; if (base == null) base = work; f = base.getAbsoluteFile(); for (int n; (n = file.indexOf('/')) > 0;) { String first = file.substring(0, n); file = file.substring(n + 1); if (first.equals("..")) f = f.getParentFile(); else f = new File(f, first); } if (file.equals("..")) return f.getParentFile(); return new File(f, file).getAbsoluteFile(); } /** * Deletes the specified file. Folders are recursively deleted.<br> * If file(s) cannot be deleted, no feedback is provided (fail silently). * * @param file file to be deleted */ public static void delete(File file) { delete(file.toPath()); } /** * Deletes the specified path. Folders are recursively deleted.<br> * If file(s) cannot be deleted, no feedback is provided (fail silently). * * @param path path to be deleted */ public static void delete(Path path) { try { deleteWithException(path); } catch (IOException e) { // Ignore a failed delete } } /** * Deletes and creates directories */ public static void initialize(File dir) { try { deleteWithException(dir); mkdirs(dir); } catch (IOException e) { throw new RuntimeException(e); } } /** * Deletes the specified file. Folders are recursively deleted.<br> * Throws exception if any of the files could not be deleted. * * @param file file to be deleted * @throws IOException if the file (or contents of a folder) could not be * deleted */ public static void deleteWithException(File file) throws IOException { deleteWithException(file.toPath()); } /** * Deletes the specified path. Folders are recursively deleted.<br> * Throws exception if any of the files could not be deleted. * * @param path path to be deleted * @throws IOException if the path (or contents of a folder) could not be * deleted */ public static void deleteWithException(Path path) throws IOException { path = path.toAbsolutePath(); if (Files.notExists(path) && !isSymbolicLink(path)) { return; } if (path.equals(path.getRoot())) throw new IllegalArgumentException("Cannot recursively delete root for safety reasons"); Files.walkFileTree(path, new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { try { Files.delete(file); } catch (IOException e) { throw exc; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (exc != null) { // directory iteration failed throw exc; } Files.delete(dir); return FileVisitResult.CONTINUE; } }); } /** * Renames <code>from</code> to <code>to</code> replacing the target file if * necessary. * * @param from source file * @param to destination file * @throws IOException if the rename operation fails */ public static void rename(File from, File to) throws IOException { rename(from.toPath(), to.toPath()); } /** * Renames <code>from</code> to <code>to</code> replacing the target file if * necessary. * * @param from source path * @param to destination path * @throws IOException if the rename operation fails */ public static void rename(Path from, Path to) throws IOException { Files.move(from, to, StandardCopyOption.REPLACE_EXISTING); } public static void mkdirs(File dir) throws IOException { mkdirs(dir.toPath()); } public static void mkdirs(Path dir) throws IOException { Files.createDirectories(dir); } public static long drain(InputStream in) throws IOException { try { long result = 0; byte[] buffer = new byte[BUFFER_SIZE]; for (int size; (size = in.read(buffer)) > 0;) { result += size; } return result; } finally { in.close(); } } public static void copy(Collection< ? > c, OutputStream out) throws IOException { PrintWriter pw = writer(out); try { for (Object o : c) { pw.println(o); } } finally { pw.flush(); } } public static Throwable close(Closeable in) { try { if (in != null) in.close(); } catch (Throwable e) { return e; } return null; } public static URL toURL(String s, File base) throws MalformedURLException { int n = s.indexOf(':'); if (n > 0 && n < 10) { // is url return new URL(s); } return getFile(base, s).toURI().toURL(); } public static void store(Object o, File file) throws IOException { store(o, file.toPath(), UTF_8); } public static void store(Object o, File file, String encoding) throws IOException { store(o, file.toPath(), Charset.forName(encoding)); } public static void store(Object o, Path path, Charset encoding) throws IOException { try (FileChannel ch = writeChannel(path)) { if (o != null) { try (Writer w = Channels.newWriter(ch, encoding.newEncoder(), -1)) { w.write(o.toString()); } } } } public static void store(Object o, OutputStream out) throws IOException { store(o, out, UTF_8); } public static void store(Object o, OutputStream out, String encoding) throws IOException { store(o, out, Charset.forName(encoding)); } public static void store(Object o, OutputStream out, Charset encoding) throws IOException { Writer w = writer(out, encoding); try { store(o, w); } finally { w.flush(); } } public static void store(Object o, Writer w) throws IOException { if (o != null) { w.write(o.toString()); } } public static InputStream stream(String s) { return stream(s, UTF_8); } public static InputStream stream(String s, String encoding) throws IOException { return stream(s, Charset.forName(encoding)); } public static InputStream stream(String s, Charset encoding) { return new ByteArrayInputStream(s.getBytes(encoding)); } public static InputStream stream(File file) throws IOException { return stream(file.toPath()); } public static InputStream stream(Path path) throws IOException { return Files.newInputStream(path); } public static InputStream stream(URL url) throws IOException { return url.openStream(); } public static FileChannel readChannel(Path path) throws IOException { return FileChannel.open(path, readOptions); } public static OutputStream outputStream(File file) throws IOException { return outputStream(file.toPath()); } public static OutputStream outputStream(Path path) throws IOException { return Files.newOutputStream(path); } public static FileChannel writeChannel(Path path) throws IOException { return FileChannel.open(path, writeOptions); } public static BufferedReader reader(String s) { return new BufferedReader(new StringReader(s)); } public static BufferedReader reader(File file) throws IOException { return reader(file.toPath(), UTF_8); } public static BufferedReader reader(File file, String encoding) throws IOException { return reader(file.toPath(), Charset.forName(encoding)); } public static BufferedReader reader(File file, Charset encoding) throws IOException { return reader(file.toPath(), encoding); } public static BufferedReader reader(Path path, Charset encoding) throws IOException { return reader(readChannel(path), encoding); } public static BufferedReader reader(ReadableByteChannel in, Charset encoding) throws IOException { return new BufferedReader(Channels.newReader(in, encoding.newDecoder(), -1)); } public static BufferedReader reader(InputStream in) throws IOException { return reader(in, UTF_8); } public static BufferedReader reader(InputStream in, String encoding) throws IOException { return reader(in, Charset.forName(encoding)); } public static BufferedReader reader(InputStream in, Charset encoding) throws IOException { return new BufferedReader(new InputStreamReader(in, encoding)); } public static PrintWriter writer(File file) throws IOException { return writer(file.toPath(), UTF_8); } public static PrintWriter writer(File file, String encoding) throws IOException { return writer(file.toPath(), Charset.forName(encoding)); } public static PrintWriter writer(File file, Charset encoding) throws IOException { return writer(file.toPath(), encoding); } public static PrintWriter writer(Path path, Charset encoding) throws IOException { return writer(writeChannel(path), encoding); } public static PrintWriter writer(WritableByteChannel out, Charset encoding) throws IOException { return new PrintWriter(Channels.newWriter(out, encoding.newEncoder(), -1)); } public static PrintWriter writer(OutputStream out) throws IOException { return writer(out, UTF_8); } public static PrintWriter writer(OutputStream out, String encoding) throws IOException { return writer(out, Charset.forName(encoding)); } public static PrintWriter writer(OutputStream out, Charset encoding) throws IOException { return new PrintWriter(new OutputStreamWriter(out, encoding)); } public static boolean createSymbolicLink(File link, File target) throws Exception { return createSymbolicLink(link.toPath(), target.toPath()); } public static boolean createSymbolicLink(Path link, Path target) throws Exception { if (isSymbolicLink(link)) { Path linkTarget = Files.readSymbolicLink(link); if (target.equals(linkTarget)) { return true; } else { Files.delete(link); } } try { Files.createSymbolicLink(link, target); return true; } catch (Exception e) { // ignore } return false; } public static boolean isSymbolicLink(File link) { return isSymbolicLink(link.toPath()); } public static boolean isSymbolicLink(Path link) { return Files.isSymbolicLink(link); } /** * Creates a symbolic link from {@code link} to the {@code target}, or * copies {@code target} to {@code link} if running on Windows. * <p> * Creating symbolic links on Windows requires administrator permissions, so * copying is a safer fallback. Copy only happens if timestamp and and file * length are different than target * * @param link the location of the symbolic link, or destination of the * copy. * @param target the source of the symbolic link, or source of the copy. * @return {@code true} if the operation succeeds, {@code false} otherwise. */ public static boolean createSymbolicLinkOrCopy(File link, File target) { return createSymbolicLinkOrCopy(link.toPath(), target.toPath()); } /** * Creates a symbolic link from {@code link} to the {@code target}, or * copies {@code target} to {@code link} if running on Windows. * <p> * Creating symbolic links on Windows requires administrator permissions, so * copying is a safer fallback. Copy only happens if timestamp and and file * length are different than target * * @param link the location of the symbolic link, or destination of the * copy. * @param target the source of the symbolic link, or source of the copy. * @return {@code true} if the operation succeeds, {@code false} otherwise. */ public static boolean createSymbolicLinkOrCopy(Path link, Path target) { try { if (isWindows() || !createSymbolicLink(link, target)) { // only copy if target length and timestamp differ BasicFileAttributes targetAttrs = Files.readAttributes(target, BasicFileAttributes.class); try { BasicFileAttributes linkAttrs = Files.readAttributes(link, BasicFileAttributes.class); if (targetAttrs.lastModifiedTime().equals(linkAttrs.lastModifiedTime()) && targetAttrs.size() == linkAttrs.size()) { return true; } } catch (IOException e) { // link does not exist } copy(target, link); Files.setLastModifiedTime(link, targetAttrs.lastModifiedTime()); } return true; } catch (Exception ignore) { // ignore } return false; } static final public OutputStream nullStream = new OutputStream() { @Override public void write(int var0) throws IOException {} @Override public void write(byte[] var0) throws IOException {} @Override public void write(byte[] var0, int from, int l) throws IOException {} }; static final public Writer nullWriter = new Writer() { public java.io.Writer append(char var0) throws java.io.IOException { return null; } public java.io.Writer append(java.lang.CharSequence var0) throws java.io.IOException { return null; } public java.io.Writer append(java.lang.CharSequence var0, int var1, int var2) throws java.io.IOException { return null; } public void write(int var0) throws java.io.IOException {} public void write(java.lang.String var0) throws java.io.IOException {} public void write(java.lang.String var0, int var1, int var2) throws java.io.IOException {} public void write(char[] var0) throws java.io.IOException {} public void write(char[] var0, int var1, int var2) throws java.io.IOException {} public void close() throws IOException {} public void flush() throws IOException {} }; public static String toSafeFileName(String string) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (c < ' ') continue; if (isWindows()) { switch (c) { case '<' : case '>' : case '"' : case '/' : case '\\' : case '|' : case '*' : case ':' : sb.append('%'); break; default : sb.append(c); } } else { switch (c) { case '/' : sb.append('%'); break; default : sb.append(c); } } } if (sb.length() == 0 || (isWindows() && RESERVED_WINDOWS_P.matcher(sb).matches())) sb.append("_"); return sb.toString(); } final static Pattern RESERVED_WINDOWS_P = Pattern.compile( "CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9]"); static boolean isWindows() { return File.separatorChar == '\\'; } }
io: Avoid Channel.newChannel when copying It creates an additional buffer. So instead we implement the copy loop through an array-backed ByteBuffer. Signed-off-by: BJ Hargrave <[email protected]>
aQute.libg/src/aQute/lib/io/IO.java
io: Avoid Channel.newChannel when copying
Java
apache-2.0
5d874d4307f28885263401a0dd2afb95ddb5c8b8
0
MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab
package org.myrobotlab.framework; import java.io.InputStream; import java.io.Serializable; import java.lang.management.ManagementFactory; import java.net.InetAddress; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import java.util.Properties; import java.util.TreeMap; import java.util.zip.ZipFile; import org.myrobotlab.io.FileIO; import org.myrobotlab.lang.NameGenerator; import org.myrobotlab.logging.LoggerFactory; import org.slf4j.Logger; /** * The purpose of this class is to retrieve all the detailed information * regarding the details of the current platform which myrobotlab is running. * * It must NOT have references to mrl services, or Runtime, or 3rd party library * dependencies except perhaps for logging * */ public class Platform implements Serializable { transient static Logger log = LoggerFactory.getLogger(Platform.class); private static final long serialVersionUID = 1L; // VM Names public final static String VM_DALVIK = "dalvik"; public final static String VM_HOTSPOT = "hotspot"; // OS Names public final static String OS_LINUX = "linux"; public final static String OS_MAC = "mac"; public final static String OS_WINDOWS = "windows"; public final static String UNKNOWN = "unknown"; // arch names public final static String ARCH_X86 = "x86"; public final static String ARCH_ARM = "arm"; // non-changing values String os; String arch; int osBitness; int jvmBitness; String lang = "java"; String vmName; String vmVersion; String mrlVersion; boolean isVirtual = false; /** * Static identifier to identify the "instance" of myrobotlab - similar to * network ip of a device and used in a similar way */ String id; String branch; String pid; String hostname; String commit; String build; String motd; Date startTime; static Platform localInstance; // = getLocalInstance(); /** * The one big convoluted function to get all the crazy platform specific * data. Potentially, it's done once and only once for a running instance. * Most of the data should be immutable, although the "id" * * All data should be accessed through public functions on the local instance. * If the local instance is desired. If its from a serialized instance, the * "getters" will be retrieving appropriate info for that serialized instance. * * @return - return the local instance of the current platform */ public static Platform getLocalInstance() { if (localInstance == null) { log.info("initializing Platform"); Platform platform = new Platform(); platform.startTime = new Date(); // === OS === platform.os = System.getProperty("os.name").toLowerCase(); if (platform.os.indexOf("win") >= 0) { platform.os = OS_WINDOWS; } else if (platform.os.indexOf("mac") >= 0) { platform.os = OS_MAC; } else if (platform.os.indexOf("linux") >= 0) { platform.os = OS_LINUX; } platform.vmName = System.getProperty("java.vm.name"); platform.vmVersion = System.getProperty("java.specification.version"); // === ARCH === String arch = System.getProperty("os.arch").toLowerCase(); if ("i386".equals(arch) || "i486".equals(arch) || "i586".equals(arch) || "i686".equals(arch) || "amd64".equals(arch) || arch.startsWith("x86")) { platform.arch = "x86"; // don't care at the moment } if ("arm".equals(arch)) { // FIXME - procparser is unsafe and borked !! // Integer armv = ProcParser.getArmInstructionVersion(); // Current work around: trigger off the os.version to choose // arm6 or arm7 // assume ras pi 1 . Integer armv = 6; // if the os version has "v7" in it, it's a pi 2 // TODO: this is still pretty hacky.. String osVersion = System.getProperty("os.version").toLowerCase(); if (osVersion.contains("v7")) { armv = 7; } // TODO: revisit how we determine the architecture version platform.arch = "armv" + armv + ".hfp"; } // for Ordroid 64 ! if ("aarch64".equals(arch)) { platform.arch = "armv8"; } if (platform.arch == null) { platform.arch = arch; } // === BITNESS === if (platform.isWindows()) { // https://blogs.msdn.microsoft.com/david.wang/2006/03/27/howto-detect-process-bitness/ // this will attempt to guess the bitness of the underlying OS, Java // tries very hard to hide this from running programs String procArch = System.getenv("PROCESSOR_ARCHITECTURE"); String procArchWow64 = System.getenv("PROCESSOR_ARCHITEW6432"); platform.osBitness = (procArch != null && procArch.endsWith("64") || procArchWow64 != null && procArchWow64.endsWith("64")) ? 64 : 32; switch (arch) { case "x86": case "i386": case "i486": case "i586": case "i686": platform.jvmBitness = 32; break; case "x86_64": case "amd64": platform.jvmBitness = 64; break; default: platform.jvmBitness = 0; // ooops, I guess break; } } else { // this is actually a really bad way of doing jvm bitness (may return // "64","32" or "unknown") - and is sometimes simply not there at all // keeping this as a fallback for all Linux and Mac machines, // I don't know enough to implement a more robust detection for them // (and this was here before me, so it has to be good) String model = System.getProperty("sun.arch.data.model"); platform.jvmBitness = "64".equals(model) ? 64 : 32; } // === MRL === if (platform.mrlVersion == null) { SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd"); platform.mrlVersion = format.format(new Date()); } // manifest Map<String, String> manifest = getManifest(); if (manifest.containsKey("GitBranch")) { platform.branch = manifest.get("GitBranch"); } else { platform.branch = "unknownBranch"; } if (manifest.containsKey("Commit")) { platform.commit = manifest.get("Commit"); } else { platform.commit = "unknownCommit"; } if (manifest.containsKey("Implementation-Version")) { platform.mrlVersion = manifest.get("Implementation-Version"); } else { platform.mrlVersion = "unknownVersion"; } // motd platform.motd = "resistance is futile, we have cookies and robots ..."; // hostname try { platform.hostname = InetAddress.getLocalHost().getHostName(); if (platform.hostname != null) { platform.hostname = platform.hostname.toLowerCase(); } } catch (Exception e) { platform.hostname = "localhost"; } SimpleDateFormat TSFormatter = new SimpleDateFormat("yyyyMMddHHmmssSSS"); platform.pid = TSFormatter.format(platform.startTime); try { // something like '<pid>@<hostname>', at least in SUN / Oracle JVMs // but non standard across jvms & hosts // here we will attempt to standardize it - when asked for pid you // "only" // get pid ... if possible String jvmName = ManagementFactory.getRuntimeMXBean().getName(); int index = jvmName.indexOf('@'); if (index > 1) { platform.pid = Long.toString(Long.parseLong(jvmName.substring(0, index))); } else { platform.pid = jvmName; } } catch (Exception e) { } localInstance = platform; } return localInstance; } public Platform() { } public String getPid() { return pid; } public String getMotd() { return motd; } public String getBranch() { return branch; } public String getBuild() { return build; } public String getCommit() { return commit; } public String getArch() { return arch; } public int getOsBitness() { return osBitness; } public int getJvmBitness() { return jvmBitness; } public String getOS() { return os; } public String getPlatformId() { return String.format("%s.%s.%s", getArch(), getJvmBitness(), getOS()); } public String getVersion() { return mrlVersion; } public String getVMName() { return vmName; } public boolean isArm() { return getArch().startsWith(ARCH_ARM); } public boolean isDalvik() { return VM_DALVIK.equals(vmName); } public boolean isLinux() { return OS_LINUX.equals(os); } public boolean isMac() { return OS_MAC.equals(os); } public boolean isWindows() { return OS_WINDOWS.equals(os); } public boolean isX86() { return getArch().equals(ARCH_X86); } static public Map<String, String> getManifest() { Map<String, String> ret = new TreeMap<String, String>(); ZipFile zf = null; try { log.info("getManifest"); String source = Platform.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath(); InputStream in = null; log.info("source {}", source); if (source.endsWith("jar")) { // runtime // DO NOT DO IT THIS WAY -> // Platform.class.getResource("/META-INF/MANIFEST.MF").openStream(); // IT DOES NOT WORK WITH OpenJDK !!! zf = new ZipFile(source); in = zf.getInputStream(zf.getEntry("META-INF/MANIFEST.MF")); // zf.close(); explodes on closing :( } else { // IDE - version ... in = Platform.class.getResource("/MANIFEST.MF").openStream(); } // String manifest = FileIO.toString(in); // log.info("loading manifest {}", manifest); Properties p = new Properties(); p.load(in); log.info("properties {}", p); for (final String name : p.stringPropertyNames()) { ret.put(name, p.getProperty(name)); log.info(name + "=" + p.getProperty(name)); } in.close(); } catch (Exception e) { e.printStackTrace(); // log.warn("getManifest threw", e); } finally { if (zf != null) { try { zf.close(); } catch (Exception e) { } } } return ret; } /* * private static Map<String, String> getAttributes(String part, Attributes * attributes) { Map<String, String> data = new TreeMap<String, String>(); * Iterator<Object> it = attributes.keySet().iterator(); while (it.hasNext()) * { java.util.jar.Attributes.Name key = (java.util.jar.Attributes.Name) * it.next(); Object value = attributes.get(key); String partKey = null; if * (part == null) { partKey = key.toString(); } else { partKey = * String.format("%s.%s", part, key); } * * // log.info( "{}: {}", value,partKey); if (value != null) { * data.put(partKey, value.toString()); } } return data; } */ @Override public String toString() { return String.format("%s.%d.%s", arch, jvmBitness, os); } public String getId() { // null ids are not allowed if (id == null) { id = NameGenerator.getName(); } return id; } public String getHostname() { return hostname; } public void setId(String newId) { id = newId; } public Date getStartTime() { return startTime; } public static boolean isVirtual() { Platform p = getLocalInstance(); return p.isVirtual; } public static void setVirtual(boolean b) { Platform p = getLocalInstance(); p.isVirtual = b; } public static void main(String[] args) { try { ZipFile zf = new ZipFile("/lhome/grperry/github/mrl.develop/myrobotlab/target/test/myrobotlab-unknownBranch-unknownVersion.jar"); InputStream in = zf.getInputStream(zf.getEntry("META-INF/MANIFEST.MF")); log.info("manifest {}", FileIO.toString(in)); Platform platform = Platform.getLocalInstance(); // log.info("platform : {}", platform.toString()); // log.info("build {}", platform.getBuild()); // log.info("branch {}", platform.getBranch()); // log.info("commit {}", platform.getCommit()); // log.info("toString {}", platform.toString()); } catch (Exception e) { e.printStackTrace(); // log.info("Exception: ", e); } } public boolean getVmVersion() { // TODO Auto-generated method stub return false; } }
src/main/java/org/myrobotlab/framework/Platform.java
package org.myrobotlab.framework; import java.io.InputStream; import java.io.Serializable; import java.lang.management.ManagementFactory; import java.net.InetAddress; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import java.util.Properties; import java.util.TreeMap; import java.util.zip.ZipFile; import org.myrobotlab.io.FileIO; import org.myrobotlab.lang.NameGenerator; import org.myrobotlab.logging.LoggerFactory; import org.slf4j.Logger; /** * The purpose of this class is to retrieve all the detailed information * regarding the details of the current platform which myrobotlab is running. * * It must NOT have references to mrl services, or Runtime, or 3rd party library * dependencies except perhaps for logging * */ public class Platform implements Serializable { transient static Logger log = LoggerFactory.getLogger(Platform.class); private static final long serialVersionUID = 1L; // VM Names public final static String VM_DALVIK = "dalvik"; public final static String VM_HOTSPOT = "hotspot"; // OS Names public final static String OS_LINUX = "linux"; public final static String OS_MAC = "mac"; public final static String OS_WINDOWS = "windows"; public final static String UNKNOWN = "unknown"; // arch names public final static String ARCH_X86 = "x86"; public final static String ARCH_ARM = "arm"; // non-changing values String os; String arch; int osBitness; int jvmBitness; String lang = "java"; String vmName; String vmVersion; String mrlVersion; boolean isVirtual = false; /** * Static identifier to identify the "instance" of myrobotlab - similar to * network ip of a device and used in a similar way */ String id; String branch; String pid; String hostname; String commit; String build; String motd; Date startTime; static Platform localInstance; // = getLocalInstance(); /** * The one big convoluted function to get all the crazy platform specific * data. Potentially, it's done once and only once for a running instance. * Most of the data should be immutable, although the "id" * * All data should be accessed through public functions on the local instance. * If the local instance is desired. If its from a serialized instance, the * "getters" will be retrieving appropriate info for that serialized instance. * * @return - return the local instance of the current platform */ public static Platform getLocalInstance() { if (localInstance == null) { log.info("initializing Platform"); Platform platform = new Platform(); platform.startTime = new Date(); // === OS === platform.os = System.getProperty("os.name").toLowerCase(); if (platform.os.indexOf("win") >= 0) { platform.os = OS_WINDOWS; } else if (platform.os.indexOf("mac") >= 0) { platform.os = OS_MAC; } else if (platform.os.indexOf("linux") >= 0) { platform.os = OS_LINUX; } platform.vmName = System.getProperty("java.vm.name"); platform.vmVersion = System.getProperty("java.specification.version"); // === ARCH === String arch = System.getProperty("os.arch").toLowerCase(); if ("i386".equals(arch) || "i486".equals(arch) || "i586".equals(arch) || "i686".equals(arch) || "amd64".equals(arch) || arch.startsWith("x86")) { platform.arch = "x86"; // don't care at the moment } if ("arm".equals(arch)) { // FIXME - procparser is unsafe and borked !! // Integer armv = ProcParser.getArmInstructionVersion(); // Current work around: trigger off the os.version to choose // arm6 or arm7 // assume ras pi 1 . Integer armv = 6; // if the os version has "v7" in it, it's a pi 2 // TODO: this is still pretty hacky.. String osVersion = System.getProperty("os.version").toLowerCase(); if (osVersion.contains("v7")) { armv = 7; } // TODO: revisit how we determine the architecture version platform.arch = "armv" + armv + ".hfp"; } // for Ordroid 64 ! if ("aarch64".equals(arch)) { platform.arch = "armv8"; } if (platform.arch == null) { platform.arch = arch; } // === BITNESS === if (platform.isWindows()) { // https://blogs.msdn.microsoft.com/david.wang/2006/03/27/howto-detect-process-bitness/ // this will attempt to guess the bitness of the underlying OS, Java // tries very hard to hide this from running programs String procArch = System.getenv("PROCESSOR_ARCHITECTURE"); String procArchWow64 = System.getenv("PROCESSOR_ARCHITEW6432"); platform.osBitness = (procArch != null && procArch.endsWith("64") || procArchWow64 != null && procArchWow64.endsWith("64")) ? 64 : 32; switch (arch) { case "x86": case "i386": case "i486": case "i586": case "i686": platform.jvmBitness = 32; break; case "x86_64": case "amd64": platform.jvmBitness = 64; break; default: platform.jvmBitness = 0; // ooops, I guess break; } } else { // this is actually a really bad way of doing jvm bitness (may return // "64","32" or "unknown") - and is sometimes simply not there at all // keeping this as a fallback for all Linux and Mac machines, // I don't know enough to implement a more robust detection for them // (and this was here before me, so it has to be good) String model = System.getProperty("sun.arch.data.model"); platform.jvmBitness = "64".equals(model) ? 64 : 32; } // === MRL === if (platform.mrlVersion == null) { SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd"); platform.mrlVersion = format.format(new Date()); } // manifest Map<String, String> manifest = getManifest(); if (manifest.containsKey("GitBranch")) { platform.branch = manifest.get("GitBranch"); } else { platform.branch = "unknownBranch"; } if (manifest.containsKey("Commit")) { platform.commit = manifest.get("Commit"); } else { platform.commit = "unknownCommit"; } if (manifest.containsKey("Implementation-Version")) { platform.mrlVersion = manifest.get("Implementation-Version"); } else { platform.mrlVersion = "unknownVersion"; } // motd platform.motd = "resistance is futile, we have cookies and robots ..."; // hostname try { platform.hostname = InetAddress.getLocalHost().getHostName(); if (platform.hostname != null) { platform.hostname = platform.hostname.toLowerCase(); } } catch (Exception e) { platform.hostname = "localhost"; } SimpleDateFormat TSFormatter = new SimpleDateFormat("yyyyMMddHHmmssSSS"); platform.pid = TSFormatter.format(platform.startTime); try { // something like '<pid>@<hostname>', at least in SUN / Oracle JVMs // but non standard across jvms & hosts // here we will attempt to standardize it - when asked for pid you // "only" // get pid ... if possible String jvmName = ManagementFactory.getRuntimeMXBean().getName(); int index = jvmName.indexOf('@'); if (index > 1) { platform.pid = Long.toString(Long.parseLong(jvmName.substring(0, index))); } else { platform.pid = jvmName; } } catch (Exception e) { } localInstance = platform; } return localInstance; } public Platform() { } public String getPid() { return pid; } public String getMotd() { return motd; } public String getBranch() { return branch; } public String getBuild() { return build; } public String getCommit() { return commit; } public String getArch() { return arch; } public int getOsBitness() { return osBitness; } public int getJvmBitness() { return jvmBitness; } public String getOS() { return os; } public String getPlatformId() { return String.format("%s.%s.%s", getArch(), getJvmBitness(), getOS()); } public String getVersion() { return mrlVersion; } public String getVMName() { return vmName; } public boolean isArm() { return getArch().startsWith(ARCH_ARM); } public boolean isDalvik() { return VM_DALVIK.equals(vmName); } public boolean isLinux() { return OS_LINUX.equals(os); } public boolean isMac() { return OS_MAC.equals(os); } public boolean isWindows() { return OS_WINDOWS.equals(os); } public boolean isX86() { return getArch().equals(ARCH_X86); } static public Map<String, String> getManifest() { Map<String, String> ret = new TreeMap<String, String>(); try { log.info("getManifest"); String source = Platform.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath(); InputStream in = null; log.info("source {}", source); if (source.endsWith("jar")) { // runtime // DO NOT DO IT THIS WAY -> Platform.class.getResource("/META-INF/MANIFEST.MF").openStream(); // IT DOES NOT WORK WITH OpenJDK !!! ZipFile zf = new ZipFile(source); in = zf.getInputStream(zf.getEntry("META-INF/MANIFEST.MF")); // zf.close(); explodes on closing :( } else { // IDE - version ... in = Platform.class.getResource("/MANIFEST.MF").openStream(); } String manifest = FileIO.toString(in); log.info("loading manifest {}", manifest); Properties p = new Properties(); p.load(in); log.info("properties {}", p); for (final String name : p.stringPropertyNames()) { ret.put(name, p.getProperty(name)); log.info(name + "=" + p.getProperty(name)); } in.close(); } catch (Exception e) { e.printStackTrace(); // log.warn("getManifest threw", e); } return ret; } /* private static Map<String, String> getAttributes(String part, Attributes attributes) { Map<String, String> data = new TreeMap<String, String>(); Iterator<Object> it = attributes.keySet().iterator(); while (it.hasNext()) { java.util.jar.Attributes.Name key = (java.util.jar.Attributes.Name) it.next(); Object value = attributes.get(key); String partKey = null; if (part == null) { partKey = key.toString(); } else { partKey = String.format("%s.%s", part, key); } // log.info( "{}: {}", value,partKey); if (value != null) { data.put(partKey, value.toString()); } } return data; } */ @Override public String toString() { return String.format("%s.%d.%s", arch, jvmBitness, os); } public String getId() { // null ids are not allowed if (id == null) { id = NameGenerator.getName(); } return id; } public String getHostname() { return hostname; } public void setId(String newId) { id = newId; } public Date getStartTime() { return startTime; } public static boolean isVirtual() { Platform p = getLocalInstance(); return p.isVirtual; } public static void setVirtual(boolean b) { Platform p = getLocalInstance(); p.isVirtual = b; } public static void main(String[] args) { try { ZipFile zf = new ZipFile("/lhome/grperry/github/mrl.develop/myrobotlab/target/test/myrobotlab-unknownBranch-unknownVersion.jar"); InputStream in = zf.getInputStream(zf.getEntry("META-INF/MANIFEST.MF")); log.info("manifest {}", FileIO.toString(in)); Platform platform = Platform.getLocalInstance(); // log.info("platform : {}", platform.toString()); // log.info("build {}", platform.getBuild()); // log.info("branch {}", platform.getBranch()); // log.info("commit {}", platform.getCommit()); // log.info("toString {}", platform.toString()); } catch (Exception e) { e.printStackTrace(); // log.info("Exception: ", e); } } public boolean getVmVersion() { // TODO Auto-generated method stub return false; } }
last adjustment - removed debugging
src/main/java/org/myrobotlab/framework/Platform.java
last adjustment - removed debugging
Java
apache-2.0
3dbd6a94aecfa8f6ccf5ef4f15147665b5ef5d5f
0
Shais14/joda-time,tingting703/mp3_maven,Guardiola31337/joda-time,CARFAX/joda-time,flightstats/joda-time,Rok-Piltaver/joda-time,mosoft521/joda-time,lousama/joda-time,Shais14/joda-time,emopers/joda-time,rbible/joda-time,hambroperks/joda-time,mosoft521/joda-time,tingting703/mp3_maven,leadVisionary/joda-time,Guardiola31337/joda-time,HossainKhademian/JodaTime,JodaOrg/joda-time,Alexey-N-Chernyshov/IU_AST_Mutation_Score,JodaOrg/joda-time,fengshao0907/joda-time,mohanaraosv/joda-time,fengshao0907/joda-time,Alexey-N-Chernyshov/IU_AST_Mutation_Score,CARFAX/joda-time,lousama/joda-time,hambroperks/joda-time,Rok-Piltaver/joda-time,mohanaraosv/joda-time,tkawachi/joda-time,flightstats/joda-time,rbible/joda-time,tkawachi/joda-time,leadVisionary/joda-time,emopers/joda-time
/* * Joda Software License, Version 1.0 * * * Copyright (c) 2001-03 Stephen Colebourne. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Joda project (http://www.joda.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The name "Joda" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Joda", * nor may "Joda" appear in their name, without prior written * permission of the Joda project. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JODA AUTHORS OR THE PROJECT * 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Joda project and was originally * created by Stephen Colebourne <[email protected]>. For more * information on the Joda project, please see <http://www.joda.org/>. */ package org.joda.time; import java.io.Serializable; /** * AbstractDuration provides the common behaviour for duration classes. * <p> * This class should generally not be used directly by API users. The * {@link ReadableDuration} interface should be used when different * kinds of durations are to be referenced. * <p> * AbstractDuration subclasses may be mutable and not thread-safe. * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public abstract class AbstractDuration implements ReadableDuration, Serializable { static final long serialVersionUID = -2110953284060001145L; private static void checkSupport(DurationField field, String name) { if (!field.isSupported()) { throw new UnsupportedOperationException ("Duration does not support field \"" + name + '"'); } } private static void checkPrecise(DurationField field, String name) { if (!field.isPrecise()) { throw new UnsupportedOperationException ("The field \"" + name + "\" is imprecise"); } } private final DurationType iType; private long iTotalMillis; // 0=unknown, 1=imprecise, 2=precise private int iTotalMillisState; private int iYears; private int iMonths; private int iWeeks; private int iDays; private int iHours; private int iMinutes; private int iSeconds; private int iMillis; /** * Copies another duration to this one. * * @throws UnsupportedOperationException if an unsupported field's value is * non-zero */ public AbstractDuration(ReadableDuration duration) { // Only call a private method setDuration(iType = duration.getDurationType(), duration); } /** * Copies another duration to this one. * * @param type use a different DurationType * @throws UnsupportedOperationException if an unsupported field's value is * non-zero */ public AbstractDuration(DurationType type, ReadableDuration duration) { // Only call a private method setDuration(iType = type, duration); } /** * Create a duration from a set of field values. * * @param type determines which set of fields this duration supports * @param years amount of years in this duration, which must be zero if * unsupported. * @param months amount of months in this duration, which must be zero if * unsupported. * @param weeks amount of weeks in this duration, which must be zero if * unsupported. * @param days amount of days in this duration, which must be zero if * unsupported. * @param hours amount of hours in this duration, which must be zero if * unsupported. * @param minutes amount of minutes in this duration, which must be zero if * unsupported. * @param seconds amount of seconds in this duration, which must be zero if * unsupported. * @param millis amount of milliseconds in this duration, which must be * zero if unsupported. * @throws UnsupportedOperationException if an unsupported field's value is * non-zero */ public AbstractDuration(DurationType type, int years, int months, int weeks, int days, int hours, int minutes, int seconds, int millis) { // Only call a private method setDuration(iType = type, years, months, weeks, days, hours, minutes, seconds, millis); } /** * Creates a duration from the given interval endpoints. * * @param type determines which set of fields this duration supports * @param startInstant interval start, in milliseconds * @param endInstant interval end, in milliseconds */ public AbstractDuration(DurationType type, long startInstant, long endInstant) { // Only call a private method setTotalMillis(iType = type, startInstant, endInstant); } /** * Creates a duration from the given interval endpoints. * * @param type determines which set of fields this duration supports * @param startInstant interval start * @param endInstant interval end */ public AbstractDuration(DurationType type, ReadableInstant startInstant, ReadableInstant endInstant) { // Only call a private method setTotalMillis(iType = type, startInstant.getMillis(), endInstant.getMillis()); } /** * Creates a duration from the given millisecond duration. If any supported * fields are imprecise, an UnsupportedOperationException is thrown. The * exception to this is when the specified duration is zero. * * @param type determines which set of fields this duration supports * @param duration the duration, in milliseconds * @throws UnsupportedOperationException if any fields are imprecise */ public AbstractDuration(DurationType type, long duration) { // Only call a private method setTotalMillis(iType = type, duration); } /** * Returns the object which defines which fields this duration supports. */ public final DurationType getDurationType() { return iType; } /** * Gets the total length of this duration in milliseconds, * failing if the duration is imprecise. * * @return the total length of the duration in milliseconds. * @throws IllegalStateException if the duration is imprecise */ public final long getTotalMillis() { int state = iTotalMillisState; if (state == 0) { state = updateTotalMillis(); } if (state != 2) { throw new IllegalStateException("Duration is imprecise"); } return iTotalMillis; } /** * Is this duration a precise length of time, or descriptive. * <p> * A precise duration could include millis, seconds, minutes or hours. * However, days, weeks, months and years can vary in length, resulting in * an imprecise duration. * <p> * An imprecise duration can be made precise by pairing it with a * date in a {@link ReadableInterval}. * * @return true if the duration is precise */ public final boolean isPrecise() { int state = iTotalMillisState; if (state == 0) { state = updateTotalMillis(); } return state == 2; } /** * Walks through the field values, determining total millis and whether * this duration is precise. * * @return new state */ private int updateTotalMillis() { final DurationType type = iType; boolean isPrecise = true; long totalMillis = 0; DurationField field; int value; if ((value = iYears) != 0) { field = type.years(); if (isPrecise &= field.isPrecise()) { totalMillis += field.getMillis(value); } } if ((value = iMonths) != 0) { field = type.months(); if (isPrecise &= field.isPrecise()) { totalMillis += field.getMillis(value); } } if ((value = iWeeks) != 0) { field = type.weeks(); if (isPrecise &= field.isPrecise()) { totalMillis += field.getMillis(value); } } if ((value = iDays) != 0) { field = type.days(); if (isPrecise &= field.isPrecise()) { totalMillis += field.getMillis(value); } } if ((value = iHours) != 0) { field = type.hours(); if (isPrecise &= field.isPrecise()) { totalMillis += field.getMillis(value); } } if ((value = iMinutes) != 0) { field = type.minutes(); if (isPrecise &= field.isPrecise()) { totalMillis += field.getMillis(value); } } if ((value = iSeconds) != 0) { field = type.seconds(); if (isPrecise &= field.isPrecise()) { totalMillis += field.getMillis(value); } } if ((value = iMillis) != 0) { field = type.millis(); if (isPrecise &= field.isPrecise()) { totalMillis += field.getMillis(value); } } if (isPrecise) { iTotalMillis = totalMillis; return iTotalMillisState = 2; } else { iTotalMillis = totalMillis; return iTotalMillisState = 1; } } //----------------------------------------------------------------------- /** * Adds this duration to the given instant, returning a new value. * <p> * To add just once, pass in a scalar of one. To subtract once, pass * in a scaler of minus one. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to add the * duration to * @param scalar the number of times to add the duration, negative to subtract * @return milliseconds value plus this duration times scalar * @throws ArithmeticException if the result of the calculation is too large */ public final long addTo(long instant, int scalar) { return addTo(instant, scalar, null); } /** * Adds this duration to the given instant, returning a new value. * <p> * To add just once, pass in a scalar of one. To subtract once, pass * in a scaler of minus one. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to add the * duration to * @param scalar the number of times to add the duration, negative to subtract * @param chrono override the duration's chronology, unless null is passed in * @return milliseconds value plus this duration times scalar * @throws ArithmeticException if the result of the calculation is too large */ public final long addTo(long instant, int scalar, Chronology chrono) { if (isPrecise()) { return instant += getTotalMillis() * scalar; } DurationType type = iType; if (chrono != null) { type = type.withChronology(chrono); } int value; if ((value = scaleValue(iYears, scalar)) != 0) { instant = type.years().add(instant, value); } if ((value = scaleValue(iMonths, scalar)) != 0) { instant = type.months().add(instant, value); } if ((value = scaleValue(iWeeks, scalar)) != 0) { instant = type.weeks().add(instant, value); } if ((value = scaleValue(iDays, scalar)) != 0) { instant = type.days().add(instant, value); } if ((value = scaleValue(iHours, scalar)) != 0) { instant = type.hours().add(instant, value); } if ((value = scaleValue(iMinutes, scalar)) != 0) { instant = type.minutes().add(instant, value); } if ((value = scaleValue(iSeconds, scalar)) != 0) { instant = type.seconds().add(instant, value); } if ((value = scaleValue(iMillis, scalar)) != 0) { instant = type.millis().add(instant, value); } return instant; } private static int scaleValue(int value, int scalar) { switch (scalar) { case -1: return -value; case 0: return 0; case 1: return value; default: return value * scalar; } } /** * Adds this duration to the given instant, returning a new Instant. * <p> * To add just once, pass in a scalar of one. To subtract once, pass * in a scaler of minus one. * * @param instant the instant to add the duration to * @param scalar the number of times to add the duration, negative to subtract * @return instant with the original value plus this duration times scalar * @throws IllegalArgumentException if the instant is null * @throws ArithmeticException if the result of the calculation is too large */ public final ReadableInstant addTo(ReadableInstant instant, int scalar) { return instant.toCopy(addTo(instant.getMillis(), scalar)); } /** * Adds this duration into the given mutable instant. * <p> * To add just once, pass in a scalar of one. To subtract once, pass * in a scaler of minus one. * * @param instant the instant to update with the added duration * @param scalar the number of times to add the duration, negative to subtract * @throws IllegalArgumentException if the instant is null * @throws ArithmeticException if the result of the calculation is too large */ public final void addInto(ReadWritableInstant instant, int scalar) { instant.setMillis(addTo(instant.getMillis(), scalar)); } //----------------------------------------------------------------------- /** * Gets the years field part of the duration. * * @return the number of years in the duration, zero if unsupported */ public final int getYears() { return iYears; } //----------------------------------------------------------------------- /** * Gets the months field part of the duration. * * @return the number of months in the duration, zero if unsupported */ public final int getMonths() { return iMonths; } //----------------------------------------------------------------------- /** * Gets the weeks field part of the duration. * * @return the number of weeks in the duration, zero if unsupported */ public final int getWeeks() { return iWeeks; } //----------------------------------------------------------------------- /** * Gets the days field part of the duration. * * @return the number of days in the duration, zero if unsupported */ public final int getDays() { return iDays; } //----------------------------------------------------------------------- /** * Gets the hours field part of the duration. * * @return the number of hours in the duration, zero if unsupported */ public final int getHours() { return iHours; } //----------------------------------------------------------------------- /** * Gets the minutes field part of the duration. * * @return the number of minutes in the duration, zero if unsupported */ public final int getMinutes() { return iMinutes; } //----------------------------------------------------------------------- /** * Gets the seconds field part of the duration. * * @return the number of seconds in the duration, zero if unsupported */ public final int getSeconds() { return iSeconds; } //----------------------------------------------------------------------- /** * Gets the millis field part of the duration. * * @return the number of millis in the duration, zero if unsupported */ public final int getMillis() { return iMillis; } //----------------------------------------------------------------------- /** * Get this object as an immutable Duration. This can be useful if you * don't trust the implementation of the interface to be well-behaved, or * to get a guaranteed immutable object. * * @return a Duration using the same field set and values */ public final Duration toDuration() { if (this instanceof Duration) { return (Duration) this; } return new Duration(this); } /** * Get this object as a MutableDuration. * * @return a MutableDuration using the same field set and values */ public final MutableDuration toMutableDuration() { return new MutableDuration(this); } //----------------------------------------------------------------------- /** * Compares this duration with the specified duration, which can only be * performed if both are precise. * * @param obj a precise duration to check against * @return negative value if this is less, 0 if equal, or positive value if greater * @throws NullPointerException if the object is null * @throws ClassCastException if the given object is not supported * @throws IllegalStateException if either duration is imprecise */ public int compareTo(Object obj) { ReadableDuration thisDuration = (ReadableDuration) this; ReadableDuration otherDuration = (ReadableDuration) obj; long thisMillis = thisDuration.getTotalMillis(); long otherMillis = otherDuration.getTotalMillis(); // cannot do (thisMillis - otherMillis) as it can overflow if (thisMillis < otherMillis) { return -1; } if (thisMillis > otherMillis) { return 1; } return 0; } /** * Is the length of this duration equal to the duration passed in. * Both durations must be precise. * * @param duration another duration to compare to * @return true if this duration is equal to than the duration passed in * @throws IllegalArgumentException if the duration is null * @throws IllegalStateException if either duration is imprecise */ public boolean isEqual(ReadableDuration duration) { if (duration == null) { throw new IllegalArgumentException("The duration must not be null"); } return compareTo(duration) == 0; } /** * Is the length of this duration longer than the duration passed in. * Both durations must be precise. * * @param duration another duration to compare to * @return true if this duration is equal to than the duration passed in * @throws IllegalArgumentException if the duration is null * @throws IllegalStateException if either duration is imprecise */ public boolean isLongerThan(ReadableDuration duration) { if (duration == null) { throw new IllegalArgumentException("The duration must not be null"); } return compareTo(duration) > 0; } /** * Is the length of this duration shorter than the duration passed in. * Both durations must be precise. * * @param duration another duration to compare to * @return true if this duration is equal to than the duration passed in * @throws IllegalArgumentException if the duration is null * @throws IllegalStateException if either duration is imprecise */ public boolean isShorterThan(ReadableDuration duration) { if (duration == null) { throw new IllegalArgumentException("The duration must not be null"); } return compareTo(duration) < 0; } //----------------------------------------------------------------------- /** * Compares this object with the specified object for equality based * on the value of each field. All ReadableDuration instances are accepted. * <p> * To compare two durations for absolute duration (ie. millisecond duration * ignoring the fields), use {@link #isEqual(ReadableDuration)} or * {@link #compareTo(Object)}. * * @param readableDuration a readable duration to check against * @return true if all the field values are equal, false if * not or the duration is null or of an incorrect type */ public boolean equals(Object readableDuration) { if (this == readableDuration) { return true; } if (readableDuration instanceof ReadableDuration == false) { return false; } ReadableDuration other = (ReadableDuration) readableDuration; DurationType type = getDurationType(); if (type.equals(other.getDurationType()) == false) { return false; } return getYears() == other.getYears() && getMonths() == other.getMonths() && getWeeks() == other.getWeeks() && getDays() == other.getDays() && getHours() == other.getHours() && getMinutes() == other.getMinutes() && getSeconds() == other.getSeconds() && getMillis() == other.getMillis(); } /** * Gets a hash code for the duration that is compatable with the * equals method. * * @return a hash code */ public int hashCode() { int hash = getDurationType().hashCode(); hash = 53 * hash + getYears(); hash = 53 * hash + getMonths(); hash = 53 * hash + getWeeks(); hash = 53 * hash + getDays(); hash = 53 * hash + getHours(); hash = 53 * hash + getMinutes(); hash = 53 * hash + getSeconds(); hash = 53 * hash + getMillis(); return hash; } //----------------------------------------------------------------------- /** * Gets the value as a String in the ISO8601 duration format. * <p> * For example, "P6H3M5S" represents 6 hours, 3 minutes, 5 seconds. * * @return the value as an ISO8601 string */ // TODO //public String toString(); /** * Sets all the fields in one go from another ReadableDuration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param duration the duration to set * @throws IllegalArgumentException if duration is null * @throws UnsupportedOperationException if an unsupported field's value is * non-zero */ protected void setDuration(ReadableDuration duration) { setDuration(iType, duration); } /** * This method is private to prevent subclasses from overriding. */ private void setDuration(DurationType type, ReadableDuration duration) { if (duration == null) { throw new IllegalArgumentException("The duration must not be null"); } setDuration(type, duration.getYears(), duration.getMonths(), duration.getWeeks(), duration.getDays(), duration.getHours(), duration.getMinutes(), duration.getSeconds(), duration.getMillis()); } /** * Sets all the fields in one go. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param years amount of years in this duration, which must be zero if * unsupported. * @param months amount of months in this duration, which must be zero if * unsupported. * @param weeks amount of weeks in this duration, which must be zero if * unsupported. * @param days amount of days in this duration, which must be zero if * unsupported. * @param hours amount of hours in this duration, which must be zero if * unsupported. * @param minutes amount of minutes in this duration, which must be zero if * unsupported. * @param seconds amount of seconds in this duration, which must be zero if * unsupported. * @param millis amount of milliseconds in this duration, which must be * zero if unsupported. * @throws UnsupportedOperationException if an unsupported field's value is * non-zero */ protected void setDuration(int years, int months, int weeks, int days, int hours, int minutes, int seconds, int millis) { setDuration(iType, years, months, weeks, days, hours, minutes, seconds, millis); } /** * This method is private to prevent subclasses from overriding. */ private void setDuration(DurationType type, int years, int months, int weeks, int days, int hours, int minutes, int seconds, int millis) { if (years != 0) { checkSupport(type.years(), "years"); } if (months != 0) { checkSupport(type.months(), "months"); } if (weeks != 0) { checkSupport(type.weeks(), "weeks"); } if (days != 0) { checkSupport(type.days(), "days"); } if (hours != 0) { checkSupport(type.hours(), "hours"); } if (minutes != 0) { checkSupport(type.minutes(), "minutes"); } if (seconds != 0) { checkSupport(type.seconds(), "seconds"); } if (millis != 0) { checkSupport(type.millis(), "millis"); } iYears = years; iMonths = months; iWeeks = weeks; iDays = days; iHours = hours; iMinutes = minutes; iSeconds = seconds; iMillis = millis; iTotalMillisState = 0; } /** * Sets all the fields in one go from a millisecond interval. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param startInstant interval start, in milliseconds * @param endInstant interval end, in milliseconds */ protected void setTotalMillis(long startInstant, long endInstant) { setTotalMillis(iType, startInstant, endInstant); } /** * This method is private to prevent subclasses from overriding. * * @param startInstant interval start, in milliseconds * @param endInstant interval end, in milliseconds */ private void setTotalMillis(DurationType type, long startInstant, long endInstant) { iTotalMillis = endInstant - startInstant; boolean isPrecise = true; DurationField field; if (!(field = type.years()).isSupported()) { iYears = 0; } else if ((iYears = field.getDifference(endInstant, startInstant)) != 0) { isPrecise &= field.isPrecise(); startInstant = field.add(startInstant, iYears); } if (!(field = type.months()).isSupported()) { iMonths = 0; } else if ((iMonths = field.getDifference(endInstant, startInstant)) != 0) { isPrecise &= field.isPrecise(); startInstant = field.add(startInstant, iMonths); } if (!(field = type.weeks()).isSupported()) { iWeeks = 0; } else if ((iWeeks = field.getDifference(endInstant, startInstant)) != 0) { isPrecise &= field.isPrecise(); startInstant = field.add(startInstant, iWeeks); } if (!(field = type.days()).isSupported()) { iDays = 0; } else if ((iDays = field.getDifference(endInstant, startInstant)) != 0) { isPrecise &= field.isPrecise(); startInstant = field.add(startInstant, iDays); } if (!(field = type.hours()).isSupported()) { iHours = 0; } else if ((iHours = field.getDifference(endInstant, startInstant)) != 0) { isPrecise &= field.isPrecise(); startInstant = field.add(startInstant, iHours); } if (!(field = type.minutes()).isSupported()) { iMinutes = 0; } else if ((iMinutes = field.getDifference(endInstant, startInstant)) != 0) { isPrecise &= field.isPrecise(); startInstant = field.add(startInstant, iMinutes); } if (!(field = type.seconds()).isSupported()) { iSeconds = 0; } else if ((iSeconds = field.getDifference(endInstant, startInstant)) != 0) { isPrecise &= field.isPrecise(); startInstant = field.add(startInstant, iSeconds); } if (!(field = type.millis()).isSupported()) { iMillis = 0; } else if ((iMillis = field.getDifference(endInstant, startInstant)) != 0) { isPrecise &= field.isPrecise(); startInstant = field.add(startInstant, iMillis); } iTotalMillisState = isPrecise ? 2 : 1; } /** * Sets all the fields in one go from a millisecond duration. If any * supported fields are imprecise, an UnsupportedOperationException is * thrown. The exception to this is when the specified duration is zero. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param duration the duration, in milliseconds * @throws UnsupportedOperationException if any fields are imprecise */ protected void setTotalMillis(long duration) { setTotalMillis(iType, duration); } /** * This method is private to prevent subclasses from overriding. * * @param duration the duration, in milliseconds * @throws UnsupportedOperationException if any fields are imprecise */ private void setTotalMillis(DurationType type, final long duration) { if (duration == 0) { iTotalMillis = duration; iTotalMillisState = 2; iYears = 0; iMonths = 0; iWeeks = 0; iDays = 0; iHours = 0; iMinutes = 0; iSeconds = 0; iMillis = 0; return; } long startInstant = 0; int years, months, weeks, days, hours, minutes, seconds, millis; DurationField field; if (!(field = type.years()).isSupported()) { years = 0; } else { checkPrecise(field, "years"); years = field.getDifference(duration, startInstant); startInstant = field.add(startInstant, years); } if (!(field = type.months()).isSupported()) { months = 0; } else { checkPrecise(field, "months"); months = field.getDifference(duration, startInstant); startInstant = field.add(startInstant, months); } if (!(field = type.weeks()).isSupported()) { weeks = 0; } else { checkPrecise(field, "weeks"); weeks = field.getDifference(duration, startInstant); startInstant = field.add(startInstant, weeks); } if (!(field = type.days()).isSupported()) { days = 0; } else { checkPrecise(field, "days"); days = field.getDifference(duration, startInstant); startInstant = field.add(startInstant, days); } if (!(field = type.hours()).isSupported()) { hours = 0; } else { checkPrecise(field, "hours"); hours = field.getDifference(duration, startInstant); startInstant = field.add(startInstant, hours); } if (!(field = type.minutes()).isSupported()) { minutes = 0; } else { checkPrecise(field, "minutes"); minutes = field.getDifference(duration, startInstant); startInstant = field.add(startInstant, minutes); } if (!(field = type.seconds()).isSupported()) { seconds = 0; } else { checkPrecise(field, "seconds"); seconds = field.getDifference(duration, startInstant); startInstant = field.add(startInstant, seconds); } if (!(field = type.millis()).isSupported()) { millis = 0; } else { checkPrecise(field, "millis"); millis = field.getDifference(duration, startInstant); startInstant = field.add(startInstant, millis); } iTotalMillis = duration; iTotalMillisState = 2; iYears = years; iMonths = months; iWeeks = weeks; iDays = days; iHours = hours; iMinutes = minutes; iSeconds = seconds; iMillis = millis; } //----------------------------------------------------------------------- /** * Adds a millisecond duration to this one. As a side-effect, all field * values are normalized. * * @param duration the duration, in milliseconds * @throws IllegalStateException if the duration is imprecise */ protected void add(long duration) { setTotalMillis(getTotalMillis() + duration); } /** * Adds a duration to this one. * * @param duration the duration to add * @throws IllegalArgumentException if the duration is null * @throws IllegalStateException if the duration is imprecise */ protected void add(ReadableDuration duration) { if (duration == null) { throw new IllegalArgumentException("The duration must not be null"); } add(duration.getTotalMillis()); } /** * Normalizes all the field values in this duration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @throws IllegalStateException if this duration is imprecise */ protected void normalize() { setTotalMillis(getTotalMillis()); } //----------------------------------------------------------------------- /** * Sets the number of years of the duration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param years the number of years * @throws UnsupportedOperationException if field is not supported. */ protected void setYears(int years) { if (years != iYears) { if (years != 0) { checkSupport(iType.years(), "years"); } iYears = years; iTotalMillisState = 0; } } /** * Adds the specified years to the number of years in the duration. * * @param years the number of years * @throws UnsupportedOperationException if field is not supported. */ protected void addYears(int years) { setYears(getYears() + years); } //----------------------------------------------------------------------- /** * Sets the number of months of the duration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param months the number of months * @throws UnsupportedOperationException if field is not supported. */ protected void setMonths(int months) { if (months != iMonths) { if (months != 0) { checkSupport(iType.months(), "months"); } iMonths = months; iTotalMillisState = 0; } } /** * Adds the specified months to the number of months in the duration. * * @param months the number of months * @throws UnsupportedOperationException if field is not supported. */ protected void addMonths(int months) { setMonths(getMonths() + months); } //----------------------------------------------------------------------- /** * Sets the number of weeks of the duration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param weeks the number of weeks * @throws UnsupportedOperationException if field is not supported. */ protected void setWeeks(int weeks) { if (weeks != iWeeks) { if (weeks != 0) { checkSupport(iType.weeks(), "weeks"); } iWeeks = weeks; iTotalMillisState = 0; } } /** * Adds the specified weeks to the number of weeks in the duration. * * @param weeks the number of weeks * @throws UnsupportedOperationException if field is not supported. */ protected void addWeeks(int weeks) { setWeeks(getWeeks() + weeks); } //----------------------------------------------------------------------- /** * Sets the number of days of the duration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param days the number of days * @throws UnsupportedOperationException if field is not supported. */ protected void setDays(int days) { if (days != iDays) { if (days != 0) { checkSupport(iType.days(), "days"); } iDays = days; iTotalMillisState = 0; } } /** * Adds the specified days to the number of days in the duration. * * @param days the number of days * @throws UnsupportedOperationException if field is not supported. */ protected void addDays(int days) { setDays(getDays() + days); } //----------------------------------------------------------------------- /** * Sets the number of hours of the duration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param hours the number of hours * @throws UnsupportedOperationException if field is not supported. */ protected void setHours(int hours) { if (hours != iHours) { if (hours != 0) { checkSupport(iType.hours(), "hours"); } iHours = hours; iTotalMillisState = 0; } } /** * Adds the specified hours to the number of hours in the duration. * * @param hours the number of hours * @throws UnsupportedOperationException if field is not supported. */ protected void addHours(int hours) { setHours(getHours() + hours); } //----------------------------------------------------------------------- /** * Sets the number of minutes of the duration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param minutes the number of minutes * @throws UnsupportedOperationException if field is not supported. */ protected void setMinutes(int minutes) { if (minutes != iMinutes) { if (minutes != 0) { checkSupport(iType.minutes(), "minutes"); } iMinutes = minutes; iTotalMillisState = 0; } } /** * Adds the specified minutes to the number of minutes in the duration. * * @param minutes the number of minutes * @throws UnsupportedOperationException if field is not supported. */ protected void addMinutes(int minutes) { setMinutes(getMinutes() + minutes); } //----------------------------------------------------------------------- /** * Sets the number of seconds of the duration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param seconds the number of seconds * @throws UnsupportedOperationException if field is not supported. */ protected void setSeconds(int seconds) { if (seconds != iSeconds) { if (seconds != 0) { checkSupport(iType.seconds(), "seconds"); } iSeconds = seconds; iTotalMillisState = 0; } } /** * Adds the specified seconds to the number of seconds in the duration. * * @param seconds the number of seconds * @throws UnsupportedOperationException if field is not supported. */ protected void addSeconds(int seconds) { setSeconds(getSeconds() + seconds); } //----------------------------------------------------------------------- /** * Sets the number of millis of the duration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param millis the number of millis * @throws UnsupportedOperationException if field is not supported. */ protected void setMillis(int millis) { if (millis != iMillis) { if (millis != 0) { checkSupport(iType.millis(), "millis"); } iMillis = millis; iTotalMillisState = 0; } } /** * Adds the specified millis to the number of millis in the duration. * * @param millis the number of millis * @throws UnsupportedOperationException if field is not supported. */ protected void addMillis(int millis) { setMillis(getMillis() + millis); } }
JodaTime/src/java/org/joda/time/AbstractDuration.java
/* * Joda Software License, Version 1.0 * * * Copyright (c) 2001-03 Stephen Colebourne. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Joda project (http://www.joda.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The name "Joda" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Joda", * nor may "Joda" appear in their name, without prior written * permission of the Joda project. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JODA AUTHORS OR THE PROJECT * 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Joda project and was originally * created by Stephen Colebourne <[email protected]>. For more * information on the Joda project, please see <http://www.joda.org/>. */ package org.joda.time; import java.io.Serializable; /** * AbstractDuration provides the common behaviour for duration classes. * <p> * This class should generally not be used directly by API users. The * {@link ReadableDuration} interface should be used when different * kinds of durations are to be referenced. * <p> * AbstractDuration subclasses may be mutable and not thread-safe. * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public abstract class AbstractDuration implements ReadableDuration, Serializable { static final long serialVersionUID = -2110953284060001145L; private static void checkSupport(DurationField field, String name) { if (!field.isSupported()) { throw new UnsupportedOperationException ("Duration does not support field \"" + name + "\". Supplied value must be zero."); } } private static void checkPrecise(DurationField field, String name) { if (!field.isPrecise()) { throw new UnsupportedOperationException ("The field \"" + name + "\" is imprecise"); } } private final DurationType iType; private long iTotalMillis; // 0=unknown, 1=imprecise, 2=precise private int iTotalMillisState; private int iYears; private int iMonths; private int iWeeks; private int iDays; private int iHours; private int iMinutes; private int iSeconds; private int iMillis; /** * Copies another duration to this one. * * @throws UnsupportedOperationException if an unsupported field's value is * non-zero */ public AbstractDuration(ReadableDuration duration) { // Only call a private method setDuration(iType = duration.getDurationType(), duration); } /** * Copies another duration to this one. * * @param type use a different DurationType * @throws UnsupportedOperationException if an unsupported field's value is * non-zero */ public AbstractDuration(DurationType type, ReadableDuration duration) { // Only call a private method setDuration(iType = type, duration); } /** * Create a duration from a set of field values. * * @param type determines which set of fields this duration supports * @param years amount of years in this duration, which must be zero if * unsupported. * @param months amount of months in this duration, which must be zero if * unsupported. * @param weeks amount of weeks in this duration, which must be zero if * unsupported. * @param days amount of days in this duration, which must be zero if * unsupported. * @param hours amount of hours in this duration, which must be zero if * unsupported. * @param minutes amount of minutes in this duration, which must be zero if * unsupported. * @param seconds amount of seconds in this duration, which must be zero if * unsupported. * @param millis amount of milliseconds in this duration, which must be * zero if unsupported. * @throws UnsupportedOperationException if an unsupported field's value is * non-zero */ public AbstractDuration(DurationType type, int years, int months, int weeks, int days, int hours, int minutes, int seconds, int millis) { // Only call a private method setDuration(iType = type, years, months, weeks, days, hours, minutes, seconds, millis); } /** * Creates a duration from the given interval endpoints. * * @param type determines which set of fields this duration supports * @param startInstant interval start, in milliseconds * @param endInstant interval end, in milliseconds */ public AbstractDuration(DurationType type, long startInstant, long endInstant) { // Only call a private method setTotalMillis(iType = type, startInstant, endInstant); } /** * Creates a duration from the given interval endpoints. * * @param type determines which set of fields this duration supports * @param startInstant interval start * @param endInstant interval end */ public AbstractDuration(DurationType type, ReadableInstant startInstant, ReadableInstant endInstant) { // Only call a private method setTotalMillis(iType = type, startInstant.getMillis(), endInstant.getMillis()); } /** * Creates a duration from the given millisecond duration. If any supported * fields are imprecise, an UnsupportedOperationException is thrown. The * exception to this is when the specified duration is zero. * * @param type determines which set of fields this duration supports * @param duration the duration, in milliseconds * @throws UnsupportedOperationException if any fields are imprecise */ public AbstractDuration(DurationType type, long duration) { // Only call a private method setTotalMillis(iType = type, duration); } /** * Returns the object which defines which fields this duration supports. */ public final DurationType getDurationType() { return iType; } /** * Gets the total length of this duration in milliseconds, * failing if the duration is imprecise. * * @return the total length of the duration in milliseconds. * @throws IllegalStateException if the duration is imprecise */ public final long getTotalMillis() { int state = iTotalMillisState; if (state == 0) { state = updateTotalMillis(); } if (state != 2) { throw new IllegalStateException("Duration is imprecise"); } return iTotalMillis; } /** * Is this duration a precise length of time, or descriptive. * <p> * A precise duration could include millis, seconds, minutes or hours. * However, days, weeks, months and years can vary in length, resulting in * an imprecise duration. * <p> * An imprecise duration can be made precise by pairing it with a * date in a {@link ReadableInterval}. * * @return true if the duration is precise */ public final boolean isPrecise() { int state = iTotalMillisState; if (state == 0) { state = updateTotalMillis(); } return state == 2; } /** * Walks through the field values, determining total millis and whether * this duration is precise. * * @return new state */ private int updateTotalMillis() { final DurationType type = iType; boolean isPrecise = true; long totalMillis = 0; DurationField field; int value; if ((value = iYears) != 0) { field = type.years(); if (isPrecise &= field.isPrecise()) { totalMillis += field.getMillis(value); } } if ((value = iMonths) != 0) { field = type.months(); if (isPrecise &= field.isPrecise()) { totalMillis += field.getMillis(value); } } if ((value = iWeeks) != 0) { field = type.weeks(); if (isPrecise &= field.isPrecise()) { totalMillis += field.getMillis(value); } } if ((value = iDays) != 0) { field = type.days(); if (isPrecise &= field.isPrecise()) { totalMillis += field.getMillis(value); } } if ((value = iHours) != 0) { field = type.hours(); if (isPrecise &= field.isPrecise()) { totalMillis += field.getMillis(value); } } if ((value = iMinutes) != 0) { field = type.minutes(); if (isPrecise &= field.isPrecise()) { totalMillis += field.getMillis(value); } } if ((value = iSeconds) != 0) { field = type.seconds(); if (isPrecise &= field.isPrecise()) { totalMillis += field.getMillis(value); } } if ((value = iMillis) != 0) { field = type.millis(); if (isPrecise &= field.isPrecise()) { totalMillis += field.getMillis(value); } } if (isPrecise) { iTotalMillis = totalMillis; return iTotalMillisState = 2; } else { iTotalMillis = totalMillis; return iTotalMillisState = 1; } } //----------------------------------------------------------------------- /** * Adds this duration to the given instant, returning a new value. * <p> * To add just once, pass in a scalar of one. To subtract once, pass * in a scaler of minus one. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to add the * duration to * @param scalar the number of times to add the duration, negative to subtract * @return milliseconds value plus this duration times scalar * @throws ArithmeticException if the result of the calculation is too large */ public final long addTo(long instant, int scalar) { return addTo(instant, scalar, null); } /** * Adds this duration to the given instant, returning a new value. * <p> * To add just once, pass in a scalar of one. To subtract once, pass * in a scaler of minus one. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to add the * duration to * @param scalar the number of times to add the duration, negative to subtract * @param chrono override the duration's chronology, unless null is passed in * @return milliseconds value plus this duration times scalar * @throws ArithmeticException if the result of the calculation is too large */ public final long addTo(long instant, int scalar, Chronology chrono) { if (isPrecise()) { return instant += getTotalMillis() * scalar; } DurationType type = iType; if (chrono != null) { type = type.withChronology(chrono); } int value; if ((value = scaleValue(iYears, scalar)) != 0) { instant = type.years().add(instant, value); } if ((value = scaleValue(iMonths, scalar)) != 0) { instant = type.months().add(instant, value); } if ((value = scaleValue(iWeeks, scalar)) != 0) { instant = type.weeks().add(instant, value); } if ((value = scaleValue(iDays, scalar)) != 0) { instant = type.days().add(instant, value); } if ((value = scaleValue(iHours, scalar)) != 0) { instant = type.hours().add(instant, value); } if ((value = scaleValue(iMinutes, scalar)) != 0) { instant = type.minutes().add(instant, value); } if ((value = scaleValue(iSeconds, scalar)) != 0) { instant = type.seconds().add(instant, value); } if ((value = scaleValue(iMillis, scalar)) != 0) { instant = type.millis().add(instant, value); } return instant; } private static int scaleValue(int value, int scalar) { switch (scalar) { case -1: return -value; case 0: return 0; case 1: return value; default: return value * scalar; } } /** * Adds this duration to the given instant, returning a new Instant. * <p> * To add just once, pass in a scalar of one. To subtract once, pass * in a scaler of minus one. * * @param instant the instant to add the duration to * @param scalar the number of times to add the duration, negative to subtract * @return instant with the original value plus this duration times scalar * @throws IllegalArgumentException if the instant is null * @throws ArithmeticException if the result of the calculation is too large */ public final ReadableInstant addTo(ReadableInstant instant, int scalar) { return instant.toCopy(addTo(instant.getMillis(), scalar)); } /** * Adds this duration into the given mutable instant. * <p> * To add just once, pass in a scalar of one. To subtract once, pass * in a scaler of minus one. * * @param instant the instant to update with the added duration * @param scalar the number of times to add the duration, negative to subtract * @throws IllegalArgumentException if the instant is null * @throws ArithmeticException if the result of the calculation is too large */ public final void addInto(ReadWritableInstant instant, int scalar) { instant.setMillis(addTo(instant.getMillis(), scalar)); } //----------------------------------------------------------------------- /** * Gets the years field part of the duration. * * @return the number of years in the duration, zero if unsupported */ public final int getYears() { return iYears; } //----------------------------------------------------------------------- /** * Gets the months field part of the duration. * * @return the number of months in the duration, zero if unsupported */ public final int getMonths() { return iMonths; } //----------------------------------------------------------------------- /** * Gets the weeks field part of the duration. * * @return the number of weeks in the duration, zero if unsupported */ public final int getWeeks() { return iWeeks; } //----------------------------------------------------------------------- /** * Gets the days field part of the duration. * * @return the number of days in the duration, zero if unsupported */ public final int getDays() { return iDays; } //----------------------------------------------------------------------- /** * Gets the hours field part of the duration. * * @return the number of hours in the duration, zero if unsupported */ public final int getHours() { return iHours; } //----------------------------------------------------------------------- /** * Gets the minutes field part of the duration. * * @return the number of minutes in the duration, zero if unsupported */ public final int getMinutes() { return iMinutes; } //----------------------------------------------------------------------- /** * Gets the seconds field part of the duration. * * @return the number of seconds in the duration, zero if unsupported */ public final int getSeconds() { return iSeconds; } //----------------------------------------------------------------------- /** * Gets the millis field part of the duration. * * @return the number of millis in the duration, zero if unsupported */ public final int getMillis() { return iMillis; } //----------------------------------------------------------------------- /** * Get this object as an immutable Duration. This can be useful if you * don't trust the implementation of the interface to be well-behaved, or * to get a guaranteed immutable object. * * @return a Duration using the same field set and values */ public final Duration toDuration() { if (this instanceof Duration) { return (Duration) this; } return new Duration(this); } /** * Get this object as a MutableDuration. * * @return a MutableDuration using the same field set and values */ public final MutableDuration toMutableDuration() { return new MutableDuration(this); } //----------------------------------------------------------------------- /** * Compares this duration with the specified duration, which can only be * performed if both are precise. * * @param obj a precise duration to check against * @return negative value if this is less, 0 if equal, or positive value if greater * @throws NullPointerException if the object is null * @throws ClassCastException if the given object is not supported * @throws IllegalStateException if either duration is imprecise */ public int compareTo(Object obj) { ReadableDuration thisDuration = (ReadableDuration) this; ReadableDuration otherDuration = (ReadableDuration) obj; long thisMillis = thisDuration.getTotalMillis(); long otherMillis = otherDuration.getTotalMillis(); // cannot do (thisMillis - otherMillis) as it can overflow if (thisMillis < otherMillis) { return -1; } if (thisMillis > otherMillis) { return 1; } return 0; } /** * Is the length of this duration equal to the duration passed in. * Both durations must be precise. * * @param duration another duration to compare to * @return true if this duration is equal to than the duration passed in * @throws IllegalArgumentException if the duration is null * @throws IllegalStateException if either duration is imprecise */ public boolean isEqual(ReadableDuration duration) { if (duration == null) { throw new IllegalArgumentException("The duration must not be null"); } return compareTo(duration) == 0; } /** * Is the length of this duration longer than the duration passed in. * Both durations must be precise. * * @param duration another duration to compare to * @return true if this duration is equal to than the duration passed in * @throws IllegalArgumentException if the duration is null * @throws IllegalStateException if either duration is imprecise */ public boolean isLongerThan(ReadableDuration duration) { if (duration == null) { throw new IllegalArgumentException("The duration must not be null"); } return compareTo(duration) > 0; } /** * Is the length of this duration shorter than the duration passed in. * Both durations must be precise. * * @param duration another duration to compare to * @return true if this duration is equal to than the duration passed in * @throws IllegalArgumentException if the duration is null * @throws IllegalStateException if either duration is imprecise */ public boolean isShorterThan(ReadableDuration duration) { if (duration == null) { throw new IllegalArgumentException("The duration must not be null"); } return compareTo(duration) < 0; } //----------------------------------------------------------------------- /** * Compares this object with the specified object for equality based * on the value of each field. All ReadableDuration instances are accepted. * <p> * To compare two durations for absolute duration (ie. millisecond duration * ignoring the fields), use {@link #isEqual(ReadableDuration)} or * {@link #compareTo(Object)}. * * @param readableDuration a readable duration to check against * @return true if all the field values are equal, false if * not or the duration is null or of an incorrect type */ public boolean equals(Object readableDuration) { if (this == readableDuration) { return true; } if (readableDuration instanceof ReadableDuration == false) { return false; } ReadableDuration other = (ReadableDuration) readableDuration; DurationType type = getDurationType(); if (type.equals(other.getDurationType()) == false) { return false; } return getYears() == other.getYears() && getMonths() == other.getMonths() && getWeeks() == other.getWeeks() && getDays() == other.getDays() && getHours() == other.getHours() && getMinutes() == other.getMinutes() && getSeconds() == other.getSeconds() && getMillis() == other.getMillis(); } /** * Gets a hash code for the duration that is compatable with the * equals method. * * @return a hash code */ public int hashCode() { int hash = getDurationType().hashCode(); hash = 53 * hash + getYears(); hash = 53 * hash + getMonths(); hash = 53 * hash + getWeeks(); hash = 53 * hash + getDays(); hash = 53 * hash + getHours(); hash = 53 * hash + getMinutes(); hash = 53 * hash + getSeconds(); hash = 53 * hash + getMillis(); return hash; } //----------------------------------------------------------------------- /** * Gets the value as a String in the ISO8601 duration format. * <p> * For example, "P6H3M5S" represents 6 hours, 3 minutes, 5 seconds. * * @return the value as an ISO8601 string */ // TODO //public String toString(); /** * Sets all the fields in one go from another ReadableDuration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param duration the duration to set * @throws IllegalArgumentException if duration is null * @throws UnsupportedOperationException if an unsupported field's value is * non-zero */ protected void setDuration(ReadableDuration duration) { setDuration(iType, duration); } /** * This method is private to prevent subclasses from overriding. */ private void setDuration(DurationType type, ReadableDuration duration) { if (duration == null) { throw new IllegalArgumentException("The duration must not be null"); } setDuration(type, duration.getYears(), duration.getMonths(), duration.getWeeks(), duration.getDays(), duration.getHours(), duration.getMinutes(), duration.getSeconds(), duration.getMillis()); } /** * Sets all the fields in one go. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param years amount of years in this duration, which must be zero if * unsupported. * @param months amount of months in this duration, which must be zero if * unsupported. * @param weeks amount of weeks in this duration, which must be zero if * unsupported. * @param days amount of days in this duration, which must be zero if * unsupported. * @param hours amount of hours in this duration, which must be zero if * unsupported. * @param minutes amount of minutes in this duration, which must be zero if * unsupported. * @param seconds amount of seconds in this duration, which must be zero if * unsupported. * @param millis amount of milliseconds in this duration, which must be * zero if unsupported. * @throws UnsupportedOperationException if an unsupported field's value is * non-zero */ protected void setDuration(int years, int months, int weeks, int days, int hours, int minutes, int seconds, int millis) { setDuration(iType, years, months, weeks, days, hours, minutes, seconds, millis); } /** * This method is private to prevent subclasses from overriding. */ private void setDuration(DurationType type, int years, int months, int weeks, int days, int hours, int minutes, int seconds, int millis) { if (years != 0) { checkSupport(type.years(), "years"); } if (months != 0) { checkSupport(type.months(), "months"); } if (weeks != 0) { checkSupport(type.weeks(), "weeks"); } if (days != 0) { checkSupport(type.days(), "days"); } if (hours != 0) { checkSupport(type.hours(), "hours"); } if (minutes != 0) { checkSupport(type.minutes(), "minutes"); } if (seconds != 0) { checkSupport(type.seconds(), "seconds"); } if (millis != 0) { checkSupport(type.millis(), "millis"); } iYears = years; iMonths = months; iWeeks = weeks; iDays = days; iHours = hours; iMinutes = minutes; iSeconds = seconds; iMillis = millis; iTotalMillisState = 0; } /** * Sets all the fields in one go from a millisecond interval. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param startInstant interval start, in milliseconds * @param endInstant interval end, in milliseconds */ protected void setTotalMillis(long startInstant, long endInstant) { setTotalMillis(iType, startInstant, endInstant); } /** * This method is private to prevent subclasses from overriding. * * @param startInstant interval start, in milliseconds * @param endInstant interval end, in milliseconds */ private void setTotalMillis(DurationType type, long startInstant, long endInstant) { iTotalMillis = endInstant - startInstant; boolean isPrecise = true; DurationField field; if (!(field = type.years()).isSupported()) { iYears = 0; } else if ((iYears = field.getDifference(endInstant, startInstant)) != 0) { isPrecise &= field.isPrecise(); startInstant = field.add(startInstant, iYears); } if (!(field = type.months()).isSupported()) { iMonths = 0; } else if ((iMonths = field.getDifference(endInstant, startInstant)) != 0) { isPrecise &= field.isPrecise(); startInstant = field.add(startInstant, iMonths); } if (!(field = type.weeks()).isSupported()) { iWeeks = 0; } else if ((iWeeks = field.getDifference(endInstant, startInstant)) != 0) { isPrecise &= field.isPrecise(); startInstant = field.add(startInstant, iWeeks); } if (!(field = type.days()).isSupported()) { iDays = 0; } else if ((iDays = field.getDifference(endInstant, startInstant)) != 0) { isPrecise &= field.isPrecise(); startInstant = field.add(startInstant, iDays); } if (!(field = type.hours()).isSupported()) { iHours = 0; } else if ((iHours = field.getDifference(endInstant, startInstant)) != 0) { isPrecise &= field.isPrecise(); startInstant = field.add(startInstant, iHours); } if (!(field = type.minutes()).isSupported()) { iMinutes = 0; } else if ((iMinutes = field.getDifference(endInstant, startInstant)) != 0) { isPrecise &= field.isPrecise(); startInstant = field.add(startInstant, iMinutes); } if (!(field = type.seconds()).isSupported()) { iSeconds = 0; } else if ((iSeconds = field.getDifference(endInstant, startInstant)) != 0) { isPrecise &= field.isPrecise(); startInstant = field.add(startInstant, iSeconds); } if (!(field = type.millis()).isSupported()) { iMillis = 0; } else if ((iMillis = field.getDifference(endInstant, startInstant)) != 0) { isPrecise &= field.isPrecise(); startInstant = field.add(startInstant, iMillis); } iTotalMillisState = isPrecise ? 2 : 1; } /** * Sets all the fields in one go from a millisecond duration. If any * supported fields are imprecise, an UnsupportedOperationException is * thrown. The exception to this is when the specified duration is zero. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param duration the duration, in milliseconds * @throws UnsupportedOperationException if any fields are imprecise */ protected void setTotalMillis(long duration) { setTotalMillis(iType, duration); } /** * This method is private to prevent subclasses from overriding. * * @param duration the duration, in milliseconds * @throws UnsupportedOperationException if any fields are imprecise */ private void setTotalMillis(DurationType type, final long duration) { if (duration == 0) { iTotalMillis = duration; iTotalMillisState = 2; iYears = 0; iMonths = 0; iWeeks = 0; iDays = 0; iHours = 0; iMinutes = 0; iSeconds = 0; iMillis = 0; return; } long startInstant = 0; int years, months, weeks, days, hours, minutes, seconds, millis; DurationField field; if (!(field = type.years()).isSupported()) { years = 0; } else { checkPrecise(field, "years"); years = field.getDifference(duration, startInstant); startInstant = field.add(startInstant, years); } if (!(field = type.months()).isSupported()) { months = 0; } else { checkPrecise(field, "months"); months = field.getDifference(duration, startInstant); startInstant = field.add(startInstant, months); } if (!(field = type.weeks()).isSupported()) { weeks = 0; } else { checkPrecise(field, "weeks"); weeks = field.getDifference(duration, startInstant); startInstant = field.add(startInstant, weeks); } if (!(field = type.days()).isSupported()) { days = 0; } else { checkPrecise(field, "days"); days = field.getDifference(duration, startInstant); startInstant = field.add(startInstant, days); } if (!(field = type.hours()).isSupported()) { hours = 0; } else { checkPrecise(field, "hours"); hours = field.getDifference(duration, startInstant); startInstant = field.add(startInstant, hours); } if (!(field = type.minutes()).isSupported()) { minutes = 0; } else { checkPrecise(field, "minutes"); minutes = field.getDifference(duration, startInstant); startInstant = field.add(startInstant, minutes); } if (!(field = type.seconds()).isSupported()) { seconds = 0; } else { checkPrecise(field, "seconds"); seconds = field.getDifference(duration, startInstant); startInstant = field.add(startInstant, seconds); } if (!(field = type.millis()).isSupported()) { millis = 0; } else { checkPrecise(field, "millis"); millis = field.getDifference(duration, startInstant); startInstant = field.add(startInstant, millis); } iTotalMillis = duration; iTotalMillisState = 2; iYears = years; iMonths = months; iWeeks = weeks; iDays = days; iHours = hours; iMinutes = minutes; iSeconds = seconds; iMillis = millis; } //----------------------------------------------------------------------- /** * Adds a millisecond duration to this one. As a side-effect, all field * values are normalized. * * @param duration the duration, in milliseconds * @throws IllegalStateException if the duration is imprecise */ protected void add(long duration) { setTotalMillis(getTotalMillis() + duration); } /** * Adds a duration to this one. * * @param duration the duration to add * @throws IllegalArgumentException if the duration is null * @throws IllegalStateException if the duration is imprecise */ protected void add(ReadableDuration duration) { if (duration == null) { throw new IllegalArgumentException("The duration must not be null"); } add(duration.getTotalMillis()); } /** * Normalizes all the field values in this duration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @throws IllegalStateException if this duration is imprecise */ protected void normalize() { setTotalMillis(getTotalMillis()); } //----------------------------------------------------------------------- /** * Sets the number of years of the duration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param years the number of years * @throws UnsupportedOperationException if field is not supported. */ protected void setYears(int years) { if (years != iYears) { if (years != 0) { checkSupport(iType.years(), "years"); } iYears = years; iTotalMillisState = 0; } } /** * Adds the specified years to the number of years in the duration. * * @param years the number of years * @throws UnsupportedOperationException if field is not supported. */ protected void addYears(int years) { setYears(getYears() + years); } //----------------------------------------------------------------------- /** * Sets the number of months of the duration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param months the number of months * @throws UnsupportedOperationException if field is not supported. */ protected void setMonths(int months) { if (months != iMonths) { if (months != 0) { checkSupport(iType.months(), "months"); } iMonths = months; iTotalMillisState = 0; } } /** * Adds the specified months to the number of months in the duration. * * @param months the number of months * @throws UnsupportedOperationException if field is not supported. */ protected void addMonths(int months) { setMonths(getMonths() + months); } //----------------------------------------------------------------------- /** * Sets the number of weeks of the duration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param weeks the number of weeks * @throws UnsupportedOperationException if field is not supported. */ protected void setWeeks(int weeks) { if (weeks != iWeeks) { if (weeks != 0) { checkSupport(iType.weeks(), "weeks"); } iWeeks = weeks; iTotalMillisState = 0; } } /** * Adds the specified weeks to the number of weeks in the duration. * * @param weeks the number of weeks * @throws UnsupportedOperationException if field is not supported. */ protected void addWeeks(int weeks) { setWeeks(getWeeks() + weeks); } //----------------------------------------------------------------------- /** * Sets the number of days of the duration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param days the number of days * @throws UnsupportedOperationException if field is not supported. */ protected void setDays(int days) { if (days != iDays) { if (days != 0) { checkSupport(iType.days(), "days"); } iDays = days; iTotalMillisState = 0; } } /** * Adds the specified days to the number of days in the duration. * * @param days the number of days * @throws UnsupportedOperationException if field is not supported. */ protected void addDays(int days) { setDays(getDays() + days); } //----------------------------------------------------------------------- /** * Sets the number of hours of the duration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param hours the number of hours * @throws UnsupportedOperationException if field is not supported. */ protected void setHours(int hours) { if (hours != iHours) { if (hours != 0) { checkSupport(iType.hours(), "hours"); } iHours = hours; iTotalMillisState = 0; } } /** * Adds the specified hours to the number of hours in the duration. * * @param hours the number of hours * @throws UnsupportedOperationException if field is not supported. */ protected void addHours(int hours) { setHours(getHours() + hours); } //----------------------------------------------------------------------- /** * Sets the number of minutes of the duration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param minutes the number of minutes * @throws UnsupportedOperationException if field is not supported. */ protected void setMinutes(int minutes) { if (minutes != iMinutes) { if (minutes != 0) { checkSupport(iType.minutes(), "minutes"); } iMinutes = minutes; iTotalMillisState = 0; } } /** * Adds the specified minutes to the number of minutes in the duration. * * @param minutes the number of minutes * @throws UnsupportedOperationException if field is not supported. */ protected void addMinutes(int minutes) { setMinutes(getMinutes() + minutes); } //----------------------------------------------------------------------- /** * Sets the number of seconds of the duration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param seconds the number of seconds * @throws UnsupportedOperationException if field is not supported. */ protected void setSeconds(int seconds) { if (seconds != iSeconds) { if (seconds != 0) { checkSupport(iType.seconds(), "seconds"); } iSeconds = seconds; iTotalMillisState = 0; } } /** * Adds the specified seconds to the number of seconds in the duration. * * @param seconds the number of seconds * @throws UnsupportedOperationException if field is not supported. */ protected void addSeconds(int seconds) { setSeconds(getSeconds() + seconds); } //----------------------------------------------------------------------- /** * Sets the number of millis of the duration. * <p> * Subclasses that wish to be immutable should override this method with an * empty implementation that is protected and final. This also ensures that * all lower subclasses are also immutable. * * @param millis the number of millis * @throws UnsupportedOperationException if field is not supported. */ protected void setMillis(int millis) { if (millis != iMillis) { if (millis != 0) { checkSupport(iType.millis(), "millis"); } iMillis = millis; iTotalMillisState = 0; } } /** * Adds the specified millis to the number of millis in the duration. * * @param millis the number of millis * @throws UnsupportedOperationException if field is not supported. */ protected void addMillis(int millis) { setMillis(getMillis() + millis); } }
Exception message more general. git-svn-id: 8a12ccb6f50c30e5a282783f538d297d22c63f8f@12 1e1cfbb7-5c0e-0410-a2f0-f98d92ec03a1
JodaTime/src/java/org/joda/time/AbstractDuration.java
Exception message more general.
Java
apache-2.0
d1a769bad3ad12176bd9328ad80bd9d1c082d73b
0
tommyettinger/sarong
package sarong; import java.util.Arrays; /** * An improvement on the performance of http://extremelearning.com.au/isotropic-blue-noise-point-sets/ . */ public class PermutationEtc { /** * Change SIZE to increase the size of the balanced permutations. */ public static final int SIZE = 52, HALF_SIZE = SIZE >>> 1, COUNT = 100; public PermutationEtc(){} public PermutationEtc(long state){ stateA = state; } /** * Can be any long. */ private long stateA = 12345678987654321L; //System.nanoTime(); /** * Must be odd. */ private long stateB = 0x1337DEADBEEFL; /** * It's a weird RNG. Returns a slightly-biased pseudo-random int between 0 inclusive and bound exclusive. The bias comes from * not completely implementing Daniel Lemire's fastrange algorithm, but it should only be relevant for huge bounds. The number * generator itself passes PractRand without anomalies, has a state size of 127 bits, and a period of 2 to the 127. * @param bound upper exclusive bound * @return an int between 0 (inclusive) and bound (exclusive) */ private int nextIntBounded (int bound) { final long s = (stateA += 0xC6BC279692B5C323L); final long z = ((s < 0x800000006F17146DL) ? stateB : (stateB += 0x9479D2858AF899E6L)) * (s ^ s >>> 31); return (int)(bound * ((z ^ z >>> 25) & 0xFFFFFFFFL) >>> 32); } private static void swap(int[] arr, int pos1, int pos2) { final int tmp = arr[pos1]; arr[pos1] = arr[pos2]; arr[pos2] = tmp; } /** * Fisher-Yates and/or Knuth shuffle, done in-place on an int array. * @param elements will be modified in-place by a relatively fair shuffle */ public void shuffleInPlace(int[] elements) { final int size = elements.length; for (int i = size; i > 1; i--) { swap(elements, i - 1, nextIntBounded(i)); } } public static void main(String[] args){ PermutationEtc p = new PermutationEtc(System.nanoTime()); final int[][] allItems = new int[COUNT][SIZE]; final int[] delta = new int[SIZE], targets = new int[SIZE]; final int LIMIT = 10000 * COUNT * COUNT; long startTime = System.currentTimeMillis(); for (int g = 0; g < COUNT; g++) { int[] items = allItems[g]; // this is limited to 10000 * COUNT * COUNT runs as an emergency stop in case we run out of distinct permutations BIG_LOOP: for (int repeat = 0; repeat < LIMIT; repeat++) { for (int i = 0; i < HALF_SIZE; i++) { delta[i] = i + 1; delta[i + HALF_SIZE] = ~i; } p.shuffleInPlace(delta); for (int i = 0; i < SIZE; i++) { targets[i] = i + 1; } targets[(items[0] = p.nextIntBounded(SIZE) + 1) - 1] = 0; for (int i = 1; i < SIZE; i++) { int d = 0; for (int j = 0; j < SIZE; j++) { d = delta[j]; if(d == 0) continue; int t = items[i-1] + d; if(t > 0 && t <= SIZE && targets[t-1] != 0){ items[i] = t; targets[t-1] = 0; delta[j] = 0; break; } else d = 0; } if(d == 0) continue BIG_LOOP; } int d = items[0] - items[SIZE - 1]; for (int j = 0; j < SIZE; j++) { if(d == delta[j]) { // distinct array check for (int i = 0; i < g; i++) { if(Arrays.equals(allItems[i], items)) continue BIG_LOOP; } System.out.print(items[0]); for (int i = 1; i < SIZE; i++) { System.out.print(", " + items[i]); } System.out.println(); break BIG_LOOP; } } } } System.out.println("Took " + (System.currentTimeMillis() - startTime) * 0.001 + " seconds to generate 100 sequences with size " + SIZE); } }
src/test/java/sarong/PermutationEtc.java
package sarong; /** * An improvement on the performance of http://extremelearning.com.au/isotropic-blue-noise-point-sets/ . * Does not currently validate that the permutations it has found are distinct from each other. */ public class PermutationEtc { /** * Change SIZE to increase the size of the balanced permutations. */ public static final int SIZE = 30, HALF_SIZE = SIZE >>> 1; public PermutationEtc(){} public PermutationEtc(long state){ stateA = state; } /** * Can be any long. */ private long stateA = 12345678987654321L; //System.nanoTime(); /** * Must be odd. */ private long stateB = 0x1337DEADBEEFL; /** * It's a weird RNG. Returns a slightly-biased pseudo-random int between 0 inclusive and bound exclusive. The bias comes from * not completely implementing Daniel Lemire's fastrange algorithm, but it should only be relevant for huge bounds. The number * generator itself passes PractRand without anomalies, has a state size of 127 bits, and a period of 2 to the 127. * @param bound upper exclusive bound * @return an int between 0 (inclusive) and bound (exclusive) */ private int nextIntBounded (int bound) { final long s = (stateA += 0xC6BC279692B5C323L); final long z = ((s < 0x800000006F17146DL) ? stateB : (stateB += 0x9479D2858AF899E6L)) * (s ^ s >>> 31); return (int)(bound * ((z ^ z >>> 25) & 0xFFFFFFFFL) >>> 32); } private static void swap(int[] arr, int pos1, int pos2) { final int tmp = arr[pos1]; arr[pos1] = arr[pos2]; arr[pos2] = tmp; } /** * Fisher-Yates and/or Knuth shuffle, done in-place on an int array. * @param elements will be modified in-place by a relatively fair shuffle */ public void shuffleInPlace(int[] elements) { final int size = elements.length; for (int i = size; i > 1; i--) { swap(elements, i - 1, nextIntBounded(i)); } } public static void main(String[] args){ long startTime = System.currentTimeMillis(); PermutationEtc p = new PermutationEtc(startTime); final int[] items = new int[SIZE], delta = new int[SIZE], targets = new int[SIZE]; for (int g = 0; g < 100; g++) { BIG_LOOP: while (true) { for (int i = 0; i < HALF_SIZE; i++) { delta[i] = i + 1; delta[i + HALF_SIZE] = ~i; } p.shuffleInPlace(delta); for (int i = 0; i < SIZE; i++) { targets[i] = i + 1; } targets[(items[0] = p.nextIntBounded(SIZE) + 1) - 1] = 0; for (int i = 1; i < SIZE; i++) { int d = 0; for (int j = 0; j < SIZE; j++) { d = delta[j]; if(d == 0) continue; int t = items[i-1] + d; if(t > 0 && t <= SIZE && targets[t-1] != 0){ items[i] = t; targets[t-1] = 0; delta[j] = 0; break; } else d = 0; } if(d == 0) continue BIG_LOOP; } int d = items[0] - items[SIZE - 1]; for (int j = 0; j < SIZE; j++) { if(d == delta[j]) { System.out.print(items[0]); for (int i = 1; i < SIZE; i++) { System.out.print(", " + items[i]); } System.out.println(); break BIG_LOOP; } } break; } } System.out.println("Took " + (System.currentTimeMillis() - startTime) * 0.001 + " seconds to generate 100 sequences with size " + SIZE); } }
Update balanced permutation code so it ensures permutations are distinct. The code is probably not ideal for larger cases, but it works for the small arrays we're using.
src/test/java/sarong/PermutationEtc.java
Update balanced permutation code so it ensures permutations are distinct.
Java
apache-2.0
c78733861f1dbcf272d3b8f6a74eb55d5fbf3972
0
BURAI-team/burai
/* * Copyright (C) 2016 Satomichi Nishihara * * This file is distributed under the terms of the * GNU General Public License. See the file `LICENSE' * in the root directory of the present distribution, * or http://www.gnu.org/copyleft/gpl.txt . */ package burai.app; import java.io.File; import java.net.URL; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.Queue; import java.util.ResourceBundle; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.geometry.Rectangle2D; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TextField; import javafx.scene.control.Tooltip; import javafx.scene.input.Dragboard; import javafx.scene.input.KeyCode; import javafx.scene.input.TransferMode; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.web.WebEngine; import javafx.stage.Screen; import javafx.stage.Stage; import javafx.stage.WindowEvent; import burai.app.about.QEFXAboutDialog; import burai.app.explorer.QEFXExplorer; import burai.app.explorer.QEFXExplorerFacade; import burai.app.icon.QEFXIcon; import burai.app.icon.QEFXProjectIcon; import burai.app.icon.QEFXWebIcon; import burai.app.matapi.QEFXMatAPIDialog; import burai.app.onclose.QEFXSavingDialog; import burai.app.proxy.QEFXProxyDialog; import burai.app.tab.QEFXTabManager; import burai.com.env.Environments; import burai.com.graphic.svg.SVGLibrary; import burai.com.graphic.svg.SVGLibrary.SVGData; import burai.com.life.Life; import burai.matapi.MaterialsAPILoader; import burai.project.Project; import burai.run.RunningManager; import burai.ver.Version; public class QEFXMainController implements Initializable { private static final long SLEEP_TIME_TO_DROP_FILES = 650L; private static final double TOPMENU_GRAPHIC_SIZE = 16.0; private static final String TOPMENU_GRAPHIC_CLASS = "picblack-button"; private static final double HOME_GRAPHIC_SIZE = 20.0; private static final String HOME_GRAPHIC_CLASS = "pichome-button"; private static final double SEARCH_GRAPHIC_SIZE = 14.0; private static final String SEARCH_GRAPHIC_CLASS = "picblack-button"; private Stage stage; private QEFXTabManager tabManager; private QEFXExplorerFacade explorerFacade; private Queue<HomeTabSelected> onHomeTabSelectedQueue; @FXML private BorderPane basePane; @FXML private Menu topMenu; @FXML private MenuItem aboutMItem; @FXML private MenuItem docsMItem; @FXML private MenuItem qeMItem; @FXML private MenuItem pseudoMItem; @FXML private MenuItem manPwMItem; @FXML private MenuItem manDosMItem; @FXML private MenuItem manProjMItem; @FXML private MenuItem manBandMItem; @FXML private MenuItem proxyMItem; @FXML private MenuItem fullScrMItem; @FXML private MenuItem quitMItem; @FXML private TabPane tabPane; @FXML private Tab homeTab; @FXML private AnchorPane homePane; @FXML private Button matApiButton; @FXML private TextField matApiField; public QEFXMainController() { this.stage = null; this.tabManager = null; this.explorerFacade = null; this.onHomeTabSelectedQueue = null; } @Override public void initialize(URL location, ResourceBundle resources) { this.setupBasePane(); this.setupTopMenu(); this.setupMenuItems(); this.setupTabPane(); this.setupHomeTab(); this.setupMatApiButton(); this.setupMatApiField(); } private void setupBasePane() { if (this.basePane == null) { return; } this.basePane.setOnDragOver(event -> { Dragboard board = event == null ? null : event.getDragboard(); if (board == null) { return; } if (board.hasFiles()) { event.acceptTransferModes(TransferMode.COPY); } }); this.basePane.setOnDragDropped(event -> { Dragboard board = event == null ? null : event.getDragboard(); if (board == null) { return; } if (!board.hasFiles()) { event.setDropCompleted(false); return; } List<File> files = board.getFiles(); if (files != null) { Thread thread = new Thread(() -> { for (File file : files) { this.showDroppedFile(file); synchronized (files) { try { files.wait(SLEEP_TIME_TO_DROP_FILES); } catch (Exception e) { e.printStackTrace(); } } } }); thread.start(); } event.setDropCompleted(true); }); } private void showDroppedFile(File file) { QEFXIcon icon = file == null ? null : QEFXIcon.getInstance(file); if (icon == null) { return; } Platform.runLater(() -> { if (icon != null && icon instanceof QEFXProjectIcon) { Project project = ((QEFXProjectIcon) icon).getContent(); if (project != null) { this.showProject(project); } } else if (icon != null && icon instanceof QEFXWebIcon) { String url = ((QEFXWebIcon) icon).getInitialURL(); if (url != null && !(url.trim().isEmpty())) { this.showWebPage(url); } } }); } private void setupTopMenu() { if (this.topMenu == null) { return; } this.topMenu.setText(""); this.topMenu.setGraphic( SVGLibrary.getGraphic(SVGData.VECTOR_RIGHT, TOPMENU_GRAPHIC_SIZE, null, TOPMENU_GRAPHIC_CLASS)); this.topMenu.showingProperty().addListener(o -> { if (this.topMenu.isShowing()) { this.topMenu.setGraphic(SVGLibrary.getGraphic( SVGData.VECTOR_DOWN, TOPMENU_GRAPHIC_SIZE, null, TOPMENU_GRAPHIC_CLASS)); } else { this.topMenu.setGraphic(SVGLibrary.getGraphic( SVGData.VECTOR_RIGHT, TOPMENU_GRAPHIC_SIZE, null, TOPMENU_GRAPHIC_CLASS)); } }); } private void setupMenuItems() { if (this.aboutMItem != null) { this.aboutMItem.setOnAction(event -> { QEFXAboutDialog dialog = new QEFXAboutDialog(); dialog.showAndWait(); }); } if (this.docsMItem != null) { this.docsMItem.setOnAction(event -> { this.showWebPage(Environments.getDocumentsWebsite()); }); } if (this.qeMItem != null) { this.qeMItem.setOnAction(event -> { this.showWebPage(Environments.getEspressoWebsite()); }); } if (this.pseudoMItem != null) { this.pseudoMItem.setOnAction(event -> { this.showWebPage(Environments.getPseudoWebsite()); }); } if (this.manPwMItem != null) { this.manPwMItem.setOnAction(event -> { this.showWebPage(Environments.getManPwscfWebsite()); }); } if (this.manDosMItem != null) { this.manDosMItem.setOnAction(event -> { this.showWebPage(Environments.getManDosWebsite()); }); } if (this.manProjMItem != null) { this.manProjMItem.setOnAction(event -> { this.showWebPage(Environments.getManProjwfcWebsite()); }); } if (this.manBandMItem != null) { this.manBandMItem.setOnAction(event -> { this.showWebPage(Environments.getManBandsWebsite()); }); } if (this.proxyMItem != null) { this.proxyMItem.setOnAction(event -> { QEFXProxyDialog dialog = new QEFXProxyDialog(); dialog.showAndSetProperties(); }); } if (this.fullScrMItem != null) { this.fullScrMItem.setOnAction(event -> { if (this.stage != null && this.stage.isFullScreen()) { this.setFullScreen(false); } else { this.setFullScreen(true); } }); } if (this.quitMItem != null) { this.quitMItem.setOnAction(event -> { this.quitSystem(); }); } } private void setupTabPane() { if (this.tabPane == null) { return; } this.tabManager = new QEFXTabManager(this, this.tabPane); } private void setupHomeTab() { if (this.homeTab == null) { return; } this.homeTab.setText(""); this.homeTab.setGraphic( SVGLibrary.getGraphic(SVGData.HOME, HOME_GRAPHIC_SIZE, null, HOME_GRAPHIC_CLASS)); this.homeTab.setClosable(false); this.homeTab.setTooltip(new Tooltip("home")); this.homeTab.setOnSelectionChanged(event -> { if (this.homeTab.isSelected()) { this.executeOnHomeTabSelected(); } }); } private void executeOnHomeTabSelected() { if (this.onHomeTabSelectedQueue == null) { return; } if (this.explorerFacade != null) { this.explorerFacade.startSingleReloadMode(); } while (!this.onHomeTabSelectedQueue.isEmpty()) { HomeTabSelected onHomeTabSelected = this.onHomeTabSelectedQueue.poll(); if (onHomeTabSelected != null && this.explorerFacade != null) { onHomeTabSelected.onHomeTabSelected(this.explorerFacade); } } if (this.explorerFacade != null) { this.explorerFacade.endSingleReloadMode(); } } private void setupMatApiButton() { if (this.matApiButton == null) { return; } this.matApiButton.setGraphic( SVGLibrary.getGraphic(SVGData.SEARCH, SEARCH_GRAPHIC_SIZE, null, SEARCH_GRAPHIC_CLASS)); this.matApiButton.setOnAction(event -> { QEFXMatAPIDialog dialog = new QEFXMatAPIDialog(); dialog.showAndSetProperties(); }); } private void setupMatApiField() { if (this.matApiField == null) { return; } String messageTip = ""; messageTip = messageTip + "1) Li-Fe-O" + System.lineSeparator(); messageTip = messageTip + "2) Fe2O3"; this.matApiField.setTooltip(new Tooltip(messageTip)); this.matApiField.setOnAction(event -> { String text = this.matApiField.getText(); text = text == null ? null : text.trim(); if (text == null || text.isEmpty()) { MaterialsAPILoader.deleteLoader(); return; } MaterialsAPILoader matApiLoader = new MaterialsAPILoader(text); if (matApiLoader.numMaterialIDs() > 0) { this.matApiField.setText(matApiLoader.getFormula()); if (this.explorerFacade != null) { this.explorerFacade.setMaterialsAPILoader(matApiLoader); this.explorerFacade.setSearchedMode(); this.showHome(); } } else { String message = "The Materials API says there are no data of " + matApiLoader.getFormula() + "."; Alert alert = new Alert(AlertType.ERROR); QEFXMain.initializeDialogOwner(alert); alert.setHeaderText(message); alert.showAndWait(); } }); } public Stage getStage() { return this.stage; } protected void setStage(Stage stage) { this.stage = stage; if (this.stage == null) { return; } Rectangle2D rectangle2d = Screen.getPrimary().getVisualBounds(); double width = rectangle2d.getWidth(); double height = rectangle2d.getHeight(); this.stage.setWidth(width); this.stage.setHeight(height); this.stage.setTitle("BURAI" + Version.VERSION + ", a GUI of Quantum ESPRESSO."); this.stage.setOnCloseRequest(event -> this.actionOnCloseRequest(event)); this.stage.setOnHidden(event -> this.actionOnHidden(event)); Scene scene = this.stage.getScene(); if (scene != null) { scene.setOnKeyPressed(event -> { if (event == null) { return; } if (event.isControlDown() && KeyCode.Q.equals(event.getCode())) { this.quitSystem(); } }); } } private void actionOnCloseRequest(WindowEvent event) { List<Project> projects = this.tabManager == null ? null : this.tabManager.getProjects(); if (projects != null && (!projects.isEmpty())) { QEFXSavingDialog dialog = new QEFXSavingDialog(projects); if (dialog.hasProjects()) { boolean status = dialog.showAndSave(); if (!status) { if (event != null) { event.consume(); } } } } if (event != null && event.isConsumed()) { return; } if (!RunningManager.getInstance().isEmpty()) { Alert alert = new Alert(AlertType.WARNING); QEFXMain.initializeDialogOwner(alert); alert.setHeaderText("Calculations are running. Do you delete them ?"); alert.getButtonTypes().clear(); alert.getButtonTypes().add(ButtonType.YES); alert.getButtonTypes().add(ButtonType.NO); Optional<ButtonType> optButtonType = alert.showAndWait(); ButtonType buttonType = null; if (optButtonType != null && optButtonType.isPresent()) { buttonType = optButtonType.get(); } if (!ButtonType.YES.equals(buttonType)) { if (event != null) { event.consume(); } } } } private void actionOnHidden(WindowEvent event) { if (event != null && event.isConsumed()) { return; } if (this.tabManager != null) { this.tabManager.hideAllTabs(); } Life.getInstance().toBeDead(); } public void quitSystem() { if (this.stage != null) { WindowEvent event = new WindowEvent(this.stage, WindowEvent.ANY); if (!event.isConsumed()) { if (this.stage.getOnCloseRequest() != null) { this.stage.getOnCloseRequest().handle(event); } } if (!event.isConsumed()) { this.stage.hide(); } } } public void setMaximized(boolean maximized) { if (this.stage != null) { this.stage.setMaximized(maximized); } } public void setFullScreen(boolean fullScreen) { if (this.stage != null) { this.stage.setFullScreen(fullScreen); } } public void setResizable(boolean resizable) { if (this.stage != null) { this.stage.setResizable(resizable); } } protected void setExplorer(QEFXExplorer explorer) { if (explorer == null) { return; } if (this.homePane != null) { Node node = explorer.getNode(); if (node != null) { this.homePane.getChildren().clear(); this.homePane.getChildren().add(node); this.explorerFacade = explorer.getFacade(); } } } public void refreshProjectOnExplorer(Project project) { if (project == null) { return; } if (this.explorerFacade != null) { this.explorerFacade.refreshProject(project); } } public void offerOnHomeTabSelected(HomeTabSelected onHomeTabSelected) { if (onHomeTabSelected == null) { return; } if (this.onHomeTabSelectedQueue == null) { this.onHomeTabSelectedQueue = new LinkedList<HomeTabSelected>(); } this.onHomeTabSelectedQueue.offer(onHomeTabSelected); } public boolean showHome() { if (this.tabManager != null) { return this.tabManager.showHomeTab(); } return false; } public Project showProject(Project project) { if (project == null) { return null; } if (this.tabManager != null) { Project project2 = this.tabManager.showTab(project); if (project2 != null) { Environments.addRecentFilePath(project2.getRelatedFilePath()); this.offerOnHomeTabSelected(explorerFacade -> { if (explorerFacade != null && explorerFacade.isRecentlyUsedMode()) { explorerFacade.reloadLocation(); } }); } return project2; } return null; } public WebEngine showWebPage(String url) { if (url == null || url.trim().isEmpty()) { return null; } if (this.tabManager != null) { return this.tabManager.showTab(url); } return null; } public boolean hideProject(Project project) { if (project == null) { return false; } if (this.tabManager != null) { return this.tabManager.hideTab(project); } return false; } public boolean hideWebPage(WebEngine engine) { if (engine == null) { return false; } if (this.tabManager != null) { return this.tabManager.hideTab(engine); } return false; } public List<Project> getShownProjects() { if (this.tabManager != null) { return this.tabManager.getProjects(); } return null; } }
src/burai/app/QEFXMainController.java
/* * Copyright (C) 2016 Satomichi Nishihara * * This file is distributed under the terms of the * GNU General Public License. See the file `LICENSE' * in the root directory of the present distribution, * or http://www.gnu.org/copyleft/gpl.txt . */ package burai.app; import java.io.File; import java.net.URL; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.Queue; import java.util.ResourceBundle; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.geometry.Rectangle2D; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TextField; import javafx.scene.control.Tooltip; import javafx.scene.input.Dragboard; import javafx.scene.input.KeyCode; import javafx.scene.input.TransferMode; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.web.WebEngine; import javafx.stage.Screen; import javafx.stage.Stage; import javafx.stage.WindowEvent; import burai.app.about.QEFXAboutDialog; import burai.app.explorer.QEFXExplorer; import burai.app.explorer.QEFXExplorerFacade; import burai.app.icon.QEFXIcon; import burai.app.icon.QEFXProjectIcon; import burai.app.icon.QEFXWebIcon; import burai.app.matapi.QEFXMatAPIDialog; import burai.app.onclose.QEFXSavingDialog; import burai.app.proxy.QEFXProxyDialog; import burai.app.tab.QEFXTabManager; import burai.com.env.Environments; import burai.com.graphic.svg.SVGLibrary; import burai.com.graphic.svg.SVGLibrary.SVGData; import burai.com.life.Life; import burai.matapi.MaterialsAPILoader; import burai.project.Project; import burai.run.RunningManager; import burai.ver.Version; public class QEFXMainController implements Initializable { private static final long SLEEP_TIME_TO_DROP_FILES = 850L; private static final double TOPMENU_GRAPHIC_SIZE = 16.0; private static final String TOPMENU_GRAPHIC_CLASS = "picblack-button"; private static final double HOME_GRAPHIC_SIZE = 20.0; private static final String HOME_GRAPHIC_CLASS = "pichome-button"; private static final double SEARCH_GRAPHIC_SIZE = 14.0; private static final String SEARCH_GRAPHIC_CLASS = "picblack-button"; private Stage stage; private QEFXTabManager tabManager; private QEFXExplorerFacade explorerFacade; private Queue<HomeTabSelected> onHomeTabSelectedQueue; @FXML private BorderPane basePane; @FXML private Menu topMenu; @FXML private MenuItem aboutMItem; @FXML private MenuItem docsMItem; @FXML private MenuItem qeMItem; @FXML private MenuItem pseudoMItem; @FXML private MenuItem manPwMItem; @FXML private MenuItem manDosMItem; @FXML private MenuItem manProjMItem; @FXML private MenuItem manBandMItem; @FXML private MenuItem proxyMItem; @FXML private MenuItem fullScrMItem; @FXML private MenuItem quitMItem; @FXML private TabPane tabPane; @FXML private Tab homeTab; @FXML private AnchorPane homePane; @FXML private Button matApiButton; @FXML private TextField matApiField; public QEFXMainController() { this.stage = null; this.tabManager = null; this.explorerFacade = null; this.onHomeTabSelectedQueue = null; } @Override public void initialize(URL location, ResourceBundle resources) { this.setupBasePane(); this.setupTopMenu(); this.setupMenuItems(); this.setupTabPane(); this.setupHomeTab(); this.setupMatApiButton(); this.setupMatApiField(); } private void setupBasePane() { if (this.basePane == null) { return; } this.basePane.setOnDragOver(event -> { Dragboard board = event == null ? null : event.getDragboard(); if (board == null) { return; } if (board.hasFiles()) { event.acceptTransferModes(TransferMode.COPY); } }); this.basePane.setOnDragDropped(event -> { Dragboard board = event == null ? null : event.getDragboard(); if (board == null) { return; } if (!board.hasFiles()) { event.setDropCompleted(false); return; } List<File> files = board.getFiles(); if (files != null) { Thread thread = new Thread(() -> { for (File file : files) { this.showDroppedFile(file); synchronized (files) { try { files.wait(SLEEP_TIME_TO_DROP_FILES); } catch (Exception e) { e.printStackTrace(); } } } }); thread.start(); } event.setDropCompleted(true); }); } private void showDroppedFile(File file) { QEFXIcon icon = file == null ? null : QEFXIcon.getInstance(file); if (icon == null) { return; } Platform.runLater(() -> { if (icon != null && icon instanceof QEFXProjectIcon) { Project project = ((QEFXProjectIcon) icon).getContent(); if (project != null) { this.showProject(project); } } else if (icon != null && icon instanceof QEFXWebIcon) { String url = ((QEFXWebIcon) icon).getInitialURL(); if (url != null && !(url.trim().isEmpty())) { this.showWebPage(url); } } }); } private void setupTopMenu() { if (this.topMenu == null) { return; } this.topMenu.setText(""); this.topMenu.setGraphic( SVGLibrary.getGraphic(SVGData.VECTOR_RIGHT, TOPMENU_GRAPHIC_SIZE, null, TOPMENU_GRAPHIC_CLASS)); this.topMenu.showingProperty().addListener(o -> { if (this.topMenu.isShowing()) { this.topMenu.setGraphic(SVGLibrary.getGraphic( SVGData.VECTOR_DOWN, TOPMENU_GRAPHIC_SIZE, null, TOPMENU_GRAPHIC_CLASS)); } else { this.topMenu.setGraphic(SVGLibrary.getGraphic( SVGData.VECTOR_RIGHT, TOPMENU_GRAPHIC_SIZE, null, TOPMENU_GRAPHIC_CLASS)); } }); } private void setupMenuItems() { if (this.aboutMItem != null) { this.aboutMItem.setOnAction(event -> { QEFXAboutDialog dialog = new QEFXAboutDialog(); dialog.showAndWait(); }); } if (this.docsMItem != null) { this.docsMItem.setOnAction(event -> { this.showWebPage(Environments.getDocumentsWebsite()); }); } if (this.qeMItem != null) { this.qeMItem.setOnAction(event -> { this.showWebPage(Environments.getEspressoWebsite()); }); } if (this.pseudoMItem != null) { this.pseudoMItem.setOnAction(event -> { this.showWebPage(Environments.getPseudoWebsite()); }); } if (this.manPwMItem != null) { this.manPwMItem.setOnAction(event -> { this.showWebPage(Environments.getManPwscfWebsite()); }); } if (this.manDosMItem != null) { this.manDosMItem.setOnAction(event -> { this.showWebPage(Environments.getManDosWebsite()); }); } if (this.manProjMItem != null) { this.manProjMItem.setOnAction(event -> { this.showWebPage(Environments.getManProjwfcWebsite()); }); } if (this.manBandMItem != null) { this.manBandMItem.setOnAction(event -> { this.showWebPage(Environments.getManBandsWebsite()); }); } if (this.proxyMItem != null) { this.proxyMItem.setOnAction(event -> { QEFXProxyDialog dialog = new QEFXProxyDialog(); dialog.showAndSetProperties(); }); } if (this.fullScrMItem != null) { this.fullScrMItem.setOnAction(event -> { if (this.stage != null && this.stage.isFullScreen()) { this.setFullScreen(false); } else { this.setFullScreen(true); } }); } if (this.quitMItem != null) { this.quitMItem.setOnAction(event -> { this.quitSystem(); }); } } private void setupTabPane() { if (this.tabPane == null) { return; } this.tabManager = new QEFXTabManager(this, this.tabPane); } private void setupHomeTab() { if (this.homeTab == null) { return; } this.homeTab.setText(""); this.homeTab.setGraphic( SVGLibrary.getGraphic(SVGData.HOME, HOME_GRAPHIC_SIZE, null, HOME_GRAPHIC_CLASS)); this.homeTab.setClosable(false); this.homeTab.setTooltip(new Tooltip("home")); this.homeTab.setOnSelectionChanged(event -> { if (this.homeTab.isSelected()) { this.executeOnHomeTabSelected(); } }); } private void executeOnHomeTabSelected() { if (this.onHomeTabSelectedQueue == null) { return; } if (this.explorerFacade != null) { this.explorerFacade.startSingleReloadMode(); } while (!this.onHomeTabSelectedQueue.isEmpty()) { HomeTabSelected onHomeTabSelected = this.onHomeTabSelectedQueue.poll(); if (onHomeTabSelected != null && this.explorerFacade != null) { onHomeTabSelected.onHomeTabSelected(this.explorerFacade); } } if (this.explorerFacade != null) { this.explorerFacade.endSingleReloadMode(); } } private void setupMatApiButton() { if (this.matApiButton == null) { return; } this.matApiButton.setGraphic( SVGLibrary.getGraphic(SVGData.SEARCH, SEARCH_GRAPHIC_SIZE, null, SEARCH_GRAPHIC_CLASS)); this.matApiButton.setOnAction(event -> { QEFXMatAPIDialog dialog = new QEFXMatAPIDialog(); dialog.showAndSetProperties(); }); } private void setupMatApiField() { if (this.matApiField == null) { return; } String messageTip = ""; messageTip = messageTip + "1) Li-Fe-O" + System.lineSeparator(); messageTip = messageTip + "2) Fe2O3"; this.matApiField.setTooltip(new Tooltip(messageTip)); this.matApiField.setOnAction(event -> { String text = this.matApiField.getText(); text = text == null ? null : text.trim(); if (text == null || text.isEmpty()) { MaterialsAPILoader.deleteLoader(); return; } MaterialsAPILoader matApiLoader = new MaterialsAPILoader(text); if (matApiLoader.numMaterialIDs() > 0) { this.matApiField.setText(matApiLoader.getFormula()); if (this.explorerFacade != null) { this.explorerFacade.setMaterialsAPILoader(matApiLoader); this.explorerFacade.setSearchedMode(); this.showHome(); } } else { String message = "The Materials API says there are no data of " + matApiLoader.getFormula() + "."; Alert alert = new Alert(AlertType.ERROR); QEFXMain.initializeDialogOwner(alert); alert.setHeaderText(message); alert.showAndWait(); } }); } public Stage getStage() { return this.stage; } protected void setStage(Stage stage) { this.stage = stage; if (this.stage == null) { return; } Rectangle2D rectangle2d = Screen.getPrimary().getVisualBounds(); double width = rectangle2d.getWidth(); double height = rectangle2d.getHeight(); this.stage.setWidth(width); this.stage.setHeight(height); this.stage.setTitle("BURAI" + Version.VERSION + ", a GUI of Quantum ESPRESSO."); this.stage.setOnCloseRequest(event -> this.actionOnCloseRequest(event)); this.stage.setOnHidden(event -> this.actionOnHidden(event)); Scene scene = this.stage.getScene(); if (scene != null) { scene.setOnKeyPressed(event -> { if (event == null) { return; } if (event.isControlDown() && KeyCode.Q.equals(event.getCode())) { this.quitSystem(); } }); } } private void actionOnCloseRequest(WindowEvent event) { List<Project> projects = this.tabManager == null ? null : this.tabManager.getProjects(); if (projects != null && (!projects.isEmpty())) { QEFXSavingDialog dialog = new QEFXSavingDialog(projects); if (dialog.hasProjects()) { boolean status = dialog.showAndSave(); if (!status) { if (event != null) { event.consume(); } } } } if (event != null && event.isConsumed()) { return; } if (!RunningManager.getInstance().isEmpty()) { Alert alert = new Alert(AlertType.WARNING); QEFXMain.initializeDialogOwner(alert); alert.setHeaderText("Calculations are running. Do you delete them ?"); alert.getButtonTypes().clear(); alert.getButtonTypes().add(ButtonType.YES); alert.getButtonTypes().add(ButtonType.NO); Optional<ButtonType> optButtonType = alert.showAndWait(); ButtonType buttonType = null; if (optButtonType != null && optButtonType.isPresent()) { buttonType = optButtonType.get(); } if (!ButtonType.YES.equals(buttonType)) { if (event != null) { event.consume(); } } } } private void actionOnHidden(WindowEvent event) { if (event != null && event.isConsumed()) { return; } if (this.tabManager != null) { this.tabManager.hideAllTabs(); } Life.getInstance().toBeDead(); } public void quitSystem() { if (this.stage != null) { WindowEvent event = new WindowEvent(this.stage, WindowEvent.ANY); if (!event.isConsumed()) { if (this.stage.getOnCloseRequest() != null) { this.stage.getOnCloseRequest().handle(event); } } if (!event.isConsumed()) { this.stage.hide(); } } } public void setMaximized(boolean maximized) { if (this.stage != null) { this.stage.setMaximized(maximized); } } public void setFullScreen(boolean fullScreen) { if (this.stage != null) { this.stage.setFullScreen(fullScreen); } } public void setResizable(boolean resizable) { if (this.stage != null) { this.stage.setResizable(resizable); } } protected void setExplorer(QEFXExplorer explorer) { if (explorer == null) { return; } if (this.homePane != null) { Node node = explorer.getNode(); if (node != null) { this.homePane.getChildren().clear(); this.homePane.getChildren().add(node); this.explorerFacade = explorer.getFacade(); } } } public void refreshProjectOnExplorer(Project project) { if (project == null) { return; } if (this.explorerFacade != null) { this.explorerFacade.refreshProject(project); } } public void offerOnHomeTabSelected(HomeTabSelected onHomeTabSelected) { if (onHomeTabSelected == null) { return; } if (this.onHomeTabSelectedQueue == null) { this.onHomeTabSelectedQueue = new LinkedList<HomeTabSelected>(); } this.onHomeTabSelectedQueue.offer(onHomeTabSelected); } public boolean showHome() { if (this.tabManager != null) { return this.tabManager.showHomeTab(); } return false; } public Project showProject(Project project) { if (project == null) { return null; } if (this.tabManager != null) { Project project2 = this.tabManager.showTab(project); if (project2 != null) { Environments.addRecentFilePath(project2.getRelatedFilePath()); this.offerOnHomeTabSelected(explorerFacade -> { if (explorerFacade != null && explorerFacade.isRecentlyUsedMode()) { explorerFacade.reloadLocation(); } }); } return project2; } return null; } public WebEngine showWebPage(String url) { if (url == null || url.trim().isEmpty()) { return null; } if (this.tabManager != null) { return this.tabManager.showTab(url); } return null; } public boolean hideProject(Project project) { if (project == null) { return false; } if (this.tabManager != null) { return this.tabManager.hideTab(project); } return false; } public boolean hideWebPage(WebEngine engine) { if (engine == null) { return false; } if (this.tabManager != null) { return this.tabManager.hideTab(engine); } return false; } public List<Project> getShownProjects() { if (this.tabManager != null) { return this.tabManager.getProjects(); } return null; } }
tune DropFiles
src/burai/app/QEFXMainController.java
tune DropFiles
Java
apache-2.0
43d5748656b23bbbd9946f7b61006d1c21a18bdd
0
TeamNexus/android_device_samsung_zero-common,TeamNexus/android_device_samsung_zero-common,TeamNexus/android_device_samsung_zero-common,TeamNexus/android_device_samsung_zero-common,TeamNexus/android_device_samsung_zero-common
/* * Copyright (C) 2012-2014 The CyanogenMod Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.internal.telephony; import static com.android.internal.telephony.RILConstants.*; import android.content.Context; import android.os.Message; import android.os.Parcel; import android.telephony.Rlog; import android.telephony.SignalStrength; import android.telephony.PhoneNumberUtils; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import com.android.internal.telephony.uicc.IccCardApplicationStatus; import com.android.internal.telephony.uicc.IccCardStatus; /** * RIL customization for Galaxy S6. * {@hide} */ public class zeroRIL extends RIL implements CommandsInterface { private boolean DBG = false; public zeroRIL(Context context, int preferredNetworkType, int cdmaSubscription, Integer instanceId) { super(context, preferredNetworkType, cdmaSubscription, instanceId); mQANElements = 6; } public zeroRIL(Context context, int networkMode, int cdmaSubscription) { super(context, networkMode, cdmaSubscription); mQANElements = 6; } @Override protected Object responseIccCardStatus(Parcel p) { IccCardApplicationStatus appStatus; IccCardStatus cardStatus = new IccCardStatus(); cardStatus.setCardState(p.readInt()); cardStatus.setUniversalPinState(p.readInt()); cardStatus.mGsmUmtsSubscriptionAppIndex = p.readInt(); cardStatus.mCdmaSubscriptionAppIndex = p.readInt(); cardStatus.mImsSubscriptionAppIndex = p.readInt(); int numApplications = p.readInt(); // limit to maximum allowed applications if (numApplications > IccCardStatus.CARD_MAX_APPS) { numApplications = IccCardStatus.CARD_MAX_APPS; } cardStatus.mApplications = new IccCardApplicationStatus[numApplications]; appStatus = new IccCardApplicationStatus(); for (int i = 0 ; i < numApplications ; i++) { if (i!=0) { appStatus = new IccCardApplicationStatus(); } appStatus.app_type = appStatus.AppTypeFromRILInt(p.readInt()); appStatus.app_state = appStatus.AppStateFromRILInt(p.readInt()); appStatus.perso_substate = appStatus.PersoSubstateFromRILInt(p.readInt()); appStatus.aid = p.readString(); appStatus.app_label = p.readString(); appStatus.pin1_replaced = p.readInt(); appStatus.pin1 = appStatus.PinStateFromRILInt(p.readInt()); appStatus.pin2 = appStatus.PinStateFromRILInt(p.readInt()); p.readInt(); // remaining_count_pin1 - pin1_num_retries p.readInt(); // remaining_count_puk1 - puk1_num_retries p.readInt(); // remaining_count_pin2 - pin2_num_retries p.readInt(); // remaining_count_puk2 - puk2_num_retries p.readInt(); // - perso_unblock_retries cardStatus.mApplications[i] = appStatus; } return cardStatus; } protected Object responseCallList(Parcel p) { int num; int voiceSettings; ArrayList<DriverCall> response; DriverCall dc; num = p.readInt(); response = new ArrayList<DriverCall>(num); if (RILJ_LOGV) { riljLog("responseCallList: num=" + num + " mEmergencyCallbackModeRegistrant=" + mEmergencyCallbackModeRegistrant + " mTestingEmergencyCall=" + mTestingEmergencyCall.get()); } for (int i = 0 ; i < num ; i++) { dc = new DriverCall(); dc.state = DriverCall.stateFromCLCC(p.readInt()); dc.index = p.readInt() & 0xff; dc.TOA = p.readInt(); dc.isMpty = (0 != p.readInt()); dc.isMT = (0 != p.readInt()); dc.als = p.readInt(); voiceSettings = p.readInt(); dc.isVoice = (0 == voiceSettings) ? false : true; p.readInt(); // samsung call detail p.readInt(); // samsung call detail p.readString(); // samsung call detail dc.isVoicePrivacy = (0 != p.readInt()); dc.number = p.readString(); int np = p.readInt(); dc.numberPresentation = DriverCall.presentationFromCLIP(np); dc.name = p.readString(); dc.namePresentation = p.readInt(); int uusInfoPresent = p.readInt(); if (uusInfoPresent == 1) { dc.uusInfo = new UUSInfo(); dc.uusInfo.setType(p.readInt()); dc.uusInfo.setDcs(p.readInt()); byte[] userData = p.createByteArray(); dc.uusInfo.setUserData(userData); riljLogv(String.format("Incoming UUS : type=%d, dcs=%d, length=%d", dc.uusInfo.getType(), dc.uusInfo.getDcs(), dc.uusInfo.getUserData().length)); riljLogv("Incoming UUS : data (string)=" + new String(dc.uusInfo.getUserData())); riljLogv("Incoming UUS : data (hex): " + IccUtils.bytesToHexString(dc.uusInfo.getUserData())); } else { riljLogv("Incoming UUS : NOT present!"); } // Make sure there's a leading + on addresses with a TOA of 145 dc.number = PhoneNumberUtils.stringFromStringAndTOA(dc.number, dc.TOA); response.add(dc); if (dc.isVoicePrivacy) { mVoicePrivacyOnRegistrants.notifyRegistrants(); riljLog("InCall VoicePrivacy is enabled"); } else { mVoicePrivacyOffRegistrants.notifyRegistrants(); riljLog("InCall VoicePrivacy is disabled"); } } Collections.sort(response); if ((num == 0) && mTestingEmergencyCall.getAndSet(false)) { if (mEmergencyCallbackModeRegistrant != null) { riljLog("responseCallList: call ended, testing emergency call," + " notify ECM Registrants"); mEmergencyCallbackModeRegistrant.notifyRegistrant(); } } return response; } @Override protected void processUnsolicited (Parcel p) { Object ret; int dataPosition = p.dataPosition(); // save off position within the Parcel int response = p.readInt(); switch(response) { // SAMSUNG STATES case 11010: // RIL_UNSOL_AM: ret = responseString(p); String amString = (String) ret; Rlog.d(RILJ_LOG_TAG, "Executing AM: " + amString); try { Runtime.getRuntime().exec("am " + amString); } catch (IOException e) { e.printStackTrace(); Rlog.e(RILJ_LOG_TAG, "am " + amString + " could not be executed."); } break; default: // Rewind the Parcel p.setDataPosition(dataPosition); if(DBG) Rlog.d("SHRILGET", "UNKNOWN UNSL: " + response); // Forward responses that we are not overriding to the super class super.processUnsolicited(p); return; } } @Override public void dial(String address, int clirMode, UUSInfo uusInfo, Message result) { if (PhoneNumberUtils.isEmergencyNumber(address)) { dialEmergencyCall(address, clirMode, result); return; } RILRequest rr = RILRequest.obtain(RIL_REQUEST_DIAL, result); rr.mParcel.writeString(address); rr.mParcel.writeInt(clirMode); rr.mParcel.writeInt(0); rr.mParcel.writeInt(1); rr.mParcel.writeString(""); if (uusInfo == null) { rr.mParcel.writeInt(0); // UUS information is absent } else { rr.mParcel.writeInt(1); // UUS information is present rr.mParcel.writeInt(uusInfo.getType()); rr.mParcel.writeInt(uusInfo.getDcs()); rr.mParcel.writeByteArray(uusInfo.getUserData()); } if (RILJ_LOGD) riljLog(rr.serialString() + "> " + requestToString(rr.mRequest)); send(rr); } static final int RIL_REQUEST_DIAL_EMERGENCY = 10001; private void dialEmergencyCall(String address, int clirMode, Message result) { RILRequest rr; Rlog.v(RILJ_LOG_TAG, "Emergency dial: " + address); rr = RILRequest.obtain(RIL_REQUEST_DIAL_EMERGENCY, result); rr.mParcel.writeString(address); rr.mParcel.writeInt(clirMode); rr.mParcel.writeInt(0); // CallDetails.call_type rr.mParcel.writeInt(3); // CallDetails.call_domain rr.mParcel.writeString(""); // CallDetails.getCsvFromExtra rr.mParcel.writeInt(0); // Unknown if (RILJ_LOGD) riljLog(rr.serialString() + "> " + requestToString(rr.mRequest)); send(rr); } @Override public void acceptCall (Message result) { RILRequest rr = RILRequest.obtain(RIL_REQUEST_ANSWER, result); if (RILJ_LOGD) riljLog(rr.serialString() + "> " + requestToString(rr.mRequest)); rr.mParcel.writeInt(1); rr.mParcel.writeInt(0); send(rr); } }
ril/telephony/java/com/android/internal/telephony/zeroRIL.java
/* * Copyright (C) 2012-2014 The CyanogenMod Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.internal.telephony; import static com.android.internal.telephony.RILConstants.*; import android.content.Context; import android.os.Message; import android.os.Parcel; import android.telephony.Rlog; import android.telephony.SignalStrength; import android.telephony.PhoneNumberUtils; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import com.android.internal.telephony.uicc.IccCardApplicationStatus; import com.android.internal.telephony.uicc.IccCardStatus; /** * RIL customization for Galaxy S6. * {@hide} */ public class zeroRIL extends RIL implements CommandsInterface { private boolean DBG = false; public zeroRIL(Context context, int preferredNetworkType, int cdmaSubscription, Integer instanceId) { super(context, preferredNetworkType, cdmaSubscription, instanceId); mQANElements = 6; } public zeroRIL(Context context, int networkMode, int cdmaSubscription) { super(context, networkMode, cdmaSubscription); mQANElements = 6; } @Override protected Object responseIccCardStatus(Parcel p) { IccCardApplicationStatus appStatus; IccCardStatus cardStatus = new IccCardStatus(); cardStatus.setCardState(p.readInt()); cardStatus.setUniversalPinState(p.readInt()); cardStatus.mGsmUmtsSubscriptionAppIndex = p.readInt(); cardStatus.mCdmaSubscriptionAppIndex = p.readInt(); cardStatus.mImsSubscriptionAppIndex = p.readInt(); int numApplications = p.readInt(); // limit to maximum allowed applications if (numApplications > IccCardStatus.CARD_MAX_APPS) { numApplications = IccCardStatus.CARD_MAX_APPS; } cardStatus.mApplications = new IccCardApplicationStatus[numApplications]; appStatus = new IccCardApplicationStatus(); for (int i = 0 ; i < numApplications ; i++) { if (i!=0) { appStatus = new IccCardApplicationStatus(); } appStatus.app_type = appStatus.AppTypeFromRILInt(p.readInt()); appStatus.app_state = appStatus.AppStateFromRILInt(p.readInt()); appStatus.perso_substate = appStatus.PersoSubstateFromRILInt(p.readInt()); appStatus.aid = p.readString(); appStatus.app_label = p.readString(); appStatus.pin1_replaced = p.readInt(); appStatus.pin1 = appStatus.PinStateFromRILInt(p.readInt()); appStatus.pin2 = appStatus.PinStateFromRILInt(p.readInt()); p.readInt(); // remaining_count_pin1 - pin1_num_retries p.readInt(); // remaining_count_puk1 - puk1_num_retries p.readInt(); // remaining_count_pin2 - pin2_num_retries p.readInt(); // remaining_count_puk2 - puk2_num_retries p.readInt(); // - perso_unblock_retries cardStatus.mApplications[i] = appStatus; } return cardStatus; } protected Object responseCallList(Parcel p) { int num; int voiceSettings; ArrayList<DriverCall> response; DriverCall dc; num = p.readInt(); response = new ArrayList<DriverCall>(num); if (RILJ_LOGV) { riljLog("responseCallList: num=" + num + " mEmergencyCallbackModeRegistrant=" + mEmergencyCallbackModeRegistrant + " mTestingEmergencyCall=" + mTestingEmergencyCall.get()); } for (int i = 0 ; i < num ; i++) { dc = new DriverCall(); dc.state = DriverCall.stateFromCLCC(p.readInt()); dc.index = p.readInt() & 0xff; dc.TOA = p.readInt(); dc.isMpty = (0 != p.readInt()); dc.isMT = (0 != p.readInt()); dc.als = p.readInt(); voiceSettings = p.readInt(); dc.isVoice = (0 == voiceSettings) ? false : true; p.readInt(); // samsung call detail p.readInt(); // samsung call detail p.readString(); // samsung call detail dc.isVoicePrivacy = (0 != p.readInt()); dc.number = p.readString(); int np = p.readInt(); dc.numberPresentation = DriverCall.presentationFromCLIP(np); dc.name = p.readString(); dc.namePresentation = p.readInt(); int uusInfoPresent = p.readInt(); if (uusInfoPresent == 1) { dc.uusInfo = new UUSInfo(); dc.uusInfo.setType(p.readInt()); dc.uusInfo.setDcs(p.readInt()); byte[] userData = p.createByteArray(); dc.uusInfo.setUserData(userData); riljLogv(String.format("Incoming UUS : type=%d, dcs=%d, length=%d", dc.uusInfo.getType(), dc.uusInfo.getDcs(), dc.uusInfo.getUserData().length)); riljLogv("Incoming UUS : data (string)=" + new String(dc.uusInfo.getUserData())); riljLogv("Incoming UUS : data (hex): " + IccUtils.bytesToHexString(dc.uusInfo.getUserData())); } else { riljLogv("Incoming UUS : NOT present!"); } // Make sure there's a leading + on addresses with a TOA of 145 dc.number = PhoneNumberUtils.stringFromStringAndTOA(dc.number, dc.TOA); response.add(dc); if (dc.isVoicePrivacy) { mVoicePrivacyOnRegistrants.notifyRegistrants(); riljLog("InCall VoicePrivacy is enabled"); } else { mVoicePrivacyOffRegistrants.notifyRegistrants(); riljLog("InCall VoicePrivacy is disabled"); } } Collections.sort(response); if ((num == 0) && mTestingEmergencyCall.getAndSet(false)) { if (mEmergencyCallbackModeRegistrant != null) { riljLog("responseCallList: call ended, testing emergency call," + " notify ECM Registrants"); mEmergencyCallbackModeRegistrant.notifyRegistrant(); } } return response; } @Override protected void processUnsolicited (Parcel p) { Object ret; int dataPosition = p.dataPosition(); // save off position within the Parcel int response = p.readInt(); switch(response) { // SAMSUNG STATES case 11010: // RIL_UNSOL_AM: ret = responseString(p); String amString = (String) ret; Rlog.d(RILJ_LOG_TAG, "Executing AM: " + amString); try { Runtime.getRuntime().exec("am " + amString); } catch (IOException e) { e.printStackTrace(); Rlog.e(RILJ_LOG_TAG, "am " + amString + " could not be executed."); } break; default: // Rewind the Parcel p.setDataPosition(dataPosition); if(DBG) Rlog.d("SHRILGET", "UNKNOWN UNSL: " + response); // Forward responses that we are not overriding to the super class super.processUnsolicited(p); return; } } @Override public void dial(String address, int clirMode, UUSInfo uusInfo, Message result) { if (PhoneNumberUtils.isEmergencyNumber(address)) { dialEmergencyCall(address, clirMode, result); return; } RILRequest rr = RILRequest.obtain(RIL_REQUEST_DIAL, result); rr.mParcel.writeString(address); rr.mParcel.writeInt(clirMode); rr.mParcel.writeInt(0); rr.mParcel.writeInt(1); rr.mParcel.writeString(""); if (uusInfo == null) { rr.mParcel.writeInt(0); // UUS information is absent } else { rr.mParcel.writeInt(1); // UUS information is present rr.mParcel.writeInt(uusInfo.getType()); rr.mParcel.writeInt(uusInfo.getDcs()); rr.mParcel.writeByteArray(uusInfo.getUserData()); } if (RILJ_LOGD) riljLog(rr.serialString() + "> " + requestToString(rr.mRequest)); send(rr); } static final int RIL_REQUEST_DIAL_EMERGENCY = 10001; private void dialEmergencyCall(String address, int clirMode, Message result) { RILRequest rr; Rlog.v(RILJ_LOG_TAG, "Emergency dial: " + address); rr = RILRequest.obtain(RIL_REQUEST_DIAL_EMERGENCY, result); rr.mParcel.writeString(address); rr.mParcel.writeInt(clirMode); rr.mParcel.writeInt(0); // CallDetails.call_type rr.mParcel.writeInt(3); // CallDetails.call_domain rr.mParcel.writeString(""); // CallDetails.getCsvFromExtra rr.mParcel.writeInt(0); // Unknown if (RILJ_LOGD) riljLog(rr.serialString() + "> " + requestToString(rr.mRequest)); send(rr); } @Override public void acceptCall (Message result) { RILRequest rr = RILRequest.obtain(RIL_REQUEST_ANSWER, result); if (RILJ_LOGD) riljLog(rr.serialString() + "> " + requestToString(rr.mRequest)); rr.mParcel.writeInt(1); rr.mParcel.writeInt(0); send(rr); } // This method is used in the search network functionality. // See mobile network setting -> network operators @Override protected Object responseOperatorInfos(Parcel p) { String strings[] = (String[])responseStrings(p); ArrayList<OperatorInfo> ret; if (strings.length % mQANElements != 0) { throw new RuntimeException("RIL_REQUEST_QUERY_AVAILABLE_NETWORKS: invalid response. Got " + strings.length + " strings, expected multiple of " + mQANElements); } ret = new ArrayList<OperatorInfo>(strings.length / mQANElements); for (int i = 0 ; i < strings.length ; i += mQANElements) { String strOperatorLong = strings[i+0]; String strOperatorNumeric = strings[i+2]; String strState = strings[i+3].toLowerCase(); Rlog.v(RILJ_LOG_TAG, "ss333: Add OperatorInfo: " + strOperatorLong + ", " + strOperatorLong + ", " + strOperatorNumeric + ", " + strState); ret.add(new OperatorInfo(strOperatorLong, // operatorAlphaLong strOperatorLong, // operatorAlphaShort strOperatorNumeric, // operatorNumeric strState)); // stateString } return ret; } }
zero: Remove overridden method for responseOperatorInfos * QANElements takes care of this Change-Id: Idb5a7fd132b4243a529b8ab3a6d7689e66f4fb4a Signed-off-by: Brandon McAnsh <[email protected]>
ril/telephony/java/com/android/internal/telephony/zeroRIL.java
zero: Remove overridden method for responseOperatorInfos
Java
bsd-2-clause
557153709d6ee4c951b48a8da981f03395296657
0
biovoxxel/imagej,TehSAUCE/imagej,TehSAUCE/imagej,TehSAUCE/imagej,biovoxxel/imagej,biovoxxel/imagej
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2013 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.script; import imagej.command.Command; import imagej.module.AbstractModuleInfo; import imagej.module.DefaultMutableModuleItem; import imagej.module.Module; import imagej.module.ModuleException; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.HashMap; import java.util.Map; import javax.script.ScriptException; import org.scijava.Context; import org.scijava.Contextual; import org.scijava.log.LogService; import org.scijava.plugin.Parameter; import org.scijava.service.Service; /** * Metadata about a script. * * @author Curtis Rueden * @author Johannes Schindelin */ public class ScriptInfo extends AbstractModuleInfo implements Contextual { private static final int PARAM_CHAR_MAX = 640 * 1024; // should be enough ;-) private final String path; private final BufferedReader reader; @Parameter private Context context; @Parameter private LogService log; private Map<String, Class<?>> typeMap; /** * Creates a script metadata object which describes the given script file. * * @param context The ImageJ application context to use when populating * service inputs. * @param file The script file. */ public ScriptInfo(final Context context, final File file) { this(context, file.getPath()); } /** * Creates a script metadata object which describes the given script file. * * @param context The ImageJ application context to use when populating * service inputs. * @param path Path to the script file. */ public ScriptInfo(final Context context, final String path) { this(context, path, null); } /** * Creates a script metadata object which describes a script provided by the * given {@link Reader}. * * @param context The ImageJ application context to use when populating * service inputs. * @param path Pseudo-path to the script file. This file does not actually * need to exist, but rather provides a name for the script with file * extension. * @param reader Reader which provides the script itself (i.e., its contents). */ public ScriptInfo(final Context context, final String path, final Reader reader) { setContext(context); this.path = path; this.reader = new BufferedReader(reader, PARAM_CHAR_MAX); try { parseInputs(); } catch (final ScriptException exc) { log.error(exc); } catch (final IOException exc) { log.error(exc); } } // -- ScriptInfo methods -- /** * Gets the path to the script on disk. * <p> * If the path doesn't actually exist on disk, then this is a pseudo-path * merely for the purpose of naming the script with a file extension, and the * actual script content is delivered by the {@link BufferedReader} given by * {@link #getReader()}. * </p> */ public String getPath() { return path; } /** * Gets the reader which delivers the script's content. * <p> * This might be null, in which case the content is stored in a file on disk * given by {@link #getPath()}. * </p> */ public BufferedReader getReader() { return reader; } /** * Parses the script's input parameters. * <p> * ImageJ's scripting framework supports specifying @{@link Parameter}-style * parameters in a preamble. The idea is to specify the input parameters in * this way: * * <pre> * // @UIService ui * // @double degrees * </pre> * * i.e. in the form <code>&#x40;&lt;type&gt; &lt;name&gt;</code>. These input * parameters will be parsed and filled just like @{@link Parameter} * -annotated fields in {@link Command}s. * </p> * * @throws ScriptException If a parameter annotation is malformed. * @throws IOException If there is a problem reading the script file. */ public void parseInputs() throws ScriptException, IOException { clearInputs(); final BufferedReader in; if (reader == null) { in = new BufferedReader(new FileReader(getPath())); } else { in = reader; in.mark(PARAM_CHAR_MAX); } while (true) { final String line = in.readLine(); if (line == null) break; // scan for lines containing an '@' stopping at the first line // containing at least one alpha-numerical character but no '@'. final int at = line.indexOf('@'); if (at < 0) { if (line.matches(".*[A-Za-z0-9].*")) break; continue; } parseInput(line.substring(at + 1)); } if (reader == null) in.close(); else in.reset(); } // -- ModuleInfo methods -- @Override public String getDelegateClassName() { return ScriptModule.class.getName(); } @Override public Module createModule() throws ModuleException { return new ScriptModule(this); } // -- Contextual methods -- @Override public Context getContext() { return context; } @Override public void setContext(final Context context) { context.inject(this); } // -- Helper methods -- private <T> void parseInput(final String line) throws ScriptException { final String[] parts = line.trim().split("[ \t\n]+"); if (parts.length != 2) { throw new ScriptException("Expected 'type name': " + line); } addInput(parts[1], parseType(parts[0])); } private <T> void addInput(final String name, final Class<T> type) { final DefaultMutableModuleItem<T> item = new DefaultMutableModuleItem<T>(this, name, type); inputMap.put(item.getName(), item); inputList.add(item); } private void clearInputs() { inputMap.clear(); inputList.clear(); } private synchronized Class<?> parseType(final String string) throws ScriptException { if (typeMap == null) { typeMap = new HashMap<String, Class<?>>(); typeMap.put("byte", Byte.TYPE); typeMap.put("short", Short.TYPE); typeMap.put("int", Integer.TYPE); typeMap.put("long", Long.TYPE); typeMap.put("float", Float.TYPE); typeMap.put("double", Double.TYPE); typeMap.put("String", String.class); typeMap.put("File", File.class); for (final Service service : context.getServiceIndex()) { final Class<?> clazz = service.getClass(); final String className = clazz.getName(); typeMap.put(className, clazz); final int dot = className.lastIndexOf('.'); if (dot > 0) typeMap.put(className.substring(dot + 1), clazz); } } final Class<?> type = typeMap.get(string); if (type == null) { try { final Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(string); typeMap.put(string, clazz); return clazz; } catch (final ClassNotFoundException e) { throw new ScriptException("Unknown type: " + string); } } return type; } }
core/core/src/main/java/imagej/script/ScriptInfo.java
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2013 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.script; import imagej.command.Command; import imagej.module.AbstractModuleInfo; import imagej.module.DefaultMutableModuleItem; import imagej.module.Module; import imagej.module.ModuleException; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.HashMap; import java.util.Map; import javax.script.ScriptException; import org.scijava.Context; import org.scijava.Contextual; import org.scijava.log.LogService; import org.scijava.plugin.Parameter; import org.scijava.service.Service; /** * Metadata about a script. * * @author Curtis Rueden * @author Johannes Schindelin */ public class ScriptInfo extends AbstractModuleInfo implements Contextual { private static final int PARAM_CHAR_MAX = 640 * 1024; // should be enough ;-) private final String path; private final BufferedReader reader; @Parameter private Context context; @Parameter private LogService log; private Map<String, Class<?>> typeMap; /** * Creates a script metadata object which describes the given script file. * * @param context The ImageJ application context to use when populating * service inputs. * @param file The script file. */ public ScriptInfo(final Context context, final File file) { this(context, file.getPath()); } /** * Creates a script metadata object which describes the given script file. * * @param context The ImageJ application context to use when populating * service inputs. * @param path Path to the script file. */ public ScriptInfo(final Context context, final String path) { this(context, path, null); } /** * Creates a script metadata object which describes a script provided by the * given {@link Reader}. * * @param context The ImageJ application context to use when populating * service inputs. * @param path Pseudo-path to the script file. This file does not actually * need to exist, but rather provides a name for the script with file * extension. * @param reader Reader which provides the script itself (i.e., its contents). */ public ScriptInfo(final Context context, final String path, final Reader reader) { setContext(context); this.path = path; this.reader = new BufferedReader(reader, PARAM_CHAR_MAX); try { parseInputs(); } catch (final ScriptException exc) { log.error(exc); } catch (final IOException exc) { log.error(exc); } } // -- ScriptInfo methods -- /** * Gets the path to the script on disk. * <p> * If the path doesn't actually exist on disk, then this is a pseudo-path * merely for the purpose of naming the script with a file extension, and the * actual script content is delivered by the {@link BufferedReader} given by * {@link #getReader()}. * </p> */ public String getPath() { return path; } /** * Gets the reader which delivers the script's content. * <p> * This might be null, in which case the content is stored in a file on disk * given by {@link #getPath()}. * </p> */ public BufferedReader getReader() { return reader; } /** * Parses the script's input parameters. * <p> * ImageJ's scripting framework supports specifying @{@link Parameter}-style * parameters in a preamble. The idea is to specify the input parameters in * this way: * * <pre> * // @UIService ui * // @double degrees * </pre> * * i.e. in the form <code>&#x40;&lt;type&gt; &lt;name&gt;</code>. These input * parameters will be parsed and filled just like @{@link Parameter} * -annotated fields in {@link Command}s. * </p> * * @throws ScriptException If a parameter annotation is malformed. * @throws IOException If there is a problem reading the script file. */ public void parseInputs() throws ScriptException, IOException { clearInputs(); final BufferedReader in; if (reader == null) { in = new BufferedReader(new FileReader(getPath())); } else { in = reader; in.mark(PARAM_CHAR_MAX); } while (true) { final String line = in.readLine(); if (line == null) break; // scan for lines containing an '@' stopping at the first line // containing at least one alpha-numerical character but no '@'. final int at = line.indexOf('@'); if (at < 0) { if (line.matches(".*[A-Za-z0-9].*")) break; continue; } parseInput(line.substring(at + 1)); } if (reader == null) in.close(); else in.reset(); } // -- ModuleInfo methods -- @Override public String getDelegateClassName() { return ScriptModule.class.getName(); } @Override public Module createModule() throws ModuleException { return new ScriptModule(this); } // -- Contextual methods -- @Override public Context getContext() { return context; } @Override public void setContext(final Context context) { context.inject(this); } // -- Helper methods -- private <T> void parseInput(final String line) throws ScriptException { final String[] parts = line.trim().split("[ \t\n]+"); if (parts.length != 2) { throw new ScriptException("Expected 'type name': " + line); } addInput(parts[1], parseType(parts[0])); } private <T> void addInput(final String name, final Class<T> type) { final DefaultMutableModuleItem<T> item = new DefaultMutableModuleItem<T>(this, name, type); inputMap.put(name, item); inputList.add(item); } private void clearInputs() { inputMap.clear(); inputList.clear(); } private synchronized Class<?> parseType(final String string) throws ScriptException { if (typeMap == null) { typeMap = new HashMap<String, Class<?>>(); typeMap.put("byte", Byte.TYPE); typeMap.put("short", Short.TYPE); typeMap.put("int", Integer.TYPE); typeMap.put("long", Long.TYPE); typeMap.put("float", Float.TYPE); typeMap.put("double", Double.TYPE); typeMap.put("String", String.class); typeMap.put("File", File.class); for (final Service service : context.getServiceIndex()) { final Class<?> clazz = service.getClass(); final String className = clazz.getName(); typeMap.put(className, clazz); final int dot = className.lastIndexOf('.'); if (dot > 0) typeMap.put(className.substring(dot + 1), clazz); } } final Class<?> type = typeMap.get(string); if (type == null) { try { final Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(string); typeMap.put(string, clazz); return clazz; } catch (final ClassNotFoundException e) { throw new ScriptException("Unknown type: " + string); } } return type; } }
ScriptInfo: grab name directly from ModuleItem
core/core/src/main/java/imagej/script/ScriptInfo.java
ScriptInfo: grab name directly from ModuleItem
Java
bsd-2-clause
f8ce18ebf452d029128057863d4f6091299aee54
0
Fedict/dcattools
/* * Copyright (c) 2015, Bart Hanssens <[email protected]> * 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. * * 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 be.fedict.dcat.datagovbe; import be.fedict.dcat.helpers.Storage; import be.fedict.dcat.vocab.DCAT; import be.fedict.dcat.vocab.DATAGOVBE; import be.fedict.dcat.vocab.MDR_LANG; import com.google.common.collect.ListMultimap; import java.io.IOException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.json.Json; import javax.json.JsonArrayBuilder; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.net.ssl.SSLContext; import org.apache.http.Header; import org.apache.http.HttpHeaders; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.LaxRedirectStrategy; import org.apache.http.ssl.SSLContexts; import org.openrdf.model.URI; import org.openrdf.model.vocabulary.DCTERMS; import org.openrdf.repository.RepositoryException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Drupal REST service class. * * @author Bart Hanssens <[email protected]> */ public class Drupal { private final Logger logger = LoggerFactory.getLogger(Drupal.class); public final static String PROP_PREFIX = "be.fedict.datagovbe7"; public final static String NODE = "/node"; public final static String TOKEN = "/restws/session/token"; public final static String X_TOKEN = "X-CSRF-Token"; public final static String POST = "Post"; public final static String PUT = "Put"; // Drupal fields public final static String TITLE = "title"; public final static String BODY = "body"; public final static String LANGUAGE = "language"; public final static String URL = "url"; public final static String AUTHOR = "author"; public final static String MODIFIED = "changed_date"; public final static String FLD_CAT = "field_category"; public final static String FLD_DETAILS = "field_details_"; public final static String FLD_FORMAT = "field_file_type"; public final static String FLD_GEO = "field_geo_coverage"; public final static String FLD_KEYWORDS = "field_keywords"; public final static String FLD_LICENSE = "field_license"; public final static String FLD_LINKS = "field_links_"; public final static String FLD_ID = "field_id"; public final static String FLD_PUBLISHER = "field_publisher"; public final static String FLD_UPSTAMP = "field_upstamp"; public final static String ID = "id"; public final static String TYPE = "type"; public final static String TYPE_DATA = "dataset"; public final static String FORMAT = "format"; public final static String FORMAT_HTML = "filtered_html"; public final static String SOURCE = "source"; public final static String SUMMARY = "summary"; public final static String VALUE = "value"; public final static String TAXO_PREFIX = "http://data.gov.be/en/taxonomy"; public final static Pattern SHORTLINK = Pattern.compile("/([0-9]+)>; rel=\"shortlink\""); public final static int LEN_TITLE = 128; public final static int LEN_LINK = 255; private final String[] langs; private final URL url; private String userid; private Executor exec; private HttpHost proxy = null; private HttpHost host = null; private String token = null; private SimpleDateFormat iso = new SimpleDateFormat("yyyy-MM-dd"); /** * Return shorter version of string, with trailing ellipsis (...) * * @param s string * @param len maximum length */ private static String ellipsis(String s, int len) { int cut = s.lastIndexOf(" ", len - 3); if (cut < 0) { cut = 125; } return s.substring(0, cut) + "..."; } /** * Prepare a POST or PUT action. * * @param method POST or PUT * @param relpath relative path * @return */ private Request prepare(String method, String relpath) { String u = this.url.toString() + relpath; Request r = method.equals(Drupal.POST) ? Request.Post(u) : Request.Put(u); r.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType()) .setHeader(Drupal.X_TOKEN, token); if (proxy != null) { r.viaProxy(proxy); } return r; } /** * Decode "\\u..." to a character. * * @param s * @return */ private String decode(String s) { return new String(s.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1); } /** * Get multiple values from map structure. * * @param map * @param prop * @param lang * @return */ private List<String> getMany(Map<URI, ListMultimap<String, String>> map, URI prop, String lang) { List<String> res = new ArrayList<>(); ListMultimap<String, String> multi = map.get(prop); if (multi != null && !multi.isEmpty()) { List<String> list = multi.get(lang); if (list != null && !list.isEmpty()) { res = list; } } return res; } /** * Get one value from map structure. * * @param map * @param prop * @param lang * @return */ private String getOne(Map<URI, ListMultimap<String, String>> map, URI prop, String lang) { String res = ""; ListMultimap<String, String> multi = map.get(prop); if (multi != null && !multi.isEmpty()) { List<String> list = multi.get(lang); if (list != null && !list.isEmpty()) { res = list.get(0); } } return res; } /** * Add a DCAT Theme / category * * @param dataset * @param property */ private JsonArrayBuilder getCategories( Map<URI, ListMultimap<String, String>> dataset, URI property) { JsonArrayBuilder arr = Json.createArrayBuilder(); List<String> themes = getMany(dataset, property, ""); for(String theme : themes) { if (theme.startsWith(Drupal.TAXO_PREFIX)) { String id = theme.substring(theme.lastIndexOf("/") + 1); arr.add(Json.createObjectBuilder().add(Drupal.ID, id).build()); } } return arr; } /** * Check if dataset with ID already exists on drupal site. * * @param id * @param lang * @return */ private String checkExists(String id, String lang) { String node = ""; String u = this.url.toString() + "/" + lang + "/" + Drupal.TYPE_DATA + "/" + id; Request r = Request.Head(u); if (proxy != null) { r.viaProxy(proxy); } try { HttpResponse resp = exec.execute(r).returnResponse(); Header header = resp.getFirstHeader("Link"); if (header != null) { Matcher m = SHORTLINK.matcher(header.getValue()); if (m.find()) { node = m.group(1); logger.info("Dataset {} exists, node {}", id, node); } } } catch (IOException ex) { logger.error("Exception getting dataset {}", id); } return node; } /** * Check if node or translations exist. * * @param builder * @param id * @param lang * @return */ private String checkExistsTrans(JsonObjectBuilder builder, String id, String lang) { String node = checkExists(id, lang); // Exists in another language ? if (node.isEmpty()) { for (String otherlang : langs) { if (!otherlang.equals(lang)) { node = checkExists(id, otherlang); if (! node.isEmpty()) { builder.add(Drupal.SOURCE, Json.createObjectBuilder() .add(otherlang, Integer.parseInt(node))); node = ""; } } } } return node; } /** * Add a dataset to Drupal form * * @param builder * @param dataset * @param lang */ private void addDataset(JsonObjectBuilder builder, Map<URI, ListMultimap<String, String>> dataset, String lang) { String id = getOne(dataset, DCTERMS.IDENTIFIER, ""); String title = getOne(dataset, DCTERMS.TITLE, lang); // Just copy the title if description is empty String desc = getOne(dataset, DCTERMS.DESCRIPTION, lang); if (desc.isEmpty()) { desc = title; } // Max size for Drupal title if (title.length() > Drupal.LEN_TITLE) { logger.warn("Title {} too long", title); title = ellipsis(title, Drupal.LEN_TITLE); } // Modified date of the metadata Date modif = new Date(); String m = getOne(dataset, DCTERMS.MODIFIED, ""); if (! m.isEmpty() && (m.length() >= 10)) { try { modif = iso.parse(m.substring(0, 10)); } catch (ParseException ex) { logger.error("Exception parsing {} as date", m); } } JsonArrayBuilder keywords = Json.createArrayBuilder(); List<String> words = getMany(dataset, DCAT.KEYWORD, lang); for(String word : words) { // keywords.add(word); } builder.add(Drupal.TYPE, Drupal.TYPE_DATA) .add(Drupal.LANGUAGE, lang) .add(Drupal.AUTHOR, Json.createObjectBuilder().add(Drupal.ID, userid)) .add(Drupal.TITLE, title) .add(Drupal.BODY, Json.createObjectBuilder() .add(Drupal.VALUE, desc) .add(Drupal.SUMMARY, "") .add(Drupal.FORMAT, Drupal.FORMAT_HTML)) .add(Drupal.FLD_UPSTAMP, modif.getTime()/1000L) .add(Drupal.FLD_LICENSE, getCategories(dataset, DATAGOVBE.LICENSE)) .add(Drupal.FLD_CAT, getCategories(dataset, DATAGOVBE.THEME)) .add(Drupal.FLD_GEO, getCategories(dataset, DATAGOVBE.SPATIAL)) .add(Drupal.FLD_PUBLISHER, getCategories(dataset, DATAGOVBE.ORG)) .add(Drupal.FLD_KEYWORDS, keywords) .add(Drupal.FLD_ID, id); } /** * * @param dist * @param property * @return */ private String getLink(Map<URI, ListMultimap<String, String>> dist, URI property) { String link = ""; String l = getOne(dist, property, ""); if (! l.isEmpty()) { link = l.replaceAll(" ", "%20"); } if (link.length() > Drupal.LEN_LINK) { logger.warn("Download URL too long ({}): {} ", l.length(), l); } return link; } /** * Add DCAT distribution * * @param store RDF store * @param uri distribution URI * @param lang language * @param builder JSON builder * @param accesses landing pages array * @param downloads download pages array * @throws RepositoryException */ private void addDist(Storage store, String uri, String lang, JsonObjectBuilder builder, JsonArrayBuilder accesses, JsonArrayBuilder downloads) throws RepositoryException { Map<URI, ListMultimap<String, String>> dist = store.queryProperties(store.getURI(uri)); String distlang = getLink(dist, DCTERMS.LANGUAGE); logger.info(distlang); logger.info(lang); logger.info(MDR_LANG.MAP.get(lang).toString()); if (MDR_LANG.MAP.get(lang).toString().equals(distlang)) { // Landing page / page(s) with more info on dataset String access = getLink(dist, DCAT.ACCESS_URL); if (! access.isEmpty()) { accesses.add(Json.createObjectBuilder().add(Drupal.URL, access)); } // Download URL String download = getLink(dist, DCAT.DOWNLOAD_URL); if (! download.isEmpty()) { downloads.add(Json.createObjectBuilder().add(Drupal.URL, download)); } builder.add(Drupal.FLD_FORMAT, getCategories(dist, DATAGOVBE.MEDIA_TYPE)); } } /** * Add a dataset to the Drupal website. * * @param store RDF store * @param uri identifier of the dataset * @throws RepositoryException */ private void add(Storage store, URI uri) throws RepositoryException { Map<URI, ListMultimap<String, String>> dataset = store.queryProperties(uri); if (dataset.isEmpty()) { logger.warn("Empty dataset for {}", uri.stringValue()); return; } for(String lang : langs) { JsonObjectBuilder builder = Json.createObjectBuilder(); addDataset(builder, dataset, lang); // Get DCAT distributions List<String> dists = getMany(dataset, DCAT.DISTRIBUTION, ""); JsonArrayBuilder accesses = Json.createArrayBuilder(); JsonArrayBuilder downloads = Json.createArrayBuilder(); for (String dist : dists) { addDist(store, dist, lang, builder, accesses, downloads); } builder.add(Drupal.FLD_DETAILS + lang, accesses); builder.add(Drupal.FLD_LINKS + lang, downloads); // Add new or update existing dataset ? String id = getOne(dataset, DCTERMS.IDENTIFIER, ""); String node = checkExistsTrans(builder, id, lang); // Build the JSON array JsonObject obj = builder.build(); logger.debug(obj.toString()); Request r = node.isEmpty() ? prepare(Drupal.POST, Drupal.NODE) : prepare(Drupal.PUT, Drupal.NODE + "/" + node); r.bodyString(obj.toString(), ContentType.APPLICATION_JSON); try { String resp = exec.authPreemptive(host) .execute(r) .returnContent().asString(); } catch (IOException ex) { logger.error("Could not update {}", uri.toString(), ex); } } } /** * Set username and password. * * @param user username * @param password password * @param userid drupal user ID */ public void setUserPassID(String user, String password, String userid) { exec = exec.clearAuth().clearCookies() .auth(host, user, password); this.userid = userid; } /** * Set HTTP proxy. * * @param proxy proxy server * @param port proxy port */ public void setProxy(String proxy, int port) { if (proxy == null || proxy.isEmpty()) { this.proxy = null; } else { this.proxy = new HttpHost(proxy, port); } } /** * Get CSRF Token * * @throws IOException */ private void getCSRFToken() throws IOException { Request r = Request.Get(this.url.toString() + Drupal.TOKEN) .setHeader(HttpHeaders.CACHE_CONTROL, "no-cache"); if (proxy != null) { r.viaProxy(proxy); } token = exec.authPreemptive(host) .execute(r) .returnContent().asString(); logger.debug("CSRF Token is {}", token); } /** * Update site * * @param store triple store containing the info * @throws IOException * @throws org.openrdf.repository.RepositoryException */ public void update(Storage store) throws IOException, RepositoryException { List<URI> datasets = store.query(DCAT.A_DATASET); logger.info("Updating {} datasets...", Integer.toString(datasets.size())); getCSRFToken(); int i = 0; for (URI d : datasets) { add(store, d); if (++i % 100 == 0) { logger.info("Updated {}", Integer.toString(i)); } } logger.info("Done updating datasets"); } /** * Drupal REST Service. * * @param url service endpoint * @param langs languages */ public Drupal(URL url, String[] langs) { this.url = url; this.langs = langs; this.host = new HttpHost(url.getHost()); Executor e = null; try { /* Self signed certificates are OK */ SSLContext ctx = SSLContexts.custom() .loadTrustMaterial(new TrustSelfSignedStrategy()).build(); /* Allow redirect on POST */ CloseableHttpClient client = HttpClients.custom() .setRedirectStrategy(new LaxRedirectStrategy()) .setSSLContext(ctx) .build(); e = Executor.newInstance(client); } catch (NoSuchAlgorithmException ex) { logger.error("Algo error", ex); } catch (KeyStoreException|KeyManagementException ex) { logger.error("Store exception", ex); } this.exec = e; } }
datagovbe/src/main/java/be/fedict/dcat/datagovbe/Drupal.java
/* * Copyright (c) 2015, Bart Hanssens <[email protected]> * 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. * * 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 be.fedict.dcat.datagovbe; import be.fedict.dcat.helpers.Storage; import be.fedict.dcat.vocab.DCAT; import be.fedict.dcat.vocab.DATAGOVBE; import be.fedict.dcat.vocab.MDR_LANG; import com.google.common.collect.ListMultimap; import java.io.IOException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.json.Json; import javax.json.JsonArrayBuilder; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.net.ssl.SSLContext; import org.apache.http.Header; import org.apache.http.HttpHeaders; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.LaxRedirectStrategy; import org.apache.http.ssl.SSLContexts; import org.openrdf.model.URI; import org.openrdf.model.vocabulary.DCTERMS; import org.openrdf.repository.RepositoryException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Drupal REST service class. * * @author Bart Hanssens <[email protected]> */ public class Drupal { private final Logger logger = LoggerFactory.getLogger(Drupal.class); public final static String PROP_PREFIX = "be.fedict.datagovbe7"; public final static String NODE = "/node"; public final static String TOKEN = "/restws/session/token"; public final static String X_TOKEN = "X-CSRF-Token"; public final static String POST = "Post"; public final static String PUT = "Put"; // Drupal fields public final static String TITLE = "title"; public final static String BODY = "body"; public final static String LANGUAGE = "language"; public final static String URL = "url"; public final static String AUTHOR = "author"; public final static String MODIFIED = "changed_date"; public final static String FLD_CAT = "field_category"; public final static String FLD_DETAILS = "field_details_"; public final static String FLD_FORMAT = "field_file_type"; public final static String FLD_GEO = "field_geo_coverage"; public final static String FLD_KEYWORDS = "field_keywords"; public final static String FLD_LICENSE = "field_license"; public final static String FLD_LINKS = "field_links_"; public final static String FLD_ID = "field_id"; public final static String FLD_PUBLISHER = "field_publisher"; public final static String FLD_UPSTAMP = "field_upstamp"; public final static String ID = "id"; public final static String TYPE = "type"; public final static String TYPE_DATA = "dataset"; public final static String FORMAT = "format"; public final static String FORMAT_HTML = "filtered_html"; public final static String SOURCE = "source"; public final static String SUMMARY = "summary"; public final static String VALUE = "value"; public final static String TAXO_PREFIX = "http://data.gov.be/en/taxonomy"; public final static Pattern SHORTLINK = Pattern.compile("/([0-9]+)>; rel=\"shortlink\""); private final String[] langs; private final URL url; private String userid; private Executor exec; private HttpHost proxy = null; private HttpHost host = null; private String token = null; private SimpleDateFormat iso = new SimpleDateFormat("yyyy-MM-dd"); /** * Prepare a POST or PUT action. * * @param method POST or PUT * @param relpath relative path * @return */ private Request prepare(String method, String relpath) { String u = this.url.toString() + relpath; Request r = method.equals(Drupal.POST) ? Request.Post(u) : Request.Put(u); r.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType()) .setHeader(Drupal.X_TOKEN, token); if (proxy != null) { r.viaProxy(proxy); } return r; } /** * Decode "\\u..." to a character. * * @param s * @return */ private String decode(String s) { return new String(s.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1); } /** * Get multiple values from map structure. * * @param map * @param prop * @param lang * @return */ private List<String> getMany(Map<URI, ListMultimap<String, String>> map, URI prop, String lang) { List<String> res = new ArrayList<>(); ListMultimap<String, String> multi = map.get(prop); if (multi != null && !multi.isEmpty()) { List<String> list = multi.get(lang); if (list != null && !list.isEmpty()) { res = list; } } return res; } /** * Get one value from map structure. * * @param map * @param prop * @param lang * @return */ private String getOne(Map<URI, ListMultimap<String, String>> map, URI prop, String lang) { String res = ""; ListMultimap<String, String> multi = map.get(prop); if (multi != null && !multi.isEmpty()) { List<String> list = multi.get(lang); if (list != null && !list.isEmpty()) { res = list.get(0); } } return res; } /** * Add a DCAT Theme / category * * @param dataset * @param property */ private JsonArrayBuilder getCategories( Map<URI, ListMultimap<String, String>> dataset, URI property) { JsonArrayBuilder arr = Json.createArrayBuilder(); List<String> themes = getMany(dataset, property, ""); for(String theme : themes) { if (theme.startsWith(Drupal.TAXO_PREFIX)) { String id = theme.substring(theme.lastIndexOf("/") + 1); arr.add(Json.createObjectBuilder().add(Drupal.ID, id).build()); } } return arr; } /** * Check if dataset with ID already exists on drupal site. * * @param id * @param lang * @return */ private String checkExists(String id, String lang) { String node = ""; String u = this.url.toString() + "/" + lang + "/" + Drupal.TYPE_DATA + "/" + id; Request r = Request.Head(u); if (proxy != null) { r.viaProxy(proxy); } try { HttpResponse resp = exec.execute(r).returnResponse(); Header header = resp.getFirstHeader("Link"); if (header != null) { Matcher m = SHORTLINK.matcher(header.getValue()); if (m.find()) { node = m.group(1); logger.info("Dataset {} exists, node {}", id, node); } } } catch (IOException ex) { logger.error("Exception getting dataset {}", id); } return node; } /** * Check if node or translations exist. * * @param builder * @param id * @param lang * @return */ private String checkExistsTrans(JsonObjectBuilder builder, String id, String lang) { String node = checkExists(id, lang); // Exists in another language ? if (node.isEmpty()) { for (String otherlang : langs) { if (!otherlang.equals(lang)) { node = checkExists(id, otherlang); if (! node.isEmpty()) { builder.add(Drupal.SOURCE, Json.createObjectBuilder() .add(otherlang, Integer.parseInt(node))); node = ""; } } } } return node; } /** * Add a dataset to Drupal form * * @param builder * @param dataset * @param lang */ private void addDataset(JsonObjectBuilder builder, Map<URI, ListMultimap<String, String>> dataset, String lang) { String id = getOne(dataset, DCTERMS.IDENTIFIER, ""); String title = getOne(dataset, DCTERMS.TITLE, lang); String desc = getOne(dataset, DCTERMS.DESCRIPTION, lang); if (desc.isEmpty()) { desc = title; } Date modif = new Date(); String m = getOne(dataset, DCTERMS.MODIFIED, ""); if (! m.isEmpty() && (m.length() >= 10)) { try { modif = iso.parse(m.substring(0, 10)); } catch (ParseException ex) { logger.error("Exception parsing {} as date", m); } } JsonArrayBuilder keywords = Json.createArrayBuilder(); List<String> words = getMany(dataset, DCAT.KEYWORD, lang); for(String word : words) { // keywords.add(word); } builder.add(Drupal.TYPE, Drupal.TYPE_DATA) .add(Drupal.LANGUAGE, lang) .add(Drupal.AUTHOR, Json.createObjectBuilder().add(Drupal.ID, userid)) .add(Drupal.TITLE, title) .add(Drupal.BODY, Json.createObjectBuilder() .add(Drupal.VALUE, desc) .add(Drupal.SUMMARY, "") .add(Drupal.FORMAT, Drupal.FORMAT_HTML)) .add(Drupal.FLD_UPSTAMP, modif.getTime()/1000L) .add(Drupal.FLD_LICENSE, getCategories(dataset, DATAGOVBE.LICENSE)) .add(Drupal.FLD_CAT, getCategories(dataset, DATAGOVBE.THEME)) .add(Drupal.FLD_GEO, getCategories(dataset, DATAGOVBE.SPATIAL)) .add(Drupal.FLD_PUBLISHER, getCategories(dataset, DATAGOVBE.ORG)) .add(Drupal.FLD_KEYWORDS, keywords) .add(Drupal.FLD_ID, id); } /** * * @param dist * @param property * @return */ private String getLink(Map<URI, ListMultimap<String, String>> dist, URI property) { String link = ""; String l = getOne(dist, property, ""); if (! l.isEmpty()) { link = l.replaceAll(" ", "%20"); } if (link.length() > 255) { logger.warn("Download URL too long ({}): {} ", l.length(), l); } return link; } /** * Add DCAT distribution * * @param store RDF store * @param uri distribution URI * @param lang language * @param builder JSON builder * @param accesses landing pages array * @param downloads download pages array * @throws RepositoryException */ private void addDist(Storage store, String uri, String lang, JsonObjectBuilder builder, JsonArrayBuilder accesses, JsonArrayBuilder downloads) throws RepositoryException { Map<URI, ListMultimap<String, String>> dist = store.queryProperties(store.getURI(uri)); String distlang = getLink(dist, DCTERMS.LANGUAGE); logger.info(distlang); logger.info(lang); logger.info(MDR_LANG.MAP.get(lang).toString()); if (MDR_LANG.MAP.get(lang).toString().equals(distlang)) { // Landing page / page(s) with more info on dataset String access = getLink(dist, DCAT.ACCESS_URL); if (! access.isEmpty()) { accesses.add(Json.createObjectBuilder().add(Drupal.URL, access)); } // Download URL String download = getLink(dist, DCAT.DOWNLOAD_URL); if (! download.isEmpty()) { downloads.add(Json.createObjectBuilder().add(Drupal.URL, download)); } builder.add(Drupal.FLD_FORMAT, getCategories(dist, DATAGOVBE.MEDIA_TYPE)); } } /** * Add a dataset to the Drupal website. * * @param store RDF store * @param uri identifier of the dataset * @throws RepositoryException */ private void add(Storage store, URI uri) throws RepositoryException { Map<URI, ListMultimap<String, String>> dataset = store.queryProperties(uri); if (dataset.isEmpty()) { logger.warn("Empty dataset for {}", uri.stringValue()); return; } for(String lang : langs) { JsonObjectBuilder builder = Json.createObjectBuilder(); addDataset(builder, dataset, lang); // Get DCAT distributions List<String> dists = getMany(dataset, DCAT.DISTRIBUTION, ""); JsonArrayBuilder accesses = Json.createArrayBuilder(); JsonArrayBuilder downloads = Json.createArrayBuilder(); for (String dist : dists) { addDist(store, dist, lang, builder, accesses, downloads); } builder.add(Drupal.FLD_DETAILS + lang, accesses); builder.add(Drupal.FLD_LINKS + lang, downloads); // Add new or update existing dataset ? String id = getOne(dataset, DCTERMS.IDENTIFIER, ""); String node = checkExistsTrans(builder, id, lang); // Build the JSON array JsonObject obj = builder.build(); logger.debug(obj.toString()); Request r = node.isEmpty() ? prepare(Drupal.POST, Drupal.NODE) : prepare(Drupal.PUT, Drupal.NODE + "/" + node); r.bodyString(obj.toString(), ContentType.APPLICATION_JSON); try { String resp = exec.authPreemptive(host) .execute(r) .returnContent().asString(); } catch (IOException ex) { logger.error("Could not update {}", uri.toString(), ex); } } } /** * Set username and password. * * @param user username * @param password password * @param userid drupal user ID */ public void setUserPassID(String user, String password, String userid) { exec = exec.clearAuth().clearCookies() .auth(host, user, password); this.userid = userid; } /** * Set HTTP proxy. * * @param proxy proxy server * @param port proxy port */ public void setProxy(String proxy, int port) { if (proxy == null || proxy.isEmpty()) { this.proxy = null; } else { this.proxy = new HttpHost(proxy, port); } } /** * Get CSRF Token * * @throws IOException */ private void getCSRFToken() throws IOException { Request r = Request.Get(this.url.toString() + Drupal.TOKEN) .setHeader(HttpHeaders.CACHE_CONTROL, "no-cache"); if (proxy != null) { r.viaProxy(proxy); } token = exec.authPreemptive(host) .execute(r) .returnContent().asString(); logger.debug("CSRF Token is {}", token); } /** * Update site * * @param store triple store containing the info * @throws IOException * @throws org.openrdf.repository.RepositoryException */ public void update(Storage store) throws IOException, RepositoryException { List<URI> datasets = store.query(DCAT.A_DATASET); logger.info("Updating {} datasets...", Integer.toString(datasets.size())); getCSRFToken(); int i = 0; for (URI d : datasets) { add(store, d); if (++i % 100 == 0) { logger.info("Updated {}", Integer.toString(i)); } } logger.info("Done updating datasets"); } /** * Drupal REST Service. * * @param url service endpoint * @param langs languages */ public Drupal(URL url, String[] langs) { this.url = url; this.langs = langs; this.host = new HttpHost(url.getHost()); Executor e = null; try { /* Self signed certificates are OK */ SSLContext ctx = SSLContexts.custom() .loadTrustMaterial(new TrustSelfSignedStrategy()).build(); /* Allow redirect on POST */ CloseableHttpClient client = HttpClients.custom() .setRedirectStrategy(new LaxRedirectStrategy()) .setSSLContext(ctx) .build(); e = Executor.newInstance(client); } catch (NoSuchAlgorithmException ex) { logger.error("Algo error", ex); } catch (KeyStoreException|KeyManagementException ex) { logger.error("Store exception", ex); } this.exec = e; } }
Added max length for node title
datagovbe/src/main/java/be/fedict/dcat/datagovbe/Drupal.java
Added max length for node title
Java
bsd-2-clause
de1630871a7fd272da58d6f6e0b16b66d7a01ea2
0
VRL-Studio/JVTK
/* * Copyright 2012 Michael Hoffer <[email protected]>. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY Michael Hoffer <[email protected]> "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 Michael Hoffer <[email protected]> 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 Michael Hoffer <[email protected]>. */ package eu.mihosoft.vtk; import java.awt.*; import java.awt.color.ColorSpace; import java.awt.event.*; import java.awt.geom.AffineTransform; import java.awt.image.*; import java.util.Timer; import java.util.TimerTask; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JWindow; import sun.awt.image.ByteInterleavedRaster; import vtk.vtkPanel; import vtk.vtkRenderWindow; import vtk.vtkRenderer; import vtk.vtkUnsignedCharArray; /** * Swing component that displays the content of a {@link vtk.vtkPanel}. In * contrast to the original vtk panel this component is a lightweight component. * Although this slows down rendering it may be usefull if transparency and * layering of components shall be used. This panle gives full access to the * offscreen image which allows to postprocess the image with AWT/Swing. * * <p>In addition to {@link vtk.vtkPanel} this component provides a fullscreen * mode that can be enabled either manually through * {@link #enterFullscreenMode() } or by double clicking on the component.</p> * * @author Michael Hoffer <[email protected]> */ public class VTKJPanel extends JPanel implements MouseListener, MouseMotionListener, KeyListener { private static final long serialVersionUID = 1L; // // vtk objects // private final vtkRenderWindow rw; private final VTKCanvas panel; private final vtkRenderer ren; // //fullscreen component // private Window window; // // offscreen image private Image img; // // offsets for sample model private final int[] bOffs = {0, 1, 2, 3}; // // sample model (used by writable raster) private SampleModel sampleModel; // // transform to get around the axis problem // @vtk devs why din't you choose the "right" orientation ;) private AffineTransform at; // // render data (contains data for the offscreen image) private byte[] renderData; // // the color model for the offscreen image private static ColorModel colorModel = createColorModel(); // // indicates whether rendering content private boolean renderContent; // // indicates whether this panel is in fullscreen mode private boolean fullscreen; // // indicates whether the content has changed and whether this component // shall be rerendered private boolean contentChanged; // // alpha value of vtk content. allows transparency. private float contentAlpha = 1.f; /** * Constructor. */ public VTKJPanel() { // panel wich leaves fullscreen if ESC is pressed panel = new VTKCanvas() { @Override public void keyPressed(KeyEvent e) { super.keyPressed(e); if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { leaveFullscreenMode(); } } }; rw = panel.GetRenderWindow(); ren = panel.GetRenderer(); // create the window if (!SysUtil.isLinux()) { window = new JWindow(); } else { window = new JFrame(); ((JFrame) window).setUndecorated(true); } initWindow(); // double click will leave fullscreen mode panel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { leaveFullscreenMode(); } } }); addMouseListener(this); addMouseMotionListener(this); addKeyListener(this); setBackground(new Color(120, 120, 120)); rw.SetAlphaBitPlanes(1); ren.SetGradientBackground(true); setOpaque(true); } public void setBackgroundTransparent(boolean v) { if (v) { rw.SetAlphaBitPlanes(1); } else { rw.SetAlphaBitPlanes(0); } } public boolean isBackgroundTransparent() { return rw.GetAlphaBitPlanes() == 1; } public void setGradientBackground(boolean v) { ren.SetGradientBackground(v); } public boolean isGradientBackground() { return ren.GetGradientBackground(); } /** * Leaves fullscreen mode. */ public void leaveFullscreenMode() { GraphicsUtil.leaveFullscreenMode(window); window.setVisible(false); fullscreen = false; this.setSize(1, 1); this.revalidate(); this.setSize(getSize()); repair(); } /** * Enters fullscreen mode. */ public void enterFullscreenMode() { GraphicsUtil.enterFullscreenMode(window); fullscreen = true; // this.setSize(getSize()); } /** * Reports rendering capabilites. * * @see vtk.vtkPanel#Report() */ public void report() { getPanel().Report(); } /** * Defines the background color of this panel. This method will also set the * background color of the vtk renderer. <p> <b>Note:</b> only red, green * abd blue values are used. Alpha is ignored. </p> * * @param c color to set */ @Override public void setBackground(Color c) { super.setBackground(c); if (ren != null) { ren.SetBackground( c.getRed() / 255.f, c.getGreen() / 255.f, c.getBlue() / 255.f); } } /** * Returns the vtk renderer used by this panel. * * @return vtk renderer */ public vtkRenderer getRenderer() { return ren; } /** * Returns the vtk render window used by this panel. * * @return */ public vtkRenderWindow getRenderWindow() { return rw; } @Override public void setBounds(int x, int y, int w, int h) { super.setBounds(x, y, w, h); if (window != null && !fullscreen) { // on windows we must manually change the size of the render window if (SysUtil.isWindows()) { rw.SetSize(w, h); } window.setSize(w, h); contentChanged(); } } /** * Renders this panel. */ private synchronized void render() { getPanel().lock(); getPanel().Render(); renderContent = ren.VisibleActorCount() > 0; updateImage(); contentChanged = false; getPanel().unlock(); } /** * Indicates that the content of this component has changed. The next * repaint event after calling this method will trigger rendering. * <p><b>Note:</b>This method does not directly trigger rendering. Thus, * calling it multiple times does not change behavior.</p> */ public void contentChanged() { contentChanged = true; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; Composite original = g2.getComposite(); // TODO find out if this condition really improves performance if (getContentAlpha() < 1.f) { AlphaComposite ac1 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getContentAlpha()); g2.setComposite(ac1); g2.drawImage(getImage(), 0, 0, /* * getWidth(), getHeight(), */ null); g2.setComposite(original); } else { g2.drawImage(getImage(), 0, 0, /* * getWidth(), getHeight(), */ null); } } /** * Returns the content of this panel as awt image. * * @return image that contains the rendered content */ private Image getImage() { if (img == null || sizeChanged() || contentChanged) { render(); } return img; } /** * Indicates whether the render window and the offscreen image differ in * size. * * @return * <code>true</code> if sizes differ; * <code>false</code> otherwise */ private boolean sizeChanged() { int[] renderSize = rw.GetSize(); int width = renderSize[0]; int height = renderSize[1]; boolean changed = width != img.getWidth(null) - 1 || height != img.getHeight(null) - 1; return changed; } /** * Updates the offscreen image of this panel. */ private synchronized void updateImage() { // if we have no content to render nothing to be done if (!renderContent) { return; } // size of render window int[] renderSize = rw.GetSize(); int width = renderSize[0]; int height = renderSize[1]; // if either samplemodel, the mirror transform are null or // render window and offscreen image have different sizes we need to // create new sample model and transform if (sampleModel == null || at == null || sizeChanged()) { // as far as I know vtk uses RGBA component layout (see below) sampleModel = new PixelInterleavedSampleModel( DataBuffer.TYPE_BYTE, width + 1, height + 1, 4, 4 * (width + 1), bOffs); // transform to get around the axis problem // @vtk devs why din't you choose the "right" orientation ;) at = new AffineTransform(1, 0.0d, 0.0d, -1, 0, height + 1); // resize hidden frame if not in fullscreen mode if (!fullscreen) { window.setSize(getWidth(), getHeight()); } } // retrieve the pixeldata from render window vtkUnsignedCharArray vtkPixelData = new vtkUnsignedCharArray(); ren.GetRenderWindow().GetRGBACharPixelData(0, 0, width, height, 1, vtkPixelData); renderData = vtkPixelData.GetJavaArray(); DataBuffer dbuf = new DataBufferByte(renderData, width * height, 0); // we now construct an image raster with sample model (see above) WritableRaster raster = new ByteInterleavedRaster(sampleModel, dbuf, new Point(0, 0)); // transform the original raster AffineTransformOp op = new AffineTransformOp( at, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); WritableRaster mirrorRaster = op.filter(raster, null); // finally, create an image img = new BufferedImage(colorModel, mirrorRaster, false, null); } /** * Returns the color model used to construct the offscreen image. * * @return color model */ private static ColorModel createColorModel() { ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB); int[] nBits = {8, 8, 8, 8}; return new ComponentColorModel(cs, nBits, true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE); } @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { enterFullscreenMode(); } // render(); contentChanged(); repaint(); getPanel().mouseClicked(e); } @Override public void mousePressed(MouseEvent e) { getPanel().mousePressed(e); // render(); contentChanged(); repaint(); } @Override public void mouseReleased(MouseEvent e) { getPanel().mouseReleased(e); } @Override public void mouseEntered(MouseEvent e) { this.requestFocus(); } @Override public void mouseExited(MouseEvent e) { getPanel().mouseMoved(e); } @Override public void mouseMoved(MouseEvent e) { getPanel().mouseMoved(e); } @Override public void mouseDragged(MouseEvent e) { getPanel().mouseDragged(e); // render(); contentChanged(); repaint(); } @Override public void keyTyped(KeyEvent e) { getPanel().keyReleased(e); // render(); contentChanged(); repaint(); } public void HardCopy(String filename, int mag) { getPanel().HardCopy(filename, mag); } @Override public void keyReleased(KeyEvent e) { getPanel().keyReleased(e); // render(); contentChanged(); repaint(); } @Override public void keyPressed(KeyEvent e) { getPanel().keyPressed(e); // render(); contentChanged(); repaint(); } /** * Disposes this component. */ public void dispose() { getPanel().Delete(); window.dispose(); } /** * Returns the content alpha value (defines transparency of vtk content). * * A value of 1.f means full opacity, 0.0f full transparency. * * @return the content alpha */ public float getContentAlpha() { return contentAlpha; } /** * Defines the content alpha value (defines transparency of vtk content). * * A value of 1.f means full opacity, 0.0f full transparency. * * @param contentAlpha the content alpha to set */ public void setContentAlpha(float contentAlpha) { this.contentAlpha = contentAlpha; contentChanged(); } // //**************************************************** //* !!! CAUTION: UGLY METHODS BELOW !!! * //**************************************************** // /** * Initializes the internal window. */ private void initWindow() { // we add the panel to give it access to native memory etc. window.add(getPanel()); // unfortunately a window has to be visible to be initialized. // that is why we toggle visibility // this window does not have a title bar and is not visible (hopefully) window.setVisible(true); // ati on linux sucks! if (SysUtil.isLinux()) { // linux: // we must ensure that the window gets painted at least once with // width and height > 0 window.setSize(1, 1); // I am so unhappy with this :( // But otherwise the window will show up detached from this panel // which looks very strange for (int i = 0; i < 15; i++) { window.paint(window.getGraphics()); try { Thread.sleep(2); } catch (InterruptedException ex) { // we don't care } } } window.setVisible(false); } /** * Repairs the visual appearance of this panel. */ private void repair() { // This is a hack! // I put his method to the bottom because no one should read its code. Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { GraphicsUtil.invokeLater(new Runnable() { @Override public void run() { contentChanged(); repaint(); } }); } }, 10); } /** * @return the panel */ public VTKCanvas getPanel() { return panel; } }
JVTK/src/eu/mihosoft/vtk/VTKJPanel.java
/* * Copyright 2012 Michael Hoffer <[email protected]>. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY Michael Hoffer <[email protected]> "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 Michael Hoffer <[email protected]> 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 Michael Hoffer <[email protected]>. */ package eu.mihosoft.vtk; import java.awt.*; import java.awt.color.ColorSpace; import java.awt.event.*; import java.awt.geom.AffineTransform; import java.awt.image.*; import java.util.Timer; import java.util.TimerTask; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JWindow; import sun.awt.image.ByteInterleavedRaster; import vtk.*; /** * Swing component that displays the content of a {@link vtk.vtkPanel}. In * contrast to the original vtk panel this component is a lightweight component. * Although this slows down rendering it may be usefull if transparency and * layering of components shall be used. This panle gives full access to the * offscreen image which allows to postprocess the image with AWT/Swing. * * <p>In addition to {@link vtk.vtkPanel} this component provides a fullscreen * mode that can be enabled either manually through * {@link #enterFullscreenMode() } or by double clicking on the component.</p> * * @author Michael Hoffer <[email protected]> */ public class VTKJPanel extends JPanel implements MouseListener, MouseMotionListener, KeyListener { private static final long serialVersionUID = 1L; // // vtk objects // private final vtkRenderWindow rw; private final VTKCanvas panel; private final vtkRenderer ren; // //fullscreen component // private Window window; // // offscreen image private Image img; // // offsets for sample model private final int[] bOffs = {0, 1, 2, 3}; // // sample model (used by writable raster) private SampleModel sampleModel; // // transform to get around the axis problem // @vtk devs why din't you choose the "right" orientation ;) private AffineTransform at; // // render data (contains data for the offscreen image) private byte[] renderData; // // the color model for the offscreen image private static ColorModel colorModel = createColorModel(); // // indicates whether rendering content private boolean renderContent; // // indicates whether this panel is in fullscreen mode private boolean fullscreen; // // indicates whether the content has changed and whether this component // shall be rerendered private boolean contentChanged; // // alpha value of vtk content. allows transparency. private float contentAlpha = 1.f; /** * Constructor. */ public VTKJPanel() { // panel wich leaves fullscreen if ESC is pressed panel = new VTKCanvas() { @Override public void keyPressed(KeyEvent e) { super.keyPressed(e); if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { leaveFullscreenMode(); } } }; rw = panel.GetRenderWindow(); ren = panel.GetRenderer(); // create the window if (!SysUtil.isLinux()) { window = new JWindow(); } else { window = new JFrame(); ((JFrame) window).setUndecorated(true); } initWindow(); // double click will leave fullscreen mode panel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { leaveFullscreenMode(); } } }); addMouseListener(this); addMouseMotionListener(this); addKeyListener(this); setBackground(new Color(120, 120, 120)); rw.SetAlphaBitPlanes(1); ren.SetGradientBackground(true); setOpaque(true); } public void setBackgroundTransparent(boolean v) { if (v) { rw.SetAlphaBitPlanes(1); } else { rw.SetAlphaBitPlanes(0); } } public boolean isBackgroundTransparent() { return rw.GetAlphaBitPlanes() == 1; } public void setGradientBackground(boolean v) { ren.SetGradientBackground(v); } public boolean isGradientBackground() { return ren.GetGradientBackground(); } /** * Leaves fullscreen mode. */ public void leaveFullscreenMode() { GraphicsUtil.leaveFullscreenMode(window); window.setVisible(false); fullscreen = false; this.setSize(1, 1); this.revalidate(); this.setSize(getSize()); repair(); } /** * Enters fullscreen mode. */ public void enterFullscreenMode() { GraphicsUtil.enterFullscreenMode(window); fullscreen = true; // this.setSize(getSize()); } /** * Reports rendering capabilites. * * @see vtk.vtkPanel#Report() */ public void report() { getVTKPanel().Report(); } /** * Defines the background color of this panel. This method will also set the * background color of the vtk renderer. <p> <b>Note:</b> only red, green * abd blue values are used. Alpha is ignored. </p> * * @param c color to set */ @Override public void setBackground(Color c) { super.setBackground(c); if (ren != null) { ren.SetBackground( c.getRed() / 255.f, c.getGreen() / 255.f, c.getBlue() / 255.f); } } /** * Returns the vtk renderer used by this panel. * * @return vtk renderer */ public vtkRenderer getRenderer() { return ren; } /** * Returns the vtk render window used by this panel. * * @return */ public vtkRenderWindow getRenderWindow() { return rw; } @Override public void setBounds(int x, int y, int w, int h) { super.setBounds(x, y, w, h); if (window != null && !fullscreen) { rw.SetSize(w, h); window.setSize(w, h); contentChanged(); } } /** * Renders this panel. */ private synchronized void render() { getVTKPanel().lock(); getVTKPanel().Render(); renderContent = ren.VisibleActorCount() > 0; updateImage(); contentChanged = false; getVTKPanel().unlock(); } /** * Indicates that the content of this component has changed. The next * repaint event after calling this method will trigger rendering. * <p><b>Note:</b>This method does not directly trigger rendering. Thus, * calling it multiple times does not change behavior.</p> */ public void contentChanged() { contentChanged = true; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; Composite original = g2.getComposite(); // TODO find out if this condition really improves performance if (getContentAlpha() < 1.f) { AlphaComposite ac1 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getContentAlpha()); g2.setComposite(ac1); g2.drawImage(getImage(), 0, 0, /* * getWidth(), getHeight(), */ null); g2.setComposite(original); } else { g2.drawImage(getImage(), 0, 0, /* * getWidth(), getHeight(), */ null); } } /** * Returns the content of this panel as awt image. * * @return image that contains the rendered content */ private Image getImage() { if (img == null || sizeChanged() || contentChanged) { render(); } return img; } /** * Indicates whether the render window and the offscreen image differ in * size. * * @return * <code>true</code> if sizes differ; * <code>false</code> otherwise */ private boolean sizeChanged() { int[] renderSize = rw.GetSize(); int width = renderSize[0]; int height = renderSize[1]; boolean changed = width != img.getWidth(null) - 1 || height != img.getHeight(null) - 1; return changed; } /** * Updates the offscreen image of this panel. */ private synchronized void updateImage() { // if we have no content to render nothing to be done if (!renderContent) { return; } // size of render window int[] renderSize = rw.GetSize(); int width = renderSize[0]; int height = renderSize[1]; // if either samplemodel, the mirror transform are null or // render window and offscreen image have different sizes we need to // create new sample model and transform if (sampleModel == null || at == null || sizeChanged()) { // as far as I know vtk uses RGBA component layout (see below) sampleModel = new PixelInterleavedSampleModel( DataBuffer.TYPE_BYTE, width + 1, height + 1, 4, 4 * (width + 1), bOffs); // transform to get around the axis problem // @vtk devs why din't you choose the "right" orientation ;) at = new AffineTransform(1, 0.0d, 0.0d, -1, 0, height + 1); // resize hidden frame if not in fullscreen mode if (!fullscreen) { window.setSize(getWidth(), getHeight()); } } // retrieve the pixeldata from render window vtkUnsignedCharArray vtkPixelData = new vtkUnsignedCharArray(); ren.GetRenderWindow().GetRGBACharPixelData(0, 0, width, height, 1, vtkPixelData); renderData = vtkPixelData.GetJavaArray(); DataBuffer dbuf = new DataBufferByte(renderData, width * height, 0); // we now construct an image raster with sample model (see above) WritableRaster raster = new ByteInterleavedRaster(sampleModel, dbuf, new Point(0, 0)); // transform the original raster AffineTransformOp op = new AffineTransformOp( at, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); WritableRaster mirrorRaster = op.filter(raster, null); // finally, create an image img = new BufferedImage(colorModel, mirrorRaster, false, null); } /** * Returns the color model used to construct the offscreen image. * * @return color model */ private static ColorModel createColorModel() { ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB); int[] nBits = {8, 8, 8, 8}; return new ComponentColorModel(cs, nBits, true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE); } @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { enterFullscreenMode(); } // render(); contentChanged(); repaint(); getVTKPanel().mouseClicked(e); } @Override public void mousePressed(MouseEvent e) { getVTKPanel().mousePressed(e); // render(); contentChanged(); repaint(); } @Override public void mouseReleased(MouseEvent e) { getVTKPanel().mouseReleased(e); } @Override public void mouseEntered(MouseEvent e) { this.requestFocus(); } @Override public void mouseExited(MouseEvent e) { getVTKPanel().mouseMoved(e); } @Override public void mouseMoved(MouseEvent e) { getVTKPanel().mouseMoved(e); } @Override public void mouseDragged(MouseEvent e) { getVTKPanel().mouseDragged(e); // render(); contentChanged(); repaint(); } @Override public void keyTyped(KeyEvent e) { getVTKPanel().keyReleased(e); // render(); contentChanged(); repaint(); } public void HardCopy(String filename, int mag) { getVTKPanel().HardCopy(filename, mag); } @Override public void keyReleased(KeyEvent e) { getVTKPanel().keyReleased(e); // render(); contentChanged(); repaint(); } @Override public void keyPressed(KeyEvent e) { getVTKPanel().keyPressed(e); // render(); contentChanged(); repaint(); } /** * Disposes this component. */ public void dispose() { getVTKPanel().Delete(); window.dispose(); } /** * Returns the content alpha value (defines transparency of vtk content). * * A value of 1.f means full opacity, 0.0f full transparency. * * @return the content alpha */ public float getContentAlpha() { return contentAlpha; } /** * Defines the content alpha value (defines transparency of vtk content). * * A value of 1.f means full opacity, 0.0f full transparency. * * @param contentAlpha the content alpha to set */ public void setContentAlpha(float contentAlpha) { this.contentAlpha = contentAlpha; contentChanged(); } // //**************************************************** //* !!! CAUTION: UGLY METHODS BELOW !!! * //**************************************************** // /** * Initializes the internal window. */ private void initWindow() { // we add the panel to give it access to native memory etc. window.add(getVTKPanel()); // unfortunately a window has to be visible to be initialized. // that is why we toggle visibility // this window does not have a title bar and is not visible (hopefully) window.setVisible(true); // ati on linux sucks! if (SysUtil.isLinux()) { // linux: // we must ensure that the window gets painted at least once with // width and height > 0 window.setSize(1, 1); // I am so unhappy with this :( for (int i = 0; i < 15; i++) { window.paint(window.getGraphics()); try { Thread.sleep(2); } catch (InterruptedException ex) { // we don't care } } } window.setVisible(false); } /** * Repairs the visual appearance of this panel. */ private void repair() { // This is a hack! // I put his method to the bottom because no one should read its code. Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { GraphicsUtil.invokeLater(new Runnable() { @Override public void run() { contentChanged(); repaint(); } }); } }, 10); } /** * @return the panel */ public VTKCanvas getVTKPanel() { return panel; } }
switched from to vtkCanvas
JVTK/src/eu/mihosoft/vtk/VTKJPanel.java
switched from to vtkCanvas
Java
bsd-3-clause
c1aa054f44edd6e21a66b82bfc700e823924fd89
0
mushroomhostage/FreeTrade,mushroomhostage/FreeTrade,mushroomhostage/FreeTrade
package com.exphc.FreeTrade; import java.util.logging.Logger; import java.util.regex.*; import java.util.ArrayList; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.command.*; import org.bukkit.entity.*; import org.bukkit.*; class ItemSpec { int quantity; Material material; public ItemSpec(String s) { Pattern p = Pattern.compile("^(\\d*)([# -]?)(\\p{Alpha}+)$"); Matcher m = p.matcher(s); while(m.find()) { String quantityString = m.group(1); String isStackString = m.group(2); String nameString = m.group(3); quantity = Integer.parseInt(quantityString); if (quantity < 0) { quantity = 1; } // TODO: really need better material matching names, shorthands // diamond_pickaxe, too long. diamondpick, dpick, would be better. // iron_ingot, want just iron or i. shortest match: cobblestone, cobble. common: diamond, d. plural. material = Material.matchMaterial(nameString); if (material == null) { // TODO: exception? } if (isStackString.equals("#")) { quantity *= material.getMaxStackSize(); } } } public String toString() { return quantity + " " + material; } } class Order { Player player; ItemSpec want, give; boolean exact; public Order(Player p, String wantString, String giveString) { player = p; if (wantString.contains("!")) { exact = true; wantString = wantString.replace("!", ""); } if (giveString.contains("!")) { exact = true; giveString = giveString.replace("!", ""); } want = new ItemSpec(wantString); give = new ItemSpec(giveString); } public String toString() { return player + " wants " + want + " for " + give + (exact ? " (exact)" : ""); } } class Market { ArrayList<Order> orders; public Market() { // TODO: load from file, save to file orders = new ArrayList<Order>(); } public boolean showOutstanding(CommandSender sender) { sender.sendMessage("TODO: show open orders"); for (int i = 0; i < orders.size(); i++) { sender.sendMessage(i + ". " + orders.get(i)); } return false; } public void placeOrder(Order order) { orders.add(order); } } public class FreeTrade extends JavaPlugin { Logger log = Logger.getLogger("Minecraft"); Market market = new Market(); public void onEnable() { log.info("FreeTrade enabled"); } public void onDisable() { log.info("FreeTrade disabled"); } public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { Player player; if (!cmd.getName().equalsIgnoreCase("want")) { return false; } // /want if (args.length == 0) { return market.showOutstanding(sender); } if (sender instanceof Player) { player = (Player)sender; } else { // TODO: get player from name as first argument sender.sendMessage("this command can only be run by a player"); player = null; //return false; } if (args.length < 2) { return false; } String wantString, giveString; wantString = args[0]; if (args[1].equalsIgnoreCase("for")) { giveString = args[2]; } else { giveString = args[1]; } Order order = new Order(player, wantString, giveString); sender.sendMessage(order.toString()); market.placeOrder(order); return true; } }
FreeTrade.java
package com.exphc.FreeTrade; import java.util.logging.Logger; import java.util.regex.*; import java.util.ArrayList; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.command.*; import org.bukkit.entity.*; import org.bukkit.*; class ItemSpec { int quantity; Material material; public ItemSpec(String s) { Pattern p = Pattern.compile("^(\\d*)([# -]?)(\\p{Alpha}+)$"); Matcher m = p.matcher(s); while(m.find()) { String quantityString = m.group(1); String isStackString = m.group(2); String nameString = m.group(3); quantity = Integer.parseInt(quantityString); if (quantity < 0) { quantity = 1; } // TODO: really need better material matching names, shorthands // diamond_pickaxe, too long. diamondpick, dpick, would be better. // iron_ingot, want just iron or i. shortest match: cobblestone, cobble. common: diamond, d. plural. material = Material.matchMaterial(nameString); if (material == null) { // TODO: exception? } if (isStackString.equals("#")) { quantity *= material.getMaxStackSize(); } } } public String toString() { return quantity + " " + material; } } class Order { Player player; ItemSpec want, give; boolean exact; public Order(Player p, String wantString, String giveString) { player = p; if (wantString.contains("!")) { exact = true; wantString = wantString.replace("!", ""); } if (giveString.contains("!")) { exact = true; giveString = giveString.replace("!", ""); } want = new ItemSpec(wantString); give = new ItemSpec(giveString); } public String toString() { return player + " wants " + want + " for " + give + (exact ? " (exact)" : ""); } } public class FreeTrade extends JavaPlugin { Logger log = Logger.getLogger("Minecraft"); ArrayList<Order> orders; public void onEnable() { log.info("FreeTrade enabled"); // TODO: load from file orders = new ArrayList<Order>(); } public void onDisable() { log.info("FreeTrade disabled"); // TODO: save to file } public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { Player player; if (!cmd.getName().equalsIgnoreCase("want")) { return false; } // /want if (args.length == 0) { return showOutstanding(sender); } if (sender instanceof Player) { player = (Player)sender; } else { // TODO: get player from name as first argument sender.sendMessage("this command can only be run by a player"); player = null; //return false; } if (args.length < 2) { return false; } String wantString, giveString; wantString = args[0]; if (args[1].equalsIgnoreCase("for")) { giveString = args[2]; } else { giveString = args[1]; } Order order = new Order(player, wantString, giveString); sender.sendMessage(order.toString()); orders.add(order); return true; } public boolean showOutstanding(CommandSender sender) { sender.sendMessage("TODO: show open orders"); for (int i = 0; i < orders.size(); i++) { sender.sendMessage(i + ". " + orders.get(i)); } return false; } }
Market class abstraction, but no functional changes
FreeTrade.java
Market class abstraction, but no functional changes
Java
bsd-3-clause
32e1364850d7d3eda3ddc28d46bce59f79b6cbff
0
dimitarp/basex,dimitarp/basex,dimitarp/basex,BaseXdb/basex,BaseXdb/basex,BaseXdb/basex,dimitarp/basex,dimitarp/basex,dimitarp/basex,BaseXdb/basex,BaseXdb/basex,dimitarp/basex,BaseXdb/basex,BaseXdb/basex,BaseXdb/basex,BaseXdb/basex,BaseXdb/basex,dimitarp/basex,dimitarp/basex,BaseXdb/basex,BaseXdb/basex,dimitarp/basex,dimitarp/basex,dimitarp/basex
package org.basex.gui.layout; import static org.basex.gui.layout.BaseXKeys.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.*; import org.basex.gui.*; import org.basex.gui.listener.*; import org.basex.util.*; import org.basex.util.options.*; /** * Project specific ComboBox implementation. * * @author BaseX Team 2005-18, BSD License * @author Christian Gruen */ public class BaseXCombo extends JComboBox<Object> { /** Options. */ private Options options; /** Option. */ private Option<?> option; /** History. */ private BaseXHistory history; /** Hint. */ private BaseXTextHint hint; /** Key listener. */ private KeyListener keys; /** Focus listener. */ private FocusListener focus; /** Reference to parent window (of type {@link BaseXDialog} or {@link GUI}). */ private final BaseXWindow win; /** * Constructor. * @param win parent window * @param option numeric value * @param options options * @param values combobox values */ public BaseXCombo(final BaseXWindow win, final NumberOption option, final Options options, final String... values) { this(win, option, options, false, values); setSelectedItem(values[options.get(option)]); } /** * Constructor. * @param win parent window * @param option boolean value * @param options options */ public BaseXCombo(final BaseXWindow win, final BooleanOption option, final Options options) { this(win, option, options, false, "true", "false"); setSelectedItem(options.get(option)); } /** * Constructor. * @param win parent window * @param option enum value * @param options options */ public BaseXCombo(final BaseXWindow win, final EnumOption<?> option, final Options options) { this(win, option, options, false, option.strings()); setSelectedItem(options.get(option)); } /** * Attaches a history and enables a listener for cursor down/up keys. * @param opt strings option * @param opts options * @return self reference */ public final BaseXCombo history(final StringsOption opt, final Options opts) { if(!isEditable()) throw Util.notExpected("Combobox is not editable."); options = opts; option = opt; history = new BaseXHistory(opt, options); setItems(opts.get(opt)); // store input if enter is pressed; scroll between history entries final JTextComponent comp = textField(); comp.removeKeyListener(keys); keys = (KeyPressedListener) e -> { final boolean next = NEXTLINE.is(e), prev = PREVLINE.is(e); if((next || prev) && e.isShiftDown()) { final String value = history.get(next); if(value != null) { setText(value); final BaseXDialog dialog = win.dialog(); if(dialog != null) dialog.action(this); } } }; comp.addKeyListener(keys); // store input if focus is lost comp.removeFocusListener(focus); focus = (FocusLostListener) e -> updateHistory(); comp.addFocusListener(focus); return this; } /** * Constructor. * @param win parent window * @param option option * @param options options * @param values values * @param editable editable flag */ private BaseXCombo(final BaseXWindow win, final Option<?> option, final Options options, final boolean editable, final String... values) { this(win, editable, values); this.options = options; this.option = option; } /** * Constructor. * @param win parent window * @param values combobox values */ public BaseXCombo(final BaseXWindow win, final String... values) { this(win, false, values); } /** * Constructor. * @param win parent window * @param editable editable flag * @param values combobox values */ public BaseXCombo(final BaseXWindow win, final boolean editable, final String... values) { super(values); this.win = win; setEditable(editable); setEditor(new BaseXEditor(win.gui())); BaseXLayout.addInteraction(this, win); final BaseXDialog dialog = win.dialog(); if(dialog == null) return; SwingUtilities.invokeLater(() -> { final BaseXTextField tf = textField(); if(tf == null) { addActionListener(e -> dialog.action(BaseXCombo.this)); } else { tf.getDocument().addDocumentListener(new DocumentListener() { @Override public void removeUpdate(final DocumentEvent e) { dialog.action(BaseXCombo.this); } @Override public void insertUpdate(final DocumentEvent e) { dialog.action(BaseXCombo.this); } @Override public void changedUpdate(final DocumentEvent e) { } }); } }); } /** * Adds a hint to the text field. * @param label text of the hint * @return self reference */ public BaseXCombo hint(final String label) { final BaseXTextField tf = textField(); if(tf != null) { if(hint == null) { hint = new BaseXTextHint(label, tf); } else { hint.setText(label); } } setToolTipText(label.replaceAll("\\.\\.\\.$", "")); return this; } @Override public void setFont(final Font font) { super.setFont(font); final BaseXTextField tf = textField(); if(hint != null && tf != null) hint.setFont(tf.getFont()); } /** * Sets the specified items. * @param items items */ public void setItems(final String... items) { setModel(new DefaultComboBoxModel<>(items)); } /** * Stores the current history and refreshes the selectable items. */ public void updateHistory() { if(history != null) { history.add(getText()); SwingUtilities.invokeLater(() -> setItems(history.values())); } } /** * Returns the current text. * @return text */ public String getText() { return getSelectedItem(); } /** * Sets the current text. * @param text text to be assigned */ public void setText(final String text) { setSelectedItem(text); } @Override public String getSelectedItem() { final Object item = isEditable() ? getEditor().getItem() : super.getSelectedItem(); return item == null ? "" : item.toString(); } /** * Returns the editor text field, or {@code null} if the combobox is not editable. * @return text field */ public BaseXTextField textField() { return isEditable() ? (BaseXTextField) getEditor().getEditorComponent() : null; } @Override public void setSelectedItem(final Object object) { if(object == null) return; if(isEditable()) { getEditor().setItem(object); } else { final ComboBoxModel<Object> model = getModel(); final int ms = model.getSize(); for(int m = 0; m < ms; m++) { if(model.getElementAt(m).equals(object)) { super.setSelectedItem(object); return; } } } if(hint != null) hint.update(); } /** * Highlights the text field. * @param hits hits */ public synchronized void highlight(final boolean hits) { final BaseXTextField tf = textField(); (tf != null ? tf : this).setBackground(hits ? GUIConstants.BACK : GUIConstants.LRED); } @Override public synchronized KeyListener[] getKeyListeners() { final BaseXTextField tf = textField(); return tf != null ? tf.getKeyListeners() : super.getKeyListeners(); } @Override public synchronized void addKeyListener(final KeyListener l) { final BaseXTextField tf = textField(); if(tf != null) tf.addKeyListener(l); else super.addKeyListener(l); } @Override public synchronized void removeKeyListener(final KeyListener l) { final BaseXTextField tf = textField(); if(tf != null) tf.removeKeyListener(l); super.removeKeyListener(l); } @Override public synchronized void addFocusListener(final FocusListener l) { final BaseXTextField tf = textField(); if(tf != null) tf.addFocusListener(l); else super.addFocusListener(l); } @Override public synchronized void removeFocusListener(final FocusListener l) { final BaseXTextField tf = textField(); if(tf != null) tf.removeFocusListener(l); super.removeFocusListener(l); } /** * Assigns the current checkbox value to the option specified in the constructor. */ public void assign() { if(option instanceof NumberOption) { options.set((NumberOption) option, getSelectedIndex()); } else if(option instanceof EnumOption) { options.set((EnumOption<?>) option, getSelectedItem()); } else if(option instanceof StringOption) { options.set((StringOption) option, getSelectedItem()); } else if(option instanceof BooleanOption) { options.set((BooleanOption) option, Boolean.parseBoolean(getSelectedItem())); } else if(option instanceof StringsOption) { updateHistory(); } else { throw Util.notExpected("Option type not supported: " + option); } } /** * Combo box editor. * * @author BaseX Team 2005-18, BSD License * @author Christian Gruen */ private static final class BaseXEditor implements ComboBoxEditor { /** Text field. */ private final BaseXTextField tf; /** * Constructor. * @param gui gui */ private BaseXEditor(final GUI gui) { tf = new BaseXTextField(gui); } @Override public Component getEditorComponent() { return tf; } @Override public void setItem(final Object text) { if(text != null) tf.setText(text.toString()); } @Override public String getItem() { return tf.getText(); } @Override public void selectAll() { tf.selectAll(); } @Override public void addActionListener(final ActionListener l) { tf.addActionListener(l); } @Override public void removeActionListener(final ActionListener l) { tf.removeActionListener(l); } } }
basex-core/src/main/java/org/basex/gui/layout/BaseXCombo.java
package org.basex.gui.layout; import static org.basex.gui.layout.BaseXKeys.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.*; import org.basex.gui.*; import org.basex.gui.listener.*; import org.basex.util.*; import org.basex.util.options.*; /** * Project specific ComboBox implementation. * * @author BaseX Team 2005-18, BSD License * @author Christian Gruen */ public class BaseXCombo extends JComboBox<Object> { /** Options. */ private Options options; /** Option. */ private Option<?> option; /** History. */ private BaseXHistory history; /** Hint. */ private BaseXTextHint hint; /** Key listener. */ private KeyListener keys; /** Focus listener. */ private FocusListener focus; /** Reference to parent window (of type {@link BaseXDialog} or {@link GUI}). */ private final BaseXWindow win; /** * Constructor. * @param win parent window * @param option numeric value * @param options options * @param values combobox values */ public BaseXCombo(final BaseXWindow win, final NumberOption option, final Options options, final String... values) { this(win, option, options, false, values); setSelectedItem(values[options.get(option)]); } /** * Constructor. * @param win parent window * @param option boolean value * @param options options */ public BaseXCombo(final BaseXWindow win, final BooleanOption option, final Options options) { this(win, option, options, false, "true", "false"); setSelectedItem(options.get(option)); } /** * Constructor. * @param win parent window * @param option enum value * @param options options */ public BaseXCombo(final BaseXWindow win, final EnumOption<?> option, final Options options) { this(win, option, options, false, option.strings()); setSelectedItem(options.get(option)); } /** * Attaches a history and enables a listener for cursor down/up keys. * @param opt strings option * @param opts options * @return self reference */ public final BaseXCombo history(final StringsOption opt, final Options opts) { if(!isEditable()) throw Util.notExpected("Combobox is not editable."); options = opts; option = opt; history = new BaseXHistory(opt, options); setItems(opts.get(opt)); // store input if enter is pressed; scroll between history entries final JTextComponent comp = textField(); comp.removeKeyListener(keys); keys = (KeyPressedListener) e -> { final boolean next = NEXTLINE.is(e), prev = PREVLINE.is(e); if((next || prev) && e.isShiftDown()) { final String value = history.get(next); if(value != null) { setText(value); final BaseXDialog dialog = win.dialog(); if(dialog != null) dialog.action(this); } } }; comp.addKeyListener(keys); // store input if focus is lost comp.removeFocusListener(focus); focus = (FocusLostListener) e -> updateHistory(); comp.addFocusListener(focus); return this; } /** * Constructor. * @param win parent window * @param option option * @param options options * @param values values * @param editable editable flag */ private BaseXCombo(final BaseXWindow win, final Option<?> option, final Options options, final boolean editable, final String... values) { this(win, editable, values); this.options = options; this.option = option; } /** * Constructor. * @param win parent window * @param values combobox values */ public BaseXCombo(final BaseXWindow win, final String... values) { this(win, false, values); } /** * Constructor. * @param win parent window * @param editable editable flag * @param values combobox values */ public BaseXCombo(final BaseXWindow win, final boolean editable, final String... values) { super(values); this.win = win; setEditable(editable); setEditor(new BaseXEditor(win.gui(), this)); BaseXLayout.addInteraction(this, win); final BaseXDialog dialog = win.dialog(); if(dialog == null) return; SwingUtilities.invokeLater(() -> { final BaseXTextField tf = textField(); if(tf == null) { addActionListener(e -> dialog.action(BaseXCombo.this)); } else { tf.getDocument().addDocumentListener(new DocumentListener() { @Override public void removeUpdate(final DocumentEvent e) { dialog.action(BaseXCombo.this); } @Override public void insertUpdate(final DocumentEvent e) { dialog.action(BaseXCombo.this); } @Override public void changedUpdate(final DocumentEvent e) { } }); } }); } /** * Adds a hint to the text field. * @param label text of the hint * @return self reference */ public BaseXCombo hint(final String label) { final BaseXTextField tf = textField(); if(tf != null) { if(hint == null) { hint = new BaseXTextHint(label, tf); } else { hint.setText(label); } } setToolTipText(label.replaceAll("\\.\\.\\.$", "")); return this; } @Override public void setFont(final Font font) { super.setFont(font); final BaseXTextField tf = textField(); if(hint != null && tf != null) hint.setFont(tf.getFont()); } /** * Sets the specified items. * @param items items */ public void setItems(final String... items) { setModel(new DefaultComboBoxModel<>(items)); } /** * Stores the current history and refreshes the selectable items. */ public void updateHistory() { if(history != null) { history.add(getText()); SwingUtilities.invokeLater(() -> setItems(history.values())); } } /** * Returns the current text. * @return text */ public String getText() { return getSelectedItem(); } /** * Sets the current text. * @param text text to be assigned */ public void setText(final String text) { setSelectedItem(text); } @Override public String getSelectedItem() { final Object item = isEditable() ? getEditor().getItem() : super.getSelectedItem(); return item == null ? "" : item.toString(); } /** * Returns the editor text field, or {@code null} if the combobox is not editable. * @return text field */ public BaseXTextField textField() { return isEditable() ? (BaseXTextField) getEditor().getEditorComponent() : null; } @Override public void setSelectedItem(final Object object) { if(object == null) return; if(isEditable()) { getEditor().setItem(object); } else { final ComboBoxModel<Object> model = getModel(); final int ms = model.getSize(); for(int m = 0; m < ms; m++) { if(model.getElementAt(m).equals(object)) { super.setSelectedItem(object); return; } } } if(hint != null) hint.update(); } /** * Highlights the text field. * @param hits hits */ public synchronized void highlight(final boolean hits) { final BaseXTextField tf = textField(); (tf != null ? tf : this).setBackground(hits ? GUIConstants.BACK : GUIConstants.LRED); } @Override public synchronized KeyListener[] getKeyListeners() { final BaseXTextField tf = textField(); return tf != null ? tf.getKeyListeners() : super.getKeyListeners(); } @Override public synchronized void addKeyListener(final KeyListener l) { final BaseXTextField tf = textField(); if(tf != null) tf.addKeyListener(l); else super.addKeyListener(l); } @Override public synchronized void removeKeyListener(final KeyListener l) { final BaseXTextField tf = textField(); if(tf != null) tf.removeKeyListener(l); super.removeKeyListener(l); } @Override public synchronized void addFocusListener(final FocusListener l) { final BaseXTextField tf = textField(); if(tf != null) tf.addFocusListener(l); else super.addFocusListener(l); } @Override public synchronized void removeFocusListener(final FocusListener l) { final BaseXTextField tf = textField(); if(tf != null) tf.removeFocusListener(l); super.removeFocusListener(l); } /** * Assigns the current checkbox value to the option specified in the constructor. */ public void assign() { if(option instanceof NumberOption) { options.set((NumberOption) option, getSelectedIndex()); } else if(option instanceof EnumOption) { options.set((EnumOption<?>) option, getSelectedItem()); } else if(option instanceof StringOption) { options.set((StringOption) option, getSelectedItem()); } else if(option instanceof BooleanOption) { options.set((BooleanOption) option, Boolean.parseBoolean(getSelectedItem())); } else if(option instanceof StringsOption) { updateHistory(); } else { throw Util.notExpected("Option type not supported: " + option); } } /** * Combo box editor. * * @author BaseX Team 2005-18, BSD License * @author Christian Gruen */ private static final class BaseXEditor implements ComboBoxEditor { /** Text field. */ private final BaseXTextField tf; /** * Constructor. * @param gui gui * @param combo combo box */ private BaseXEditor(final GUI gui, final BaseXCombo combo) { tf = new BaseXTextField(gui); // adopt border of original editor final Component comp = combo.getEditor().getEditorComponent(); if(comp instanceof JTextField) tf.setBorder(((JTextField) comp).getBorder()); } @Override public Component getEditorComponent() { return tf; } @Override public void setItem(final Object text) { if(text != null) tf.setText(text.toString()); } @Override public String getItem() { return tf.getText(); } @Override public void selectAll() { tf.selectAll(); } @Override public void addActionListener(final ActionListener l) { tf.addActionListener(l); } @Override public void removeActionListener(final ActionListener l) { tf.removeActionListener(l); } } }
[MOD] GUI: Generic text border layout of editable dropdown menus
basex-core/src/main/java/org/basex/gui/layout/BaseXCombo.java
[MOD] GUI: Generic text border layout of editable dropdown menus
Java
bsd-3-clause
f8a7d6d3d1d8a63996bf747c319c58a3ac5304b0
0
webhost/jing-trang,webhost/jing-trang,webhost/jing-trang
package com.thaiopensource.relaxng.input; public class CommentTrimmer { private CommentTrimmer() { } public static String trimComment(String value) { return trim(unindent(value)); } private static String trim(String value) { int len = value.length(); loop1: for (; len > 0; --len) { switch (value.charAt(len - 1)) { case ' ': case '\t': break; case '\n': --len; break loop1; default: break loop1; } } int start = 0; loop2: for (; start < len; start++) { switch (value.charAt(start)) { case ' ': case '\t': break; case '\n': ++start; break loop2; default: break loop2; } } if (start < 0 || len < value.length()) return value.substring(start, len); return value; } private static String unindent(String value) { int minIndent = -1; boolean usedTabs = false; for (int i = value.indexOf('\n'), len = value.length(); i >= 0; i = value.indexOf('\n', i)) { ++i; int currentIndent = 0; loop: for (; i < len; i++) { switch (value.charAt(i)) { case '\n': currentIndent = 0; break; case ' ': ++currentIndent; break; case '\t': currentIndent = ((currentIndent/8) + 1)*8; usedTabs = true; break; default: break loop; } } if (i >= len) break; if (currentIndent < minIndent || minIndent < 0) minIndent = currentIndent; } if (minIndent < 0) return value; StringBuffer buf = new StringBuffer(); int currentIndent = -1; for (int i = 0, len = value.length(); i < len; i++) { char c = value.charAt(i); switch (c) { case ' ': if (currentIndent >= 0) currentIndent++; else buf.append(c); break; case '\t': if (currentIndent >= 0) currentIndent = ((currentIndent/8) + 1)*8; else buf.append(c); break; case '\n': buf.append(c); currentIndent = 0; break; default: if (currentIndent > minIndent) { currentIndent -= minIndent; if (usedTabs) { while (currentIndent >= 8) { buf.append('\t'); currentIndent -= 8; } } while (currentIndent > 0) { buf.append(' '); currentIndent--; } } currentIndent = -1; buf.append(c); break; } } return buf.toString(); } }
trang/src/com/thaiopensource/relaxng/input/CommentTrimmer.java
package com.thaiopensource.relaxng.input; public class CommentTrimmer { private CommentTrimmer() { } public static String trimComment(String value) { return trim(unindent(value)); } private static String trim(String value) { int len = value.length(); loop1: for (; len > 0; --len) { switch (value.charAt(len - 1)) { case ' ': case '\t': break; case '\n': --len; break loop1; default: break loop1; } } int start = 0; loop2: for (; start < len; start++) { switch (value.charAt(start)) { case ' ': case '\t': break; case '\n': --len; break loop2; default: break loop2; } } if (start < 0 || len < value.length()) return value.substring(start, len); return value; } private static String unindent(String value) { int minIndent = -1; boolean usedTabs = false; for (int i = value.indexOf('\n'), len = value.length(); i >= 0; i = value.indexOf('\n', i)) { ++i; int currentIndent = 0; loop: for (; i < len; i++) { switch (value.charAt(i)) { case '\n': currentIndent = 0; break; case ' ': ++currentIndent; break; case '\t': currentIndent = ((currentIndent/8) + 1)*8; usedTabs = true; break; default: break loop; } } if (i >= len) break; if (currentIndent < minIndent || minIndent < 0) minIndent = currentIndent; } if (minIndent < 0) return value; StringBuffer buf = new StringBuffer(); int currentIndent = -1; for (int i = 0, len = value.length(); i < len; i++) { char c = value.charAt(i); switch (c) { case ' ': if (currentIndent >= 0) currentIndent++; else buf.append(c); break; case '\t': if (currentIndent >= 0) currentIndent = ((currentIndent/8) + 1)*8; else buf.append(c); break; case '\n': buf.append(c); currentIndent = 0; break; default: if (currentIndent > minIndent) { currentIndent -= minIndent; if (usedTabs) { while (currentIndent >= 8) { buf.append('\t'); currentIndent -= 8; } } while (currentIndent > 0) { buf.append(' '); currentIndent--; } } currentIndent = -1; buf.append(c); break; } } return buf.toString(); } }
Fix bug trimming initial newline
trang/src/com/thaiopensource/relaxng/input/CommentTrimmer.java
Fix bug trimming initial newline
Java
mit
4f4e3114614ab8f4c5a6006585b8e1160e9cef73
0
kirillovsky/otus-java-2017-10-kirillov,kirillovsky/otus-java-2017-10-kirillov,kirillovsky/otus-java-2017-10-kirillov,kirillovsky/otus-java-2017-10-kirillov
package ru.otus.kirillov; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import ru.otus.kirillov.testAdapter.LocalDateTimeAdapter; import java.time.LocalDateTime; import java.util.Arrays; /** Тест работы с новым адаптером * Created by Александр on 17.01.2018. */ public class JsonSerializerImplAdditionalObjectTypeTest { private static JsonSerializer serializer; private String jsonData; private static class TestField { LocalDateTime timeNow = LocalDateTime.parse("2018-11-17T11:48:58.571"); } private static final String JSON_REPRESENTATION_TEST_FIELD = "{\"timeNow\":\"2018-11-17T11:48:58.571\"}"; @BeforeClass public static void init() { serializer = new JsonSerializerImpl(Arrays.asList( new LocalDateTimeAdapter() )); } @Test public void testSimpleSerialize() { LocalDateTime localDateTime = LocalDateTime.now(); jsonData = serializer.toJson(localDateTime); Assert.assertEquals("\"" + localDateTime.toString() + "\"", jsonData); } @Test public void testSerializeAsField() { TestField testField = new TestField(); jsonData = serializer.toJson(testField); Assert.assertEquals(JSON_REPRESENTATION_TEST_FIELD, jsonData); } }
hw08/src/test/java/ru/otus/kirillov/JsonSerializerImplAdditionalObjectTypeTest.java
package ru.otus.kirillov; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import ru.otus.kirillov.testAdapter.LocalDateTimeAdapter; import java.time.LocalDateTime; import java.util.Arrays; /** Тест работы с новым адаптером * Created by Александр on 17.01.2018. */ public class JsonSerializerImplAdditionalObjectTypeTest { private static JsonSerializer serializer; private String jsonData; private static class TestField { LocalDateTime timeNow = LocalDateTime.parse("2018-11-17T11:48:58.571"); } private static final String JSON_REPRESENTATION_TEST_FIELD = "{\"timeNow\":\"2018-11-17T11:48:58.571\"}"; @BeforeClass public static void init() { serializer = new JsonSerializerImpl(Arrays.asList( new LocalDateTimeAdapter() )); } @Test public void testSimpleSerialize() { LocalDateTime localDateTime = LocalDateTime.now(); jsonData = serializer.toJson(localDateTime); System.out.println(jsonData); Assert.assertEquals("\"" + localDateTime.toString() + "\"", jsonData); } @Test public void testSerializeAsField() { TestField testField = new TestField(); jsonData = serializer.toJson(testField); Assert.assertEquals(JSON_REPRESENTATION_TEST_FIELD, jsonData); } }
Убрал лишний sout
hw08/src/test/java/ru/otus/kirillov/JsonSerializerImplAdditionalObjectTypeTest.java
Убрал лишний sout
Java
mit
e546e5dc476351e8cc369349b551dd7965c9fd09
0
TheJumpCloud/DotCi,groupon/DotCi,dimacus/DotCi,dimacus/DotCi,dimacus/DotCi,erikdw/DotCi,DotCi/DotCi,jkrems/DotCi,TheJumpCloud/DotCi,michaelstandley/DotCi,groupon/DotCi,michaelstandley/DotCi,jkrems/DotCi,suryagaddipati/DotCi,suryagaddipati/DotCi,jkrems/DotCi,michaelstandley/DotCi,DotCi/DotCi,TheJumpCloud/DotCi,DotCi/DotCi,groupon/DotCi,bschmeck/DotCi,suryagaddipati/DotCi,bschmeck/DotCi,bschmeck/DotCi,erikdw/DotCi,erikdw/DotCi
/* The MIT License (MIT) Copyright (c) 2014, Groupon, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.groupon.jenkins.github; import com.groupon.jenkins.dynamic.build.cause.GitHubPullRequestCause; import com.groupon.jenkins.dynamic.build.cause.GitHubPushCause; import com.groupon.jenkins.dynamic.build.cause.GithubLogEntry; import com.groupon.jenkins.github.services.GithubRepositoryService; import hudson.model.Cause; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.kohsuke.github.GHRepository; import java.util.ArrayList; import java.util.List; import java.util.Map; public class Payload { private final JSONObject repository; private final JSONObject payloadJson; public Payload(String payload) { this.payloadJson = JSONObject.fromObject(payload); this.repository = payloadJson.getJSONObject("repository"); } public GHRepository getProject() { String url = repository.getString("url").replace("/api/v3/repos", ""); return getGithubRepository(url); } protected GHRepository getGithubRepository(String url) { return new GithubRepositoryService(url).getGithubRepository(); } public boolean isPullRequest() { return payloadJson.containsKey("pull_request"); } public Cause getCause() { if (isPullRequest()) { JSONObject pullRequest = getPullRequest(); final String label = pullRequest.getJSONObject("head").getString("label"); String number = pullRequest.getString("number"); return new GitHubPullRequestCause(this, getSha(), label, number); } else { final String pusherName = payloadJson.getJSONObject("pusher").getString("name"); final String email = payloadJson.getJSONObject("pusher").getString("email"); return new GitHubPushCause(this, getSha(), pusherName, email); } } public String getSha() { if (isPullRequest()) { return getPullRequest().getJSONObject("head").getString("sha"); } else { return payloadJson.getString("after"); } } private JSONObject getPullRequest() { return payloadJson.getJSONObject("pull_request"); } public String getBranch() { if (isPullRequest()) { return "Pull Request: " + getPullRequestNumber(); } else { return payloadJson.getString("ref").replaceAll("refs/heads/", ""); } } public boolean needsBuild() { if (payloadJson.has("ref") && payloadJson.getString("ref").startsWith("refs/tags/")) { return false; } if (isPullRequest()) { return !isPullRequestClosed() && !isPullRequestFromWithinSameRepo(); } else { return !payloadJson.getBoolean("deleted"); } } private boolean isPullRequestClosed() { return "closed".equals(getPullRequest().getString("state")); } private boolean isPullRequestFromWithinSameRepo() { String headRepoUrl = getPullRequest().getJSONObject("head").getJSONObject("repo").getString("ssh_url"); String pullRequestRepoUrl = getPullRequest().getJSONObject("base").getJSONObject("repo").getString("ssh_url"); return headRepoUrl.equals(pullRequestRepoUrl); } public String getBuildDescription() { String shortSha = getSha().substring(0, 7); return String.format("<b>%s</b> (<a href=\"%s\">%s...</a>) <br> %s", getBranchDescription(), getDiffUrl(), shortSha, getPusher()); } public String getBranchDescription() { if (isPullRequest()) { return "Pull Request " + getPullRequestNumber(); } else { return getBranch().replace("origin/", ""); } } public String getPullRequestNumber() { return getPullRequest().getString("number"); } public String getPusher() { if (isPullRequest()) { return payloadJson.getJSONObject("sender").getString("login"); } else { return payloadJson.getJSONObject("pusher").getString("name"); } } public String getDiffUrl() { if (isPullRequest()) { return getPullRequest().getString("html_url"); } else { return payloadJson.getString("compare"); } } public String getProjectUrl() { return getProject().getUrl(); } public Iterable<GithubLogEntry> getLogEntries() { List<GithubLogEntry> logEntries = new ArrayList<GithubLogEntry>(); if (!isPullRequest()) { JSONArray commits = payloadJson.getJSONArray("commits"); for (Object commit : commits) { logEntries.add(convertToLogEntry((Map<String, Object>) commit)); } } return logEntries; } private GithubLogEntry convertToLogEntry(Map<String, Object> commit) { return new GithubLogEntry(commit.get("message").toString(), commit.get("url").toString(), commit.get("id").toString()); } }
src/main/java/com/groupon/jenkins/github/Payload.java
/* The MIT License (MIT) Copyright (c) 2014, Groupon, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.groupon.jenkins.github; import com.groupon.jenkins.dynamic.build.cause.GitHubPullRequestCause; import com.groupon.jenkins.dynamic.build.cause.GitHubPushCause; import com.groupon.jenkins.dynamic.build.cause.GithubLogEntry; import com.groupon.jenkins.github.services.GithubRepositoryService; import hudson.model.Cause; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.kohsuke.github.GHRepository; import java.util.ArrayList; import java.util.List; import java.util.Map; public class Payload { private final JSONObject repository; private final JSONObject payloadJson; public Payload(String payload) { this.payloadJson = JSONObject.fromObject(payload); this.repository = payloadJson.getJSONObject("repository"); } public GHRepository getProject() { String url = repository.getString("url").replace("/api/v3/repos", ""); return getGithubRepository(url); } protected GHRepository getGithubRepository(String url) { return new GithubRepositoryService(url).getGithubRepository(); } public boolean isPullRequest() { return payloadJson.containsKey("pull_request"); } public Cause getCause() { if (isPullRequest()) { JSONObject pullRequest = getPullRequest(); final String label = pullRequest.getJSONObject("head").getString("label"); String number = pullRequest.getString("number"); return new GitHubPullRequestCause(this, getSha(), label, number); } else { final String pusherName = payloadJson.getJSONObject("pusher").getString("name"); final String email = payloadJson.getJSONObject("pusher").getString("email"); return new GitHubPushCause(this, getSha(), pusherName, email); } } public String getSha() { if (isPullRequest()) { return getPullRequest().getJSONObject("head").getString("sha"); } else { return payloadJson.getString("after"); } } private JSONObject getPullRequest() { return payloadJson.getJSONObject("pull_request"); } public String getBranch() { if (isPullRequest()) { return "Pull Request: " + getPullRequestNumber(); } else { return payloadJson.getString("ref").replaceAll("refs/heads/", ""); } } public String getRefSpec() { return isPullRequest() ? "+refs/pull/*:refs/remotes/origin/pr/*" : "+refs/heads/*:refs/remotes/origin/*"; } public boolean needsBuild() { if (payloadJson.has("ref") && payloadJson.getString("ref").startsWith("refs/tags/")) { return false; } if (isPullRequest()) { return !isPullRequestClosed() && !isPullRequestFromWithinSameRepo(); } else { return !payloadJson.getBoolean("deleted"); } } private boolean isPullRequestClosed() { return "closed".equals(getPullRequest().getString("state")); } private boolean isPullRequestFromWithinSameRepo() { String headRepoUrl = getPullRequest().getJSONObject("head").getJSONObject("repo").getString("ssh_url"); String pullRequestRepoUrl = getPullRequest().getJSONObject("base").getJSONObject("repo").getString("ssh_url"); return headRepoUrl.equals(pullRequestRepoUrl); } public String getBuildDescription() { String shortSha = getSha().substring(0, 7); return String.format("<b>%s</b> (<a href=\"%s\">%s...</a>) <br> %s", getBranchDescription(), getDiffUrl(), shortSha, getPusher()); } public String getBranchDescription() { if (isPullRequest()) { return "Pull Request " + getPullRequestNumber(); } else { return getBranch().replace("origin/", ""); } } public String getPullRequestNumber() { return getPullRequest().getString("number"); } public String getPusher() { if (isPullRequest()) { return payloadJson.getJSONObject("sender").getString("login"); } else { return payloadJson.getJSONObject("pusher").getString("name"); } } public String getDiffUrl() { if (isPullRequest()) { return getPullRequest().getString("html_url"); } else { return payloadJson.getString("compare"); } } public String getProjectUrl() { return getProject().getUrl(); } public Iterable<GithubLogEntry> getLogEntries() { List<GithubLogEntry> logEntries = new ArrayList<GithubLogEntry>(); if (!isPullRequest()) { JSONArray commits = payloadJson.getJSONArray("commits"); for (Object commit : commits) { logEntries.add(convertToLogEntry((Map<String, Object>) commit)); } } return logEntries; } private GithubLogEntry convertToLogEntry(Map<String, Object> commit) { return new GithubLogEntry(commit.get("message").toString(), commit.get("url").toString(), commit.get("id").toString()); } }
Remove obsolote method
src/main/java/com/groupon/jenkins/github/Payload.java
Remove obsolote method
Java
mit
5be3cdc07aea086f6fc8363227f3219bdba9c78b
0
checkout/checkout-java-library,CKOTech/checkout-java-library
package test.chargeservice; import static org.junit.Assert.*; import java.io.IOException; import org.junit.Before; import org.junit.Test; import test.TestHelper; import com.checkout.APIClient; import com.checkout.api.services.card.request.CardCreate; import com.checkout.api.services.card.response.Card; import com.checkout.api.services.charge.request.BaseCharge; import com.checkout.api.services.charge.request.BaseChargeInfo; import com.checkout.api.services.charge.request.CardCharge; import com.checkout.api.services.charge.request.CardIdCharge; import com.checkout.api.services.charge.request.CardTokenCharge; import com.checkout.api.services.charge.request.ChargeCapture; import com.checkout.api.services.charge.request.ChargeRefund; import com.checkout.api.services.charge.request.ChargeVoid; import com.checkout.api.services.charge.request.DefaultCardCharge; import com.checkout.api.services.charge.response.Capture; import com.checkout.api.services.charge.response.Charge; import com.checkout.api.services.charge.response.Refund; import com.checkout.api.services.charge.response.Void; import com.checkout.api.services.customer.response.Customer; import com.checkout.api.services.shared.OkResponse; import com.checkout.api.services.shared.Response; import com.checkout.helpers.Environment; import com.google.gson.JsonSyntaxException; public class ChargeServiceTests { APIClient ckoClient; @Before public void setUp() throws Exception { ckoClient = new APIClient("sk_CC937715-4F68-4306-BCBE-640B249A4D50",true); } @Test public void verifyChargeByPaymentToken() throws JsonSyntaxException, IOException { String paymentToken ="pay_tok_4bf11f31-ae5f-4ac6-a942-2105f0f41860";// payment token for the JS charge Response<Charge> chargeResponse = ckoClient.chargeService.verifyCharge(paymentToken); assertEquals(false, chargeResponse.hasError); assertEquals(200, chargeResponse.httpStatus); assertNotNull(chargeResponse.model.id); } @Test public void chargeWithCardToken() throws JsonSyntaxException, IOException, InstantiationException, IllegalAccessException { String cardToken ="card_tok_220E97F3-4DA3-4F09-B7AE-C633D8D5E3E2";// card token for charge CardTokenCharge payload = TestHelper.getCardTokenChargeModel(cardToken); Response<Charge> chargeResponse = ckoClient.chargeService.chargeWithCardToken(payload); Charge charge = chargeResponse.model; assertEquals(false, chargeResponse.hasError); assertEquals(200, chargeResponse.httpStatus); assertEquals(payload.transactionIndicator,charge.transactionIndicator); validateBaseCharge(payload, charge); } @Test public void createChargeWithCard() throws JsonSyntaxException, IOException, InstantiationException, IllegalAccessException { CardCharge payload =TestHelper.getCardChargeModel(); Response<Charge> chargeResponse= ckoClient.chargeService.chargeWithCard(payload); Charge charge = chargeResponse.model; assertEquals(false, chargeResponse.hasError); assertEquals(200, chargeResponse.httpStatus); assertEquals(payload.transactionIndicator,charge.transactionIndicator); validateBaseCharge(payload, charge); validateCard(payload.card, charge.card); } @Test public void createChargeWithCardId() throws JsonSyntaxException, IOException, InstantiationException, IllegalAccessException { Response<Customer> customerResponse = ckoClient.customerService.createCustomer(TestHelper.getCustomerCreateModel()); String cardId = customerResponse.model.cards.data.get(0).id; String customerEmail = customerResponse.model.email; CardIdCharge payload = TestHelper.getCardIdChargeModel(cardId, customerEmail); Response<Charge> chargeResponse= ckoClient.chargeService.chargeWithCardId(payload); Charge charge = chargeResponse.model; assertEquals(false, chargeResponse.hasError); assertEquals(200, chargeResponse.httpStatus); assertEquals(payload.transactionIndicator,charge.transactionIndicator); validateBaseCharge(payload, charge); } @Test public void createChargeWithCustomerDefaultCard() throws JsonSyntaxException, IOException, InstantiationException, IllegalAccessException { Response<Customer> customerResponse = ckoClient.customerService.createCustomer(TestHelper.getCustomerCreateModel()); DefaultCardCharge payload =TestHelper.getDefaultCardChargeModel(customerResponse.model.email); Response<Charge> chargeResponse= ckoClient.chargeService.chargeWithDefaultCustomerCard(payload); Charge charge = chargeResponse.model; assertEquals(false, chargeResponse.hasError); assertEquals(200, chargeResponse.httpStatus); assertEquals(payload.transactionIndicator,charge.transactionIndicator); validateBaseCharge(payload, charge); } @Test public void getCharge() throws JsonSyntaxException, IOException, InstantiationException, IllegalAccessException { CardCharge payload =TestHelper.getCardChargeModel(); Response<Charge> createChargeResponse= ckoClient.chargeService.chargeWithCard(payload); Response<Charge> chargeResponse= ckoClient.chargeService.getCharge(createChargeResponse.model.id); Charge charge = chargeResponse.model; assertEquals(false, chargeResponse.hasError); assertEquals(200, chargeResponse.httpStatus); assertEquals(createChargeResponse.model.transactionIndicator,charge.transactionIndicator); validateBaseCharge(payload, charge); validateCard(payload.card, charge.card); } @Test public void updateCharge() throws JsonSyntaxException, IOException, InstantiationException, IllegalAccessException { Response<Charge> createChargeResponse= ckoClient.chargeService.chargeWithCard(TestHelper.getCardChargeModel()); Response<OkResponse> chargeResponse= ckoClient.chargeService.updateCharge(createChargeResponse.model.id,TestHelper.getChargeUpdateModel()); assertEquals(false, chargeResponse.hasError); assertEquals(200, chargeResponse.httpStatus); assertEquals(chargeResponse.model.message,"ok"); } @Test public void voidCharge() throws JsonSyntaxException, IOException, InstantiationException, IllegalAccessException { Response<Charge> createChargeResponse= ckoClient.chargeService.chargeWithCard(TestHelper.getCardChargeModel()); ChargeVoid payload =TestHelper.getChargeVoidModel(); Response<Void> voidResponse= ckoClient.chargeService.voidCharge(createChargeResponse.model.id,payload); assertEquals(false, voidResponse.hasError); assertEquals(200, voidResponse.httpStatus); assertEquals(voidResponse.model.status.toLowerCase(),"voided"); validateBaseChargeInfo(payload,voidResponse.model); } @Test public void captureChargeWithNoParameters() throws JsonSyntaxException, IOException, InstantiationException, IllegalAccessException { CardCharge cardChargePayload =TestHelper.getCardChargeModel(); Response<Charge> createChargeResponse= ckoClient.chargeService.chargeWithCard(cardChargePayload); Response<Capture> captureResponse= ckoClient.chargeService.captureCharge(createChargeResponse.model.id,null); assertEquals(false, captureResponse.hasError); assertEquals(200, captureResponse.httpStatus); assertEquals(captureResponse.model.status.toLowerCase(),"captured"); validateBaseChargeInfo(cardChargePayload,captureResponse.model); } @Test public void captureChargeWithParameters() throws JsonSyntaxException, IOException, InstantiationException, IllegalAccessException { Response<Charge> createChargeResponse= ckoClient.chargeService.chargeWithCard(TestHelper.getCardChargeModel()); ChargeCapture cardChargePayload =TestHelper.getChargeCaptureModel(); cardChargePayload.value = createChargeResponse.model.value; Response<Capture> captureResponse= ckoClient.chargeService.captureCharge(createChargeResponse.model.id,cardChargePayload); assertEquals(false, captureResponse.hasError); assertEquals(200, captureResponse.httpStatus); assertEquals(cardChargePayload.value,Integer.toString(captureResponse.model.value)); assertEquals(captureResponse.model.status.toLowerCase(),"captured"); validateBaseChargeInfo(cardChargePayload,captureResponse.model); } @Test public void refundChargeWithParameters() throws JsonSyntaxException, IOException, InstantiationException, IllegalAccessException { Response<Charge> createChargeResponse= ckoClient.chargeService.chargeWithCard(TestHelper.getCardChargeModel()); Response<Capture> captureResponse= ckoClient.chargeService.captureCharge(createChargeResponse.model.id,null); ChargeRefund refundPayload =TestHelper.getChargeRefundModel(); Response<Refund> refundResponse= ckoClient.chargeService.refundRequest(captureResponse.model.id,refundPayload); assertEquals(false, refundResponse.hasError); assertEquals(200, refundResponse.httpStatus); assertEquals(refundResponse.model.status.toLowerCase(),"refunded"); validateBaseChargeInfo(refundPayload,refundResponse.model); } /* * Checks if the card returned for charge is same as the payload card * */ private void validateCard(CardCreate payload, Card chargeCard) { assertNotNull(chargeCard.id); assertNotNull(chargeCard.customerId); assertEquals(chargeCard.paymentMethod.toLowerCase(),"visa"); assertNotNull(chargeCard.fingerprint); assertTrue(payload.number.endsWith(chargeCard.last4)); assertEquals(payload.name,chargeCard.name); assertEquals(payload.expiryMonth,chargeCard.expiryMonth); assertEquals(payload.expiryYear,chargeCard.expiryYear); assertEquals(payload.billingDetails.addressLine1, chargeCard.billingDetails.addressLine1); assertEquals(payload.billingDetails.addressLine2, chargeCard.billingDetails.addressLine2); assertEquals(payload.billingDetails.city, chargeCard.billingDetails.city); assertEquals(payload.billingDetails.country, chargeCard.billingDetails.country); assertEquals(payload.billingDetails.phone.countryCode, chargeCard.billingDetails.phone.countryCode); assertEquals(payload.billingDetails.phone.number, chargeCard.billingDetails.phone.number); assertEquals(payload.billingDetails.postcode, chargeCard.billingDetails.postcode); assertEquals(payload.billingDetails.state, chargeCard.billingDetails.state); } /* * Checks if the card charge information for baseCharge matches the payload * */ private void validateBaseCharge(BaseCharge payload, Charge charge) { assertNotNull(charge.id); assertNotNull(charge.created); assertNotNull(charge.status); assertNotNull(charge.metadata); assertNotNull(charge.products); assertEquals(charge.responseCode,"10000"); assertEquals(payload.trackId,charge.trackId); assertEquals(payload.value,charge.value); assertEquals(payload.currency,charge.currency); assertEquals(payload.description,charge.description); assertEquals(payload.email,charge.email); assertEquals(payload.chargeMode,charge.chargeMode); assertEquals(payload.customerIp,charge.customerIp); assertEquals(payload.autoCapture,charge.autoCapture); assertEquals(payload.autoCapTime,charge.autoCapTime); assertEquals(payload.udf1, charge.udf1); assertEquals(payload.udf2, charge.udf2); assertEquals(payload.udf3, charge.udf3); assertEquals(payload.udf4, charge.udf4); assertEquals(payload.udf5, charge.udf5); } private void validateBaseChargeInfo(BaseChargeInfo payload, Void charge) { assertNotNull(charge.id); assertNotNull(charge.originalId); assertNotNull(charge.created); assertNotNull(charge.value); assertNotNull(charge.currency); assertNotNull(charge.metadata); assertNotNull(charge.products); assertEquals(charge.responseCode,"10000"); assertEquals(payload.trackId,charge.trackId); assertEquals(payload.description,charge.description); assertEquals(payload.udf1, charge.udf1); assertEquals(payload.udf2, charge.udf2); assertEquals(payload.udf3, charge.udf3); assertEquals(payload.udf4, charge.udf4); assertEquals(payload.udf5, charge.udf5); } }
checkout/src/test/chargeservice/ChargeServiceTests.java
package test.chargeservice; import static org.junit.Assert.*; import java.io.IOException; import org.junit.Before; import org.junit.Test; import test.TestHelper; import com.checkout.APIClient; import com.checkout.api.services.card.request.CardCreate; import com.checkout.api.services.card.response.Card; import com.checkout.api.services.charge.request.BaseCharge; import com.checkout.api.services.charge.request.BaseChargeInfo; import com.checkout.api.services.charge.request.CardCharge; import com.checkout.api.services.charge.request.CardIdCharge; import com.checkout.api.services.charge.request.CardTokenCharge; import com.checkout.api.services.charge.request.ChargeCapture; import com.checkout.api.services.charge.request.ChargeRefund; import com.checkout.api.services.charge.request.ChargeVoid; import com.checkout.api.services.charge.request.DefaultCardCharge; import com.checkout.api.services.charge.response.Capture; import com.checkout.api.services.charge.response.Charge; import com.checkout.api.services.charge.response.Refund; import com.checkout.api.services.charge.response.Void; import com.checkout.api.services.customer.response.Customer; import com.checkout.api.services.shared.OkResponse; import com.checkout.api.services.shared.Response; import com.checkout.helpers.Environment; import com.google.gson.JsonSyntaxException; public class ChargeServiceTests { APIClient ckoClient; @Before public void setUp() throws Exception { ckoClient = new APIClient("sk_CC937715-4F68-4306-BCBE-640B249A4D50",true); } @Test public void verifyChargeByPaymentToken() throws JsonSyntaxException, IOException { String paymentToken ="pay_tok_4bf11f31-ae5f-4ac6-a942-2105f0f41860";// payment token for the JS charge Response<Charge> chargeResponse = ckoClient.chargeService.verifyCharge(paymentToken); assertEquals(false, chargeResponse.hasError); assertEquals(200, chargeResponse.httpStatus); assertNotNull(chargeResponse.model.id); } @Test public void chargeWithCardToken() throws JsonSyntaxException, IOException, InstantiationException, IllegalAccessException { ckoClient = new APIClient("sk_CC937715-4F68-4306-BCBE-640B249A4D50",Environment.LIVE,true); String cardToken ="card_tok_220E97F3-4DA3-4F09-B7AE-C633D8D5E3E2";// card token for charge CardTokenCharge payload = TestHelper.getCardTokenChargeModel(cardToken); Response<Charge> chargeResponse = ckoClient.chargeService.chargeWithCardToken(payload); Charge charge = chargeResponse.model; assertEquals(false, chargeResponse.hasError); assertEquals(200, chargeResponse.httpStatus); assertEquals(payload.transactionIndicator,charge.transactionIndicator); validateBaseCharge(payload, charge); } @Test public void createChargeWithCard() throws JsonSyntaxException, IOException, InstantiationException, IllegalAccessException { CardCharge payload =TestHelper.getCardChargeModel(); Response<Charge> chargeResponse= ckoClient.chargeService.chargeWithCard(payload); Charge charge = chargeResponse.model; assertEquals(false, chargeResponse.hasError); assertEquals(200, chargeResponse.httpStatus); assertEquals(payload.transactionIndicator,charge.transactionIndicator); validateBaseCharge(payload, charge); validateCard(payload.card, charge.card); } @Test public void createChargeWithCardId() throws JsonSyntaxException, IOException, InstantiationException, IllegalAccessException { Response<Customer> customerResponse = ckoClient.customerService.createCustomer(TestHelper.getCustomerCreateModel()); String cardId = customerResponse.model.cards.data.get(0).id; String customerEmail = customerResponse.model.email; CardIdCharge payload = TestHelper.getCardIdChargeModel(cardId, customerEmail); Response<Charge> chargeResponse= ckoClient.chargeService.chargeWithCardId(payload); Charge charge = chargeResponse.model; assertEquals(false, chargeResponse.hasError); assertEquals(200, chargeResponse.httpStatus); assertEquals(payload.transactionIndicator,charge.transactionIndicator); validateBaseCharge(payload, charge); } @Test public void createChargeWithCustomerDefaultCard() throws JsonSyntaxException, IOException, InstantiationException, IllegalAccessException { Response<Customer> customerResponse = ckoClient.customerService.createCustomer(TestHelper.getCustomerCreateModel()); DefaultCardCharge payload =TestHelper.getDefaultCardChargeModel(customerResponse.model.email); Response<Charge> chargeResponse= ckoClient.chargeService.chargeWithDefaultCustomerCard(payload); Charge charge = chargeResponse.model; assertEquals(false, chargeResponse.hasError); assertEquals(200, chargeResponse.httpStatus); assertEquals(payload.transactionIndicator,charge.transactionIndicator); validateBaseCharge(payload, charge); } @Test public void getCharge() throws JsonSyntaxException, IOException, InstantiationException, IllegalAccessException { CardCharge payload =TestHelper.getCardChargeModel(); Response<Charge> createChargeResponse= ckoClient.chargeService.chargeWithCard(payload); Response<Charge> chargeResponse= ckoClient.chargeService.getCharge(createChargeResponse.model.id); Charge charge = chargeResponse.model; assertEquals(false, chargeResponse.hasError); assertEquals(200, chargeResponse.httpStatus); assertEquals(createChargeResponse.model.transactionIndicator,charge.transactionIndicator); validateBaseCharge(payload, charge); validateCard(payload.card, charge.card); } @Test public void updateCharge() throws JsonSyntaxException, IOException, InstantiationException, IllegalAccessException { Response<Charge> createChargeResponse= ckoClient.chargeService.chargeWithCard(TestHelper.getCardChargeModel()); Response<OkResponse> chargeResponse= ckoClient.chargeService.updateCharge(createChargeResponse.model.id,TestHelper.getChargeUpdateModel()); assertEquals(false, chargeResponse.hasError); assertEquals(200, chargeResponse.httpStatus); assertEquals(chargeResponse.model.message,"ok"); } @Test public void voidCharge() throws JsonSyntaxException, IOException, InstantiationException, IllegalAccessException { Response<Charge> createChargeResponse= ckoClient.chargeService.chargeWithCard(TestHelper.getCardChargeModel()); ChargeVoid payload =TestHelper.getChargeVoidModel(); Response<Void> voidResponse= ckoClient.chargeService.voidCharge(createChargeResponse.model.id,payload); assertEquals(false, voidResponse.hasError); assertEquals(200, voidResponse.httpStatus); assertEquals(voidResponse.model.status.toLowerCase(),"voided"); validateBaseChargeInfo(payload,voidResponse.model); } @Test public void captureChargeWithNoParameters() throws JsonSyntaxException, IOException, InstantiationException, IllegalAccessException { CardCharge cardChargePayload =TestHelper.getCardChargeModel(); Response<Charge> createChargeResponse= ckoClient.chargeService.chargeWithCard(cardChargePayload); Response<Capture> captureResponse= ckoClient.chargeService.captureCharge(createChargeResponse.model.id,null); assertEquals(false, captureResponse.hasError); assertEquals(200, captureResponse.httpStatus); assertEquals(captureResponse.model.status.toLowerCase(),"captured"); validateBaseChargeInfo(cardChargePayload,captureResponse.model); } @Test public void captureChargeWithParameters() throws JsonSyntaxException, IOException, InstantiationException, IllegalAccessException { Response<Charge> createChargeResponse= ckoClient.chargeService.chargeWithCard(TestHelper.getCardChargeModel()); ChargeCapture cardChargePayload =TestHelper.getChargeCaptureModel(); cardChargePayload.value = createChargeResponse.model.value; Response<Capture> captureResponse= ckoClient.chargeService.captureCharge(createChargeResponse.model.id,cardChargePayload); assertEquals(false, captureResponse.hasError); assertEquals(200, captureResponse.httpStatus); assertEquals(cardChargePayload.value,Integer.toString(captureResponse.model.value)); assertEquals(captureResponse.model.status.toLowerCase(),"captured"); validateBaseChargeInfo(cardChargePayload,captureResponse.model); } @Test public void refundChargeWithParameters() throws JsonSyntaxException, IOException, InstantiationException, IllegalAccessException { Response<Charge> createChargeResponse= ckoClient.chargeService.chargeWithCard(TestHelper.getCardChargeModel()); Response<Capture> captureResponse= ckoClient.chargeService.captureCharge(createChargeResponse.model.id,null); ChargeRefund refundPayload =TestHelper.getChargeRefundModel(); Response<Refund> refundResponse= ckoClient.chargeService.refundRequest(captureResponse.model.id,refundPayload); assertEquals(false, refundResponse.hasError); assertEquals(200, refundResponse.httpStatus); assertEquals(refundResponse.model.status.toLowerCase(),"refunded"); validateBaseChargeInfo(refundPayload,refundResponse.model); } /* * Checks if the card returned for charge is same as the payload card * */ private void validateCard(CardCreate payload, Card chargeCard) { assertNotNull(chargeCard.id); assertNotNull(chargeCard.customerId); assertEquals(chargeCard.paymentMethod.toLowerCase(),"visa"); assertNotNull(chargeCard.fingerprint); assertTrue(payload.number.endsWith(chargeCard.last4)); assertEquals(payload.name,chargeCard.name); assertEquals(payload.expiryMonth,chargeCard.expiryMonth); assertEquals(payload.expiryYear,chargeCard.expiryYear); assertEquals(payload.billingDetails.addressLine1, chargeCard.billingDetails.addressLine1); assertEquals(payload.billingDetails.addressLine2, chargeCard.billingDetails.addressLine2); assertEquals(payload.billingDetails.city, chargeCard.billingDetails.city); assertEquals(payload.billingDetails.country, chargeCard.billingDetails.country); assertEquals(payload.billingDetails.phone.countryCode, chargeCard.billingDetails.phone.countryCode); assertEquals(payload.billingDetails.phone.number, chargeCard.billingDetails.phone.number); assertEquals(payload.billingDetails.postcode, chargeCard.billingDetails.postcode); assertEquals(payload.billingDetails.state, chargeCard.billingDetails.state); } /* * Checks if the card charge information for baseCharge matches the payload * */ private void validateBaseCharge(BaseCharge payload, Charge charge) { assertNotNull(charge.id); assertNotNull(charge.created); assertNotNull(charge.status); assertNotNull(charge.metadata); assertNotNull(charge.products); assertEquals(charge.responseCode,"10000"); assertEquals(payload.trackId,charge.trackId); assertEquals(payload.value,charge.value); assertEquals(payload.currency,charge.currency); assertEquals(payload.description,charge.description); assertEquals(payload.email,charge.email); assertEquals(payload.chargeMode,charge.chargeMode); assertEquals(payload.customerIp,charge.customerIp); assertEquals(payload.autoCapture,charge.autoCapture); assertEquals(payload.autoCapTime,charge.autoCapTime); assertEquals(payload.udf1, charge.udf1); assertEquals(payload.udf2, charge.udf2); assertEquals(payload.udf3, charge.udf3); assertEquals(payload.udf4, charge.udf4); assertEquals(payload.udf5, charge.udf5); } private void validateBaseChargeInfo(BaseChargeInfo payload, Void charge) { assertNotNull(charge.id); assertNotNull(charge.originalId); assertNotNull(charge.created); assertNotNull(charge.value); assertNotNull(charge.currency); assertNotNull(charge.metadata); assertNotNull(charge.products); assertEquals(charge.responseCode,"10000"); assertEquals(payload.trackId,charge.trackId); assertEquals(payload.description,charge.description); assertEquals(payload.udf1, charge.udf1); assertEquals(payload.udf2, charge.udf2); assertEquals(payload.udf3, charge.udf3); assertEquals(payload.udf4, charge.udf4); assertEquals(payload.udf5, charge.udf5); } }
Live test reference removed
checkout/src/test/chargeservice/ChargeServiceTests.java
Live test reference removed
Java
mit
10499fced107fb080a0108a2fbd0ad9e6470add5
0
Wei620/LC150
import java.util.List; import java.util.ArrayList; import java.util.Arrays; /** * Given an array S of n integers, are there elements a, b, c in S such that a * + b + c = 0? Find all unique triplets in the array which gives the sum * of zero. * * Note: * Elements in a triplet (a,b,c) must be in <strong>non-descending</strong> * order. * (ie, a ≤ b ≤ c) * The solution set must not contain <strong>duplicate</strong> triplets. * * For example, given array S = {-1 0 1 2 -1 -4}, * * A solution set is: * (-1, 0, 1) * (-1, -1, 2) * * Tags: Array, Two Pointers */ class ThreeSum { public static void main(String[] args) { ThreeSum t = new ThreeSum(); int[] s = { -1, 0, 1, 2, -1, -4 }; t.printResult(t.threeSum(s)); } /** * Two Pointers. * Sort given array first. * Traverse the array with 1 pointer * Use 2 more pointers from both start(i + 1) and end to find target */ public List<List<Integer>> threeSum(int[] num) { List<List<Integer>> res = new ArrayList<List<Integer>>(); Arrays.sort(num); for (int i = 0; i < num.length - 2; i++) { //Line 43 and 52 rules out the impossible case in advance. if (i > 0 && num[i] == num[i - 1]) continue; // skip duplicate if (num[i] > 0) break; // stop at positive integers int j = i + 1; int k = num.length - 1; while (j < k) { if (j > i + 1 && num[j] == num[j - 1]) { // skip duplicate j++; continue; } if (num[i] + num[j] > 0) break;// already bigger than 0 /* No need for checking duplicates of num[k] considering j++ and k-- at the end; Both num[i] and num[j] are free of duplicates already. */ if (num[i] + num[j] + num[k] < 0) j++; else if (num[i] + num[j] + num[k] > 0) k--; else { // num[i] + num[j] + num[k] == 0 List<Integer> triplets = new ArrayList<Integer>(); triplets.add(num[i]); triplets.add(num[j]); triplets.add(num[k]); res.add(triplets); j++; // move j ahead k--; } } } return res; } private void printResult(List<List<Integer>> result) { for (List<Integer> l : result) { System.out.print("{"); for (Integer i : l) { System.out.print(" " + i); } System.out.println(" }"); } } }
Medium/ThreeSum.java
import java.util.List; import java.util.ArrayList; import java.util.Arrays; /** * Given an array S of n integers, are there elements a, b, c in S such that a * + b + c = 0? Find all unique triplets in the array which gives the sum * of zero. * * Note: * Elements in a triplet (a,b,c) must be in <strong>non-descending</strong> * order. * (ie, a ≤ b ≤ c) * The solution set must not contain <strong>duplicate</strong> triplets. * * For example, given array S = {-1 0 1 2 -1 -4}, * * A solution set is: * (-1, 0, 1) * (-1, -1, 2) * * Tags: Array, Two Pointers */ class ThreeSum { public static void main(String[] args) { ThreeSum t = new ThreeSum(); int[] s = { -1, 0, 1, 2, -1, -4 }; t.printResult(t.threeSum(s)); } /** * Two Pointers. * Sort given array first. * Traverse the array with 1 pointer * Use 2 more pointers from both start(i + 1) and end to find target */ public List<List<Integer>> threeSum(int[] num) { List<List<Integer>> res = new ArrayList<List<Integer>>(); Arrays.sort(num); for (int i = 0; i < num.length - 2; i++) { if (i > 0 && num[i] == num[i - 1]) continue; // skip duplicate if (num[i] > 0) break; // stop at positive integers int j = i + 1; int k = num.length - 1; while (j < k) { if (j > i + 1 && num[j] == num[j - 1]) { // skip duplicate j++; continue; } if (num[i] + num[j] > 0) break;// already bigger than 0 if (num[i] + num[j] + num[k] < 0) j++; else if (num[i] + num[j] + num[k] > 0) k--; else { // num[i] + num[j] + num[k] == 0 List<Integer> triplets = new ArrayList<Integer>(); triplets.add(num[i]); triplets.add(num[j]); triplets.add(num[k]); res.add(triplets); j++; // move j ahead k--; } } } return res; } private void printResult(List<List<Integer>> result) { for (List<Integer> l : result) { System.out.print("{"); for (Integer i : l) { System.out.print(" " + i); } System.out.println(" }"); } } }
Added comments on why there's no need on checking duplicates of K. Added comments on the benefit of ruling out the impossible cases.
Medium/ThreeSum.java
Added comments on why there's no need on checking duplicates of K. Added comments on the benefit of ruling out the impossible cases.
Java
mit
d0da0e366d83af102b1c6104021102abb8ac960f
0
seqcode/seqcode-core,seqcode/seqcode-core,seqcode/seqcode-core,seqcode/seqcode-core
package org.seqcode.projects.galaxyexo; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.seqcode.deepseq.experiments.ControlledExperiment; import org.seqcode.deepseq.experiments.ExperimentCondition; import org.seqcode.deepseq.experiments.ExperimentManager; import org.seqcode.deepseq.experiments.ExptConfig; import org.seqcode.deepseq.experiments.Sample; import org.seqcode.genome.Genome; import org.seqcode.genome.GenomeConfig; import org.seqcode.genome.location.Region; import org.seqcode.gseutils.ArgParser; /** * Utility to output a signal fraction calculated based on a normalization. It will also output a scaling factor, number of reads etc. * It includes an option to output hit counts of signal and control experiments in a given bin size in genome wide. * * Input: * - Genome * - Signal experiment * - Control experiment * Output: * - A text file listing condition, signal hits, control hits, scaling factor, and a signal fraction. * * @author naomi yamada */ public class ChIPQC { protected GenomeConfig gconfig; protected ExptConfig econfig; protected ExperimentManager manager; protected Genome genome; public ChIPQC(GenomeConfig gcon, ExptConfig econ, ExperimentManager man){ gconfig = gcon; econfig = econ; manager = man; genome = econfig.getGenome(); } public void printQCMetrics(){ double ncis, signalHits, controlHits; double IPstrength=0; for(ExperimentCondition exptCond: manager.getConditions()){ for(ControlledExperiment rep : exptCond.getReplicates()){ if (!rep.hasControl()){ System.err.println("Please provide a control experiment"); System.exit(1); } ncis = rep.getControlScaling(); signalHits = rep.getSignal().getHitCount(); controlHits = rep.getControl().getHitCount(); IPstrength = 1-(ncis/(signalHits/controlHits)); if (IPstrength<0) IPstrength=0; System.out.println("Condition:"+rep.getCondName()+"\tSignal:"+signalHits+"\tControl:"+controlHits+"\tScalingFactor:"+ncis+"\tIPstrength: "+IPstrength); } } manager.close(); } public void printPairedBinCounts(int scalingWindowSize) throws FileNotFoundException, UnsupportedEncodingException{ Map<Sample, List<Float>> sampleWindowCounts = new HashMap<Sample, List<Float>>(); List<Sample> allSamples = new ArrayList<Sample>(); List<Sample> signalSamples = new ArrayList<Sample>(); List<Sample> controlSamples = new ArrayList<Sample>(); for(ExperimentCondition exptCond: manager.getConditions()){ for(ControlledExperiment rep : exptCond.getReplicates()){ signalSamples.add(rep.getSignal()); controlSamples.add(rep.getControl()); } allSamples.addAll(signalSamples); allSamples.addAll(controlSamples); int listSize=0; for(Sample samp : allSamples){ List<Float> currSampCounts = new ArrayList<Float>(); for(String chrom:genome.getChromList()) { int chrlen = genome.getChromLength(chrom); for (int start = 1; start < chrlen - scalingWindowSize; start += scalingWindowSize) { Region r = new Region(genome, chrom, start, start + scalingWindowSize); currSampCounts.add(samp.countHits(r)); } } sampleWindowCounts.put(samp, currSampCounts); listSize = currSampCounts.size(); } } for(ExperimentCondition exptCond: manager.getConditions()){ for(ControlledExperiment rep : exptCond.getReplicates()){ PrintWriter writer = new PrintWriter(rep.getName()+rep.getCondName()+".counts.txt","UTF-8"); writer.println("#signalBinCounts : controlBinCounts"+"\t"+"#"+rep.getCondName()); List<Float> signalSampCounts = new ArrayList<Float>(); List<Float> controlSampCounts = new ArrayList<Float>(); signalSampCounts = sampleWindowCounts.get(rep.getSignal()); controlSampCounts = sampleWindowCounts.get(rep.getControl()); for (int i = 0; i < signalSampCounts.size(); i ++){ if (signalSampCounts.get(i)+controlSampCounts.get(i)>0) writer.println(signalSampCounts.get(i)+":"+controlSampCounts.get(i)); } } } manager.close(); } public void printGenomeBins(int scalingWindowSize) throws FileNotFoundException{ File outFile = new File(System.getProperty("user.dir")+File.separator+"genome_windows.bed"); PrintWriter writer = new PrintWriter(outFile); for(String chrom:genome.getChromList()) { int chrlen = genome.getChromLength(chrom); for (int start = 1; start < chrlen - scalingWindowSize; start += scalingWindowSize) { Region r = new Region(genome, chrom, start, start + scalingWindowSize); writer.write("chrm"+chrom.toString()+"\t"+start+"\t"+start + scalingWindowSize+"\n"); } } writer.close(); } public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException { /*** * example: * java org.seqcode.projects.galaxyexo.ChIPQC --species "Homo sapiens;hg19" --expt expt.bam --ctrl ctrl.bam --format BAM --scalewin 5000 --plotscaling --binCounts > NCIS.out ***/ ArgParser ap = new ArgParser(args); if((!ap.hasKey("species") && !ap.hasKey("geninfo"))) { System.err.println("Usage:\n" + "RegionCountSorter\n" + "\t--species <organism;genome> OR\n" + "\t--geninfo <genome info file> AND --seq <path to seqs>\n" + "\t--expt <experiments> \n" + "\nOPTIONS:\n" + "\t--scalewin <window size for scaling procedure (default=10000)>\n" + "\t--binCounts [flag to print bin counts] \n" + "\t--plotscaling [flag to plot diagnostic information for the chosen scaling method]\n" + "\t--printBins [flag to print genomic bin coordinates in bed file]\n" + ""); System.exit(0); } GenomeConfig gconf = new GenomeConfig(args); ExptConfig econf = new ExptConfig(gconf.getGenome(), args); econf.setPerBaseReadFiltering(false); ExperimentManager manager = new ExperimentManager(econf); ChIPQC exoQC = new ChIPQC(gconf, econf, manager); exoQC.printQCMetrics(); if (ap.hasKey("binCounts")) exoQC.printPairedBinCounts(econf.getScalingSlidingWindow()); if (ap.hasKey("printBins")) exoQC.printGenomeBins(econf.getScalingSlidingWindow()); manager.close(); } }
src/org/seqcode/projects/galaxyexo/ChIPQC.java
package org.seqcode.projects.galaxyexo; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.seqcode.deepseq.experiments.ControlledExperiment; import org.seqcode.deepseq.experiments.ExperimentCondition; import org.seqcode.deepseq.experiments.ExperimentManager; import org.seqcode.deepseq.experiments.ExptConfig; import org.seqcode.deepseq.experiments.Sample; import org.seqcode.genome.Genome; import org.seqcode.genome.GenomeConfig; import org.seqcode.genome.location.Region; import org.seqcode.gseutils.ArgParser; /** * Utility to output a signal fraction calculated based on a normalization. It will also output a scaling factor, number of reads etc. * It includes an option to output hit counts of signal and control experiments in a given bin size in genome wide. * * Input: * - Genome * - Signal experiment * - Control experiment * Output: * - A text file listing condition, signal hits, control hits, scaling factor, and a signal fraction. * * @author naomi yamada */ public class ChIPQC { protected GenomeConfig gconfig; protected ExptConfig econfig; protected ExperimentManager manager; public ChIPQC(GenomeConfig gcon, ExptConfig econ, ExperimentManager man){ gconfig = gcon; econfig = econ; manager = man; } public void printQCMetrics(){ double ncis, signalHits, controlHits; double IPstrength=0; for(ExperimentCondition exptCond: manager.getConditions()){ for(ControlledExperiment rep : exptCond.getReplicates()){ if (!rep.hasControl()){ System.err.println("Please provide a control experiment"); System.exit(1); } ncis = rep.getControlScaling(); signalHits = rep.getSignal().getHitCount(); controlHits = rep.getControl().getHitCount(); IPstrength = 1-(ncis/(signalHits/controlHits)); if (IPstrength<0) IPstrength=0; System.out.println("Condition:"+rep.getCondName()+"\tSignal:"+signalHits+"\tControl:"+controlHits+"\tScalingFactor:"+ncis+"\tIPstrength: "+IPstrength); } } manager.close(); } public void printPairedBinCounts(int scalingWindowSize) throws FileNotFoundException, UnsupportedEncodingException{ Genome genome = econfig.getGenome(); Map<Sample, List<Float>> sampleWindowCounts = new HashMap<Sample, List<Float>>(); List<Sample> allSamples = new ArrayList<Sample>(); List<Sample> signalSamples = new ArrayList<Sample>(); List<Sample> controlSamples = new ArrayList<Sample>(); for(ExperimentCondition exptCond: manager.getConditions()){ for(ControlledExperiment rep : exptCond.getReplicates()){ signalSamples.add(rep.getSignal()); controlSamples.add(rep.getControl()); } allSamples.addAll(signalSamples); allSamples.addAll(controlSamples); int listSize=0; for(Sample samp : allSamples){ List<Float> currSampCounts = new ArrayList<Float>(); for(String chrom:genome.getChromList()) { int chrlen = genome.getChromLength(chrom); for (int start = 1; start < chrlen - scalingWindowSize; start += scalingWindowSize) { Region r = new Region(genome, chrom, start, start + scalingWindowSize); currSampCounts.add(samp.countHits(r)); } } sampleWindowCounts.put(samp, currSampCounts); listSize = currSampCounts.size(); } } for(ExperimentCondition exptCond: manager.getConditions()){ for(ControlledExperiment rep : exptCond.getReplicates()){ PrintWriter writer = new PrintWriter(rep.getName()+rep.getCondName()+".counts.txt","UTF-8"); writer.println("#signalBinCounts : controlBinCounts"+"\t"+"#"+rep.getCondName()); List<Float> signalSampCounts = new ArrayList<Float>(); List<Float> controlSampCounts = new ArrayList<Float>(); signalSampCounts = sampleWindowCounts.get(rep.getSignal()); controlSampCounts = sampleWindowCounts.get(rep.getControl()); for (int i = 0; i < signalSampCounts.size(); i ++){ if (signalSampCounts.get(i)+controlSampCounts.get(i)>0) writer.println(signalSampCounts.get(i)+":"+controlSampCounts.get(i)); } } } manager.close(); } public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException { /*** * example: * java org.seqcode.projects.galaxyexo.ChIPQC --species "Homo sapiens;hg19" --expt expt.bam --ctrl ctrl.bam --format BAM --scalewin 5000 --plotscaling --binCounts > NCIS.out ***/ ArgParser ap = new ArgParser(args); if((!ap.hasKey("species") && !ap.hasKey("geninfo"))) { System.err.println("Usage:\n" + "RegionCountSorter\n" + "\t--species <organism;genome> OR\n" + "\t--geninfo <genome info file> AND --seq <path to seqs>\n" + "\t--expt <experiments> \n" + "\nOPTIONS:\n" + "\t--scalewin <window size for scaling procedure (default=10000)>\n" + "\t--binCounts [flag to print bin counts] \n" + "\t--plotscaling [flag to plot diagnostic information for the chosen scaling method]\n" + ""); System.exit(0); } GenomeConfig gconf = new GenomeConfig(args); ExptConfig econf = new ExptConfig(gconf.getGenome(), args); econf.setPerBaseReadFiltering(false); ExperimentManager manager = new ExperimentManager(econf); ChIPQC exoQC = new ChIPQC(gconf, econf, manager); exoQC.printQCMetrics(); if (ap.hasKey("binCounts")) exoQC.printPairedBinCounts(econf.getScalingSlidingWindow()); manager.close(); } }
Adding a function to print genomic bin coordinates used for scaling.
src/org/seqcode/projects/galaxyexo/ChIPQC.java
Adding a function to print genomic bin coordinates used for scaling.
Java
mit
a26b0ba58c7fbbaa35851ef20e7dd0cb0691fe9e
0
bedditor/ohtu-Alarmclock
package ohtu.beddit.activity; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.WindowManager; import android.webkit.*; import ohtu.beddit.R; import ohtu.beddit.io.FileHandler; import ohtu.beddit.io.PreferenceService; import ohtu.beddit.api.ApiController; import ohtu.beddit.api.jsonclassimpl.ApiControllerClassImpl; import ohtu.beddit.utils.Utils; import ohtu.beddit.web.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class AuthActivity extends Activity implements TokenListener { WebView webview; private final String TAG = "AuthActivity"; private FileHandler fileHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.v(TAG, "OnCreate"); setContentView(R.layout.webview); fileHandler = new FileHandler(this); webview = (WebView) findViewById(R.id.webLayout); webview.clearHistory(); removeCookies(); setSettings(); openAuthBrowser(); } @Override public void onTokenReceived(String token) { // Seeing if we get the right url Pattern code = Pattern.compile("\\Qhttps://peach-app.appspot.com/oauth?code=\\E(.+)"); Pattern error = Pattern.compile("\\Qhttps://peach-app.appspot.com/oauth?error=access_denied\\E"); Matcher match = code.matcher(token); Matcher problem = error.matcher(token); Log.v(TAG, "Trying to match url: " + token); if (match.matches()) { Log.v(TAG, "Success"); // We got the right url so we construct our https get url and give it to OAuthHandling class which will get the access token by https connection token = "https://api.beddit.com/api/oauth/access_token?client_id="+ fileHandler.getClientInfo(FileHandler.CLIENT_ID) + "&redirect_uri=https://peach-app.appspot.com/oauth&client_secret="+ fileHandler.getClientInfo(FileHandler.CLIENT_SECRET) + "&grant_type=code&code="+match.group(1); String result = OAuthHandling.getAccessToken(this, token); // If we get error, well you shouldn't. We close the program because we won't get correct access_token. Breaks other code? if (result.equalsIgnoreCase("error")) { Log.v(TAG, "Something went wrong while getting access token from correct url. *pfft*"); fail(false); }else{ Log.v(TAG, "result: "+result); // We put the correct access token to safe and be happy. User is allowed to use the program now. PreferenceService.setToken(this, result); Log.v("Toukenizer:", PreferenceService.getToken(this)); saveUserData(); finish(); } } // If user doesn't allow the program to access, we simply terminate the program. if (problem.matches()) { Log.v(TAG, "problem.matches() == true"); fail(false); } } public void derpDialog(){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("CRASH!"); builder.setCancelable(false); builder.setPositiveButton("D:", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { BedditWebConnector blob = new BedditWebConnector(); try{ Log.v("derp", "tila on: "+blob.getQueueStateJson(AuthActivity.this, Utils.getTodayAsQueryDateString())); }catch (Exception e){ } } }); AlertDialog alert = builder.create(); Log.v("dialogi", "nakyy: "+alert.isShowing()); alert.show(); Log.v("dialogi", "nakyy: "+alert.isShowing()); } private void fail(boolean cancelledByUser){ Log.v(TAG, "fail called"); Intent resultIntent = new Intent((String) null); if(cancelledByUser){ setResult(MainActivity.RESULT_AUTH_CANCELLED, resultIntent); } else { setResult(MainActivity.RESULT_AUTH_FAILED, resultIntent); } PreferenceService.setUsername(this, ""); PreferenceService.setToken(this, ""); finish(); } private void saveUserData() { Log.v(TAG, "saving user data"); try{ ApiController apiController = new ApiControllerClassImpl(new BedditWebConnector()); apiController.updateUserInfo(this); //updates the info in apicontroller for lines below: PreferenceService.setUsername(this, apiController.getUsername(0)); PreferenceService.setFirstName(this, apiController.getFirstName(0)); PreferenceService.setLastName(this, apiController.getLastName(0)); } catch (Exception e){ Log.v(TAG, "saving user data failed"); fail(false); } } @Override public void onBackPressed() { fail(true); } @Override public void finish() { Log.v(TAG, "finishing"); webview.clearCache(true); webview.clearView(); webview.clearHistory(); super.finish(); } private void setSettings() { // Here we set various settings regarding browser experience. WebSettings settings = webview.getSettings(); webview.setInitialScale(1); settings.setSavePassword(false); settings.setCacheMode(WebSettings.LOAD_NO_CACHE); settings.setAppCacheEnabled(false); settings.setUseWideViewPort(true); settings.setLoadWithOverviewMode(true); settings.setDefaultZoom(WebSettings.ZoomDensity.FAR); } private void openAuthBrowser() { // Initialize the webclient and open it to this webview. AmazingWebClient client = new AmazingWebClient(this); client.addTokenListener(this); webview.setWebViewClient(client); Log.v(TAG, fileHandler.getClientInfo(FileHandler.CLIENT_ID) + " secret: " + fileHandler.getClientInfo(FileHandler.CLIENT_SECRET)); webview.loadUrl("https://api.beddit.com/api/oauth/authorize?client_id="+ fileHandler.getClientInfo(FileHandler.CLIENT_ID) + "&redirect_uri=https://peach-app.appspot.com/oauth&response_type=code"); } private void removeCookies() { // Removes all cookies that the webviewclient or webview has. CookieSyncManager cookieMonster = CookieSyncManager.createInstance(webview.getContext()); CookieManager.getInstance().removeSessionCookie(); CookieManager.getInstance().removeAllCookie(); cookieMonster.sync(); } @Override public void onAttachedToWindow() { Log.v(TAG,"SETTING KEYGUARD ON"); Log.v(TAG, "onAttachedToWindow"); this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); super.onAttachedToWindow(); //To change body of overridden methods use File | Settings | File Templates. } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_HOME) { Log.v(TAG, "HOME PRESSED"); exitApplication(); } if (keyCode == KeyEvent.KEYCODE_BACK) { Log.v(TAG, "BACK PRESSED"); } if (keyCode == KeyEvent.KEYCODE_CALL) { Log.v(TAG, "CALL PRESSED"); exitApplication(); } return super.onKeyDown(keyCode, event); } private void exitApplication() { Log.v(TAG, "CLOSING APPLICATION"); Intent exitIntent = new Intent(this, ExitActivity.class); exitIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(exitIntent); fail(true); } }
beddit_alarm/src/ohtu/beddit/activity/AuthActivity.java
package ohtu.beddit.activity; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.WindowManager; import android.webkit.*; import ohtu.beddit.R; import ohtu.beddit.io.FileHandler; import ohtu.beddit.io.PreferenceService; import ohtu.beddit.api.ApiController; import ohtu.beddit.api.jsonclassimpl.ApiControllerClassImpl; import ohtu.beddit.utils.Utils; import ohtu.beddit.web.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class AuthActivity extends Activity implements TokenListener { WebView webview; private final String TAG = "AuthActivity"; private FileHandler fileHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.v(TAG, "OnCreate"); setContentView(R.layout.webview); fileHandler = new FileHandler(this); webview = (WebView) findViewById(R.id.webLayout); webview.clearHistory(); removeCookies(); setSettings(); openAuthBrowser(); } @Override public void onTokenReceived(String token) { // Seeing if we get the right url Pattern code = Pattern.compile("\\Qhttps://peach-app.appspot.com/oauth?code=\\E(.+)"); Pattern error = Pattern.compile("\\Qhttps://peach-app.appspot.com/oauth?error=access_denied\\E"); Matcher match = code.matcher(token); Matcher problem = error.matcher(token); Log.v(TAG, "Trying to match url: " + token); if (match.matches()) { Log.v(TAG, "Success"); // We got the right url so we construct our https get url and give it to OAuthHandling class which will get the access token by https connection token = "https://api.beddit.com/api/oauth/access_token?client_id="+ fileHandler.getClientInfo(FileHandler.CLIENT_ID) + "&redirect_uri=https://peach-app.appspot.com/oauth&client_secret="+ fileHandler.getClientInfo(FileHandler.CLIENT_SECRET) + "&grant_type=code&code="+match.group(1); String result = OAuthHandling.getAccessToken(this, token); // If we get error, well you shouldn't. We close the program because we won't get correct access_token. Breaks other code? if (result.equalsIgnoreCase("error")) { Log.v(TAG, "Something went wrong while getting access token from correct url. *pfft*"); fail(false); }else{ Log.v(TAG, "result: "+result); // We put the correct access token to safe and be happy. User is allowed to use the program now. PreferenceService.setToken(this, result); Log.v("Toukenizer:", PreferenceService.getToken(this)); saveUserData(); finish(); } } // If user doesn't allow the program to access, we simply terminate the program. if (problem.matches()) { Log.v(TAG, "problem.matches() == true"); fail(false); } } public void derpDialog(){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("CRASH!"); builder.setCancelable(false); builder.setPositiveButton("D:", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { BedditWebConnector blob = new BedditWebConnector(); try{ Log.v("derp", "tila on: "+blob.getQueueStateJson(AuthActivity.this, Utils.getTodayAsQueryDateString())); }catch (Exception e){ } } }); AlertDialog alert = builder.create(); Log.v("dialogi", "nakyy: "+alert.isShowing()); alert.show(); Log.v("dialogi", "nakyy: "+alert.isShowing()); } private void fail(boolean cancelledByUser){ Log.v(TAG, "fail called"); Intent resultIntent = new Intent((String) null); if(cancelledByUser){ setResult(MainActivity.RESULT_AUTH_CANCELLED, resultIntent); } else { setResult(MainActivity.RESULT_AUTH_FAILED, resultIntent); } PreferenceService.setUsername(this, ""); PreferenceService.setToken(this, ""); finish(); } private void saveUserData() { Log.v(TAG, "saving user data"); try{ ApiController apiController = new ApiControllerClassImpl(new BedditWebConnector()); apiController.updateUserInfo(this); //updates the info in apicontroller for lines below: PreferenceService.setUsername(this, apiController.getUsername(0)); PreferenceService.setFirstName(this, apiController.getFirstName(0)); PreferenceService.setLastName(this, apiController.getLastName(0)); } catch (Exception e){ Log.v(TAG, "saving user data failed"); fail(false); } } @Override public void onBackPressed() { fail(true); } @Override public void finish() { Log.v(TAG, "finishing"); webview.clearCache(true); webview.clearView(); webview.clearHistory(); super.finish(); } private void setSettings() { // Here we set various settings regarding browser experience. WebSettings settings = webview.getSettings(); webview.setInitialScale(1); settings.setSavePassword(false); settings.setCacheMode(WebSettings.LOAD_NO_CACHE); settings.setAppCacheEnabled(false); settings.setUseWideViewPort(true); settings.setLoadWithOverviewMode(true); settings.setDefaultZoom(WebSettings.ZoomDensity.FAR); } private void openAuthBrowser() { // Initialize the webclient and open it to this webview. AmazingWebClient client = new AmazingWebClient(this); client.addTokenListener(this); webview.setWebViewClient(client); Log.v(TAG, fileHandler.getClientInfo(FileHandler.CLIENT_ID) + " secret: " + fileHandler.getClientInfo(FileHandler.CLIENT_SECRET)); webview.loadUrl("https://api.beddit.com/api/oauth/authorize?client_id="+ fileHandler.getClientInfo(FileHandler.CLIENT_ID) + "&redirect_uri=https://peach-app.appspot.com/oauth&response_type=code"); } private void removeCookies() { // Removes all cookies that the webviewclient or webview has. CookieSyncManager cookieMonster = CookieSyncManager.createInstance(webview.getContext()); CookieManager.getInstance().removeSessionCookie(); CookieManager.getInstance().removeAllCookie(); cookieMonster.sync(); } @Override public void onAttachedToWindow() { Log.v(TAG,"SETTING KEYGUARD ON"); Log.v(TAG, "onAttachedToWindow"); this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); super.onAttachedToWindow(); //To change body of overridden methods use File | Settings | File Templates. } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_HOME) { Log.v(TAG, "HOME PRESSED"); exitApplication(); } if (keyCode == KeyEvent.KEYCODE_BACK) { Log.v(TAG, "BACK PRESSED"); } if (keyCode == KeyEvent.KEYCODE_CALL) { Log.v(TAG, "CALL PRESSED"); exitApplication(); } return super.onKeyDown(keyCode, event); } private void exitApplication() { Log.v(TAG, "CLOSING APPLICATION"); Intent exitIntent = new Intent(this, ExitActivity.class); exitIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(exitIntent); finish(); } }
fixed home on login bug
beddit_alarm/src/ohtu/beddit/activity/AuthActivity.java
fixed home on login bug
Java
mit
4acdea4edf3e06156c15d2a0509abdde8b286409
0
SnapGames/GDJ105,SnapGames/GDJ105
/** * SnapGames * * Game Development Java * * GDJ105 * * @year 2017 */ package com.snapgames.gdj.core.ui; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import com.snapgames.gdj.core.Game; import com.snapgames.gdj.core.entity.AbstractGameObject; /** * The Background image is a simple image to be displayed in background. * * @author Frédéric Delorme * */ public class ImageObject extends AbstractGameObject { public BufferedImage image; /** * * @param name * @param x * @param y * @param width * @param height * @param layer * @param priority * @param color */ public ImageObject(String name, BufferedImage image, int x, int y, int layer, int priority) { super(name, x, y, image.getWidth(), image.getHeight(), layer, priority, null); this.image = image; this.width = image.getWidth(); this.height = image.getHeight(); } /* * (non-Javadoc) * * @see * com.snapgames.gdj.core.entity.AbstractGameObject#draw(com.snapgames.gdj.core. * Game, java.awt.Graphics2D) */ @Override public void draw(Game game, Graphics2D g) { g.drawImage(image, (int) (x), (int) (y), null); g.drawImage(image, (int) (x) + width, (int) (y), null); } }
src/main/java/com/snapgames/gdj/core/ui/ImageObject.java
/** * SnapGames * * Game Development Java * * GDJ105 * * @year 2017 */ package com.snapgames.gdj.core.ui; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.BufferedImage; import com.snapgames.gdj.core.Game; import com.snapgames.gdj.core.entity.AbstractGameObject; /** * The Background image is a simple image to be displayed in background. * * @author Frédéric Delorme * */ public class ImageObject extends AbstractGameObject { public BufferedImage image; /** * * @param name * @param x * @param y * @param width * @param height * @param layer * @param priority * @param color */ public ImageObject(String name, BufferedImage image, int x, int y, int layer, int priority) { super(name, x, y, image.getWidth(), image.getHeight(), layer, priority, null); this.image = image; this.width = image.getWidth(); this.height = image.getHeight(); } /* * (non-Javadoc) * * @see * com.snapgames.gdj.core.entity.AbstractGameObject#draw(com.snapgames.gdj.core. * Game, java.awt.Graphics2D) */ @Override public void draw(Game game, Graphics2D g) { g.drawImage(image, (int) (x), (int) (y),null); g.drawImage(image, (int) (x)+width, (int) (y),null); } }
fix some typo in ImageObject class.
src/main/java/com/snapgames/gdj/core/ui/ImageObject.java
fix some typo in ImageObject class.
Java
mit
cade2e289372bb210dd59974605cd581a26d42f6
0
DemigodsRPG/Demigods3
package com.legit2.Demigods.Listeners; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import com.legit2.Demigods.Demigods; import com.legit2.Demigods.Utilities.DDeityUtil; public class DCommandListener implements Listener { static Demigods plugin; public DCommandListener(Demigods instance) { plugin = instance; } @EventHandler(priority = EventPriority.MONITOR) public static void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { String message = event.getMessage(); message = message.substring(1); String[] args = message.split("\\s+"); Player player = event.getPlayer(); try { if(DDeityUtil.invokeDeityCommand(player, args)) { event.setCancelled(true); return; } } catch(Exception e) { // Not a command e.printStackTrace(); } } }
src/com/legit2/Demigods/Listeners/DCommandListener.java
package com.legit2.Demigods.Listeners; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import com.legit2.Demigods.Demigods; import com.legit2.Demigods.Utilities.DDeityUtil; import com.legit2.Demigods.Utilities.DMiscUtil; public class DCommandListener implements Listener { static Demigods plugin; public DCommandListener(Demigods instance) { plugin = instance; } @EventHandler(priority = EventPriority.MONITOR) public static void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { String message = event.getMessage(); message = message.substring(1); DMiscUtil.serverMsg(message); //DEBUG String[] args = message.split("\\s+"); for(String arg : args) { DMiscUtil.serverMsg(arg); //DEBUG } Player player = event.getPlayer(); try { if(DDeityUtil.invokeDeityCommand(player, args)) { event.setCancelled(true); return; } } catch(Exception e) { // Not a command e.printStackTrace(); } } }
Remove debug messages.
src/com/legit2/Demigods/Listeners/DCommandListener.java
Remove debug messages.
Java
mit
b7789ce895eebb8b69f1a248232edb5b6b0c9eff
0
PFGimenez/The-Kraken-Pathfinding
/* * Copyright (C) 2013-2017 Pierre-François Gimenez * Distributed under the MIT License. */ package pfg.kraken.astar.tentacles; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import pfg.config.Config; import pfg.injector.Injector; import pfg.injector.InjectorException; import pfg.kraken.ColorKraken; import pfg.kraken.ConfigInfoKraken; import pfg.kraken.LogCategoryKraken; import pfg.kraken.SeverityCategoryKraken; import pfg.kraken.astar.AStarNode; import pfg.kraken.astar.DirectionStrategy; import pfg.kraken.astar.ResearchMode; import pfg.kraken.astar.tentacles.types.TentacleType; import pfg.kraken.astar.thread.TentacleTask; import pfg.kraken.astar.thread.TentacleThread; import pfg.kraken.dstarlite.DStarLite; import pfg.kraken.memory.NodePool; import pfg.kraken.obstacles.Obstacle; import pfg.kraken.obstacles.container.DynamicObstacles; import pfg.kraken.obstacles.container.StaticObstacles; import pfg.kraken.robot.Cinematique; import pfg.kraken.robot.CinematiqueObs; import pfg.kraken.robot.ItineraryPoint; import pfg.kraken.utils.XY; import pfg.kraken.utils.XYO; import pfg.graphic.GraphicDisplay; import pfg.log.Log; import pfg.graphic.printable.Layer; import static pfg.kraken.astar.tentacles.Tentacle.*; /** * Réalise des calculs pour l'A* courbe. * * @author pf * */ public class TentacleManager implements Iterator<AStarNode> { protected Log log; private DStarLite dstarlite; private DynamicObstacles dynamicObs; private double courbureMax, maxLinearAcceleration, vitesseMax; private boolean printObstacles; private Injector injector; private StaticObstacles fixes; private double deltaSpeedFromStop; private GraphicDisplay display; private TentacleThread[] threads; private ResearchMode mode; private DirectionStrategy directionstrategyactuelle; private Cinematique arrivee = new Cinematique(); // private ResearchProfileManager profiles; private ResearchProfileManager profiles; private List<TentacleType> currentProfile = new ArrayList<TentacleType>(); // private List<StaticObstacles> disabledObstaclesFixes = new ArrayList<StaticObstacles>(); private List<TentacleTask> tasks = new ArrayList<TentacleTask>(); private BlockingQueue<AStarNode> successeurs = new LinkedBlockingQueue<AStarNode>(); private BlockingQueue<TentacleTask> buffer = new LinkedBlockingQueue<TentacleTask>(); private int nbLeft; public TentacleManager(Log log, StaticObstacles fixes, DStarLite dstarlite, Config config, DynamicObstacles dynamicObs, Injector injector, ResearchProfileManager profiles, NodePool memorymanager, GraphicDisplay display) throws InjectorException { this.injector = injector; this.fixes = fixes; this.dynamicObs = dynamicObs; this.log = log; this.dstarlite = dstarlite; this.display = display; this.profiles = profiles; int maxSize = 0; for(List<TentacleType> p : profiles) { maxSize = Math.max(maxSize, p.size()); for(TentacleType t : p) injector.getService(t.getComputer()); } for(int i = 0; i < maxSize; i++) tasks.add(new TentacleTask()); maxLinearAcceleration = config.getDouble(ConfigInfoKraken.MAX_LINEAR_ACCELERATION); deltaSpeedFromStop = Math.sqrt(2 * PRECISION_TRACE * maxLinearAcceleration); printObstacles = config.getBoolean(ConfigInfoKraken.GRAPHIC_ROBOT_COLLISION); int nbThreads = config.getInt(ConfigInfoKraken.THREAD_NUMBER); threads = new TentacleThread[nbThreads]; for(int i = 0; i < nbThreads; i++) { threads[i] = new TentacleThread(log, config, memorymanager, i, successeurs, buffer); if(nbThreads != 1) threads[i].start(); } courbureMax = config.getDouble(ConfigInfoKraken.MAX_CURVATURE); coins[0] = fixes.getBottomLeftCorner(); coins[2] = fixes.getTopRightCorner(); coins[1] = new XY(coins[0].getX(), coins[2].getY()); coins[3] = new XY(coins[2].getX(), coins[0].getY()); } private XY[] coins = new XY[4]; /** * Retourne faux si un obstacle est sur la route * * @param node * @return * @throws FinMatchException */ public boolean isReachable(AStarNode node) { // le tout premier nœud n'a pas de parent if(node.parent == null) return true; int nbOmbres = node.getArc().getNbPoints(); // On vérifie la collision avec les murs for(int j = 0; j < nbOmbres; j++) for(int i = 0; i < 4; i++) if(node.getArc().getPoint(j).obstacle.isColliding(coins[i], coins[(i+1)&3])) return false; // Collision avec un obstacle fixe? for(Obstacle o : fixes.getObstacles()) for(int i = 0; i < nbOmbres; i++) if(/*!disabledObstaclesFixes.contains(o) && */o.isColliding(node.getArc().getPoint(i).obstacle)) { // log.debug("Collision avec "+o); return false; } // Collision avec un obstacle de proximité ? try { Iterator<Obstacle> iter = dynamicObs.getFutureDynamicObstacles(0); // TODO date ! while(iter.hasNext()) { Obstacle n = iter.next(); for(int i = 0; i < nbOmbres; i++) if(n.isColliding(node.getArc().getPoint(i).obstacle)) { // log.debug("Collision avec un obstacle de proximité."); return false; } } } catch(NullPointerException e) { log.write(e.toString(), SeverityCategoryKraken.CRITICAL, LogCategoryKraken.PF); } /* * node.state.iterator.reinit(); * while(node.state.iterator.hasNext()) * if(node.state.iterator.next().isColliding(obs)) * { * // log.debug("Collision avec un obstacle de proximité."); * return false; * } */ return true; } /** * Initialise l'arc manager avec les infos donnée * * @param directionstrategyactuelle * @param sens * @param arrivee */ public void configure(DirectionStrategy directionstrategyactuelle, double vitesseMax, XYO arrivee, ResearchMode mode) { this.vitesseMax = vitesseMax; this.directionstrategyactuelle = directionstrategyactuelle; this.mode = mode; currentProfile = profiles.getProfile(mode.ordinal()); // on récupère les tentacules qui correspondent à ce mode this.arrivee.updateReel(arrivee.position.getX(), arrivee.position.getY(), arrivee.orientation, true, 0); } public void reconstruct(LinkedList<ItineraryPoint> trajectory, AStarNode best) { AStarNode noeudParent = best; Tentacle arcParent = best.getArc(); CinematiqueObs current; boolean lastStop = true; double lastPossibleSpeed = 0; while(noeudParent.parent != null) { for(int i = arcParent.getNbPoints() - 1; i >= 0; i--) { current = arcParent.getPoint(i); if(printObstacles) display.addTemporaryPrintable(current.obstacle.clone(), ColorKraken.ROBOT.color, Layer.BACKGROUND.layer); // vitesse maximale du robot à ce point double maxSpeed = current.possibleSpeed; double currentSpeed = lastPossibleSpeed; if(lastStop) current.possibleSpeed = 0; else if(currentSpeed < maxSpeed) { double deltaVitesse; if(currentSpeed < 0.1) deltaVitesse = deltaSpeedFromStop; else deltaVitesse = 2 * maxLinearAcceleration * PRECISION_TRACE / currentSpeed; currentSpeed += deltaVitesse; currentSpeed = Math.min(currentSpeed, maxSpeed); current.possibleSpeed = currentSpeed; } trajectory.addFirst(new ItineraryPoint(current, lastStop)); // stop : on va devoir s'arrêter lastPossibleSpeed = current.possibleSpeed; lastStop = current.stop; } noeudParent = noeudParent.parent; arcParent = noeudParent.getArc(); } } /** * Réinitialise l'itérateur à partir d'un nouvel état * * @param current * @param directionstrategyactuelle */ public void computeTentacles(AStarNode current) { successeurs.clear(); int index = 0; assert nbLeft == 0; for(TentacleType v : currentProfile) { if(v.isAcceptable(current.robot.getCinematique(), directionstrategyactuelle, courbureMax)) { nbLeft++; assert tasks.size() > index; TentacleTask tt = tasks.get(index++); tt.arrivee = arrivee; tt.current = current; tt.v = v; tt.computer = injector.getExistingService(v.getComputer()); tt.vitesseMax = vitesseMax; if(threads.length == 1) // no multithreading in this case threads[0].compute(tt); else buffer.add(tt); } } /* if(threads.length > 1) { for(int i = 0; i < threads.length; i++) synchronized(threads[i]) { // on lance les calculs threads[i].notify(); } for(int i = 0; i < threads.length; i++) { synchronized(threads[i]) { // on attend la fin des calculs if(!threads[i].done) try { threads[i].wait(); } catch (InterruptedException e) { e.printStackTrace(); } assert threads[i].buffer.isEmpty(); } successeurs.addAll(threads[i].successeurs); threads[i].successeurs.clear(); } }*/ } public synchronized Integer heuristicCostCourbe(Cinematique c) { Double h = dstarlite.heuristicCostCourbe(c); if(h == null) return null; return (int) (1000.*(h / vitesseMax)); } public boolean isArrived(AStarNode successeur) { if(mode == ResearchMode.XYO2XY) return successeur.getArc() != null && successeur.getArc().getLast().getPosition().squaredDistance(arrivee.getPosition()) < 5; else if(mode == ResearchMode.XYO2XYO) return successeur.getArc() != null && successeur.getArc().getLast().getPosition().squaredDistance(arrivee.getPosition()) < 5 && XYO.angleDifference(successeur.getArc().getLast().orientationReelle, arrivee.orientationReelle) < 0.05; else { assert false; return successeur.getArc() != null && successeur.getArc().getLast().getPosition().squaredDistance(arrivee.getPosition()) < 5; } } public void stopThreads() { if(threads.length > 1) for(int i = 0; i < threads.length; i++) threads[i].interrupt(); } private AStarNode next; @Override public boolean hasNext() { assert threads.length > 1 || successeurs.size() == nbLeft : successeurs.size() + " " + nbLeft; // s'il n'y a qu'un seul thread, alors tous les successeurs sont dans la liste if(nbLeft == 0) { assert successeurs.isEmpty(); return false; } try { do { next = successeurs.take(); nbLeft--; } while(nbLeft > 0 && next == TentacleThread.placeholder); return next != TentacleThread.placeholder; } catch (InterruptedException e) { e.printStackTrace(); return false; } } @Override public AStarNode next() { return next; } }
core/src/main/java/pfg/kraken/astar/tentacles/TentacleManager.java
/* * Copyright (C) 2013-2017 Pierre-François Gimenez * Distributed under the MIT License. */ package pfg.kraken.astar.tentacles; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import pfg.config.Config; import pfg.injector.Injector; import pfg.injector.InjectorException; import pfg.kraken.ColorKraken; import pfg.kraken.ConfigInfoKraken; import pfg.kraken.LogCategoryKraken; import pfg.kraken.SeverityCategoryKraken; import pfg.kraken.astar.AStarNode; import pfg.kraken.astar.DirectionStrategy; import pfg.kraken.astar.ResearchMode; import pfg.kraken.astar.tentacles.types.TentacleType; import pfg.kraken.astar.thread.TentacleTask; import pfg.kraken.astar.thread.TentacleThread; import pfg.kraken.dstarlite.DStarLite; import pfg.kraken.memory.NodePool; import pfg.kraken.obstacles.Obstacle; import pfg.kraken.obstacles.container.DynamicObstacles; import pfg.kraken.obstacles.container.StaticObstacles; import pfg.kraken.robot.Cinematique; import pfg.kraken.robot.CinematiqueObs; import pfg.kraken.robot.ItineraryPoint; import pfg.kraken.utils.XY; import pfg.kraken.utils.XYO; import pfg.graphic.GraphicDisplay; import pfg.log.Log; import pfg.graphic.printable.Layer; import static pfg.kraken.astar.tentacles.Tentacle.*; /** * Réalise des calculs pour l'A* courbe. * * @author pf * */ public class TentacleManager implements Iterator<AStarNode> { protected Log log; private DStarLite dstarlite; private DynamicObstacles dynamicObs; private double courbureMax, maxLinearAcceleration, vitesseMax; private boolean printObstacles; private Injector injector; private StaticObstacles fixes; private double deltaSpeedFromStop; private GraphicDisplay display; private TentacleThread[] threads; private ResearchMode mode; private DirectionStrategy directionstrategyactuelle; private Cinematique arrivee = new Cinematique(); // private ResearchProfileManager profiles; private ResearchProfileManager profiles; private List<TentacleType> currentProfile = new ArrayList<TentacleType>(); // private List<StaticObstacles> disabledObstaclesFixes = new ArrayList<StaticObstacles>(); private List<TentacleTask> tasks = new ArrayList<TentacleTask>(); private BlockingQueue<AStarNode> successeurs = new LinkedBlockingQueue<AStarNode>(); private BlockingQueue<TentacleTask> buffer = new LinkedBlockingQueue<TentacleTask>(); private int nbLeft; public TentacleManager(Log log, StaticObstacles fixes, DStarLite dstarlite, Config config, DynamicObstacles dynamicObs, Injector injector, ResearchProfileManager profiles, NodePool memorymanager, GraphicDisplay display) throws InjectorException { this.injector = injector; this.fixes = fixes; this.dynamicObs = dynamicObs; this.log = log; this.dstarlite = dstarlite; this.display = display; this.profiles = profiles; int maxSize = 0; for(List<TentacleType> p : profiles) { maxSize = Math.max(maxSize, p.size()); for(TentacleType t : p) injector.getService(t.getComputer()); } for(int i = 0; i < maxSize; i++) tasks.add(new TentacleTask()); maxLinearAcceleration = config.getDouble(ConfigInfoKraken.MAX_LINEAR_ACCELERATION); deltaSpeedFromStop = Math.sqrt(2 * PRECISION_TRACE * maxLinearAcceleration); printObstacles = config.getBoolean(ConfigInfoKraken.GRAPHIC_ROBOT_COLLISION); int nbThreads = config.getInt(ConfigInfoKraken.THREAD_NUMBER); threads = new TentacleThread[nbThreads]; for(int i = 0; i < nbThreads; i++) { threads[i] = new TentacleThread(log, config, memorymanager, i, successeurs, buffer); if(nbThreads != 1) threads[i].start(); } courbureMax = config.getDouble(ConfigInfoKraken.MAX_CURVATURE); coins[0] = fixes.getBottomLeftCorner(); coins[2] = fixes.getTopRightCorner(); coins[1] = new XY(coins[0].getX(), coins[2].getY()); coins[3] = new XY(coins[2].getX(), coins[0].getY()); } private XY[] coins = new XY[4]; /** * Retourne faux si un obstacle est sur la route * * @param node * @return * @throws FinMatchException */ public boolean isReachable(AStarNode node) { // le tout premier nœud n'a pas de parent if(node.parent == null) return true; int nbOmbres = node.getArc().getNbPoints(); // On vérifie la collision avec les murs for(int j = 0; j < nbOmbres; j++) for(int i = 0; i < 4; i++) if(node.getArc().getPoint(j).obstacle.isColliding(coins[i], coins[(i+1)&3])) return false; // Collision avec un obstacle fixe? for(Obstacle o : fixes.getObstacles()) for(int i = 0; i < nbOmbres; i++) if(/*!disabledObstaclesFixes.contains(o) && */o.isColliding(node.getArc().getPoint(i).obstacle)) { // log.debug("Collision avec "+o); return false; } // Collision avec un obstacle de proximité ? try { Iterator<Obstacle> iter = dynamicObs.getFutureDynamicObstacles(0); // TODO date ! while(iter.hasNext()) { Obstacle n = iter.next(); for(int i = 0; i < nbOmbres; i++) if(n.isColliding(node.getArc().getPoint(i).obstacle)) { // log.debug("Collision avec un obstacle de proximité."); return false; } } } catch(NullPointerException e) { log.write(e.toString(), SeverityCategoryKraken.CRITICAL, LogCategoryKraken.PF); } /* * node.state.iterator.reinit(); * while(node.state.iterator.hasNext()) * if(node.state.iterator.next().isColliding(obs)) * { * // log.debug("Collision avec un obstacle de proximité."); * return false; * } */ return true; } /** * Initialise l'arc manager avec les infos donnée * * @param directionstrategyactuelle * @param sens * @param arrivee */ public void configure(DirectionStrategy directionstrategyactuelle, double vitesseMax, XYO arrivee, ResearchMode mode) { this.vitesseMax = vitesseMax; this.directionstrategyactuelle = directionstrategyactuelle; this.mode = mode; currentProfile = profiles.getProfile(mode.ordinal()); // on récupère les tentacules qui correspondent à ce mode this.arrivee.updateReel(arrivee.position.getX(), arrivee.position.getY(), arrivee.orientation, true, 0); } public void reconstruct(LinkedList<ItineraryPoint> trajectory, AStarNode best) { AStarNode noeudParent = best; Tentacle arcParent = best.getArc(); CinematiqueObs current; boolean lastStop = true; double lastPossibleSpeed = 0; while(noeudParent.parent != null) { for(int i = arcParent.getNbPoints() - 1; i >= 0; i--) { current = arcParent.getPoint(i); if(printObstacles) display.addTemporaryPrintable(current.obstacle.clone(), ColorKraken.ROBOT.color, Layer.BACKGROUND.layer); // vitesse maximale du robot à ce point double maxSpeed = current.possibleSpeed; double currentSpeed = lastPossibleSpeed; if(lastStop) current.possibleSpeed = 0; else if(currentSpeed < maxSpeed) { double deltaVitesse; if(currentSpeed < 0.1) deltaVitesse = deltaSpeedFromStop; else deltaVitesse = 2 * maxLinearAcceleration * PRECISION_TRACE / currentSpeed; currentSpeed += deltaVitesse; currentSpeed = Math.min(currentSpeed, maxSpeed); current.possibleSpeed = currentSpeed; } trajectory.addFirst(new ItineraryPoint(current, lastStop)); // stop : on va devoir s'arrêter lastPossibleSpeed = current.possibleSpeed; lastStop = current.stop; } noeudParent = noeudParent.parent; arcParent = noeudParent.getArc(); } } /** * Réinitialise l'itérateur à partir d'un nouvel état * * @param current * @param directionstrategyactuelle */ public void computeTentacles(AStarNode current) { successeurs.clear(); int index = 0; assert nbLeft == 0; for(TentacleType v : currentProfile) { if(v.isAcceptable(current.robot.getCinematique(), directionstrategyactuelle, courbureMax)) { nbLeft++; assert tasks.size() > index; TentacleTask tt = tasks.get(index++); tt.arrivee = arrivee; tt.current = current; tt.v = v; tt.computer = injector.getExistingService(v.getComputer()); tt.vitesseMax = vitesseMax; if(threads.length == 1) // no multithreading in this case threads[0].compute(tt); else buffer.add(tt); } } /* if(threads.length > 1) { for(int i = 0; i < threads.length; i++) synchronized(threads[i]) { // on lance les calculs threads[i].notify(); } for(int i = 0; i < threads.length; i++) { synchronized(threads[i]) { // on attend la fin des calculs if(!threads[i].done) try { threads[i].wait(); } catch (InterruptedException e) { e.printStackTrace(); } assert threads[i].buffer.isEmpty(); } successeurs.addAll(threads[i].successeurs); threads[i].successeurs.clear(); } }*/ } public synchronized Integer heuristicCostCourbe(Cinematique c) { if(dstarlite.heuristicCostCourbe(c) == null) return null; return (int) (1000.*(dstarlite.heuristicCostCourbe(c) / vitesseMax)); } public boolean isArrived(AStarNode successeur) { if(mode == ResearchMode.XYO2XY) return successeur.getArc() != null && successeur.getArc().getLast().getPosition().squaredDistance(arrivee.getPosition()) < 5; else if(mode == ResearchMode.XYO2XYO) return successeur.getArc() != null && successeur.getArc().getLast().getPosition().squaredDistance(arrivee.getPosition()) < 5 && XYO.angleDifference(successeur.getArc().getLast().orientationReelle, arrivee.orientationReelle) < 0.05; else { assert false; return successeur.getArc() != null && successeur.getArc().getLast().getPosition().squaredDistance(arrivee.getPosition()) < 5; } } public void stopThreads() { if(threads.length > 1) for(int i = 0; i < threads.length; i++) threads[i].interrupt(); } private AStarNode next; @Override public boolean hasNext() { assert threads.length > 1 || successeurs.size() == nbLeft : successeurs.size() + " " + nbLeft; // s'il n'y a qu'un seul thread, alors tous les successeurs sont dans la liste if(nbLeft == 0) { assert successeurs.isEmpty(); return false; } try { do { next = successeurs.take(); nbLeft--; } while(nbLeft > 0 && next == TentacleThread.placeholder); return next != TentacleThread.placeholder; } catch (InterruptedException e) { e.printStackTrace(); return false; } } @Override public AStarNode next() { return next; } }
Bugfix
core/src/main/java/pfg/kraken/astar/tentacles/TentacleManager.java
Bugfix
Java
mit
620fbb839baa96ad12d94feb72c32ad935f3e61e
0
andrewdavidmackenzie/viskell,viskell/viskell,wandernauta/viskell
package nl.utwente.viskell.ui; import javafx.scene.control.MenuItem; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.util.Duration; import jfxtras.scene.layout.CircularPane; import jfxtras.scene.menu.CirclePopupMenu; import nl.utwente.viskell.ui.components.Block; /** * Circle menu is a context based menu implementation for {@link Block} classes. * Preferably each block class has it's own instance of circle menu. When a * block based class has significant differences to other block classes that * result in different context based actions it should use a specialized * extension of circle menu instead of this one. * <p> * Current context based features include delete. Copy, Paste and Save * functionality is under development. * </p> */ public class CircleMenu extends CirclePopupMenu { /** The context of the menu. */ private Block block; /** Show the Circle menu for a specific block. */ public static void showFor(Block block, MouseEvent t) { CircleMenu menu = new CircleMenu(block); menu.show(t); } public CircleMenu(Block block) { super(block, null); this.block = block; // Define menu items // Cut Option ImageView image = makeImageView("/ui/cut32.png"); MenuItem delete = new MenuItem("cut", image); delete.setOnAction(t -> delete()); // Copy Option image = makeImageView("/ui/copy32.png"); MenuItem copy = new MenuItem("copy", image); copy.setOnAction(t -> copy()); // Paste Option image = makeImageView("/ui/paste32.png"); MenuItem paste = new MenuItem("paste", image); paste.setOnAction(t -> paste()); // Save Option image = makeImageView("/ui/save32.png"); MenuItem save = new MenuItem("save", image); save.setOnAction(t -> saveBlock()); // Registration this.getItems().addAll(copy, paste, delete, save); // Animation this.setAnimationInterpolation(CircularPane::animateOverTheArcWithFade); this.setAnimationDuration(Duration.ONE); } private ImageView makeImageView(String path) { ImageView image = new ImageView(new Image(this.getClass().getResourceAsStream(path))); image.getStyleClass().add("hoverMenu"); return image; } /** Copy the {@link Block} in this context. */ public void copy() { // TODO implement clipBoard in main app. } /** Paste {@link Block} from memory. */ public void paste() { } /** Delete the {@link Block} in this context. */ public void delete() { block.getPane().removeBlock(block); } /** Saves the {@link Block} in this context. */ public void saveBlock() { // TODO store block in custom catalog? } }
Code/src/main/java/nl/utwente/viskell/ui/CircleMenu.java
package nl.utwente.viskell.ui; import javafx.scene.control.MenuItem; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.util.Duration; import jfxtras.scene.layout.CircularPane; import jfxtras.scene.menu.CirclePopupMenu; import nl.utwente.viskell.ui.components.Block; /** * Circle menu is a context based menu implementation for {@link Block} classes. * Preferably each block class has it's own instance of circle menu. When a * block based class has significant differences to other block classes that * result in different context based actions it should use a specialized * extension of circle menu instead of this one. * <p> * Current context based features include delete. Copy, Paste and Save * functionality is under development. * </p> */ public class CircleMenu extends CirclePopupMenu { /** The context of the menu. */ private Block block; /** Show the Circle menu for a block if not already active. */ public static void showFor(Block block, MouseEvent t) { CircleMenu menu = new CircleMenu(block); menu.show(t); } public CircleMenu(Block block) { super(block, null); this.block = block; // Define menu items // Cut Option ImageView image = makeImageView("/ui/cut32.png"); MenuItem delete = new MenuItem("cut", image); delete.setOnAction(t -> delete()); // Copy Option image = makeImageView("/ui/copy32.png"); MenuItem copy = new MenuItem("copy", image); copy.setOnAction(t -> copy()); // Paste Option image = makeImageView("/ui/paste32.png"); MenuItem paste = new MenuItem("paste", image); paste.setOnAction(t -> paste()); // Save Option image = makeImageView("/ui/save32.png"); MenuItem save = new MenuItem("save", image); save.setOnAction(t -> saveBlock()); // Registration this.getItems().addAll(copy, paste, delete, save); // Animation this.setAnimationInterpolation(CircularPane::animateOverTheArcWithFade); this.setAnimationDuration(Duration.ONE); } private ImageView makeImageView(String path) { ImageView image = new ImageView(new Image(this.getClass().getResourceAsStream(path))); image.getStyleClass().add("hoverMenu"); return image; } /** Copy the {@link Block} in this context. */ public void copy() { // TODO implement clipBoard in main app. } /** Paste {@link Block} from memory. */ public void paste() { } /** Delete the {@link Block} in this context. */ public void delete() { block.getPane().removeBlock(block); } /** Saves the {@link Block} in this context. */ public void saveBlock() { // TODO store block in custom catalog? } }
Comments are always outdated...
Code/src/main/java/nl/utwente/viskell/ui/CircleMenu.java
Comments are always outdated...
Java
mit
4277aa12804a847055d41b81f617a2d9754b4e32
0
macrat/RuuMusic,macrat/RuuMusic,macrat/RuuMusic
package jp.blanktar.ruumusic.client; import java.util.ArrayList; import java.util.List; import java.util.Stack; import android.support.annotation.IntRange; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.UiThread; import android.support.v4.app.Fragment; import android.support.v7.widget.SearchView; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import jp.blanktar.ruumusic.R; import jp.blanktar.ruumusic.service.RuuService; import jp.blanktar.ruumusic.util.RuuDirectory; import jp.blanktar.ruumusic.util.RuuFile; import jp.blanktar.ruumusic.util.RuuFileBase; @UiThread public class PlaylistFragment extends Fragment implements SearchView.OnQueryTextListener, SearchView.OnCloseListener{ private RuuAdapter adapter; private final Stack<DirectoryInfo> directoryCache = new Stack<>(); @Nullable DirectoryInfo current; @Nullable public String searchQuery = null; @Override @NonNull public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState){ View view = inflater.inflate(R.layout.fragment_playlist, container, false); adapter = new RuuAdapter(view.getContext()); final ListView lv = (ListView)view.findViewById(R.id.playlist); lv.setAdapter(adapter); lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){ @Override public void onItemClick(@NonNull AdapterView<?> parent, @Nullable View view, int position, long id){ RuuFileBase selected = (RuuFileBase)lv.getItemAtPosition(position); if(selected.isDirectory()){ changeDir((RuuDirectory)selected); }else{ changeMusic((RuuFile)selected); } } }); String currentPath = PreferenceManager.getDefaultSharedPreferences(getContext()) .getString("current_view_path", null); try{ if(currentPath != null){ changeDir(RuuDirectory.getInstance(getContext(), currentPath)); }else{ changeDir(RuuDirectory.getInstance(getContext(), Environment.getExternalStorageDirectory().getPath())); } }catch(RuuFileBase.CanNotOpen err){ try{ changeDir(RuuDirectory.rootDirectory(getContext())); }catch(RuuFileBase.CanNotOpen e){ Toast.makeText(getActivity(), String.format(getString(R.string.cant_open_dir), e.path), Toast.LENGTH_LONG).show(); PreferenceManager.getDefaultSharedPreferences(getContext()).edit() .remove("root_directory") .apply(); } } return view; } @Override public void onPause(){ super.onPause(); if(current != null){ PreferenceManager.getDefaultSharedPreferences(getContext()).edit() .putString("current_view_path", current.path.getFullPath()) .apply(); } } public void updateTitle(@NonNull Activity activity){ if(current == null){ activity.setTitle(""); }else{ try{ activity.setTitle(current.path.getRuuPath()); }catch(RuuFileBase.OutOfRootDirectory e){ activity.setTitle(""); Toast.makeText(getActivity(), String.format(getString(R.string.out_of_root), current.path.getFullPath()), Toast.LENGTH_LONG).show(); } } } private void updateTitle(){ updateTitle(getActivity()); } public void updateRoot(){ updateTitle(); updateMenu(); if(current != null){ changeDir(current.path); } } void changeDir(@NonNull RuuDirectory dir){ RuuDirectory rootDirectory; try{ rootDirectory = RuuDirectory.rootDirectory(getContext()); }catch(RuuFileBase.CanNotOpen e){ Toast.makeText(getActivity(), String.format(getString(R.string.cant_open_dir), "root directory"), Toast.LENGTH_LONG).show(); return; } if(!rootDirectory.contains(dir)){ Toast.makeText(getActivity(), String.format(getString(R.string.out_of_root), dir.getFullPath()), Toast.LENGTH_LONG).show(); return; } MainActivity main = (MainActivity)getActivity(); if(main.searchView != null && !main.searchView.isIconified()){ main.searchView.setQuery("", false); main.searchView.setIconified(true); } while(!directoryCache.empty() && !directoryCache.peek().path.contains(dir)){ directoryCache.pop(); } if(!directoryCache.empty() && directoryCache.peek().path.equals(dir)){ current = directoryCache.pop(); }else{ if(current != null){ current.selection = ((ListView)getActivity().findViewById(R.id.playlist)).getFirstVisiblePosition(); directoryCache.push(current); } current = new DirectoryInfo(dir); } if(((MainActivity)getActivity()).getCurrentPage() == 1){ updateTitle(); } try{ adapter.setRuuFiles(current); }catch(RuuFileBase.CanNotOpen e){ Toast.makeText(getActivity(), String.format(getString(R.string.cant_open_dir), e.path), Toast.LENGTH_LONG).show(); return; } updateMenu(); } public void updateMenu(@NonNull MainActivity activity){ Menu menu = activity.menu; if(menu != null){ RuuDirectory rootDirectory; try{ rootDirectory = RuuDirectory.rootDirectory(getContext()); }catch(RuuFileBase.CanNotOpen e){ Toast.makeText(getActivity(), String.format(getString(R.string.cant_open_dir), "root directory"), Toast.LENGTH_LONG).show(); return; } menu.findItem(R.id.action_set_root).setVisible(current != null && !rootDirectory.equals(current.path) && searchQuery == null); menu.findItem(R.id.action_unset_root).setVisible(!rootDirectory.getFullPath().equals("/") && searchQuery == null); menu.findItem(R.id.action_search_play).setVisible(searchQuery != null && adapter.musicNum > 0); menu.findItem(R.id.action_recursive_play).setVisible(searchQuery == null && adapter.musicNum + adapter.directoryNum > 0); menu.findItem(R.id.menu_search).setVisible(true); menu.findItem(R.id.action_audio_preference).setVisible(false); } } private void updateMenu(){ updateMenu((MainActivity)getActivity()); } private void changeMusic(@NonNull RuuFile file){ Intent intent = new Intent(getActivity(), RuuService.class); intent.setAction(RuuService.ACTION_PLAY); intent.putExtra("path", file.getFullPath()); getActivity().startService(intent); ((MainActivity)getActivity()).moveToPlayer(); } public boolean onBackKey(){ SearchView search = ((MainActivity)getActivity()).searchView; if(search != null && !search.isIconified()){ search.setQuery("", false); search.setIconified(true); onClose(); return true; } RuuDirectory root; try{ root = RuuDirectory.rootDirectory(getContext()); }catch(RuuFileBase.CanNotOpen e){ return false; } if(current == null){ return false; }else if(current.path.equals(root)){ return false; }else{ int i=0; while(true){ i++; try{ changeDir(current.path.getParent(i)); return true; }catch(RuuFileBase.CanNotOpen e){ if(e.path == null){ return false; } } } } } public void setSearchQuery(@NonNull RuuDirectory path, @NonNull String query){ changeDir(path); ((MainActivity)getActivity()).searchView.setIconified(false); ((MainActivity)getActivity()).searchView.setQuery(query, true); } @Override public boolean onQueryTextChange(@NonNull String text){ return false; } @Override public boolean onQueryTextSubmit(@NonNull String text){ if(current == null){ return false; } if(TextUtils.isEmpty(text)){ onClose(); return false; } ((MainActivity)getActivity()).searchView.clearFocus(); String[] queries = TextUtils.split(text.toLowerCase(), " \t"); ArrayList<RuuFileBase> filtered = new ArrayList<>(); try{ for(RuuFileBase file: current.path.getAllRecursive()){ String name = file.getName().toLowerCase(); boolean isOk = true; for(String query: queries){ if(!name.contains(query)){ isOk = false; break; } } if(isOk){ filtered.add(file); } } }catch(RuuFileBase.CanNotOpen e){ Toast.makeText(getActivity(), String.format(getString(R.string.cant_open_dir), e.path), Toast.LENGTH_LONG).show(); return false; } adapter.setSearchResults(filtered); searchQuery = text; updateMenu(); return false; } @Override public boolean onClose(){ try{ adapter.resumeFromSearch(); }catch(RuuFileBase.CanNotOpen e){ Toast.makeText(getActivity(), String.format(getString(R.string.cant_open_dir), e.path), Toast.LENGTH_LONG).show(); adapter.clear(); } updateMenu(); return false; } class DirectoryInfo{ public final RuuDirectory path; public int selection = 0; public DirectoryInfo(@NonNull RuuDirectory path){ this.path = path; } } @UiThread private class RuuAdapter extends ArrayAdapter<RuuFileBase>{ @Nullable private DirectoryInfo dirInfo; int musicNum = 0; int directoryNum = 0; RuuAdapter(@NonNull Context context){ super(context, R.layout.list_item); } void setRuuFiles(@NonNull DirectoryInfo dirInfo) throws RuuFileBase.CanNotOpen{ clear(); searchQuery = null; this.dirInfo = dirInfo; RuuDirectory rootDirectory = RuuDirectory.rootDirectory(getContext()); if(!rootDirectory.equals(dirInfo.path) && rootDirectory.contains(dirInfo.path)){ int i=0; while(true){ i++; try{ add(dirInfo.path.getParent(i)); break; }catch(RuuFileBase.CanNotOpen e){ if(e.path == null){ break; } } } } List<RuuDirectory> directories = dirInfo.path.getDirectories(); directoryNum = directories.size(); for(RuuDirectory dir: directories){ add(dir); } List<RuuFile> musics = dirInfo.path.getMusics(); musicNum = musics.size(); for(RuuFile music: musics){ add(music); } ListView listView = (ListView)getActivity().findViewById(R.id.playlist); if(listView != null){ listView.setSelection(dirInfo.selection); } } void setSearchResults(@NonNull List<RuuFileBase> results){ if(dirInfo != null){ dirInfo.selection = ((ListView)getActivity().findViewById(R.id.playlist)).getFirstVisiblePosition(); } clear(); musicNum = 0; directoryNum = 0; for(RuuFileBase result: results){ add(result); } for(RuuFileBase file: results){ if(file.isDirectory()){ directoryNum++; }else{ musicNum++; } } ListView listView = (ListView)getActivity().findViewById(R.id.playlist); if(listView != null){ listView.setSelection(0); } } void resumeFromSearch() throws RuuFileBase.CanNotOpen{ if(dirInfo != null){ clear(); setRuuFiles(dirInfo); } } @Override public int getViewTypeCount(){ return 3; } @Override @IntRange(from=0, to=2) public int getItemViewType(int position){ if(searchQuery != null){ return 2; } if(getItem(position).isDirectory() && dirInfo != null && ((RuuDirectory)getItem(position)).contains(dirInfo.path)){ return 1; }else{ return 0; } } @Override @NonNull public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent){ RuuFileBase item = getItem(position); if(searchQuery != null){ if(convertView == null){ convertView = ((LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.list_item_search, null); } ((TextView)convertView.findViewById(R.id.search_name)).setText(item.getName() + (item.isDirectory() ? "/" : "")); try{ ((TextView)convertView.findViewById(R.id.search_path)).setText(item.getParent().getRuuPath()); }catch(RuuFileBase.CanNotOpen | RuuFileBase.OutOfRootDirectory e){ ((TextView)convertView.findViewById(R.id.search_path)).setText(""); } }else{ assert dirInfo != null; if(item.isDirectory() && ((RuuDirectory)item).contains(dirInfo.path)){ if(convertView == null){ convertView = ((LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.list_item_upper, null); } }else{ if(convertView == null){ convertView = ((LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.list_item, null); } ((TextView)convertView).setText(item.getName() + (item.isDirectory() ? "/" : "")); } } return convertView; } } }
app/src/main/java/jp/blanktar/ruumusic/client/PlaylistFragment.java
package jp.blanktar.ruumusic.client; import java.util.ArrayList; import java.util.List; import java.util.Stack; import android.support.annotation.IntRange; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.UiThread; import android.support.v4.app.Fragment; import android.support.v7.widget.SearchView; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import jp.blanktar.ruumusic.R; import jp.blanktar.ruumusic.service.RuuService; import jp.blanktar.ruumusic.util.RuuDirectory; import jp.blanktar.ruumusic.util.RuuFile; import jp.blanktar.ruumusic.util.RuuFileBase; @UiThread public class PlaylistFragment extends Fragment implements SearchView.OnQueryTextListener, SearchView.OnCloseListener{ private RuuAdapter adapter; private final Stack<DirectoryInfo> directoryCache = new Stack<>(); @Nullable DirectoryInfo current; @Nullable public String searchQuery = null; @Override @NonNull public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState){ View view = inflater.inflate(R.layout.fragment_playlist, container, false); adapter = new RuuAdapter(view.getContext()); final ListView lv = (ListView)view.findViewById(R.id.playlist); lv.setAdapter(adapter); lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){ @Override public void onItemClick(@NonNull AdapterView<?> parent, @Nullable View view, int position, long id){ RuuFileBase selected = (RuuFileBase)lv.getItemAtPosition(position); if(selected.isDirectory()){ changeDir((RuuDirectory)selected); }else{ changeMusic((RuuFile)selected); } } }); String currentPath = PreferenceManager.getDefaultSharedPreferences(getContext()) .getString("current_view_path", null); try{ if(currentPath != null){ changeDir(RuuDirectory.getInstance(getContext(), currentPath)); }else{ changeDir(RuuDirectory.getInstance(getContext(), Environment.getExternalStorageDirectory().getPath())); } }catch(RuuFileBase.CanNotOpen err){ try{ changeDir(RuuDirectory.rootDirectory(getContext())); }catch(RuuFileBase.CanNotOpen e){ Toast.makeText(getActivity(), String.format(getString(R.string.cant_open_dir), e.path), Toast.LENGTH_LONG).show(); PreferenceManager.getDefaultSharedPreferences(getContext()).edit() .remove("root_directory") .apply(); } } return view; } @Override public void onPause(){ super.onPause(); if(current != null){ PreferenceManager.getDefaultSharedPreferences(getContext()).edit() .putString("current_view_path", current.path.getFullPath()) .apply(); } } public void updateTitle(@NonNull Activity activity){ if(current == null){ activity.setTitle(""); }else{ try{ activity.setTitle(current.path.getRuuPath()); }catch(RuuFileBase.OutOfRootDirectory e){ activity.setTitle(""); Toast.makeText(getActivity(), String.format(getString(R.string.out_of_root), current.path.getFullPath()), Toast.LENGTH_LONG).show(); } } } private void updateTitle(){ updateTitle(getActivity()); } public void updateRoot(){ updateTitle(); updateMenu(); if(current != null){ changeDir(current.path); } } void changeDir(@NonNull RuuDirectory dir){ RuuDirectory rootDirectory; try{ rootDirectory = RuuDirectory.rootDirectory(getContext()); }catch(RuuFileBase.CanNotOpen e){ Toast.makeText(getActivity(), String.format(getString(R.string.cant_open_dir), "root directory"), Toast.LENGTH_LONG).show(); return; } if(!rootDirectory.contains(dir)){ Toast.makeText(getActivity(), String.format(getString(R.string.out_of_root), dir.getFullPath()), Toast.LENGTH_LONG).show(); return; } MainActivity main = (MainActivity)getActivity(); if(main.searchView != null && !main.searchView.isIconified()){ main.searchView.setQuery("", false); main.searchView.setIconified(true); } while(!directoryCache.empty() && !directoryCache.peek().path.contains(dir)){ directoryCache.pop(); } if(!directoryCache.empty() && directoryCache.peek().path.equals(dir)){ current = directoryCache.pop(); }else{ if(current != null){ current.selection = ((ListView)getActivity().findViewById(R.id.playlist)).getFirstVisiblePosition(); directoryCache.push(current); } current = new DirectoryInfo(dir); } if(((MainActivity)getActivity()).getCurrentPage() == 1){ updateTitle(); } try{ adapter.setRuuFiles(current); }catch(RuuFileBase.CanNotOpen e){ Toast.makeText(getActivity(), String.format(getString(R.string.cant_open_dir), e.path), Toast.LENGTH_LONG).show(); return; } updateMenu(); } public void updateMenu(@NonNull MainActivity activity){ Menu menu = activity.menu; if(menu != null){ RuuDirectory rootDirectory; try{ rootDirectory = RuuDirectory.rootDirectory(getContext()); }catch(RuuFileBase.CanNotOpen e){ Toast.makeText(getActivity(), String.format(getString(R.string.cant_open_dir), "root directory"), Toast.LENGTH_LONG).show(); return; } menu.findItem(R.id.action_set_root).setVisible(current != null && !rootDirectory.equals(current.path) && searchQuery == null); menu.findItem(R.id.action_unset_root).setVisible(!rootDirectory.getFullPath().equals("/") && searchQuery == null); menu.findItem(R.id.action_search_play).setVisible(searchQuery != null && adapter.musicNum > 0); menu.findItem(R.id.action_recursive_play).setVisible(searchQuery == null && adapter.musicNum + adapter.directoryNum > 0); menu.findItem(R.id.menu_search).setVisible(true); menu.findItem(R.id.action_audio_preference).setVisible(false); } } private void updateMenu(){ updateMenu((MainActivity)getActivity()); } private void changeMusic(@NonNull RuuFile file){ Intent intent = new Intent(getActivity(), RuuService.class); intent.setAction(RuuService.ACTION_PLAY); intent.putExtra("path", file.getFullPath()); getActivity().startService(intent); ((MainActivity)getActivity()).moveToPlayer(); } public boolean onBackKey(){ SearchView search = ((MainActivity)getActivity()).searchView; if(search != null && !search.isIconified()){ search.setQuery("", false); search.setIconified(true); onClose(); return true; } RuuDirectory root; try{ root = RuuDirectory.rootDirectory(getContext()); }catch(RuuFileBase.CanNotOpen e){ return false; } if(current == null){ return false; }else if(current.path.equals(root)){ return false; }else{ try{ changeDir(current.path.getParent()); }catch(RuuDirectory.CanNotOpen e){ Toast.makeText(getActivity(), String.format(getString(R.string.cant_open_dir), current.path.path.getParent()), Toast.LENGTH_LONG).show(); } return true; } } public void setSearchQuery(@NonNull RuuDirectory path, @NonNull String query){ changeDir(path); ((MainActivity)getActivity()).searchView.setIconified(false); ((MainActivity)getActivity()).searchView.setQuery(query, true); } @Override public boolean onQueryTextChange(@NonNull String text){ return false; } @Override public boolean onQueryTextSubmit(@NonNull String text){ if(current == null){ return false; } if(TextUtils.isEmpty(text)){ onClose(); return false; } ((MainActivity)getActivity()).searchView.clearFocus(); String[] queries = TextUtils.split(text.toLowerCase(), " \t"); ArrayList<RuuFileBase> filtered = new ArrayList<>(); try{ for(RuuFileBase file: current.path.getAllRecursive()){ String name = file.getName().toLowerCase(); boolean isOk = true; for(String query: queries){ if(!name.contains(query)){ isOk = false; break; } } if(isOk){ filtered.add(file); } } }catch(RuuFileBase.CanNotOpen e){ Toast.makeText(getActivity(), String.format(getString(R.string.cant_open_dir), e.path), Toast.LENGTH_LONG).show(); return false; } adapter.setSearchResults(filtered); searchQuery = text; updateMenu(); return false; } @Override public boolean onClose(){ try{ adapter.resumeFromSearch(); }catch(RuuFileBase.CanNotOpen e){ Toast.makeText(getActivity(), String.format(getString(R.string.cant_open_dir), e.path), Toast.LENGTH_LONG).show(); adapter.clear(); } updateMenu(); return false; } class DirectoryInfo{ public final RuuDirectory path; public int selection = 0; public DirectoryInfo(@NonNull RuuDirectory path){ this.path = path; } } @UiThread private class RuuAdapter extends ArrayAdapter<RuuFileBase>{ @Nullable private DirectoryInfo dirInfo; int musicNum = 0; int directoryNum = 0; RuuAdapter(@NonNull Context context){ super(context, R.layout.list_item); } void setRuuFiles(@NonNull DirectoryInfo dirInfo) throws RuuFileBase.CanNotOpen{ clear(); searchQuery = null; this.dirInfo = dirInfo; RuuDirectory rootDirectory = RuuDirectory.rootDirectory(getContext()); if(!rootDirectory.equals(dirInfo.path) && rootDirectory.contains(dirInfo.path)){ int i=0; while(true){ i++; try{ add(dirInfo.path.getParent(i)); break; }catch(RuuFileBase.CanNotOpen e){ if(e.path == null){ break; } } } } List<RuuDirectory> directories = dirInfo.path.getDirectories(); directoryNum = directories.size(); for(RuuDirectory dir: directories){ add(dir); } List<RuuFile> musics = dirInfo.path.getMusics(); musicNum = musics.size(); for(RuuFile music: musics){ add(music); } ListView listView = (ListView)getActivity().findViewById(R.id.playlist); if(listView != null){ listView.setSelection(dirInfo.selection); } } void setSearchResults(@NonNull List<RuuFileBase> results){ if(dirInfo != null){ dirInfo.selection = ((ListView)getActivity().findViewById(R.id.playlist)).getFirstVisiblePosition(); } clear(); musicNum = 0; directoryNum = 0; for(RuuFileBase result: results){ add(result); } for(RuuFileBase file: results){ if(file.isDirectory()){ directoryNum++; }else{ musicNum++; } } ListView listView = (ListView)getActivity().findViewById(R.id.playlist); if(listView != null){ listView.setSelection(0); } } void resumeFromSearch() throws RuuFileBase.CanNotOpen{ if(dirInfo != null){ clear(); setRuuFiles(dirInfo); } } @Override public int getViewTypeCount(){ return 3; } @Override @IntRange(from=0, to=2) public int getItemViewType(int position){ if(searchQuery != null){ return 2; } if(getItem(position).isDirectory() && dirInfo != null && ((RuuDirectory)getItem(position)).contains(dirInfo.path)){ return 1; }else{ return 0; } } @Override @NonNull public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent){ RuuFileBase item = getItem(position); if(searchQuery != null){ if(convertView == null){ convertView = ((LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.list_item_search, null); } ((TextView)convertView.findViewById(R.id.search_name)).setText(item.getName() + (item.isDirectory() ? "/" : "")); try{ ((TextView)convertView.findViewById(R.id.search_path)).setText(item.getParent().getRuuPath()); }catch(RuuFileBase.CanNotOpen | RuuFileBase.OutOfRootDirectory e){ ((TextView)convertView.findViewById(R.id.search_path)).setText(""); } }else{ assert dirInfo != null; if(item.isDirectory() && ((RuuDirectory)item).contains(dirInfo.path)){ if(convertView == null){ convertView = ((LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.list_item_upper, null); } }else{ if(convertView == null){ convertView = ((LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.list_item, null); } ((TextView)convertView).setText(item.getName() + (item.isDirectory() ? "/" : "")); } } return convertView; } } }
Fixed problem that didn't work back key if couldn't open upper directory
app/src/main/java/jp/blanktar/ruumusic/client/PlaylistFragment.java
Fixed problem that didn't work back key if couldn't open upper directory
Java
lgpl-2.1
2895b65909931b553c8a8fda5c1b8ef00caa6bf2
0
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
// // $Id: SoundManager.java,v 1.33 2002/11/27 00:12:14 ray Exp $ package com.threerings.media; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.File; import java.io.FileInputStream; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.DataLine.Info; import javax.sound.sampled.DataLine; import javax.sound.sampled.FloatControl; import javax.sound.sampled.FloatControl.Type; import javax.sound.sampled.Line; import javax.sound.sampled.LineEvent; import javax.sound.sampled.LineListener; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.Mixer; import javax.sound.sampled.Mixer; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.UnsupportedAudioFileException; import javax.swing.Timer; import org.apache.commons.io.StreamUtils; import com.samskivert.util.Config; import com.samskivert.util.LockableLRUHashMap; import com.samskivert.util.LRUHashMap; import com.samskivert.util.Queue; import com.threerings.resource.ResourceManager; import com.threerings.util.RandomUtil; import com.threerings.media.Log; /** * Manages the playing of audio files. */ // TODO: // - fade music out when stopped? public class SoundManager implements MusicPlayer.MusicEventListener { /** * Create instances of this for your application to differentiate * between different types of sounds. */ public static class SoundType { /** * Construct a new SoundType. * Which should be a static variable stashed somewhere for the * entire application to share. * * @param strname a short string identifier, preferably without spaces. */ public SoundType (String strname) { _strname = strname; } public String toString () { return _strname; } protected String _strname; } /** The default sound type. */ public static final SoundType DEFAULT = new SoundType("default"); /** * Constructs a sound manager. */ public SoundManager (ResourceManager rmgr) { // save things off _rmgr = rmgr; // create a thread to plays sounds and load sound // data from the resource manager _player = new Thread("narya SoundManager") { public void run () { Object command = null; SoundKey key = null; MusicInfo musicInfo = null; while (amRunning()) { try { // Get the next command and arguments synchronized (_queue) { command = _queue.get(); // some commands have an additional argument. if ((PLAY == command) || (STOPMUSIC == command) || (LOCK == command) || (UNLOCK == command)) { key = (SoundKey) _queue.get(); } else if (PLAYMUSIC == command) { musicInfo = (MusicInfo) _queue.get(); } } // execute the command outside of the queue synch if (PLAY == command) { playSound(key); } else if (PLAYMUSIC == command) { playMusic(musicInfo); } else if (STOPMUSIC == command) { stopMusic(key); } else if (LOCK == command) { _clipCache.lock(key); getClipData(key); // preload } else if (UNLOCK == command) { _clipCache.unlock(key); } else if (UPDATE_MUSIC_VOL == command) { updateMusicVolume(); } else if (DIE == command) { LineSpooler.shutdown(); shutdownMusic(); } } catch (Exception e) { Log.warning("Captured exception in SoundManager loop."); Log.logStackTrace(e); } } Log.debug("SoundManager exit."); } }; _player.setDaemon(true); _player.start(); } /** * Shut the damn thing off. */ public synchronized void shutdown () { _player = null; synchronized (_queue) { _queue.clear(); _queue.append(DIE); // signal death } } /** * Used by the sound playing thread to determine whether or not to * shut down. */ protected synchronized boolean amRunning () { return (_player == Thread.currentThread()); } /** * Is the specified soundtype enabled? */ public boolean isEnabled (SoundType type) { // by default, types are enabled.. return (!_disabledTypes.contains(type)); } /** * Turns on or off the specified sound type. */ public void setEnabled (SoundType type, boolean enabled) { if (enabled) { _disabledTypes.remove(type); } else { _disabledTypes.add(type); } } /** * Set the test sound clip directory. */ public void setTestDir (String testy) { _testDir = testy; } /** * Sets the volume for all sound clips. * * @param val a volume parameter between 0f and 1f, inclusive. */ public void setClipVolume (float vol) { _clipVol = Math.max(0f, Math.min(1f, vol)); } /** * Get the volume for all sound clips. */ public float getClipVolume () { return _clipVol; } /** * Sets the volume for music. * * @param val a volume parameter between 0f and 1f, inclusive. */ public void setMusicVolume (float vol) { float oldvol = _musicVol; _musicVol = Math.max(0f, Math.min(1f, vol)); if ((oldvol == 0f) && (_musicVol != 0f)) { _musicAction = START; } else if ((oldvol != 0f) && (_musicVol == 0f)) { _musicAction = STOP; } else { _musicAction = NONE; } _queue.append(UPDATE_MUSIC_VOL); } /** * Get the music volume. */ public float getMusicVolume () { return _musicVol; } /** * Optionally lock the sound data prior to playing, to guarantee * that it will be quickly available for playing. */ public void lock (String pkgPath, String key) { synchronized (_queue) { _queue.append(LOCK); _queue.append(new SoundKey(pkgPath, key)); } } /** * Unlock the specified sound so that its resources can be freed. */ public void unlock (String pkgPath, String key) { synchronized (_queue) { _queue.append(UNLOCK); _queue.append(new SoundKey(pkgPath, key)); } } /** * Play the specified sound of as the specified type of sound. * Note that a sound need not be locked prior to playing. */ public void play (SoundType type, String pkgPath, String key) { if (type == null) { // let the lazy kids play too type = DEFAULT; } if (_player != null && (_clipVol != 0f) && isEnabled(type)) { synchronized (_queue) { if (_queue.size() < MAX_QUEUE_SIZE) { _queue.append(PLAY); _queue.append(new SoundKey(pkgPath, key)); } else { Log.warning("SoundManager not playing sound because " + "too many sounds in queue [pkgPath=" + pkgPath + ", key=" + key + ", type=" + type + "]."); } } } } /** * Start playing the specified music repeatedly. */ public void pushMusic (String pkgPath, String key) { pushMusic(pkgPath, key, -1); } /** * Start playing music for the specified number of loops. */ public void pushMusic (String pkgPath, String key, int numloops) { synchronized (_queue) { _queue.append(PLAYMUSIC); _queue.append(new MusicInfo(pkgPath, key, numloops)); } } /** * Remove the specified music from the playlist. If it is currently * playing, it will be stopped and the previous song will be started. */ public void removeMusic (String pkgPath, String key) { synchronized (_queue) { _queue.append(STOPMUSIC); _queue.append(new SoundKey(pkgPath, key)); } } /** * On the SoundManager thread, * plays the sound file with the given pathname. */ protected void playSound (SoundKey key) { try { // get the sound data from our LRU cache byte[] data = getClipData(key); if (data == null) { return; // borked! } AudioInputStream stream = AudioSystem.getAudioInputStream( new ByteArrayInputStream(data)); LineSpooler.play(stream, _clipVol); } catch (IOException ioe) { Log.warning("Error loading sound file [key=" + key + ", e=" + ioe + "]."); } catch (UnsupportedAudioFileException uafe) { Log.warning("Unsupported sound format [key=" + key + ", e=" + uafe + "]."); } catch (LineUnavailableException lue) { Log.warning("Line not available to play sound [key=" + key + ", e=" + lue + "]."); } } /** * Play a song from the specified path. */ protected void playMusic (MusicInfo info) { // stop whatever's currently playing if (_musicPlayer != null) { _musicPlayer.stop(); handleMusicStopped(); } // add the new song _musicStack.addFirst(info); // and play it playTopMusic(); } /** * Start the specified sequence. */ protected void playTopMusic () { if (_musicStack.isEmpty()) { return; } // if the volume is off, we don't actually want to play anything // but we want to at least decrement any loopers by one // and keep them on the top of the queue if (_musicVol == 0f) { handleMusicStopped(); return; } MusicInfo info = (MusicInfo) _musicStack.getFirst(); Config c = getConfig(info); String[] names = c.getValue(info.key, (String[])null); if (names == null) { Log.warning("No such music [key=" + info + "]."); _musicStack.removeFirst(); playTopMusic(); return; } String music = names[RandomUtil.getInt(names.length)]; Class playerClass = getMusicPlayerClass(music); // shutdown the old player if we're switching music types if (! playerClass.isInstance(_musicPlayer)) { if (_musicPlayer != null) { _musicPlayer.shutdown(); } // set up the new player try { _musicPlayer = (MusicPlayer) playerClass.newInstance(); _musicPlayer.init(this); } catch (Exception e) { Log.warning("Unable to instantiate music player [class=" + playerClass + ", e=" + e + "]."); // scrap it, try again with the next song _musicPlayer = null; _musicStack.removeFirst(); playTopMusic(); return; } _musicPlayer.setVolume(_musicVol); } // play! String bundle = c.getValue("bundle", (String)null); try { // TODO: buffer for the music player? _musicPlayer.start(_rmgr.getResource(bundle, music)); } catch (Exception e) { Log.warning("Error playing music, skipping [e=" + e + ", bundle=" + bundle + ", music=" + music + "]."); _musicStack.removeFirst(); playTopMusic(); return; } } /** * Get the appropriate music player for the specified music file. */ protected static Class getMusicPlayerClass (String path) { path = path.toLowerCase(); if (path.endsWith(".mid") || path.endsWith(".rmf")) { return MidiPlayer.class; } else if (path.endsWith(".mod")) { return ModPlayer.class; } else if (path.endsWith(".mp3")) { return Mp3Player.class; } else { return null; } } /** * Stop whatever song is currently playing and deal with the * MusicInfo associated with it. */ protected void handleMusicStopped () { if (_musicStack.isEmpty()) { return; } // see what was playing MusicInfo current = (MusicInfo) _musicStack.getFirst(); // see how many times the song was to loop and act accordingly switch (current.loops) { default: current.loops--; break; case 1: // sorry charlie _musicStack.removeFirst(); break; } } /** * Stop the sequence at the specified path. */ protected void stopMusic (SoundKey key) { if (! _musicStack.isEmpty()) { MusicInfo current = (MusicInfo) _musicStack.getFirst(); // if we're currently playing this song.. if (key.equals(current)) { // stop it _musicPlayer.stop(); // remove it from the stack _musicStack.removeFirst(); // start playing the next.. playTopMusic(); return; } else { // we aren't currently playing this song. Simply remove. for (Iterator iter=_musicStack.iterator(); iter.hasNext(); ) { if (key.equals(iter.next())) { iter.remove(); return; } } } } Log.debug("Sequence stopped that wasn't in the stack anymore " + "[key=" + key + "]."); } /** * Attempt to modify the music volume for any playing tracks. * * @param start */ protected void updateMusicVolume () { if (_musicPlayer != null) { _musicPlayer.setVolume(_musicVol); } switch (_musicAction) { case START: playTopMusic(); break; case STOP: stopMusicPlayer(); break; } } // documentation inherited from interface MusicPlayer.MusicEventListener public void musicStopped () { handleMusicStopped(); playTopMusic(); } /** * Shutdown the music subsystem. */ protected void shutdownMusic () { _musicStack.clear(); stopMusicPlayer(); } /** * Stop the current music player. */ protected void stopMusicPlayer () { if (_musicPlayer != null) { _musicPlayer.stop(); _musicPlayer.shutdown(); _musicPlayer = null; } } /** * Get the audio data for the specified path. */ protected byte[] getClipData (SoundKey key) throws IOException, UnsupportedAudioFileException { // if we're testing, clear all non-locked sounds every time if (_testDir != null) { _clipCache.clear(); } byte[][] data = (byte[][]) _clipCache.get(key); if (data == null) { // if there is a test sound, JUST use the test sound. InputStream stream = getTestClip(key); if (stream != null) { data = new byte[1][]; data[0] = StreamUtils.streamAsBytes(stream, BUFFER_SIZE); } else { // otherwise, randomize between all available sounds Config c = getConfig(key); String[] names = c.getValue(key.key, (String[])null); if (names == null) { Log.warning("No such sound [key=" + key + "]."); return null; } data = new byte[names.length][]; String bundle = c.getValue("bundle", (String)null); for (int ii=0; ii < names.length; ii++) { data[ii] = StreamUtils.streamAsBytes( _rmgr.getResource(bundle, names[ii]), BUFFER_SIZE); } } _clipCache.put(key, data); } return data[RandomUtil.getInt(data.length)]; } protected InputStream getTestClip (SoundKey key) { if (_testDir == null) { return null; } final String namePrefix = key.key + "."; File f = new File(_testDir); File[] list = f.listFiles(new FilenameFilter() { public boolean accept (File f, String name) { return name.startsWith(namePrefix); } }); if ((list != null) && (list.length > 0)) { try { return new FileInputStream(list[0]); } catch (Exception e) { Log.warning("Error reading test sound [e=" + e + ", file=" + list[0] + "]."); } } return null; } protected Config getConfig (SoundKey key) { Config c = (Config) _configs.get(key.pkgPath); if (c == null) { String propPath = key.pkgPath + Sounds.PROP_NAME; c = new Config(propPath); _configs.put(key.pkgPath, c); } return c; } // /** // * Adjust the volume of this clip. // */ // protected static void adjustVolumeIdeally (Line line, float volume) // { // if (line.isControlSupported(FloatControl.Type.VOLUME)) { // FloatControl vol = (FloatControl) // line.getControl(FloatControl.Type.VOLUME); // // float min = vol.getMinimum(); // float max = vol.getMaximum(); // // float ourval = (volume * (max - min)) + min; // Log.debug("adjust vol: [min=" + min + ", ourval=" + ourval + // ", max=" + max + "]."); // vol.setValue(ourval); // // } else { // // fall back // adjustVolume(line, volume); // } // } /** * Use the gain control to implement volume. */ protected static void adjustVolume (Line line, float vol) { FloatControl control = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN); // the only problem is that gain is specified in decibals, // which is a logarithmic scale. // Since we want max volume to leave the sample unchanged, our // maximum volume translates into a 0db gain. float gain; if (vol == 0f) { gain = control.getMinimum(); } else { gain = (float) ((Math.log(vol) / Math.log(10.0)) * 20.0); } control.setValue(gain); //Log.info("Set gain: " + gain); } /** * Handles the playing of sound clip data. */ protected static class LineSpooler extends Thread { /** * Attempt to play the specified sound. */ public static void play (AudioInputStream stream, float volume) throws LineUnavailableException { AudioFormat format = stream.getFormat(); LineSpooler spooler; for (int ii=0, nn=_openSpoolers.size(); ii < nn; ii++) { spooler = (LineSpooler) _openSpoolers.get(ii); // we have this thread remove the spooler if it's dead // so that we avoid deadlock conditions if (spooler.isDead()) { _openSpoolers.remove(ii--); nn--; } else if (spooler.checkPlay(format, stream, volume)) { return; } } if (_openSpoolers.size() >= MAX_SPOOLERS) { throw new LineUnavailableException("Exceeded maximum number " + "of narya sound spoolers."); } spooler = new LineSpooler(format); _openSpoolers.add(spooler); spooler.checkPlay(format, stream, volume); spooler.start(); } /** * Shutdown the linespooler subsystem. */ public static void shutdown () { // this is all that is needed, after 30 seconds each spooler for (int ii=0, nn=_openSpoolers.size(); ii < nn; ii++) { // this will stop playback now ((LineSpooler) _openSpoolers.get(ii)).setDead(); } // and this will remove all the spoolers. They'll still be // around while they drain their lines and then wait 30 seconds // to die... _openSpoolers.clear(); } /** * Private constructor. */ private LineSpooler (AudioFormat format) throws LineUnavailableException { super("narya SoundManager LineSpooler"); _format = format; _line = (SourceDataLine) AudioSystem.getLine(new DataLine.Info( SourceDataLine.class, _format)); _line.open(_format); _line.start(); } /** * Set this line to dead. */ protected void setDead () { _valid = false; } /** * Has this line been closed? */ protected boolean isDead () { return !_valid; } /** * Check-and-set method to see if we can play and to start * doing so if we can. */ protected synchronized boolean checkPlay ( AudioFormat format, AudioInputStream stream, float volume) { if (_valid && (_stream == null) && _format.matches(format)) { _stream = stream; SoundManager.adjustVolume(_line, volume); notify(); return true; } return false; } /** * @return true if we have sound data to play. */ protected synchronized boolean waitForData () { if (_stream == null) { try { wait(MAX_WAIT_TIME); } catch (InterruptedException ie) { // ignore. } if (_stream == null) { setDead(); // we waited 30 seconds and never got a sound. return false; } } return true; } /** * Main loop for the LineSpooler. */ public void run () { while (waitForData()) { playStream(); } _line.close(); } /** * Play the current stream. */ protected void playStream () { int count = 0; byte[] data = new byte[BUFFER_SIZE]; while (_valid && count != -1) { try { count = _stream.read(data, 0, data.length); } catch (IOException e) { // this shouldn't ever ever happen because the stream // we're given is from a reliable source Log.warning("Error reading clip data! [e=" + e + "]."); _stream = null; return; } if (count >= 0) { _line.write(data, 0, count); } } // SO, I used to just always drain, but I found what appears // to be a bug in linux's native implementation of drain // that sometimes resulted in the internals of drain // going into an infinite loop. Checking to see if the line // isActive (engaging in I/O) before calling drain seems // to have stopped the problem from happening. // // TODO: look at this some more. // For now I'm turning draining back on, because I've seen // instances of longer sounds reporting that they're not active // while they're still playing, and so the next sound // is significantly delayed. That sucks. //if (_line.isActive()) { // Log.info("Waiting for drain (" + hashCode() + ", active=" + // _line.isActive() + ", running=" + _line.isRunning()+ // ") : " + incDrainers()); // wait for it to play all the way _line.drain(); // Log.info("drained: (" + hashCode() + ") :" + decDrainers()); //} // clear it out so that we can wait for more. _stream = null; } // protected static final synchronized int incDrainers () // { // return ++drainers; // } // // protected static final synchronized int decDrainers () // { // return --drainers; // } // static int drainers = 0; /** The format that our line was opened with. */ protected AudioFormat _format; /** The stream we're currently spooling out. */ protected AudioInputStream _stream; /** The line that we spool to. */ protected SourceDataLine _line; /** Are we still active and usable for spooling sounds, or should * we be removed. */ protected boolean _valid = true; /** The list of all the currently instantiated spoolers. */ protected static ArrayList _openSpoolers = new ArrayList(); /** The maximum time a spooler will wait for a stream before * deciding to shut down. */ protected static final long MAX_WAIT_TIME = 30000L; /** The maximum number of spoolers we'll allow. This is a lot. */ protected static final int MAX_SPOOLERS = 24; } /** * A key for tracking sounds. */ protected static class SoundKey { public String pkgPath; public String key; public SoundKey (String pkgPath, String key) { this.pkgPath = pkgPath; this.key = key; } // documentation inherited public String toString () { return "SoundKey{pkgPath=" + pkgPath + ", key=" + key + "}"; } // documentation inherited public int hashCode () { return pkgPath.hashCode() ^ key.hashCode(); } // documentation inherited public boolean equals (Object o) { if (o instanceof SoundKey) { SoundKey that = (SoundKey) o; return this.pkgPath.equals(that.pkgPath) && this.key.equals(that.key); } return false; } } /** * A class that tracks the information about our playing music files. */ protected static class MusicInfo extends SoundKey { /** How many times to loop, or -1 for forever. */ public int loops; // TODO rename public MusicInfo (String set, String path, int loops) { super(set, path); this.loops = loops; } } /** Directory from which we load test sounds. */ protected String _testDir; /** The resource manager from which we obtain audio files. */ protected ResourceManager _rmgr; /** The thread that plays sounds. */ protected Thread _player; /** The queue of sound clips to be played. */ protected Queue _queue = new Queue(); /** Volume levels for both sound clips and music. */ protected float _clipVol = 1f, _musicVol = 1f; /** The action to take when adjusting music volume. */ protected int _musicAction = NONE; /** The cache of recent audio clips . */ protected LockableLRUHashMap _clipCache = new LockableLRUHashMap(10); /** The clips that are currently active. */ protected ArrayList _activeClips = new ArrayList(); /** The stack of songs that we're playing. */ protected LinkedList _musicStack = new LinkedList(); /** The current music player, if any. */ protected MusicPlayer _musicPlayer; /** A set of soundTypes for which sound is enabled. */ protected HashSet _disabledTypes = new HashSet(); /** A cache of config objects we've created. */ protected HashMap _configs = new HashMap(); /** Signals to the queue to do different things. */ protected Object PLAY = new Object(); protected Object PLAYMUSIC = new Object(); protected Object STOPMUSIC = new Object(); protected Object UPDATE_MUSIC_VOL = new Object(); protected Object LOCK = new Object(); protected Object UNLOCK = new Object(); protected Object DIE = new Object(); /** Music action constants. */ protected static final int NONE = 0; protected static final int START = 1; protected static final int STOP = 2; /** The queue size at which we start to ignore requests to play sounds. */ protected static final int MAX_QUEUE_SIZE = 25; /** The buffer size in bytes used when reading audio file data. */ protected static final int BUFFER_SIZE = 1024 * 24; }
src/java/com/threerings/media/sound/SoundManager.java
// // $Id: SoundManager.java,v 1.32 2002/11/26 21:14:11 ray Exp $ package com.threerings.media; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.File; import java.io.FileInputStream; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.DataLine.Info; import javax.sound.sampled.DataLine; import javax.sound.sampled.FloatControl; import javax.sound.sampled.FloatControl.Type; import javax.sound.sampled.Line; import javax.sound.sampled.LineEvent; import javax.sound.sampled.LineListener; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.Mixer; import javax.sound.sampled.Mixer; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.UnsupportedAudioFileException; import javax.swing.Timer; import org.apache.commons.io.StreamUtils; import com.samskivert.util.Config; import com.samskivert.util.LockableLRUHashMap; import com.samskivert.util.LRUHashMap; import com.samskivert.util.Queue; import com.threerings.resource.ResourceManager; import com.threerings.util.RandomUtil; import com.threerings.media.Log; /** * Manages the playing of audio files. */ // TODO: // - fade music out when stopped? public class SoundManager implements MusicPlayer.MusicEventListener { /** * Create instances of this for your application to differentiate * between different types of sounds. */ public static class SoundType { /** * Construct a new SoundType. * Which should be a static variable stashed somewhere for the * entire application to share. * * @param strname a short string identifier, preferably without spaces. */ public SoundType (String strname) { _strname = strname; } public String toString () { return _strname; } protected String _strname; } /** The default sound type. */ public static final SoundType DEFAULT = new SoundType("default"); /** * Constructs a sound manager. */ public SoundManager (ResourceManager rmgr) { // save things off _rmgr = rmgr; // create a thread to plays sounds and load sound // data from the resource manager _player = new Thread("narya SoundManager") { public void run () { Object command = null; SoundKey key = null; MusicInfo musicInfo = null; while (amRunning()) { try { // Get the next command and arguments synchronized (_queue) { command = _queue.get(); // some commands have an additional argument. if ((PLAY == command) || (STOPMUSIC == command) || (LOCK == command) || (UNLOCK == command)) { key = (SoundKey) _queue.get(); } else if (PLAYMUSIC == command) { musicInfo = (MusicInfo) _queue.get(); } } // execute the command outside of the queue synch if (PLAY == command) { playSound(key); } else if (PLAYMUSIC == command) { playMusic(musicInfo); } else if (STOPMUSIC == command) { stopMusic(key); } else if (LOCK == command) { _clipCache.lock(key); getClipData(key); // preload } else if (UNLOCK == command) { _clipCache.unlock(key); } else if (UPDATE_MUSIC_VOL == command) { updateMusicVolume(); } else if (DIE == command) { LineSpooler.shutdown(); shutdownMusic(); } } catch (Exception e) { Log.warning("Captured exception in SoundManager loop."); Log.logStackTrace(e); } } Log.debug("SoundManager exit."); } }; _player.setDaemon(true); _player.start(); } /** * Shut the damn thing off. */ public synchronized void shutdown () { _player = null; synchronized (_queue) { _queue.clear(); _queue.append(DIE); // signal death } } /** * Used by the sound playing thread to determine whether or not to * shut down. */ protected synchronized boolean amRunning () { return (_player == Thread.currentThread()); } /** * Is the specified soundtype enabled? */ public boolean isEnabled (SoundType type) { // by default, types are enabled.. return (!_disabledTypes.contains(type)); } /** * Turns on or off the specified sound type. */ public void setEnabled (SoundType type, boolean enabled) { if (enabled) { _disabledTypes.remove(type); } else { _disabledTypes.add(type); } } /** * Set the test sound clip directory. */ public void setTestDir (String testy) { _testDir = testy; } /** * Sets the volume for all sound clips. * * @param val a volume parameter between 0f and 1f, inclusive. */ public void setClipVolume (float vol) { _clipVol = Math.max(0f, Math.min(1f, vol)); } /** * Get the volume for all sound clips. */ public float getClipVolume () { return _clipVol; } /** * Sets the volume for music. * * @param val a volume parameter between 0f and 1f, inclusive. */ public void setMusicVolume (float vol) { float oldvol = _musicVol; _musicVol = Math.max(0f, Math.min(1f, vol)); if ((oldvol == 0f) && (_musicVol != 0f)) { _musicAction = START; } else if ((oldvol != 0f) && (_musicVol == 0f)) { _musicAction = STOP; } else { _musicAction = NONE; } _queue.append(UPDATE_MUSIC_VOL); } /** * Get the music volume. */ public float getMusicVolume () { return _musicVol; } /** * Optionally lock the sound data prior to playing, to guarantee * that it will be quickly available for playing. */ public void lock (String pkgPath, String key) { synchronized (_queue) { _queue.append(LOCK); _queue.append(new SoundKey(pkgPath, key)); } } /** * Unlock the specified sound so that its resources can be freed. */ public void unlock (String pkgPath, String key) { synchronized (_queue) { _queue.append(UNLOCK); _queue.append(new SoundKey(pkgPath, key)); } } /** * Play the specified sound of as the specified type of sound. * Note that a sound need not be locked prior to playing. */ public void play (SoundType type, String pkgPath, String key) { if (type == null) { // let the lazy kids play too type = DEFAULT; } if (_player != null && (_clipVol != 0f) && isEnabled(type)) { synchronized (_queue) { if (_queue.size() < MAX_QUEUE_SIZE) { _queue.append(PLAY); _queue.append(new SoundKey(pkgPath, key)); } else { Log.warning("SoundManager not playing sound because " + "too many sounds in queue [pkgPath=" + pkgPath + ", key=" + key + ", type=" + type + "]."); } } } } /** * Start playing the specified music repeatedly. */ public void pushMusic (String pkgPath, String key) { pushMusic(pkgPath, key, -1); } /** * Start playing music for the specified number of loops. */ public void pushMusic (String pkgPath, String key, int numloops) { synchronized (_queue) { _queue.append(PLAYMUSIC); _queue.append(new MusicInfo(pkgPath, key, numloops)); } } /** * Remove the specified music from the playlist. If it is currently * playing, it will be stopped and the previous song will be started. */ public void removeMusic (String pkgPath, String key) { synchronized (_queue) { _queue.append(STOPMUSIC); _queue.append(new SoundKey(pkgPath, key)); } } /** * On the SoundManager thread, * plays the sound file with the given pathname. */ protected void playSound (SoundKey key) { try { // get the sound data from our LRU cache byte[] data = getClipData(key); if (data == null) { return; // borked! } AudioInputStream stream = AudioSystem.getAudioInputStream( new ByteArrayInputStream(data)); LineSpooler.play(stream, _clipVol); } catch (IOException ioe) { Log.warning("Error loading sound file [key=" + key + ", e=" + ioe + "]."); } catch (UnsupportedAudioFileException uafe) { Log.warning("Unsupported sound format [key=" + key + ", e=" + uafe + "]."); } catch (LineUnavailableException lue) { Log.warning("Line not available to play sound [key=" + key + ", e=" + lue + "]."); } } /** * Play a song from the specified path. */ protected void playMusic (MusicInfo info) { // stop whatever's currently playing if (_musicPlayer != null) { _musicPlayer.stop(); handleMusicStopped(); } // add the new song _musicStack.addFirst(info); // and play it playTopMusic(); } /** * Start the specified sequence. */ protected void playTopMusic () { if (_musicStack.isEmpty()) { return; } // if the volume is off, we don't actually want to play anything // but we want to at least decrement any loopers by one // and keep them on the top of the queue if (_musicVol == 0f) { handleMusicStopped(); return; } MusicInfo info = (MusicInfo) _musicStack.getFirst(); Config c = getConfig(info); String[] names = c.getValue(info.key, (String[])null); if (names == null) { Log.warning("No such music [key=" + info + "]."); _musicStack.removeFirst(); playTopMusic(); return; } String music = names[RandomUtil.getInt(names.length)]; Class playerClass = getMusicPlayerClass(music); // shutdown the old player if we're switching music types if (! playerClass.isInstance(_musicPlayer)) { if (_musicPlayer != null) { _musicPlayer.shutdown(); } // set up the new player try { _musicPlayer = (MusicPlayer) playerClass.newInstance(); _musicPlayer.init(this); } catch (Exception e) { Log.warning("Unable to instantiate music player [class=" + playerClass + ", e=" + e + "]."); // scrap it, try again with the next song _musicPlayer = null; _musicStack.removeFirst(); playTopMusic(); return; } _musicPlayer.setVolume(_musicVol); } // play! String bundle = c.getValue("bundle", (String)null); try { // TODO: buffer for the music player? _musicPlayer.start(_rmgr.getResource(bundle, music)); } catch (Exception e) { Log.warning("Error playing music, skipping [e=" + e + ", bundle=" + bundle + ", music=" + music + "]."); _musicStack.removeFirst(); playTopMusic(); return; } } /** * Get the appropriate music player for the specified music file. */ protected static Class getMusicPlayerClass (String path) { path = path.toLowerCase(); if (path.endsWith(".mid") || path.endsWith(".rmf")) { return MidiPlayer.class; } else if (path.endsWith(".mod")) { return ModPlayer.class; } else if (path.endsWith(".mp3")) { return Mp3Player.class; } else { return null; } } /** * Stop whatever song is currently playing and deal with the * MusicInfo associated with it. */ protected void handleMusicStopped () { if (_musicStack.isEmpty()) { return; } // see what was playing MusicInfo current = (MusicInfo) _musicStack.getFirst(); // see how many times the song was to loop and act accordingly switch (current.loops) { default: current.loops--; break; case 1: // sorry charlie _musicStack.removeFirst(); break; } } /** * Stop the sequence at the specified path. */ protected void stopMusic (SoundKey key) { if (! _musicStack.isEmpty()) { MusicInfo current = (MusicInfo) _musicStack.getFirst(); // if we're currently playing this song.. if (key.equals(current)) { // stop it _musicPlayer.stop(); // remove it from the stack _musicStack.removeFirst(); // start playing the next.. playTopMusic(); return; } else { // we aren't currently playing this song. Simply remove. for (Iterator iter=_musicStack.iterator(); iter.hasNext(); ) { if (key.equals(iter.next())) { iter.remove(); return; } } } } Log.debug("Sequence stopped that wasn't in the stack anymore " + "[key=" + key + "]."); } /** * Attempt to modify the music volume for any playing tracks. * * @param start */ protected void updateMusicVolume () { if (_musicPlayer != null) { _musicPlayer.setVolume(_musicVol); } switch (_musicAction) { case START: playTopMusic(); break; case STOP: stopMusicPlayer(); break; } } // documentation inherited from interface MusicPlayer.MusicEventListener public void musicStopped () { handleMusicStopped(); playTopMusic(); } /** * Shutdown the music subsystem. */ protected void shutdownMusic () { _musicStack.clear(); stopMusicPlayer(); } /** * Stop the current music player. */ protected void stopMusicPlayer () { if (_musicPlayer != null) { _musicPlayer.stop(); _musicPlayer.shutdown(); _musicPlayer = null; } } /** * Get the audio data for the specified path. */ protected byte[] getClipData (SoundKey key) throws IOException, UnsupportedAudioFileException { // if we're testing, clear all non-locked sounds every time if (_testDir != null) { _clipCache.clear(); } byte[][] data = (byte[][]) _clipCache.get(key); if (data == null) { // if there is a test sound, JUST use the test sound. InputStream stream = getTestClip(key); if (stream != null) { data = new byte[1][]; data[0] = StreamUtils.streamAsBytes(stream, BUFFER_SIZE); } else { // otherwise, randomize between all available sounds Config c = getConfig(key); String[] names = c.getValue(key.key, (String[])null); if (names == null) { Log.warning("No such sound [key=" + key + "]."); return null; } data = new byte[names.length][]; String bundle = c.getValue("bundle", (String)null); for (int ii=0; ii < names.length; ii++) { data[ii] = StreamUtils.streamAsBytes( _rmgr.getResource(bundle, names[ii]), BUFFER_SIZE); } } _clipCache.put(key, data); } return data[RandomUtil.getInt(data.length)]; } protected InputStream getTestClip (SoundKey key) { if (_testDir == null) { return null; } final String namePrefix = key.key + "."; File f = new File(_testDir); File[] list = f.listFiles(new FilenameFilter() { public boolean accept (File f, String name) { return name.startsWith(namePrefix); } }); if ((list != null) && (list.length > 0)) { try { return new FileInputStream(list[0]); } catch (Exception e) { Log.warning("Error reading test sound [e=" + e + ", file=" + list[0] + "]."); } } return null; } protected Config getConfig (SoundKey key) { Config c = (Config) _configs.get(key.pkgPath); if (c == null) { String propPath = key.pkgPath + Sounds.PROP_NAME; c = new Config(propPath); _configs.put(key.pkgPath, c); } return c; } // /** // * Adjust the volume of this clip. // */ // protected static void adjustVolumeIdeally (Line line, float volume) // { // if (line.isControlSupported(FloatControl.Type.VOLUME)) { // FloatControl vol = (FloatControl) // line.getControl(FloatControl.Type.VOLUME); // // float min = vol.getMinimum(); // float max = vol.getMaximum(); // // float ourval = (volume * (max - min)) + min; // Log.debug("adjust vol: [min=" + min + ", ourval=" + ourval + // ", max=" + max + "]."); // vol.setValue(ourval); // // } else { // // fall back // adjustVolume(line, volume); // } // } /** * Use the gain control to implement volume. */ protected static void adjustVolume (Line line, float vol) { FloatControl control = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN); // the only problem is that gain is specified in decibals, // which is a logarithmic scale. // Since we want max volume to leave the sample unchanged, our // maximum volume translates into a 0db gain. float gain; if (vol == 0f) { gain = control.getMinimum(); } else { gain = (float) ((Math.log(vol) / Math.log(10.0)) * 20.0); } control.setValue(gain); //Log.info("Set gain: " + gain); } /** * Handles the playing of sound clip data. */ protected static class LineSpooler extends Thread { /** * Attempt to play the specified sound. */ public static void play (AudioInputStream stream, float volume) throws LineUnavailableException { AudioFormat format = stream.getFormat(); LineSpooler spooler; for (int ii=0, nn=_openSpoolers.size(); ii < nn; ii++) { spooler = (LineSpooler) _openSpoolers.get(ii); // we have this thread remove the spooler if it's dead // so that we avoid deadlock conditions if (spooler.isDead()) { _openSpoolers.remove(ii--); nn--; } else if (spooler.checkPlay(format, stream, volume)) { return; } } if (_openSpoolers.size() >= MAX_SPOOLERS) { throw new LineUnavailableException("Exceeded maximum number " + "of narya sound spoolers."); } spooler = new LineSpooler(format); _openSpoolers.add(spooler); spooler.checkPlay(format, stream, volume); spooler.start(); } /** * Shutdown the linespooler subsystem. */ public static void shutdown () { // this is all that is needed, after 30 seconds each spooler for (int ii=0, nn=_openSpoolers.size(); ii < nn; ii++) { // this will stop playback now ((LineSpooler) _openSpoolers.get(ii)).setDead(); } // and this will remove all the spoolers. They'll still be // around while they drain their lines and then wait 30 seconds // to die... _openSpoolers.clear(); } /** * Private constructor. */ private LineSpooler (AudioFormat format) throws LineUnavailableException { super("narya SoundManager LineSpooler"); _format = format; _line = (SourceDataLine) AudioSystem.getLine(new DataLine.Info( SourceDataLine.class, _format)); _line.open(_format); _line.start(); } /** * Set this line to dead. */ protected void setDead () { _valid = false; } /** * Has this line been closed? */ protected boolean isDead () { return !_valid; } /** * Check-and-set method to see if we can play and to start * doing so if we can. */ protected synchronized boolean checkPlay ( AudioFormat format, AudioInputStream stream, float volume) { if (_valid && (_stream == null) && _format.matches(format)) { _stream = stream; SoundManager.adjustVolume(_line, volume); notify(); return true; } return false; } /** * @return true if we have sound data to play. */ protected synchronized boolean waitForData () { if (_stream == null) { try { wait(MAX_WAIT_TIME); } catch (InterruptedException ie) { // ignore. } if (_stream == null) { setDead(); // we waited 30 seconds and never got a sound. return false; } } return true; } /** * Main loop for the LineSpooler. */ public void run () { while (waitForData()) { playStream(); } _line.close(); } /** * Play the current stream. */ protected void playStream () { int count = 0; byte[] data = new byte[BUFFER_SIZE]; while (_valid && count != -1) { try { count = _stream.read(data, 0, data.length); } catch (IOException e) { // this shouldn't ever ever happen because the stream // we're given is from a reliable source Log.warning("Error reading clip data! [e=" + e + "]."); _stream = null; return; } if (count >= 0) { _line.write(data, 0, count); } } // SO, I used to just always drain, but I found what appears // to be a bug in linux's native implementation of drain // that sometimes resulted in the internals of drain // going into an infinite loop. Checking to see if the line // isActive (engaging in I/O) before calling drain seems // to have stopped the problem from happening. if (_line.isActive()) { // Log.info("Waiting for drain (" + hashCode() + ", active=" + // _line.isActive() + ", running=" + _line.isRunning()+ // ") : " + incDrainers()); // wait for it to play all the way _line.drain(); // Log.info("drained: (" + hashCode() + ") :" + decDrainers()); } // clear it out so that we can wait for more. _stream = null; } // protected static final synchronized int incDrainers () // { // return ++drainers; // } // // protected static final synchronized int decDrainers () // { // return --drainers; // } // static int drainers = 0; /** The format that our line was opened with. */ protected AudioFormat _format; /** The stream we're currently spooling out. */ protected AudioInputStream _stream; /** The line that we spool to. */ protected SourceDataLine _line; /** Are we still active and usable for spooling sounds, or should * we be removed. */ protected boolean _valid = true; /** The list of all the currently instantiated spoolers. */ protected static ArrayList _openSpoolers = new ArrayList(); /** The maximum time a spooler will wait for a stream before * deciding to shut down. */ protected static final long MAX_WAIT_TIME = 30000L; /** The maximum number of spoolers we'll allow. This is a lot. */ protected static final int MAX_SPOOLERS = 24; } /** * A key for tracking sounds. */ protected static class SoundKey { public String pkgPath; public String key; public SoundKey (String pkgPath, String key) { this.pkgPath = pkgPath; this.key = key; } // documentation inherited public String toString () { return "SoundKey{pkgPath=" + pkgPath + ", key=" + key + "}"; } // documentation inherited public int hashCode () { return pkgPath.hashCode() ^ key.hashCode(); } // documentation inherited public boolean equals (Object o) { if (o instanceof SoundKey) { SoundKey that = (SoundKey) o; return this.pkgPath.equals(that.pkgPath) && this.key.equals(that.key); } return false; } } /** * A class that tracks the information about our playing music files. */ protected static class MusicInfo extends SoundKey { /** How many times to loop, or -1 for forever. */ public int loops; // TODO rename public MusicInfo (String set, String path, int loops) { super(set, path); this.loops = loops; } } /** Directory from which we load test sounds. */ protected String _testDir; /** The resource manager from which we obtain audio files. */ protected ResourceManager _rmgr; /** The thread that plays sounds. */ protected Thread _player; /** The queue of sound clips to be played. */ protected Queue _queue = new Queue(); /** Volume levels for both sound clips and music. */ protected float _clipVol = 1f, _musicVol = 1f; /** The action to take when adjusting music volume. */ protected int _musicAction = NONE; /** The cache of recent audio clips . */ protected LockableLRUHashMap _clipCache = new LockableLRUHashMap(10); /** The clips that are currently active. */ protected ArrayList _activeClips = new ArrayList(); /** The stack of songs that we're playing. */ protected LinkedList _musicStack = new LinkedList(); /** The current music player, if any. */ protected MusicPlayer _musicPlayer; /** A set of soundTypes for which sound is enabled. */ protected HashSet _disabledTypes = new HashSet(); /** A cache of config objects we've created. */ protected HashMap _configs = new HashMap(); /** Signals to the queue to do different things. */ protected Object PLAY = new Object(); protected Object PLAYMUSIC = new Object(); protected Object STOPMUSIC = new Object(); protected Object UPDATE_MUSIC_VOL = new Object(); protected Object LOCK = new Object(); protected Object UNLOCK = new Object(); protected Object DIE = new Object(); /** Music action constants. */ protected static final int NONE = 0; protected static final int START = 1; protected static final int STOP = 2; /** The queue size at which we start to ignore requests to play sounds. */ protected static final int MAX_QUEUE_SIZE = 25; /** The buffer size in bytes used when reading audio file data. */ protected static final int BUFFER_SIZE = 8192; }
- always drain again - increased buffer size to 24k git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@1999 542714f4-19e9-0310-aa3c-eee0fc999fb1
src/java/com/threerings/media/sound/SoundManager.java
- always drain again - increased buffer size to 24k
Java
lgpl-2.1
4dd309e4e8b4694ee5b9561befc44fb7938689a1
0
MariaDB/mariadb-connector-j,MariaDB/mariadb-connector-j
package org.mariadb.jdbc; import org.junit.Assert; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; import org.mariadb.jdbc.internal.queryresults.resultset.MariaSelectResultSet; import org.mariadb.jdbc.internal.util.DefaultOptions; import org.mariadb.jdbc.internal.util.constant.HaMode; import java.math.BigDecimal; import java.sql.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.GregorianCalendar; import static org.junit.Assert.*; public class DriverTest extends BaseTest { /** * Tables initialisation. * * @throws SQLException exception */ @BeforeClass() public static void initClass() throws SQLException { createTable("tt1", "id int , name varchar(20)"); createTable("tt2", "id int , name varchar(20)"); createTable("Drivert2", "id int not null primary key auto_increment, test varchar(10)"); createTable("utente", "id int not null primary key auto_increment, test varchar(10)"); createTable("Drivert3", "id int not null primary key auto_increment, test varchar(10)"); createTable("Drivert30", "id int not null primary key auto_increment, test varchar(20)", "engine=innodb"); createTable("Drivert4", "id int not null primary key auto_increment, test varchar(20)", "engine=innodb"); createTable("test_float", "id int not null primary key auto_increment, a float"); createTable("test_big_autoinc2", "id int not null primary key auto_increment, test varchar(10)"); createTable("test_big_update", "id int primary key not null, updateme int"); createTable("sharedConnection", "id int"); createTable("extest", "id int not null primary key"); createTable("commentPreparedStatements", "id int not null primary key auto_increment, a varchar(10)"); createTable("quotesPreparedStatements", "id int not null primary key auto_increment, a varchar(10) , " + "b varchar(10)"); createTable("ressetpos", "i int not null primary key", "engine=innodb"); createTable("streamingtest", "val varchar(20)"); createTable("testBlob2", "a blob"); createTable("testString2", "a varchar(10)"); createTable("testBlob2", "a blob"); createTable("unsignedtest", "a int unsigned"); createTable("conj25", "a VARCHAR(1024)"); createTable("DriverTestt1", "id int not null primary key auto_increment, test varchar(20)"); createTable("DriverTestt2", "id int not null primary key auto_increment, test varchar(20)"); createTable("DriverTestt3", "id int not null primary key auto_increment, test varchar(20)"); createTable("DriverTestt4", "id int not null primary key auto_increment, test varchar(20)"); createTable("DriverTestt5", "id int not null primary key auto_increment, test varchar(20)"); createProcedure("foo", "() BEGIN SELECT 1; END"); createTable("conj275", "a VARCHAR(10)"); } @Test public void doQuery() throws SQLException { Statement stmt = sharedConnection.createStatement(); stmt.execute("insert into DriverTestt1 (test) values ('hej1')"); stmt.execute("insert into DriverTestt1 (test) values ('hej2')"); stmt.execute("insert into DriverTestt1 (test) values ('hej3')"); stmt.execute("insert into DriverTestt1 (test) values (null)"); ResultSet rs = stmt.executeQuery("select * from DriverTestt1"); for (int i = 1; i < 4; i++) { rs.next(); assertEquals(String.valueOf(i), rs.getString(1)); assertEquals("hej" + i, rs.getString("test")); } rs.next(); assertEquals(null, rs.getString("test")); } @Test(expected = SQLException.class) public void askForBadColumnTest() throws SQLException { Statement stmt = sharedConnection.createStatement(); stmt.execute("insert into DriverTestt2 (test) values ('hej1')"); stmt.execute("insert into DriverTestt2 (test) values ('hej2')"); stmt.execute("insert into DriverTestt2 (test) values ('hej3')"); stmt.execute("insert into DriverTestt2 (test) values (null)"); ResultSet rs = stmt.executeQuery("select * from DriverTestt2"); if (rs.next()) { rs.getInt("non_existing_column"); } else { fail(); } } @Test(expected = SQLException.class) public void askForBadColumnIndexTest() throws SQLException { Statement stmt = sharedConnection.createStatement(); stmt.execute("insert into DriverTestt3 (test) values ('hej1')"); stmt.execute("insert into DriverTestt3 (test) values ('hej2')"); stmt.execute("insert into DriverTestt3 (test) values ('hej3')"); stmt.execute("insert into DriverTestt3 (test) values (null)"); ResultSet rs = stmt.executeQuery("select * from DriverTestt3"); rs.next(); rs.getInt(102); } @Test /* Accessing result set using table.column */ public void tableDotColumnInResultSet() throws SQLException { Statement stmt = sharedConnection.createStatement(); stmt.execute("insert into tt1 values(1, 'one')"); stmt.execute("insert into tt2 values(1, 'two')"); ResultSet rs = stmt.executeQuery("select tt1.*, tt2.* from tt1, tt2 where tt1.id = tt2.id"); rs.next(); assertEquals(1, rs.getInt("tt1.id")); assertEquals(1, rs.getInt("tt2.id")); assertEquals("one", rs.getString("tt1.name")); assertEquals("two", rs.getString("tt2.name")); } @Test(expected = SQLException.class) public void badQuery() throws SQLException { Statement stmt = sharedConnection.createStatement(); stmt.executeQuery("whraoaooa"); } @Test public void preparedTest() throws SQLException { Statement stmt = sharedConnection.createStatement(); stmt.execute("insert into DriverTestt4 (test) values ('hej1')"); stmt.close(); String query = "SELECT * FROM DriverTestt4 WHERE test = ? and id = ?"; PreparedStatement prepStmt = sharedConnection.prepareStatement(query); prepStmt.setString(1, "hej1"); prepStmt.setInt(2, 1); ResultSet results = prepStmt.executeQuery(); String res = ""; while (results.next()) { res = results.getString("test"); } assertEquals("hej1", res); assertEquals(2, prepStmt.getParameterMetaData().getParameterCount()); } @Test public void streamingResultSet() throws Exception { Statement stmt = sharedConnection.createStatement(); stmt.setFetchSize(Integer.MIN_VALUE); ResultSet rs = stmt.executeQuery("SELECT 1"); assertTrue(rs.isBeforeFirst()); try { rs.first(); assertFalse("should not get there", true); } catch (SQLException sqle) { assertTrue(sqle.getMessage().toLowerCase().contains("invalid operation")); } } @Test public void updateTest() throws SQLException { Statement stmt = sharedConnection.createStatement(); stmt.execute("insert into DriverTestt5 (test) values ('hej1')"); stmt.execute("insert into DriverTestt5 (test) values ('hej2')"); stmt.execute("insert into DriverTestt5 (test) values ('hej3')"); stmt.execute("insert into DriverTestt5 (test) values (null)"); String query = "UPDATE DriverTestt5 SET test = ? where id = ?"; PreparedStatement prepStmt = sharedConnection.prepareStatement(query); prepStmt.setString(1, "updated"); prepStmt.setInt(2, 3); int updateCount = prepStmt.executeUpdate(); assertEquals(1, updateCount); String query2 = "SELECT * FROM DriverTestt5 WHERE id=?"; prepStmt = sharedConnection.prepareStatement(query2); prepStmt.setInt(1, 3); ResultSet results = prepStmt.executeQuery(); String result = ""; while (results.next()) { result = results.getString("test"); } assertEquals("updated", result); } @Test public void ralfTest() throws SQLException { Statement stmt = sharedConnection.createStatement(); for (int i = 0; i < 10; i++) { stmt.execute("INSERT INTO Drivert2 (test) VALUES ('aßa" + i + "')"); } PreparedStatement ps = sharedConnection.prepareStatement("SELECT * FROM Drivert2 where test like'%ß%' limit ?"); ps.setInt(1, 5); ps.addBatch(); ResultSet rs = ps.executeQuery(); int result = 0; while (rs.next()) { result++; } assertEquals(result, 5); } @Test public void autoIncTest() throws SQLException { Statement stmt = sharedConnection.createStatement(); stmt.execute("INSERT INTO Drivert3 (test) VALUES ('aa')", Statement.RETURN_GENERATED_KEYS); ResultSet rs = stmt.getGeneratedKeys(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals(1, rs.getInt("insert_id")); stmt.execute("INSERT INTO Drivert3 (test) VALUES ('aa')", Statement.RETURN_GENERATED_KEYS); rs = stmt.getGeneratedKeys(); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertEquals(2, rs.getInt("insert_id")); /* multi-row inserts */ stmt.execute("INSERT INTO Drivert3 (test) VALUES ('bb'),('cc'),('dd')", Statement.RETURN_GENERATED_KEYS); rs = stmt.getGeneratedKeys(); for (int i = 0; i < 3; i++) { assertTrue(rs.next()); assertEquals(3 + i, rs.getInt(1)); } requireMinimumVersion(5, 0); /* non-standard autoIncrementIncrement */ int autoIncrementIncrement = 2; Connection connection = null; try { connection = setConnection("&sessionVariables=auto_increment_increment=" + autoIncrementIncrement); stmt = connection.createStatement(); stmt.execute("INSERT INTO Drivert3 (test) values ('bb'),('cc')", Statement.RETURN_GENERATED_KEYS); rs = stmt.getGeneratedKeys(); assertTrue(rs.next()); assertEquals(7, rs.getInt(1)); assertTrue(rs.next()); assertEquals(7 + autoIncrementIncrement, rs.getInt(1)); } finally { if (connection != null) { connection.close(); } } } @Test public void autoInc2Test() throws SQLException { Statement stmt = sharedConnection.createStatement(); stmt.execute("ALTER TABLE `utente` AUTO_INCREMENT=1", Statement.RETURN_GENERATED_KEYS); } @Test public void transactionTest() throws SQLException { Statement stmt = sharedConnection.createStatement(); sharedConnection.setAutoCommit(false); stmt.executeUpdate("INSERT INTO Drivert30 (test) VALUES ('heja')"); stmt.executeUpdate("INSERT INTO Drivert30 (test) VALUES ('japp')"); sharedConnection.commit(); ResultSet rs = stmt.executeQuery("SELECT * FROM Drivert30"); assertEquals(true, rs.next()); assertEquals("heja", rs.getString("test")); assertEquals(true, rs.next()); assertEquals("japp", rs.getString("test")); assertEquals(false, rs.next()); stmt.executeUpdate("INSERT INTO Drivert30 (test) VALUES ('rollmeback')", Statement.RETURN_GENERATED_KEYS); ResultSet rsGen = stmt.getGeneratedKeys(); rsGen.next(); assertEquals(3, rsGen.getInt(1)); sharedConnection.rollback(); rs = stmt.executeQuery("SELECT * FROM Drivert30 WHERE id=3"); assertEquals(false, rs.next()); sharedConnection.setAutoCommit(true); } @Test public void savepointTest() throws SQLException { Statement stmt = sharedConnection.createStatement(); sharedConnection.setAutoCommit(false); stmt.executeUpdate("INSERT INTO Drivert4 (test) values('hej1')"); stmt.executeUpdate("INSERT INTO Drivert4 (test) values('hej2')"); Savepoint savepoint = sharedConnection.setSavepoint("yep"); stmt.executeUpdate("INSERT INTO Drivert4 (test) values('hej3')"); stmt.executeUpdate("INSERT INTO Drivert4 (test) values('hej4')"); sharedConnection.rollback(savepoint); stmt.executeUpdate("INSERT INTO Drivert4 (test) values('hej5')"); stmt.executeUpdate("INSERT INTO Drivert4 (test) values('hej6')"); sharedConnection.commit(); ResultSet rs = stmt.executeQuery("SELECT * FROM Drivert4"); assertEquals(true, rs.next()); assertEquals("hej1", rs.getString(2)); assertEquals(true, rs.next()); assertEquals("hej2", rs.getString(2)); assertEquals(true, rs.next()); assertEquals("hej5", rs.getString(2)); assertEquals(true, rs.next()); assertEquals("hej6", rs.getString(2)); assertEquals(false, rs.next()); sharedConnection.setAutoCommit(true); } @Test public void isolationLevel() throws SQLException { Connection connection = null; try { connection = setConnection(); int[] levels = new int[]{ Connection.TRANSACTION_READ_UNCOMMITTED, Connection.TRANSACTION_READ_COMMITTED, Connection.TRANSACTION_SERIALIZABLE, Connection.TRANSACTION_REPEATABLE_READ }; for (int level : levels) { connection.setTransactionIsolation(level); assertEquals(level, connection.getTransactionIsolation()); } } finally { connection.close(); } } @Test public void isValidTest() throws SQLException { assertEquals(true, sharedConnection.isValid(0)); } @Test public void testConnectorJurl() throws SQLException { UrlParser url = UrlParser.parse("jdbc:mysql://localhost/test"); assertEquals("localhost", url.getHostAddresses().get(0).host); assertEquals("test", url.getDatabase()); assertEquals(3306, url.getHostAddresses().get(0).port); url = UrlParser.parse("jdbc:mysql://localhost:3307/test"); assertEquals("localhost", url.getHostAddresses().get(0).host); assertEquals("test", url.getDatabase()); assertEquals(3307, url.getHostAddresses().get(0).port); } @Test public void testAliasReplication() throws SQLException { UrlParser url = UrlParser.parse("jdbc:mysql:replication://localhost/test"); UrlParser url2 = UrlParser.parse("jdbc:mariadb:replication://localhost/test"); assertEquals(url, url2); } @Test public void testAliasDataSource() throws SQLException { ArrayList<HostAddress> hostAddresses = new ArrayList<>(); hostAddresses.add(new HostAddress(hostname, port)); UrlParser urlParser = new UrlParser(database, hostAddresses, DefaultOptions.defaultValues(HaMode.NONE), HaMode.NONE); UrlParser urlParser2 = new UrlParser(database, hostAddresses, DefaultOptions.defaultValues(HaMode.NONE), HaMode.NONE); urlParser.parseUrl("jdbc:mysql:replication://localhost/test"); urlParser2.parseUrl("jdbc:mariadb:replication://localhost/test"); assertEquals(urlParser, urlParser2); } @Test public void testEscapes() throws SQLException { String query = "select ?"; PreparedStatement stmt = sharedConnection.prepareStatement(query); stmt.setString(1, "hej\""); ResultSet rs = stmt.executeQuery(); assertEquals(true, rs.next()); assertEquals(rs.getString(1), "hej\""); } @Test public void testPreparedWithNull() throws SQLException { String query = "select ? as test"; PreparedStatement pstmt = sharedConnection.prepareStatement(query); pstmt.setNull(1, 1); ResultSet rs = pstmt.executeQuery(); assertEquals(true, rs.next()); assertEquals(null, rs.getString("test")); assertEquals(true, rs.wasNull()); } @Test public void connectFailover() throws SQLException { Assume.assumeTrue(hostname != null); String hosts = hostname + ":" + port + "," + hostname + ":" + (port + 1); String url = "jdbc:mysql://" + hosts + "/" + database + "?user=" + username; url += (password != null && !"".equals(password) ? "&password=" + password : ""); try (Connection connection = openNewConnection(url)) { MariaDbConnection my = (MariaDbConnection) connection; assertTrue(my.getPort() == port); ResultSet rs = connection.createStatement().executeQuery("select 1"); if (rs.next()) { assertEquals(rs.getInt(1), 1); } else { fail(); } } } @Test public void floatingNumbersTest() throws SQLException { PreparedStatement ps = sharedConnection.prepareStatement("insert into test_float (a) values (?)"); ps.setDouble(1, 3.99); ps.executeUpdate(); ResultSet rs = sharedConnection.createStatement().executeQuery("select a from test_float"); assertEquals(true, rs.next()); assertEquals((float) 3.99, rs.getFloat(1), 0.00001); assertEquals((float) 3.99, rs.getFloat("a"), 0.00001); assertEquals(false, rs.next()); } @Test public void manyColumnsTest() throws SQLException { Statement stmt = sharedConnection.createStatement(); stmt.execute("drop table if exists test_many_columns"); String query = "create table test_many_columns (a0 int primary key not null"; for (int i = 1; i < 1000; i++) { query += ",a" + i + " int"; } query += ")"; stmt.execute(query); query = "insert into test_many_columns values (0"; for (int i = 1; i < 1000; i++) { query += "," + i; } query += ")"; stmt.execute(query); ResultSet rs = stmt.executeQuery("select * from test_many_columns"); assertEquals(true, rs.next()); for (int i = 0; i < 1000; i++) { assertEquals(rs.getInt("a" + i), i); } } @Test public void bigAutoIncTest() throws SQLException { Statement stmt = sharedConnection.createStatement(); stmt.execute("alter table test_big_autoinc2 auto_increment = 1000"); stmt.execute("insert into test_big_autoinc2 values (null, 'hej')", Statement.RETURN_GENERATED_KEYS); ResultSet rsGen = stmt.getGeneratedKeys(); assertEquals(true, rsGen.next()); assertEquals(1000, rsGen.getInt(1)); stmt.execute("alter table test_big_autoinc2 auto_increment = " + Short.MAX_VALUE); stmt.execute("insert into test_big_autoinc2 values (null, 'hej')", Statement.RETURN_GENERATED_KEYS); rsGen = stmt.getGeneratedKeys(); assertEquals(true, rsGen.next()); assertEquals(Short.MAX_VALUE, rsGen.getInt(1)); stmt.execute("alter table test_big_autoinc2 auto_increment = " + Integer.MAX_VALUE); stmt.execute("insert into test_big_autoinc2 values (null, 'hej')", Statement.RETURN_GENERATED_KEYS); rsGen = stmt.getGeneratedKeys(); assertEquals(true, rsGen.next()); assertEquals(Integer.MAX_VALUE, rsGen.getInt(1)); } @Test public void bigUpdateCountTest() throws SQLException { Statement stmt = sharedConnection.createStatement(); for (int i = 0; i < 4; i++) { stmt.execute("insert into test_big_update values (" + i + "," + i + ")"); } ResultSet rs = stmt.executeQuery("select count(*) from test_big_update"); assertEquals(true, rs.next()); assertEquals(4, rs.getInt(1)); int updateCount = stmt.executeUpdate("update test_big_update set updateme=updateme+1"); assertEquals(4, updateCount); } @Test(expected = SQLIntegrityConstraintViolationException.class) public void testException1() throws SQLException { sharedConnection.createStatement().execute("insert into extest values (1)"); sharedConnection.createStatement().execute("insert into extest values (1)"); } @Test public void testExceptionDivByZero() throws SQLException { ResultSet rs = sharedConnection.createStatement().executeQuery("select 1/0"); assertEquals(rs.next(), true); assertEquals(null, rs.getString(1)); } @Test(expected = SQLSyntaxErrorException.class) public void testSyntaxError() throws SQLException { sharedConnection.createStatement().executeQuery("create asdf b"); } @Test public void testPreparedStatementsWithComments() throws SQLException { String query = "INSERT INTO commentPreparedStatements (a) VALUES (?) # ?"; PreparedStatement pstmt = sharedConnection.prepareStatement(query); pstmt.setString(1, "yeah"); pstmt.execute(); } @Test public void testPreparedStatementsWithQuotes() throws SQLException { String query = "INSERT INTO quotesPreparedStatements (a,b) VALUES ('hellooo?', ?) # ?"; PreparedStatement pstmt = sharedConnection.prepareStatement(query); pstmt.setString(1, "ff"); pstmt.execute(); } @Test public void testResultSetPositions() throws SQLException { sharedConnection.createStatement().execute("insert into ressetpos values (1),(2),(3),(4)"); ResultSet rs = sharedConnection.createStatement().executeQuery("select * from ressetpos"); assertTrue(rs.isBeforeFirst()); rs.next(); assertTrue(!rs.isBeforeFirst()); assertTrue(rs.isFirst()); rs.beforeFirst(); assertTrue(rs.isBeforeFirst()); while (rs.next()) { //just load datas. } assertTrue(rs.isAfterLast()); rs.absolute(4); assertTrue(!rs.isAfterLast()); rs.absolute(2); assertEquals(2, rs.getInt(1)); rs.relative(2); assertEquals(4, rs.getInt(1)); assertFalse(rs.next()); rs.previous(); assertEquals(4, rs.getInt(1)); rs.relative(-3); assertEquals(1, rs.getInt(1)); assertEquals(false, rs.relative(-1)); assertEquals(1, rs.getInt(1)); rs.last(); assertEquals(4, rs.getInt(1)); assertEquals(4, rs.getRow()); assertTrue(rs.isLast()); rs.first(); assertEquals(1, rs.getInt(1)); assertEquals(1, rs.getRow()); rs.absolute(-1); assertEquals(4, rs.getRow()); assertEquals(4, rs.getInt(1)); } @Test(expected = SQLException.class) public void findColumnTest() throws SQLException { ResultSet rs = sharedConnection.createStatement().executeQuery("select 1 as 'hej'"); assertEquals(1, rs.findColumn("hej")); rs.findColumn("nope"); } @Test public void getStatementTest() throws SQLException { Statement stmt1 = sharedConnection.createStatement(); ResultSet rs = stmt1.executeQuery("select 1 as 'hej'"); assertEquals(stmt1, rs.getStatement()); } @Test public void testAutocommit() throws SQLException { assertTrue(sharedConnection.getAutoCommit()); sharedConnection.setAutoCommit(false); assertFalse(sharedConnection.getAutoCommit()); /* Check that autocommit value "false" , that driver derives from server status flags * remains the same when EOF, ERROR or OK stream were received. */ sharedConnection.createStatement().executeQuery("select 1"); assertFalse(sharedConnection.getAutoCommit()); sharedConnection.createStatement().execute("set @a=1"); assertFalse(sharedConnection.getAutoCommit()); try { sharedConnection.createStatement().execute("insert into nosuchtable values(1)"); } catch (Exception e) { //eat exception } assertFalse(sharedConnection.getAutoCommit()); ResultSet rs = sharedConnection.createStatement().executeQuery("select @@autocommit"); rs.next(); assertEquals(0, rs.getInt(1)); sharedConnection.setAutoCommit(true); /* Check that autocommit value "true" , that driver derives from server status flags * remains the same when EOF, ERROR or OK stream were received. */ assertTrue(sharedConnection.getAutoCommit()); sharedConnection.createStatement().execute("set @a=1"); assertTrue(sharedConnection.getAutoCommit()); try { sharedConnection.createStatement().execute("insert into nosuchtable values(1)"); } catch (Exception e) { //eat exception } assertTrue(sharedConnection.getAutoCommit()); rs = sharedConnection.createStatement().executeQuery("select @@autocommit"); rs.next(); assertEquals(1, rs.getInt(1)); /* Set autocommit value using Statement.execute */ sharedConnection.createStatement().execute("set @@autocommit=0"); assertFalse(sharedConnection.getAutoCommit()); sharedConnection.createStatement().execute("set @@autocommit=1"); assertTrue(sharedConnection.getAutoCommit()); /* Use session variable to set autocommit to 0 */ Connection connection = null; try { connection = setConnection("&sessionVariables=autocommit=0"); assertFalse(connection.getAutoCommit()); sharedConnection.setAutoCommit(true); } finally { connection.close(); } } @Test public void testUpdateCountSingle() throws SQLException { Statement stmt = sharedConnection.createStatement(); stmt.execute("select 1"); assertTrue(-1 == stmt.getUpdateCount()); } @Test public void testUpdateCountMulti() throws SQLException { try (Connection connection = setConnection("&allowMultiQueries=true")) { Statement stmt = connection.createStatement(); stmt.execute("select 1;select 1"); assertTrue(-1 == stmt.getUpdateCount()); stmt.getMoreResults(); assertTrue(-1 == stmt.getUpdateCount()); } } /** * CONJ-385 - stored procedure update count regression. * * @throws SQLException if connection error occur. */ @Test public void testUpdateCountProcedure() throws SQLException { createProcedure("multiUpdateCount", "() BEGIN SELECT 1; SELECT 2; END"); CallableStatement callableStatement = sharedConnection.prepareCall("{call multiUpdateCount()}"); callableStatement.execute(); assertTrue(-1 == callableStatement.getUpdateCount()); callableStatement.getMoreResults(); assertTrue(-1 == callableStatement.getUpdateCount()); } @Test public void testConnectWithDb() throws SQLException { requireMinimumVersion(5, 0); try { sharedConnection.createStatement().executeUpdate("drop database test_testdrop"); } catch (Exception e) { //eat exception } try (Connection connection = setConnection("&createDatabaseIfNotExist=true", "test_testdrop")) { DatabaseMetaData dbmd = connection.getMetaData(); ResultSet rs = dbmd.getCatalogs(); boolean foundDb = false; while (rs.next()) { if (rs.getString("table_cat").equals("test_testdrop")) { foundDb = true; } } assertTrue(foundDb); sharedConnection.createStatement().executeUpdate("drop database test_testdrop"); } } @Test public void streamingResult() throws SQLException { Statement st = sharedConnection.createStatement(); for (int i = 0; i < 100; i++) { st.execute("insert into streamingtest values('aaaaaaaaaaaaaaaaaa')"); } st.setFetchSize(Integer.MIN_VALUE); ResultSet rs = st.executeQuery("select * from streamingtest"); rs.next(); rs.close(); Statement st2 = sharedConnection.createStatement(); ResultSet rs2 = st2.executeQuery("select * from streamingtest"); rs2.next(); rs.close(); } // Test if driver works with sql_mode= NO_BACKSLASH_ESCAPES @Test public void noBackslashEscapes() throws SQLException { requireMinimumVersion(5, 0); // super privilege is needed for this test Assume.assumeTrue(hasSuperPrivilege("NoBackslashEscapes")); Statement st = sharedConnection.createStatement(); ResultSet rs = st.executeQuery("select @@global.sql_mode"); rs.next(); String originalSqlMode = rs.getString(1); st.execute("set @@global.sql_mode = '" + originalSqlMode + ",NO_BACKSLASH_ESCAPES'"); try { try (Connection connection = setConnection("&profileSql=true")) { PreparedStatement preparedStatement = connection.prepareStatement("insert into testBlob2(a) values(?)"); byte[] bytes = new byte[255]; for (byte i = -128; i < 127; i++) { bytes[i + 128] = i; } MariaDbBlob blob = new MariaDbBlob(bytes); preparedStatement.setBlob(1, blob); int affectedRows = preparedStatement.executeUpdate(); Assert.assertEquals(affectedRows, 1); } } finally { st.execute("set @@global.sql_mode='" + originalSqlMode + "'"); } } // Test if driver works with sql_mode= NO_BACKSLASH_ESCAPES @Test public void noBackslashEscapes2() throws SQLException { requireMinimumVersion(5, 0); // super privilege is needed for this test Assume.assumeTrue(hasSuperPrivilege("NoBackslashEscapes2")); Statement st = sharedConnection.createStatement(); ResultSet rs = st.executeQuery("select @@global.sql_mode"); rs.next(); String originalSqlMode = rs.getString(1); st.execute("set @@global.sql_mode = '" + originalSqlMode + ",NO_BACKSLASH_ESCAPES'"); try { try (Connection connection = setConnection("&profileSql=true")) { PreparedStatement preparedStatement = connection.prepareStatement("insert into testString2(a) values(?)"); preparedStatement.setString(1, "'\\"); int affectedRows = preparedStatement.executeUpdate(); Assert.assertEquals(affectedRows, 1); preparedStatement.close(); preparedStatement = connection.prepareStatement("select * from testString2"); rs = preparedStatement.executeQuery(); rs.next(); String out = rs.getString(1); assertEquals(out, "'\\"); Statement st2 = connection.createStatement(); rs = st2.executeQuery("select 'a\\b\\c'"); rs.next(); assertEquals("a\\b\\c", rs.getString(1)); } } finally { st.execute("set @@global.sql_mode='" + originalSqlMode + "'"); } } // Test if driver works with sql_mode= ANSI_QUOTES @Test public void ansiQuotes() throws SQLException { // super privilege is needed for this test Assume.assumeTrue(hasSuperPrivilege("AnsiQuotes")); Statement st = sharedConnection.createStatement(); ResultSet rs = st.executeQuery("select @@global.sql_mode"); rs.next(); String originalSqlMode = rs.getString(1); st.execute("set @@global.sql_mode = '" + originalSqlMode + ",ANSI_QUOTES'"); try { try (Connection connection = setConnection("&profileSql=true")) { PreparedStatement preparedStatement = connection.prepareStatement("insert into testBlob2(a) values(?)"); byte[] bytes = new byte[255]; for (byte i = -128; i < 127; i++) { bytes[i + 128] = i; } MariaDbBlob blob = new MariaDbBlob(bytes); preparedStatement.setBlob(1, blob); int affectedRows = preparedStatement.executeUpdate(); Assert.assertEquals(affectedRows, 1); } } finally { st.execute("set @@global.sql_mode='" + originalSqlMode + "'"); } } @Test public void unsignedTest() throws Exception { Statement st = sharedConnection.createStatement(); st.execute("insert into unsignedtest values(4294967295)"); ResultSet rs = st.executeQuery("select * from unsignedtest"); rs.next(); assertNotNull(rs.getLong("unsignedtest.a")); } @Test // Bug in URL parser public void mdev3916() throws Exception { try { setConnection("&password="); } catch (SQLException ex) { //SQLException is ok because we might get for example an access denied exception if (!(ex.getMessage().indexOf("Could not connect: Access denied") > -1)) { throw ex; } } } @Test public void conj1() throws Exception { requireMinimumVersion(5, 0); try (Connection connection = setConnection("&profileSql=true")) { Statement st = connection.createStatement(); st.setQueryTimeout(1); st.execute("select sleep(0.5)"); try { st.execute("select * from information_schema.columns as c1, information_schema.tables, information_schema.tables as t2"); assertFalse("must be exception here", true); } catch (Exception e) { //normal exception } Statement st2 = connection.createStatement(); assertEquals(st2.getQueryTimeout(), 0); // no exception ResultSet rs = st2.executeQuery("select sleep(1.5)"); assertTrue(rs.next()); assertEquals(0, rs.getInt(1)); Statement st3 = connection.createStatement(); st3.setQueryTimeout(1); rs = st3.executeQuery("select sleep(0.1)"); assertTrue(rs.next()); assertEquals(0, rs.getInt(1)); assertEquals(st3.getQueryTimeout(), 1); } } /* Check that exception contains SQL statement, for queries with syntax errors */ @Test public void dumpQueryOnSyntaxException() throws Exception { String syntacticallyWrongQuery = "banana"; try { Statement st = sharedConnection.createStatement(); st.execute(syntacticallyWrongQuery); } catch (SQLException sqle) { assertTrue(sqle.getMessage().contains("Query is : " + syntacticallyWrongQuery)); } } /* Check that query contains SQL statement, if dumpQueryOnException is true */ @Test public void dumpQueryOnException() throws Exception { try (Connection connection = setConnection("&profileSql=true&dumpQueriesOnException=true")) { String selectFromNonExistingTable = "select * from banana"; try { Statement st = connection.createStatement(); st.execute(selectFromNonExistingTable); } catch (SQLException sqle) { assertTrue(sqle.getMessage().contains("Query is : " + selectFromNonExistingTable)); } } } /* CONJ-14 * getUpdateCount(), getResultSet() should indicate "no more results" with * (getUpdateCount() == -1 && getResultSet() == null) */ @Test public void conj14() throws Exception { Statement st = sharedConnection.createStatement(); /* 1. Test update statement */ st.execute("use " + database); assertEquals(0, st.getUpdateCount()); /* No more results */ assertFalse(st.getMoreResults()); assertEquals(-1, st.getUpdateCount()); assertEquals(null, st.getResultSet()); /* 2. Test select statement */ st.execute("select 1"); assertEquals(-1, st.getUpdateCount()); assertTrue(st.getResultSet() != null); /* No More results */ assertFalse(st.getMoreResults()); assertEquals(-1, st.getUpdateCount()); assertEquals(null, st.getResultSet()); /* Test batch */ try (Connection connection = setConnection("&profileSql=true&allowMultiQueries=true")) { st = connection.createStatement(); /* 3. Batch with two SELECTs */ st.execute("select 1;select 2"); /* First result (select)*/ assertEquals(-1, st.getUpdateCount()); assertTrue(st.getResultSet() != null); /* has more results */ assertTrue(st.getMoreResults()); /* Second result (select) */ assertEquals(-1, st.getUpdateCount()); assertTrue(st.getResultSet() != null); /* no more results */ assertFalse(st.getMoreResults()); assertEquals(-1, st.getUpdateCount()); assertEquals(null, st.getResultSet()); /* 4. Batch with a SELECT and non-SELECT */ st.execute("select 1; use " + database); /* First result (select)*/ assertEquals(-1, st.getUpdateCount()); assertTrue(st.getResultSet() != null); /* Next result is no ResultSet */ assertFalse(st.getMoreResults()); /* Second result (use) */ assertEquals(0, st.getUpdateCount()); assertTrue(st.getResultSet() == null); /* no more results */ assertFalse(st.getMoreResults()); assertEquals(-1, st.getUpdateCount()); assertEquals(null, st.getResultSet()); } } @Test public void conj25() throws Exception { try (Statement stmt = sharedConnection.createStatement()) { String st = "INSERT INTO conj25 VALUES (REPEAT('a',1024))"; for (int i = 1; i <= 100; i++) { st = st + ",(REPEAT('a',1024))"; } stmt.setFetchSize(Integer.MIN_VALUE); stmt.execute(st); stmt.executeQuery("SELECT * FROM conj25 a, conj25 b"); } } @Test public void namedPipe() throws Exception { try { ResultSet rs = sharedConnection.createStatement().executeQuery("select @@named_pipe,@@socket"); rs.next(); if (rs.getBoolean(1)) { String namedPipeName = rs.getString(2); //skip test if no namedPipeName was obtained because then we do not use a socket connection Assume.assumeTrue(namedPipeName != null); try (Connection connection = setConnection("&pipe=" + namedPipeName)) { Statement stmt = connection.createStatement(); rs = stmt.executeQuery("SELECT 1"); assertTrue(rs.next()); rs.close(); } } } catch (SQLException e) { //not on windows } } /** * CONJ-293 : permit connection to named pipe when no host is defined. * * @throws Exception mustn't occur. */ @Test public void namedPipeWithoutHost() throws Exception { try { ResultSet rs = sharedConnection.createStatement().executeQuery("select @@named_pipe,@@socket"); rs.next(); if (rs.getBoolean(1)) { String namedPipeName = rs.getString(2); //skip test if no namedPipeName was obtained because then we do not use a socket connection Assume.assumeTrue(namedPipeName != null); try (Connection connection = DriverManager.getConnection("jdbc:mariadb:///testj?user=" + username + "&pipe=" + namedPipeName)) { Statement stmt = connection.createStatement(); rs = stmt.executeQuery("SELECT 1"); assertTrue(rs.next()); rs.close(); } } } catch (SQLException e) { //not on windows } } @Test public void localSocket() throws Exception { requireMinimumVersion(5, 1); Assume.assumeTrue(isLocalConnection("localSocket")); Statement st = sharedConnection.createStatement(); ResultSet rs = st.executeQuery("select @@version_compile_os,@@socket"); if (!rs.next()) { return; } System.out.println("os:" + rs.getString(1) + " path:" + rs.getString(2)); String os = rs.getString(1); if (os.toLowerCase().startsWith("win")) { return; } String path = rs.getString(2); try (Connection connection = setConnection("&localSocket=" + path + "&profileSql=true")) { rs = connection.createStatement().executeQuery("select 1"); rs.next(); } } @Test public void sharedMemory() throws Exception { requireMinimumVersion(5, 1); Statement st = sharedConnection.createStatement(); ResultSet rs = st.executeQuery("select @@version_compile_os"); if (!rs.next()) { return; } String os = rs.getString(1); if (!os.toLowerCase().startsWith("win")) { return; // skip test on non-Windows } rs = st.executeQuery("select @@shared_memory,@@shared_memory_base_name"); if (!rs.next()) { return; } if (!rs.getString(1).equals("1")) { return; } String shmBaseName = rs.getString(2); try (Connection connection = setConnection("&sharedMemory=" + shmBaseName + "&profileSql=true")) { rs = connection.createStatement().executeQuery("select repeat('a',100000)"); rs.next(); assertEquals(100000, rs.getString(1).length()); char[] arr = new char[100000]; Arrays.fill(arr, 'a'); rs = connection.createStatement().executeQuery("select '" + new String(arr) + "'"); rs.next(); assertEquals(100000, rs.getString(1).length()); } } @Test public void preparedStatementToString() throws Exception { PreparedStatement ps = sharedConnection.prepareStatement("SELECT ?,?,?,?,?,?"); ps.setInt(1, 1); ps.setBigDecimal(2, new BigDecimal("1")); ps.setString(3, "one"); ps.setBoolean(4, true); Calendar calendar = new GregorianCalendar(1972, 3, 22); ps.setDate(5, new Date(calendar.getTime().getTime())); ps.setDouble(6, 1.5); assertEquals("sql : 'SELECT ?,?,?,?,?,?', parameters : [1,1,'one',1,'1972-04-22',1.5]", ps.toString()); ps.close(); } /* Test that CLOSE_CURSORS_ON_COMMIT is silently ignored, and HOLD_CURSORS_OVER_COMMIT is actually used*/ @Test public void resultSetHoldability() throws Exception { Statement st = sharedConnection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.CLOSE_CURSORS_AT_COMMIT); assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, st.getResultSetHoldability()); PreparedStatement ps = sharedConnection.prepareStatement("SELECT 1", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.CLOSE_CURSORS_AT_COMMIT); assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, ps.getResultSetHoldability()); ResultSet rs = ps.executeQuery(); assertEquals(rs.getHoldability(), ResultSet.HOLD_CURSORS_OVER_COMMIT); CallableStatement cs = sharedConnection.prepareCall("{CALL foo}", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.CLOSE_CURSORS_AT_COMMIT); assertEquals(cs.getResultSetHoldability(), ResultSet.HOLD_CURSORS_OVER_COMMIT); } @Test public void emptyBatch() throws Exception { Statement st = sharedConnection.createStatement(); st.executeBatch(); } @Test public void createDbWithSpacesTest() throws SQLException { try (Connection connection = setConnection("&createDatabaseIfNotExist=true&profileSql=true", "test with spaces")) { DatabaseMetaData dbmd = connection.getMetaData(); ResultSet rs = dbmd.getCatalogs(); boolean foundDb = false; while (rs.next()) { if (rs.getString("table_cat").equals("test with spaces")) { foundDb = true; } } assertTrue("database \"test with spaces\" not created !?", foundDb); connection.createStatement().execute("drop database `test with spaces`"); } } /** * CONJ-275 : Streaming resultSet with no result must not have a next() value to true. * * @throws Exception exception */ @Test public void checkStreamingWithoutResult() throws Exception { PreparedStatement pstmt = sharedConnection.prepareStatement("SELECT * FROM conj275 where a = ?"); pstmt.setFetchSize(10); pstmt.setString(1, "no result"); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { fail("must not have result value"); } } }
src/test/java/org/mariadb/jdbc/DriverTest.java
package org.mariadb.jdbc; import org.junit.Assert; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; import org.mariadb.jdbc.internal.queryresults.resultset.MariaSelectResultSet; import org.mariadb.jdbc.internal.util.DefaultOptions; import org.mariadb.jdbc.internal.util.constant.HaMode; import java.math.BigDecimal; import java.sql.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.GregorianCalendar; import static org.junit.Assert.*; public class DriverTest extends BaseTest { /** * Tables initialisation. * * @throws SQLException exception */ @BeforeClass() public static void initClass() throws SQLException { createTable("tt1", "id int , name varchar(20)"); createTable("tt2", "id int , name varchar(20)"); createTable("Drivert2", "id int not null primary key auto_increment, test varchar(10)"); createTable("utente", "id int not null primary key auto_increment, test varchar(10)"); createTable("Drivert3", "id int not null primary key auto_increment, test varchar(10)"); createTable("Drivert30", "id int not null primary key auto_increment, test varchar(20)", "engine=innodb"); createTable("Drivert4", "id int not null primary key auto_increment, test varchar(20)", "engine=innodb"); createTable("test_float", "id int not null primary key auto_increment, a float"); createTable("test_big_autoinc2", "id int not null primary key auto_increment, test varchar(10)"); createTable("test_big_update", "id int primary key not null, updateme int"); createTable("sharedConnection", "id int"); createTable("extest", "id int not null primary key"); createTable("commentPreparedStatements", "id int not null primary key auto_increment, a varchar(10)"); createTable("quotesPreparedStatements", "id int not null primary key auto_increment, a varchar(10) , " + "b varchar(10)"); createTable("ressetpos", "i int not null primary key", "engine=innodb"); createTable("streamingtest", "val varchar(20)"); createTable("testBlob2", "a blob"); createTable("testString2", "a varchar(10)"); createTable("testBlob2", "a blob"); createTable("unsignedtest", "a int unsigned"); createTable("conj25", "a VARCHAR(1024)"); createTable("DriverTestt1", "id int not null primary key auto_increment, test varchar(20)"); createTable("DriverTestt2", "id int not null primary key auto_increment, test varchar(20)"); createTable("DriverTestt3", "id int not null primary key auto_increment, test varchar(20)"); createTable("DriverTestt4", "id int not null primary key auto_increment, test varchar(20)"); createTable("DriverTestt5", "id int not null primary key auto_increment, test varchar(20)"); createProcedure("foo", "() BEGIN SELECT 1; END"); createTable("conj275", "a VARCHAR(10)"); } @Test public void doQuery() throws SQLException { Statement stmt = sharedConnection.createStatement(); stmt.execute("insert into DriverTestt1 (test) values ('hej1')"); stmt.execute("insert into DriverTestt1 (test) values ('hej2')"); stmt.execute("insert into DriverTestt1 (test) values ('hej3')"); stmt.execute("insert into DriverTestt1 (test) values (null)"); ResultSet rs = stmt.executeQuery("select * from DriverTestt1"); for (int i = 1; i < 4; i++) { rs.next(); assertEquals(String.valueOf(i), rs.getString(1)); assertEquals("hej" + i, rs.getString("test")); } rs.next(); assertEquals(null, rs.getString("test")); } @Test(expected = SQLException.class) public void askForBadColumnTest() throws SQLException { Statement stmt = sharedConnection.createStatement(); stmt.execute("insert into DriverTestt2 (test) values ('hej1')"); stmt.execute("insert into DriverTestt2 (test) values ('hej2')"); stmt.execute("insert into DriverTestt2 (test) values ('hej3')"); stmt.execute("insert into DriverTestt2 (test) values (null)"); ResultSet rs = stmt.executeQuery("select * from DriverTestt2"); if (rs.next()) { rs.getInt("non_existing_column"); } else { fail(); } } @Test(expected = SQLException.class) public void askForBadColumnIndexTest() throws SQLException { Statement stmt = sharedConnection.createStatement(); stmt.execute("insert into DriverTestt3 (test) values ('hej1')"); stmt.execute("insert into DriverTestt3 (test) values ('hej2')"); stmt.execute("insert into DriverTestt3 (test) values ('hej3')"); stmt.execute("insert into DriverTestt3 (test) values (null)"); ResultSet rs = stmt.executeQuery("select * from DriverTestt3"); rs.next(); rs.getInt(102); } @Test /* Accessing result set using table.column */ public void tableDotColumnInResultSet() throws SQLException { Statement stmt = sharedConnection.createStatement(); stmt.execute("insert into tt1 values(1, 'one')"); stmt.execute("insert into tt2 values(1, 'two')"); ResultSet rs = stmt.executeQuery("select tt1.*, tt2.* from tt1, tt2 where tt1.id = tt2.id"); rs.next(); assertEquals(1, rs.getInt("tt1.id")); assertEquals(1, rs.getInt("tt2.id")); assertEquals("one", rs.getString("tt1.name")); assertEquals("two", rs.getString("tt2.name")); } @Test(expected = SQLException.class) public void badQuery() throws SQLException { Statement stmt = sharedConnection.createStatement(); stmt.executeQuery("whraoaooa"); } @Test public void preparedTest() throws SQLException { Statement stmt = sharedConnection.createStatement(); stmt.execute("insert into DriverTestt4 (test) values ('hej1')"); stmt.close(); String query = "SELECT * FROM DriverTestt4 WHERE test = ? and id = ?"; PreparedStatement prepStmt = sharedConnection.prepareStatement(query); prepStmt.setString(1, "hej1"); prepStmt.setInt(2, 1); ResultSet results = prepStmt.executeQuery(); String res = ""; while (results.next()) { res = results.getString("test"); } assertEquals("hej1", res); assertEquals(2, prepStmt.getParameterMetaData().getParameterCount()); } @Test public void streamingResultSet() throws Exception { Statement stmt = sharedConnection.createStatement(); stmt.setFetchSize(Integer.MIN_VALUE); ResultSet rs = stmt.executeQuery("SELECT 1"); assertTrue(rs.isBeforeFirst()); try { rs.first(); assertFalse("should not get there", true); } catch (SQLException sqle) { assertTrue(sqle.getMessage().toLowerCase().contains("invalid operation")); } } @Test public void updateTest() throws SQLException { Statement stmt = sharedConnection.createStatement(); stmt.execute("insert into DriverTestt5 (test) values ('hej1')"); stmt.execute("insert into DriverTestt5 (test) values ('hej2')"); stmt.execute("insert into DriverTestt5 (test) values ('hej3')"); stmt.execute("insert into DriverTestt5 (test) values (null)"); String query = "UPDATE DriverTestt5 SET test = ? where id = ?"; PreparedStatement prepStmt = sharedConnection.prepareStatement(query); prepStmt.setString(1, "updated"); prepStmt.setInt(2, 3); int updateCount = prepStmt.executeUpdate(); assertEquals(1, updateCount); String query2 = "SELECT * FROM DriverTestt5 WHERE id=?"; prepStmt = sharedConnection.prepareStatement(query2); prepStmt.setInt(1, 3); ResultSet results = prepStmt.executeQuery(); String result = ""; while (results.next()) { result = results.getString("test"); } assertEquals("updated", result); } @Test public void ralfTest() throws SQLException { Statement stmt = sharedConnection.createStatement(); for (int i = 0; i < 10; i++) { stmt.execute("INSERT INTO Drivert2 (test) VALUES ('aßa" + i + "')"); } PreparedStatement ps = sharedConnection.prepareStatement("SELECT * FROM Drivert2 where test like'%ß%' limit ?"); ps.setInt(1, 5); ps.addBatch(); ResultSet rs = ps.executeQuery(); int result = 0; while (rs.next()) { result++; } assertEquals(result, 5); } @Test public void autoIncTest() throws SQLException { Statement stmt = sharedConnection.createStatement(); stmt.execute("INSERT INTO Drivert3 (test) VALUES ('aa')", Statement.RETURN_GENERATED_KEYS); ResultSet rs = stmt.getGeneratedKeys(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals(1, rs.getInt("insert_id")); stmt.execute("INSERT INTO Drivert3 (test) VALUES ('aa')", Statement.RETURN_GENERATED_KEYS); rs = stmt.getGeneratedKeys(); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertEquals(2, rs.getInt("insert_id")); /* multi-row inserts */ stmt.execute("INSERT INTO Drivert3 (test) VALUES ('bb'),('cc'),('dd')", Statement.RETURN_GENERATED_KEYS); rs = stmt.getGeneratedKeys(); for (int i = 0; i < 3; i++) { assertTrue(rs.next()); assertEquals(3 + i, rs.getInt(1)); } requireMinimumVersion(5, 0); /* non-standard autoIncrementIncrement */ int autoIncrementIncrement = 2; Connection connection = null; try { connection = setConnection("&sessionVariables=auto_increment_increment=" + autoIncrementIncrement); stmt = connection.createStatement(); stmt.execute("INSERT INTO Drivert3 (test) values ('bb'),('cc')", Statement.RETURN_GENERATED_KEYS); rs = stmt.getGeneratedKeys(); assertTrue(rs.next()); assertEquals(7, rs.getInt(1)); assertTrue(rs.next()); assertEquals(7 + autoIncrementIncrement, rs.getInt(1)); } finally { if (connection != null) { connection.close(); } } } @Test public void autoInc2Test() throws SQLException { Statement stmt = sharedConnection.createStatement(); stmt.execute("ALTER TABLE `utente` AUTO_INCREMENT=1", Statement.RETURN_GENERATED_KEYS); } @Test public void transactionTest() throws SQLException { Statement stmt = sharedConnection.createStatement(); sharedConnection.setAutoCommit(false); stmt.executeUpdate("INSERT INTO Drivert30 (test) VALUES ('heja')"); stmt.executeUpdate("INSERT INTO Drivert30 (test) VALUES ('japp')"); sharedConnection.commit(); ResultSet rs = stmt.executeQuery("SELECT * FROM Drivert30"); assertEquals(true, rs.next()); assertEquals("heja", rs.getString("test")); assertEquals(true, rs.next()); assertEquals("japp", rs.getString("test")); assertEquals(false, rs.next()); stmt.executeUpdate("INSERT INTO Drivert30 (test) VALUES ('rollmeback')", Statement.RETURN_GENERATED_KEYS); ResultSet rsGen = stmt.getGeneratedKeys(); rsGen.next(); assertEquals(3, rsGen.getInt(1)); sharedConnection.rollback(); rs = stmt.executeQuery("SELECT * FROM Drivert30 WHERE id=3"); assertEquals(false, rs.next()); sharedConnection.setAutoCommit(true); } @Test public void savepointTest() throws SQLException { Statement stmt = sharedConnection.createStatement(); sharedConnection.setAutoCommit(false); stmt.executeUpdate("INSERT INTO Drivert4 (test) values('hej1')"); stmt.executeUpdate("INSERT INTO Drivert4 (test) values('hej2')"); Savepoint savepoint = sharedConnection.setSavepoint("yep"); stmt.executeUpdate("INSERT INTO Drivert4 (test) values('hej3')"); stmt.executeUpdate("INSERT INTO Drivert4 (test) values('hej4')"); sharedConnection.rollback(savepoint); stmt.executeUpdate("INSERT INTO Drivert4 (test) values('hej5')"); stmt.executeUpdate("INSERT INTO Drivert4 (test) values('hej6')"); sharedConnection.commit(); ResultSet rs = stmt.executeQuery("SELECT * FROM Drivert4"); assertEquals(true, rs.next()); assertEquals("hej1", rs.getString(2)); assertEquals(true, rs.next()); assertEquals("hej2", rs.getString(2)); assertEquals(true, rs.next()); assertEquals("hej5", rs.getString(2)); assertEquals(true, rs.next()); assertEquals("hej6", rs.getString(2)); assertEquals(false, rs.next()); sharedConnection.setAutoCommit(true); } @Test public void isolationLevel() throws SQLException { Connection connection = null; try { connection = setConnection(); int[] levels = new int[]{ Connection.TRANSACTION_READ_UNCOMMITTED, Connection.TRANSACTION_READ_COMMITTED, Connection.TRANSACTION_SERIALIZABLE, Connection.TRANSACTION_REPEATABLE_READ }; for (int level : levels) { connection.setTransactionIsolation(level); assertEquals(level, connection.getTransactionIsolation()); } } finally { connection.close(); } } @Test public void isValidTest() throws SQLException { assertEquals(true, sharedConnection.isValid(0)); } @Test public void testConnectorJurl() throws SQLException { UrlParser url = UrlParser.parse("jdbc:mysql://localhost/test"); assertEquals("localhost", url.getHostAddresses().get(0).host); assertEquals("test", url.getDatabase()); assertEquals(3306, url.getHostAddresses().get(0).port); url = UrlParser.parse("jdbc:mysql://localhost:3307/test"); assertEquals("localhost", url.getHostAddresses().get(0).host); assertEquals("test", url.getDatabase()); assertEquals(3307, url.getHostAddresses().get(0).port); } @Test public void testAliasReplication() throws SQLException { UrlParser url = UrlParser.parse("jdbc:mysql:replication://localhost/test"); UrlParser url2 = UrlParser.parse("jdbc:mariadb:replication://localhost/test"); assertEquals(url, url2); } @Test public void testAliasDataSource() throws SQLException { ArrayList<HostAddress> hostAddresses = new ArrayList<>(); hostAddresses.add(new HostAddress(hostname, port)); UrlParser urlParser = new UrlParser(database, hostAddresses, DefaultOptions.defaultValues(HaMode.NONE), HaMode.NONE); UrlParser urlParser2 = new UrlParser(database, hostAddresses, DefaultOptions.defaultValues(HaMode.NONE), HaMode.NONE); urlParser.parseUrl("jdbc:mysql:replication://localhost/test"); urlParser2.parseUrl("jdbc:mariadb:replication://localhost/test"); assertEquals(urlParser, urlParser2); } @Test public void testEscapes() throws SQLException { String query = "select ?"; PreparedStatement stmt = sharedConnection.prepareStatement(query); stmt.setString(1, "hej\""); ResultSet rs = stmt.executeQuery(); assertEquals(true, rs.next()); assertEquals(rs.getString(1), "hej\""); } @Test public void testPreparedWithNull() throws SQLException { String query = "select ? as test"; PreparedStatement pstmt = sharedConnection.prepareStatement(query); pstmt.setNull(1, 1); ResultSet rs = pstmt.executeQuery(); assertEquals(true, rs.next()); assertEquals(null, rs.getString("test")); assertEquals(true, rs.wasNull()); } @Test public void connectFailover() throws SQLException { Assume.assumeTrue(hostname != null); String hosts = hostname + ":" + port + "," + hostname + ":" + (port + 1); String url = "jdbc:mysql://" + hosts + "/" + database + "?user=" + username; url += (password != null && !"".equals(password) ? "&password=" + password : ""); try (Connection connection = openNewConnection(url)) { MariaDbConnection my = (MariaDbConnection) connection; assertTrue(my.getPort() == port); ResultSet rs = connection.createStatement().executeQuery("select 1"); if (rs.next()) { assertEquals(rs.getInt(1), 1); } else { fail(); } } } @Test public void floatingNumbersTest() throws SQLException { PreparedStatement ps = sharedConnection.prepareStatement("insert into test_float (a) values (?)"); ps.setDouble(1, 3.99); ps.executeUpdate(); ResultSet rs = sharedConnection.createStatement().executeQuery("select a from test_float"); assertEquals(true, rs.next()); assertEquals((float) 3.99, rs.getFloat(1), 0.00001); assertEquals((float) 3.99, rs.getFloat("a"), 0.00001); assertEquals(false, rs.next()); } @Test public void manyColumnsTest() throws SQLException { Statement stmt = sharedConnection.createStatement(); stmt.execute("drop table if exists test_many_columns"); String query = "create table test_many_columns (a0 int primary key not null"; for (int i = 1; i < 1000; i++) { query += ",a" + i + " int"; } query += ")"; stmt.execute(query); query = "insert into test_many_columns values (0"; for (int i = 1; i < 1000; i++) { query += "," + i; } query += ")"; stmt.execute(query); ResultSet rs = stmt.executeQuery("select * from test_many_columns"); assertEquals(true, rs.next()); for (int i = 0; i < 1000; i++) { assertEquals(rs.getInt("a" + i), i); } } @Test public void bigAutoIncTest() throws SQLException { Statement stmt = sharedConnection.createStatement(); stmt.execute("alter table test_big_autoinc2 auto_increment = 1000"); stmt.execute("insert into test_big_autoinc2 values (null, 'hej')", Statement.RETURN_GENERATED_KEYS); ResultSet rsGen = stmt.getGeneratedKeys(); assertEquals(true, rsGen.next()); assertEquals(1000, rsGen.getInt(1)); stmt.execute("alter table test_big_autoinc2 auto_increment = " + Short.MAX_VALUE); stmt.execute("insert into test_big_autoinc2 values (null, 'hej')", Statement.RETURN_GENERATED_KEYS); rsGen = stmt.getGeneratedKeys(); assertEquals(true, rsGen.next()); assertEquals(Short.MAX_VALUE, rsGen.getInt(1)); stmt.execute("alter table test_big_autoinc2 auto_increment = " + Integer.MAX_VALUE); stmt.execute("insert into test_big_autoinc2 values (null, 'hej')", Statement.RETURN_GENERATED_KEYS); rsGen = stmt.getGeneratedKeys(); assertEquals(true, rsGen.next()); assertEquals(Integer.MAX_VALUE, rsGen.getInt(1)); } @Test public void bigUpdateCountTest() throws SQLException { Statement stmt = sharedConnection.createStatement(); for (int i = 0; i < 4; i++) { stmt.execute("insert into test_big_update values (" + i + "," + i + ")"); } ResultSet rs = stmt.executeQuery("select count(*) from test_big_update"); assertEquals(true, rs.next()); assertEquals(4, rs.getInt(1)); int updateCount = stmt.executeUpdate("update test_big_update set updateme=updateme+1"); assertEquals(4, updateCount); } @Test(expected = SQLIntegrityConstraintViolationException.class) public void testException1() throws SQLException { sharedConnection.createStatement().execute("insert into extest values (1)"); sharedConnection.createStatement().execute("insert into extest values (1)"); } @Test public void testExceptionDivByZero() throws SQLException { ResultSet rs = sharedConnection.createStatement().executeQuery("select 1/0"); assertEquals(rs.next(), true); assertEquals(null, rs.getString(1)); } @Test(expected = SQLSyntaxErrorException.class) public void testSyntaxError() throws SQLException { sharedConnection.createStatement().executeQuery("create asdf b"); } @Test public void testPreparedStatementsWithComments() throws SQLException { String query = "INSERT INTO commentPreparedStatements (a) VALUES (?) # ?"; PreparedStatement pstmt = sharedConnection.prepareStatement(query); pstmt.setString(1, "yeah"); pstmt.execute(); } @Test public void testPreparedStatementsWithQuotes() throws SQLException { String query = "INSERT INTO quotesPreparedStatements (a,b) VALUES ('hellooo?', ?) # ?"; PreparedStatement pstmt = sharedConnection.prepareStatement(query); pstmt.setString(1, "ff"); pstmt.execute(); } @Test public void testResultSetPositions() throws SQLException { sharedConnection.createStatement().execute("insert into ressetpos values (1),(2),(3),(4)"); ResultSet rs = sharedConnection.createStatement().executeQuery("select * from ressetpos"); assertTrue(rs.isBeforeFirst()); rs.next(); assertTrue(!rs.isBeforeFirst()); assertTrue(rs.isFirst()); rs.beforeFirst(); assertTrue(rs.isBeforeFirst()); while (rs.next()) { //just load datas. } assertTrue(rs.isAfterLast()); rs.absolute(4); assertTrue(!rs.isAfterLast()); rs.absolute(2); assertEquals(2, rs.getInt(1)); rs.relative(2); assertEquals(4, rs.getInt(1)); assertFalse(rs.next()); rs.previous(); assertEquals(4, rs.getInt(1)); rs.relative(-3); assertEquals(1, rs.getInt(1)); assertEquals(false, rs.relative(-1)); assertEquals(1, rs.getInt(1)); rs.last(); assertEquals(4, rs.getInt(1)); assertEquals(4, rs.getRow()); assertTrue(rs.isLast()); rs.first(); assertEquals(1, rs.getInt(1)); assertEquals(1, rs.getRow()); rs.absolute(-1); assertEquals(4, rs.getRow()); assertEquals(4, rs.getInt(1)); } @Test(expected = SQLException.class) public void findColumnTest() throws SQLException { ResultSet rs = sharedConnection.createStatement().executeQuery("select 1 as 'hej'"); assertEquals(1, rs.findColumn("hej")); rs.findColumn("nope"); } @Test public void getStatementTest() throws SQLException { Statement stmt1 = sharedConnection.createStatement(); ResultSet rs = stmt1.executeQuery("select 1 as 'hej'"); assertEquals(stmt1, rs.getStatement()); } @Test public void testAutocommit() throws SQLException { assertTrue(sharedConnection.getAutoCommit()); sharedConnection.setAutoCommit(false); assertFalse(sharedConnection.getAutoCommit()); /* Check that autocommit value "false" , that driver derives from server status flags * remains the same when EOF, ERROR or OK stream were received. */ sharedConnection.createStatement().executeQuery("select 1"); assertFalse(sharedConnection.getAutoCommit()); sharedConnection.createStatement().execute("set @a=1"); assertFalse(sharedConnection.getAutoCommit()); try { sharedConnection.createStatement().execute("insert into nosuchtable values(1)"); } catch (Exception e) { //eat exception } assertFalse(sharedConnection.getAutoCommit()); ResultSet rs = sharedConnection.createStatement().executeQuery("select @@autocommit"); rs.next(); assertEquals(0, rs.getInt(1)); sharedConnection.setAutoCommit(true); /* Check that autocommit value "true" , that driver derives from server status flags * remains the same when EOF, ERROR or OK stream were received. */ assertTrue(sharedConnection.getAutoCommit()); sharedConnection.createStatement().execute("set @a=1"); assertTrue(sharedConnection.getAutoCommit()); try { sharedConnection.createStatement().execute("insert into nosuchtable values(1)"); } catch (Exception e) { //eat exception } assertTrue(sharedConnection.getAutoCommit()); rs = sharedConnection.createStatement().executeQuery("select @@autocommit"); rs.next(); assertEquals(1, rs.getInt(1)); /* Set autocommit value using Statement.execute */ sharedConnection.createStatement().execute("set @@autocommit=0"); assertFalse(sharedConnection.getAutoCommit()); sharedConnection.createStatement().execute("set @@autocommit=1"); assertTrue(sharedConnection.getAutoCommit()); /* Use session variable to set autocommit to 0 */ Connection connection = null; try { connection = setConnection("&sessionVariables=autocommit=0"); assertFalse(connection.getAutoCommit()); sharedConnection.setAutoCommit(true); } finally { connection.close(); } } @Test public void testUpdateCountSingle() throws SQLException { Statement stmt = sharedConnection.createStatement(); stmt.execute("select 1"); assertTrue(-1 == stmt.getUpdateCount()); } @Test public void testUpdateCountMulti() throws SQLException { try (Connection connection = setConnection("&allowMultiQueries=true")) { Statement stmt = connection.createStatement(); stmt.execute("select 1;select 1"); assertTrue(-1 == stmt.getUpdateCount()); stmt.getMoreResults(); assertTrue(-1 == stmt.getUpdateCount()); } } /** * CONJ-385 - stored procedure update count regression. * * @throws SQLException if connection error occur. */ @Test public void testUpdateCountProcedure() throws SQLException { createProcedure("multiUpdateCount", "() BEGIN SELECT 1; SELECT 2; END"); CallableStatement callableStatement = sharedConnection.prepareCall("{call multiUpdateCount()}"); callableStatement.execute(); assertTrue(-1 == callableStatement.getUpdateCount()); callableStatement.getMoreResults(); assertTrue(-1 == callableStatement.getUpdateCount()); } @Test public void testConnectWithDb() throws SQLException { requireMinimumVersion(5, 0); try { sharedConnection.createStatement().executeUpdate("drop database test_testdrop"); } catch (Exception e) { //eat exception } try (Connection connection = setConnection("&createDatabaseIfNotExist=true", "test_testdrop")) { DatabaseMetaData dbmd = connection.getMetaData(); ResultSet rs = dbmd.getCatalogs(); boolean foundDb = false; while (rs.next()) { if (rs.getString("table_cat").equals("test_testdrop")) { foundDb = true; } } assertTrue(foundDb); sharedConnection.createStatement().executeUpdate("drop database test_testdrop"); } } @Test public void streamingResult() throws SQLException { Statement st = sharedConnection.createStatement(); for (int i = 0; i < 100; i++) { st.execute("insert into streamingtest values('aaaaaaaaaaaaaaaaaa')"); } st.setFetchSize(Integer.MIN_VALUE); ResultSet rs = st.executeQuery("select * from streamingtest"); rs.next(); rs.close(); Statement st2 = sharedConnection.createStatement(); ResultSet rs2 = st2.executeQuery("select * from streamingtest"); rs2.next(); rs.close(); } // Test if driver works with sql_mode= NO_BACKSLASH_ESCAPES @Test public void noBackslashEscapes() throws SQLException { requireMinimumVersion(5, 0); // super privilege is needed for this test Assume.assumeTrue(hasSuperPrivilege("NoBackslashEscapes")); Statement st = sharedConnection.createStatement(); ResultSet rs = st.executeQuery("select @@global.sql_mode"); rs.next(); String originalSqlMode = rs.getString(1); st.execute("set @@global.sql_mode = '" + originalSqlMode + ",NO_BACKSLASH_ESCAPES'"); try { try (Connection connection = setConnection("&profileSql=true")) { PreparedStatement preparedStatement = connection.prepareStatement("insert into testBlob2(a) values(?)"); byte[] bytes = new byte[255]; for (byte i = -128; i < 127; i++) { bytes[i + 128] = i; } MariaDbBlob blob = new MariaDbBlob(bytes); preparedStatement.setBlob(1, blob); int affectedRows = preparedStatement.executeUpdate(); Assert.assertEquals(affectedRows, 1); } } finally { st.execute("set @@global.sql_mode='" + originalSqlMode + "'"); } } // Test if driver works with sql_mode= NO_BACKSLASH_ESCAPES @Test public void noBackslashEscapes2() throws SQLException { requireMinimumVersion(5, 0); // super privilege is needed for this test Assume.assumeTrue(hasSuperPrivilege("NoBackslashEscapes2")); Statement st = sharedConnection.createStatement(); ResultSet rs = st.executeQuery("select @@global.sql_mode"); rs.next(); String originalSqlMode = rs.getString(1); st.execute("set @@global.sql_mode = '" + originalSqlMode + ",NO_BACKSLASH_ESCAPES'"); try { try (Connection connection = setConnection("&profileSql=true")) { PreparedStatement preparedStatement = connection.prepareStatement("insert into testString2(a) values(?)"); preparedStatement.setString(1, "'\\"); int affectedRows = preparedStatement.executeUpdate(); Assert.assertEquals(affectedRows, 1); preparedStatement.close(); preparedStatement = connection.prepareStatement("select * from testString2"); rs = preparedStatement.executeQuery(); rs.next(); String out = rs.getString(1); assertEquals(out, "'\\"); Statement st2 = connection.createStatement(); rs = st2.executeQuery("select 'a\\b\\c'"); rs.next(); assertEquals("a\\b\\c", rs.getString(1)); } } finally { st.execute("set @@global.sql_mode='" + originalSqlMode + "'"); } } // Test if driver works with sql_mode= ANSI_QUOTES @Test public void ansiQuotes() throws SQLException { // super privilege is needed for this test Assume.assumeTrue(hasSuperPrivilege("AnsiQuotes")); Statement st = sharedConnection.createStatement(); ResultSet rs = st.executeQuery("select @@global.sql_mode"); rs.next(); String originalSqlMode = rs.getString(1); st.execute("set @@global.sql_mode = '" + originalSqlMode + ",ANSI_QUOTES'"); try { try (Connection connection = setConnection("&profileSql=true")) { PreparedStatement preparedStatement = connection.prepareStatement("insert into testBlob2(a) values(?)"); byte[] bytes = new byte[255]; for (byte i = -128; i < 127; i++) { bytes[i + 128] = i; } MariaDbBlob blob = new MariaDbBlob(bytes); preparedStatement.setBlob(1, blob); int affectedRows = preparedStatement.executeUpdate(); Assert.assertEquals(affectedRows, 1); } } finally { st.execute("set @@global.sql_mode='" + originalSqlMode + "'"); } } @Test public void unsignedTest() throws Exception { Statement st = sharedConnection.createStatement(); st.execute("insert into unsignedtest values(4294967295)"); ResultSet rs = st.executeQuery("select * from unsignedtest"); rs.next(); assertNotNull(rs.getLong("unsignedtest.a")); } @Test // Bug in URL parser public void mdev3916() throws Exception { try { setConnection("&password="); } catch (SQLException ex) { //SQLException is ok because we might get for example an access denied exception if (!(ex.getMessage().indexOf("Could not connect: Access denied") > -1)) { throw ex; } } } @Test public void conj1() throws Exception { requireMinimumVersion(5, 0); try (Connection connection = setConnection("&profileSql=true")) { Statement st = connection.createStatement(); st.setQueryTimeout(1); st.execute("select sleep(0.5)"); try { st.execute("select * from information_schema.columns as c1, information_schema.tables, information_schema.tables as t2"); assertFalse("must be exception here", true); } catch (Exception e) { //normal exception } Statement st2 = connection.createStatement(); assertEquals(st2.getQueryTimeout(), 0); // no exception st2.execute("select * from information_schema.columns as c1, information_schema.tables as t2"); Statement st3 = connection.createStatement(); st3.setQueryTimeout(1); st3.execute("select * from information_schema.columns as c1"); assertEquals(st3.getQueryTimeout(), 1); } } /* Check that exception contains SQL statement, for queries with syntax errors */ @Test public void dumpQueryOnSyntaxException() throws Exception { String syntacticallyWrongQuery = "banana"; try { Statement st = sharedConnection.createStatement(); st.execute(syntacticallyWrongQuery); } catch (SQLException sqle) { assertTrue(sqle.getMessage().contains("Query is : " + syntacticallyWrongQuery)); } } /* Check that query contains SQL statement, if dumpQueryOnException is true */ @Test public void dumpQueryOnException() throws Exception { try (Connection connection = setConnection("&profileSql=true&dumpQueriesOnException=true")) { String selectFromNonExistingTable = "select * from banana"; try { Statement st = connection.createStatement(); st.execute(selectFromNonExistingTable); } catch (SQLException sqle) { assertTrue(sqle.getMessage().contains("Query is : " + selectFromNonExistingTable)); } } } /* CONJ-14 * getUpdateCount(), getResultSet() should indicate "no more results" with * (getUpdateCount() == -1 && getResultSet() == null) */ @Test public void conj14() throws Exception { Statement st = sharedConnection.createStatement(); /* 1. Test update statement */ st.execute("use " + database); assertEquals(0, st.getUpdateCount()); /* No more results */ assertFalse(st.getMoreResults()); assertEquals(-1, st.getUpdateCount()); assertEquals(null, st.getResultSet()); /* 2. Test select statement */ st.execute("select 1"); assertEquals(-1, st.getUpdateCount()); assertTrue(st.getResultSet() != null); /* No More results */ assertFalse(st.getMoreResults()); assertEquals(-1, st.getUpdateCount()); assertEquals(null, st.getResultSet()); /* Test batch */ try (Connection connection = setConnection("&profileSql=true&allowMultiQueries=true")) { st = connection.createStatement(); /* 3. Batch with two SELECTs */ st.execute("select 1;select 2"); /* First result (select)*/ assertEquals(-1, st.getUpdateCount()); assertTrue(st.getResultSet() != null); /* has more results */ assertTrue(st.getMoreResults()); /* Second result (select) */ assertEquals(-1, st.getUpdateCount()); assertTrue(st.getResultSet() != null); /* no more results */ assertFalse(st.getMoreResults()); assertEquals(-1, st.getUpdateCount()); assertEquals(null, st.getResultSet()); /* 4. Batch with a SELECT and non-SELECT */ st.execute("select 1; use " + database); /* First result (select)*/ assertEquals(-1, st.getUpdateCount()); assertTrue(st.getResultSet() != null); /* Next result is no ResultSet */ assertFalse(st.getMoreResults()); /* Second result (use) */ assertEquals(0, st.getUpdateCount()); assertTrue(st.getResultSet() == null); /* no more results */ assertFalse(st.getMoreResults()); assertEquals(-1, st.getUpdateCount()); assertEquals(null, st.getResultSet()); } } @Test public void conj25() throws Exception { try (Statement stmt = sharedConnection.createStatement()) { String st = "INSERT INTO conj25 VALUES (REPEAT('a',1024))"; for (int i = 1; i <= 100; i++) { st = st + ",(REPEAT('a',1024))"; } stmt.setFetchSize(Integer.MIN_VALUE); stmt.execute(st); stmt.executeQuery("SELECT * FROM conj25 a, conj25 b"); } } @Test public void namedPipe() throws Exception { try { ResultSet rs = sharedConnection.createStatement().executeQuery("select @@named_pipe,@@socket"); rs.next(); if (rs.getBoolean(1)) { String namedPipeName = rs.getString(2); //skip test if no namedPipeName was obtained because then we do not use a socket connection Assume.assumeTrue(namedPipeName != null); try (Connection connection = setConnection("&pipe=" + namedPipeName)) { Statement stmt = connection.createStatement(); rs = stmt.executeQuery("SELECT 1"); assertTrue(rs.next()); rs.close(); } } } catch (SQLException e) { //not on windows } } /** * CONJ-293 : permit connection to named pipe when no host is defined. * * @throws Exception mustn't occur. */ @Test public void namedPipeWithoutHost() throws Exception { try { ResultSet rs = sharedConnection.createStatement().executeQuery("select @@named_pipe,@@socket"); rs.next(); if (rs.getBoolean(1)) { String namedPipeName = rs.getString(2); //skip test if no namedPipeName was obtained because then we do not use a socket connection Assume.assumeTrue(namedPipeName != null); try (Connection connection = DriverManager.getConnection("jdbc:mariadb:///testj?user=" + username + "&pipe=" + namedPipeName)) { Statement stmt = connection.createStatement(); rs = stmt.executeQuery("SELECT 1"); assertTrue(rs.next()); rs.close(); } } } catch (SQLException e) { //not on windows } } @Test public void localSocket() throws Exception { requireMinimumVersion(5, 1); Assume.assumeTrue(isLocalConnection("localSocket")); Statement st = sharedConnection.createStatement(); ResultSet rs = st.executeQuery("select @@version_compile_os,@@socket"); if (!rs.next()) { return; } System.out.println("os:" + rs.getString(1) + " path:" + rs.getString(2)); String os = rs.getString(1); if (os.toLowerCase().startsWith("win")) { return; } String path = rs.getString(2); try (Connection connection = setConnection("&localSocket=" + path + "&profileSql=true")) { rs = connection.createStatement().executeQuery("select 1"); rs.next(); } } @Test public void sharedMemory() throws Exception { requireMinimumVersion(5, 1); Statement st = sharedConnection.createStatement(); ResultSet rs = st.executeQuery("select @@version_compile_os"); if (!rs.next()) { return; } String os = rs.getString(1); if (!os.toLowerCase().startsWith("win")) { return; // skip test on non-Windows } rs = st.executeQuery("select @@shared_memory,@@shared_memory_base_name"); if (!rs.next()) { return; } if (!rs.getString(1).equals("1")) { return; } String shmBaseName = rs.getString(2); try (Connection connection = setConnection("&sharedMemory=" + shmBaseName + "&profileSql=true")) { rs = connection.createStatement().executeQuery("select repeat('a',100000)"); rs.next(); assertEquals(100000, rs.getString(1).length()); char[] arr = new char[100000]; Arrays.fill(arr, 'a'); rs = connection.createStatement().executeQuery("select '" + new String(arr) + "'"); rs.next(); assertEquals(100000, rs.getString(1).length()); } } @Test public void preparedStatementToString() throws Exception { PreparedStatement ps = sharedConnection.prepareStatement("SELECT ?,?,?,?,?,?"); ps.setInt(1, 1); ps.setBigDecimal(2, new BigDecimal("1")); ps.setString(3, "one"); ps.setBoolean(4, true); Calendar calendar = new GregorianCalendar(1972, 3, 22); ps.setDate(5, new Date(calendar.getTime().getTime())); ps.setDouble(6, 1.5); assertEquals("sql : 'SELECT ?,?,?,?,?,?', parameters : [1,1,'one',1,'1972-04-22',1.5]", ps.toString()); ps.close(); } /* Test that CLOSE_CURSORS_ON_COMMIT is silently ignored, and HOLD_CURSORS_OVER_COMMIT is actually used*/ @Test public void resultSetHoldability() throws Exception { Statement st = sharedConnection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.CLOSE_CURSORS_AT_COMMIT); assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, st.getResultSetHoldability()); PreparedStatement ps = sharedConnection.prepareStatement("SELECT 1", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.CLOSE_CURSORS_AT_COMMIT); assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, ps.getResultSetHoldability()); ResultSet rs = ps.executeQuery(); assertEquals(rs.getHoldability(), ResultSet.HOLD_CURSORS_OVER_COMMIT); CallableStatement cs = sharedConnection.prepareCall("{CALL foo}", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.CLOSE_CURSORS_AT_COMMIT); assertEquals(cs.getResultSetHoldability(), ResultSet.HOLD_CURSORS_OVER_COMMIT); } @Test public void emptyBatch() throws Exception { Statement st = sharedConnection.createStatement(); st.executeBatch(); } @Test public void createDbWithSpacesTest() throws SQLException { try (Connection connection = setConnection("&createDatabaseIfNotExist=true&profileSql=true", "test with spaces")) { DatabaseMetaData dbmd = connection.getMetaData(); ResultSet rs = dbmd.getCatalogs(); boolean foundDb = false; while (rs.next()) { if (rs.getString("table_cat").equals("test with spaces")) { foundDb = true; } } assertTrue("database \"test with spaces\" not created !?", foundDb); connection.createStatement().execute("drop database `test with spaces`"); } } /** * CONJ-275 : Streaming resultSet with no result must not have a next() value to true. * * @throws Exception exception */ @Test public void checkStreamingWithoutResult() throws Exception { PreparedStatement pstmt = sharedConnection.prepareStatement("SELECT * FROM conj275 where a = ?"); pstmt.setFetchSize(10); pstmt.setString(1, "no result"); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { fail("must not have result value"); } } }
[CONJ-393] changing test for mysql compatibility
src/test/java/org/mariadb/jdbc/DriverTest.java
[CONJ-393] changing test for mysql compatibility
Java
unlicense
5c6e5bffb20cf034c47828284dbfc72543585370
0
Samourai-Wallet/samourai-wallet-android
package com.samourai.wallet; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.v4.content.LocalBroadcastManager; import android.widget.ArrayAdapter; import com.samourai.wallet.access.AccessFactory; import com.samourai.wallet.api.APIFactory; import com.samourai.wallet.crypto.AESUtil; import com.samourai.wallet.payload.PayloadUtil; import com.samourai.wallet.prng.PRNGFixes; import com.samourai.wallet.service.BackgroundManager; import com.samourai.wallet.service.RefreshService; import com.samourai.wallet.service.WebSocketService; import com.samourai.wallet.util.AppUtil; import com.samourai.wallet.util.CharSequenceX; import com.samourai.wallet.util.ConnectivityStatus; import com.samourai.wallet.util.ExchangeRateFactory; import com.samourai.wallet.util.PrefsUtil; import com.samourai.wallet.util.ReceiversUtil; import com.samourai.wallet.util.TimeOutUtil; import com.samourai.wallet.util.WebUtil; import org.apache.commons.codec.DecoderException; import org.bitcoinj.crypto.MnemonicException; import org.bitcoinj.params.MainNetParams; import org.bitcoinj.params.TestNet3Params; public class MainActivity2 extends Activity { private ProgressDialog progress = null; /** An array of strings to populate dropdown list */ private static String[] account_selections = null; private static ArrayAdapter<String> adapter = null; private static boolean loadedBalanceFragment = false; public static final String ACTION_RESTART = "com.samourai.wallet.MainActivity2.RESTART_SERVICE"; protected BroadcastReceiver receiver_restart = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if(ACTION_RESTART.equals(intent.getAction())) { ReceiversUtil.getInstance(MainActivity2.this).initReceivers(); if(AppUtil.getInstance(MainActivity2.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) { stopService(new Intent(MainActivity2.this.getApplicationContext(), WebSocketService.class)); } startService(new Intent(MainActivity2.this.getApplicationContext(), WebSocketService.class)); } } }; protected BackgroundManager.Listener bgListener = new BackgroundManager.Listener() { public void onBecameForeground() { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { Intent intent = new Intent("com.samourai.wallet.BalanceFragment.REFRESH"); intent.putExtra("notifTx", false); LocalBroadcastManager.getInstance(MainActivity2.this.getApplicationContext()).sendBroadcast(intent); Intent _intent = new Intent("com.samourai.wallet.MainActivity2.RESTART_SERVICE"); LocalBroadcastManager.getInstance(MainActivity2.this.getApplicationContext()).sendBroadcast(_intent); } } public void onBecameBackground() { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if(AppUtil.getInstance(MainActivity2.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) { stopService(new Intent(MainActivity2.this.getApplicationContext(), WebSocketService.class)); } } new Thread(new Runnable() { @Override public void run() { try { PayloadUtil.getInstance(MainActivity2.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(MainActivity2.this).getGUID() + AccessFactory.getInstance(MainActivity2.this).getPIN())); } catch(Exception e) { ; } } }).start(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); loadedBalanceFragment = false; // if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { BackgroundManager.get(MainActivity2.this).addListener(bgListener); // } getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); ActionBar.OnNavigationListener navigationListener = new ActionBar.OnNavigationListener() { @Override public boolean onNavigationItemSelected(int itemPosition, long itemId) { if(itemPosition == 2 && PrefsUtil.getInstance(MainActivity2.this).getValue(PrefsUtil.FIRST_USE_SHUFFLE, true) == true) { new AlertDialog.Builder(MainActivity2.this) .setTitle(R.string.app_name) .setMessage(R.string.first_use_shuffle) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { PrefsUtil.getInstance(MainActivity2.this).setValue(PrefsUtil.FIRST_USE_SHUFFLE, false); } }).show(); } SamouraiWallet.getInstance().setCurrentSelectedAccount(itemPosition); if(account_selections.length > 1) { SamouraiWallet.getInstance().setShowTotalBalance(true); } else { SamouraiWallet.getInstance().setShowTotalBalance(false); } if(loadedBalanceFragment) { Intent intent = new Intent(MainActivity2.this, BalanceActivity.class); intent.putExtra("notifTx", false); intent.putExtra("fetch", false); startActivity(intent); } return false; } }; getActionBar().setListNavigationCallbacks(adapter, navigationListener); getActionBar().setSelectedNavigationItem(1); // Apply PRNG fixes for Android 4.1 if(!AppUtil.getInstance(MainActivity2.this).isPRNG_FIXED()) { PRNGFixes.apply(); AppUtil.getInstance(MainActivity2.this).setPRNG_FIXED(true); } if(!ConnectivityStatus.hasConnectivity(MainActivity2.this) && !(AccessFactory.getInstance(MainActivity2.this).getGUID().length() < 1 || !PayloadUtil.getInstance(MainActivity2.this).walletFileExists())) { new AlertDialog.Builder(MainActivity2.this) .setTitle(R.string.app_name) .setMessage(R.string.no_internet) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { AppUtil.getInstance(MainActivity2.this).restartApp(); } }).show(); } else { // SSLVerifierThreadUtil.getInstance(MainActivity2.this).validateSSLThread(); // APIFactory.getInstance(MainActivity2.this).validateAPIThread(); exchangeRateThread(); boolean isDial = false; String strUri = null; String strPCode = null; Bundle extras = getIntent().getExtras(); if(extras != null && extras.containsKey("dialed")) { isDial = extras.getBoolean("dialed"); } if(extras != null && extras.containsKey("uri")) { strUri = extras.getString("uri"); } if(extras != null && extras.containsKey("pcode")) { strPCode = extras.getString("pcode"); } doAppInit(isDial, strUri, strPCode); } ReceiversUtil.getInstance(MainActivity2.this).checkSIMSwitch(); } @Override protected void onResume() { super.onResume(); AppUtil.getInstance(MainActivity2.this).setIsInForeground(true); AppUtil.getInstance(MainActivity2.this).deleteQR(); AppUtil.getInstance(MainActivity2.this).deleteBackup(); IntentFilter filter_restart = new IntentFilter(ACTION_RESTART); LocalBroadcastManager.getInstance(MainActivity2.this).registerReceiver(receiver_restart, filter_restart); doAccountSelection(); } @Override protected void onPause() { super.onPause(); LocalBroadcastManager.getInstance(MainActivity2.this).unregisterReceiver(receiver_restart); AppUtil.getInstance(MainActivity2.this).setIsInForeground(false); } @Override protected void onDestroy() { AppUtil.getInstance(MainActivity2.this).deleteQR(); AppUtil.getInstance(MainActivity2.this).deleteBackup(); // if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { BackgroundManager.get(this).removeListener(bgListener); // } super.onDestroy(); } private void initDialog() { Intent intent = new Intent(MainActivity2.this, LandingActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } private void validatePIN(String strUri) { if (AccessFactory.getInstance(MainActivity2.this).isLoggedIn() && !TimeOutUtil.getInstance().isTimedOut()) { return; } AccessFactory.getInstance(MainActivity2.this).setIsLoggedIn(false); Intent intent = new Intent(MainActivity2.this, PinEntryActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); if (strUri != null) { intent.putExtra("uri", strUri); PrefsUtil.getInstance(MainActivity2.this).setValue("SCHEMED_URI", strUri); } startActivity(intent); } private void launchFromDialer(final String pin) { if (progress != null && progress.isShowing()) { progress.dismiss(); progress = null; } progress = new ProgressDialog(MainActivity2.this); progress.setCancelable(false); progress.setTitle(R.string.app_name); progress.setMessage(getString(R.string.please_wait)); progress.show(); new Thread(new Runnable() { @Override public void run() { Looper.prepare(); try { PayloadUtil.getInstance(MainActivity2.this).restoreWalletfromJSON(new CharSequenceX(AccessFactory.getInstance(MainActivity2.this).getGUID() + pin)); if (progress != null && progress.isShowing()) { progress.dismiss(); progress = null; } AccessFactory.getInstance(MainActivity2.this).setIsLoggedIn(true); TimeOutUtil.getInstance().updatePin(); AppUtil.getInstance(MainActivity2.this).restartApp(); } catch (MnemonicException.MnemonicLengthException mle) { mle.printStackTrace(); } catch (DecoderException de) { de.printStackTrace(); } finally { if (progress != null && progress.isShowing()) { progress.dismiss(); progress = null; } } Looper.loop(); } }).start(); } private void exchangeRateThread() { final Handler handler = new Handler(); new Thread(new Runnable() { @Override public void run() { Looper.prepare(); String response = null; try { response = WebUtil.getInstance(null).getURL(WebUtil.LBC_EXCHANGE_URL); ExchangeRateFactory.getInstance(MainActivity2.this).setDataLBC(response); ExchangeRateFactory.getInstance(MainActivity2.this).parseLBC(); } catch(Exception e) { e.printStackTrace(); } response = null; try { response = WebUtil.getInstance(null).getURL(WebUtil.BTCe_EXCHANGE_URL + "btc_usd"); ExchangeRateFactory.getInstance(MainActivity2.this).setDataBTCe(response); ExchangeRateFactory.getInstance(MainActivity2.this).parseBTCe(); } catch(Exception e) { e.printStackTrace(); } response = null; try { response = WebUtil.getInstance(null).getURL(WebUtil.BTCe_EXCHANGE_URL + "btc_rur"); ExchangeRateFactory.getInstance(MainActivity2.this).setDataBTCe(response); ExchangeRateFactory.getInstance(MainActivity2.this).parseBTCe(); } catch(Exception e) { e.printStackTrace(); } response = null; try { response = WebUtil.getInstance(null).getURL(WebUtil.BTCe_EXCHANGE_URL + "btc_eur"); ExchangeRateFactory.getInstance(MainActivity2.this).setDataBTCe(response); ExchangeRateFactory.getInstance(MainActivity2.this).parseBTCe(); } catch(Exception e) { e.printStackTrace(); } response = null; try { response = WebUtil.getInstance(null).getURL(WebUtil.BFX_EXCHANGE_URL); ExchangeRateFactory.getInstance(MainActivity2.this).setDataBFX(response); ExchangeRateFactory.getInstance(MainActivity2.this).parseBFX(); } catch(Exception e) { e.printStackTrace(); } handler.post(new Runnable() { @Override public void run() { ; } }); Looper.loop(); } }).start(); } private void doAppInit(boolean isDial, final String strUri, final String strPCode) { if((strUri != null || strPCode != null) && AccessFactory.getInstance(MainActivity2.this).isLoggedIn()) { progress = new ProgressDialog(MainActivity2.this); progress.setCancelable(false); progress.setTitle(R.string.app_name); progress.setMessage(getText(R.string.please_wait)); progress.show(); new Thread(new Runnable() { @Override public void run() { Looper.prepare(); APIFactory.getInstance(MainActivity2.this).initWallet(); if (progress != null && progress.isShowing()) { progress.dismiss(); progress = null; } Intent intent = new Intent(MainActivity2.this, SendActivity.class); intent.putExtra("uri", strUri); intent.putExtra("pcode", strPCode); startActivity(intent); Looper.loop(); } }).start(); } else if(AccessFactory.getInstance(MainActivity2.this).getGUID().length() < 1 || !PayloadUtil.getInstance(MainActivity2.this).walletFileExists()) { AccessFactory.getInstance(MainActivity2.this).setIsLoggedIn(false); if(AppUtil.getInstance(MainActivity2.this).isSideLoaded()) { doSelectNet(); } else { initDialog(); } } else if(isDial && AccessFactory.getInstance(MainActivity2.this).validateHash(PrefsUtil.getInstance(MainActivity2.this).getValue(PrefsUtil.ACCESS_HASH, ""), AccessFactory.getInstance(MainActivity2.this).getGUID(), new CharSequenceX(AccessFactory.getInstance(MainActivity2.this).getPIN()), AESUtil.DefaultPBKDF2Iterations)) { TimeOutUtil.getInstance().updatePin(); launchFromDialer(AccessFactory.getInstance(MainActivity2.this).getPIN()); } else if(TimeOutUtil.getInstance().isTimedOut()) { AccessFactory.getInstance(MainActivity2.this).setIsLoggedIn(false); validatePIN(strUri == null ? null : strUri); } else if(AccessFactory.getInstance(MainActivity2.this).isLoggedIn() && !TimeOutUtil.getInstance().isTimedOut()) { TimeOutUtil.getInstance().updatePin(); loadedBalanceFragment = true; Intent intent = new Intent(MainActivity2.this, BalanceActivity.class); intent.putExtra("notifTx", true); intent.putExtra("fetch", true); startActivity(intent); } else { AccessFactory.getInstance(MainActivity2.this).setIsLoggedIn(false); validatePIN(strUri == null ? null : strUri); } } private void doAccountSelection() { if(!PayloadUtil.getInstance(MainActivity2.this).walletFileExists()) { return; } account_selections = new String[] { getString(R.string.total), getString(R.string.account_Samourai), getString(R.string.account_shuffling), }; adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_dropdown_item, account_selections); if(account_selections.length > 1) { SamouraiWallet.getInstance().setShowTotalBalance(true); } else { SamouraiWallet.getInstance().setShowTotalBalance(false); } } private void doSelectNet() { AlertDialog.Builder dlg = new AlertDialog.Builder(this) .setTitle(R.string.app_name) .setMessage(R.string.select_network) .setCancelable(false) .setPositiveButton(R.string.MainNet, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); PrefsUtil.getInstance(MainActivity2.this).removeValue(PrefsUtil.TESTNET); SamouraiWallet.getInstance().setCurrentNetworkParams(MainNetParams.get()); initDialog(); } }) .setNegativeButton(R.string.TestNet, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); PrefsUtil.getInstance(MainActivity2.this).setValue(PrefsUtil.TESTNET, true); SamouraiWallet.getInstance().setCurrentNetworkParams(TestNet3Params.get()); initDialog(); } }); if(!isFinishing()) { dlg.show(); } } }
app/src/main/java/com/samourai/wallet/MainActivity2.java
package com.samourai.wallet; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.v4.content.LocalBroadcastManager; import android.widget.ArrayAdapter; import com.samourai.wallet.access.AccessFactory; import com.samourai.wallet.api.APIFactory; import com.samourai.wallet.crypto.AESUtil; import com.samourai.wallet.payload.PayloadUtil; import com.samourai.wallet.prng.PRNGFixes; import com.samourai.wallet.service.BackgroundManager; import com.samourai.wallet.service.RefreshService; import com.samourai.wallet.service.WebSocketService; import com.samourai.wallet.util.AppUtil; import com.samourai.wallet.util.CharSequenceX; import com.samourai.wallet.util.ConnectivityStatus; import com.samourai.wallet.util.ExchangeRateFactory; import com.samourai.wallet.util.PrefsUtil; import com.samourai.wallet.util.ReceiversUtil; import com.samourai.wallet.util.TimeOutUtil; import com.samourai.wallet.util.WebUtil; import org.apache.commons.codec.DecoderException; import org.bitcoinj.crypto.MnemonicException; import org.bitcoinj.params.MainNetParams; import org.bitcoinj.params.TestNet3Params; public class MainActivity2 extends Activity { private ProgressDialog progress = null; /** An array of strings to populate dropdown list */ private static String[] account_selections = null; private static ArrayAdapter<String> adapter = null; private static boolean loadedBalanceFragment = false; public static final String ACTION_RESTART = "com.samourai.wallet.MainActivity2.RESTART_SERVICE"; protected BroadcastReceiver receiver_restart = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if(ACTION_RESTART.equals(intent.getAction())) { ReceiversUtil.getInstance(MainActivity2.this).initReceivers(); if(AppUtil.getInstance(MainActivity2.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) { stopService(new Intent(MainActivity2.this.getApplicationContext(), WebSocketService.class)); } startService(new Intent(MainActivity2.this.getApplicationContext(), WebSocketService.class)); } } }; protected BackgroundManager.Listener bgListener = new BackgroundManager.Listener() { public void onBecameForeground() { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { Intent intent = new Intent("com.samourai.wallet.BalanceFragment.REFRESH"); intent.putExtra("notifTx", false); LocalBroadcastManager.getInstance(MainActivity2.this.getApplicationContext()).sendBroadcast(intent); Intent _intent = new Intent("com.samourai.wallet.MainActivity2.RESTART_SERVICE"); LocalBroadcastManager.getInstance(MainActivity2.this.getApplicationContext()).sendBroadcast(_intent); } } public void onBecameBackground() { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if(AppUtil.getInstance(MainActivity2.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) { stopService(new Intent(MainActivity2.this.getApplicationContext(), WebSocketService.class)); } } new Thread(new Runnable() { @Override public void run() { try { PayloadUtil.getInstance(MainActivity2.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(MainActivity2.this).getGUID() + AccessFactory.getInstance(MainActivity2.this).getPIN())); } catch(Exception e) { ; } } }).start(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); loadedBalanceFragment = false; // if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { BackgroundManager.get(MainActivity2.this).addListener(bgListener); // } getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); ActionBar.OnNavigationListener navigationListener = new ActionBar.OnNavigationListener() { @Override public boolean onNavigationItemSelected(int itemPosition, long itemId) { if(itemPosition == 2 && PrefsUtil.getInstance(MainActivity2.this).getValue(PrefsUtil.FIRST_USE_SHUFFLE, true) == true) { new AlertDialog.Builder(MainActivity2.this) .setTitle(R.string.app_name) .setMessage(R.string.first_use_shuffle) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { PrefsUtil.getInstance(MainActivity2.this).setValue(PrefsUtil.FIRST_USE_SHUFFLE, false); } }).show(); } SamouraiWallet.getInstance().setCurrentSelectedAccount(itemPosition); if(account_selections.length > 1) { SamouraiWallet.getInstance().setShowTotalBalance(true); } else { SamouraiWallet.getInstance().setShowTotalBalance(false); } if(loadedBalanceFragment) { Intent intent = new Intent(MainActivity2.this, BalanceActivity.class); intent.putExtra("notifTx", false); intent.putExtra("fetch", false); startActivity(intent); } return false; } }; getActionBar().setListNavigationCallbacks(adapter, navigationListener); getActionBar().setSelectedNavigationItem(1); // Apply PRNG fixes for Android 4.1 if(!AppUtil.getInstance(MainActivity2.this).isPRNG_FIXED()) { PRNGFixes.apply(); AppUtil.getInstance(MainActivity2.this).setPRNG_FIXED(true); } if(!ConnectivityStatus.hasConnectivity(MainActivity2.this) && !(AccessFactory.getInstance(MainActivity2.this).getGUID().length() < 1 || !PayloadUtil.getInstance(MainActivity2.this).walletFileExists())) { new AlertDialog.Builder(MainActivity2.this) .setTitle(R.string.app_name) .setMessage(R.string.no_internet) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { AppUtil.getInstance(MainActivity2.this).restartApp(); } }).show(); } else { // SSLVerifierThreadUtil.getInstance(MainActivity2.this).validateSSLThread(); // APIFactory.getInstance(MainActivity2.this).validateAPIThread(); exchangeRateThread(); boolean isDial = false; String strUri = null; String strPCode = null; Bundle extras = getIntent().getExtras(); if(extras != null && extras.containsKey("dialed")) { isDial = extras.getBoolean("dialed"); } if(extras != null && extras.containsKey("uri")) { strUri = extras.getString("uri"); } if(extras != null && extras.containsKey("pcode")) { strPCode = extras.getString("pcode"); } doAppInit(isDial, strUri, strPCode); } } @Override protected void onResume() { super.onResume(); AppUtil.getInstance(MainActivity2.this).setIsInForeground(true); AppUtil.getInstance(MainActivity2.this).deleteQR(); AppUtil.getInstance(MainActivity2.this).deleteBackup(); IntentFilter filter_restart = new IntentFilter(ACTION_RESTART); LocalBroadcastManager.getInstance(MainActivity2.this).registerReceiver(receiver_restart, filter_restart); doAccountSelection(); } @Override protected void onPause() { super.onPause(); LocalBroadcastManager.getInstance(MainActivity2.this).unregisterReceiver(receiver_restart); AppUtil.getInstance(MainActivity2.this).setIsInForeground(false); } @Override protected void onDestroy() { AppUtil.getInstance(MainActivity2.this).deleteQR(); AppUtil.getInstance(MainActivity2.this).deleteBackup(); // if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { BackgroundManager.get(this).removeListener(bgListener); // } super.onDestroy(); } private void initDialog() { Intent intent = new Intent(MainActivity2.this, LandingActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } private void validatePIN(String strUri) { if (AccessFactory.getInstance(MainActivity2.this).isLoggedIn() && !TimeOutUtil.getInstance().isTimedOut()) { return; } AccessFactory.getInstance(MainActivity2.this).setIsLoggedIn(false); Intent intent = new Intent(MainActivity2.this, PinEntryActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); if (strUri != null) { intent.putExtra("uri", strUri); PrefsUtil.getInstance(MainActivity2.this).setValue("SCHEMED_URI", strUri); } startActivity(intent); } private void launchFromDialer(final String pin) { if (progress != null && progress.isShowing()) { progress.dismiss(); progress = null; } progress = new ProgressDialog(MainActivity2.this); progress.setCancelable(false); progress.setTitle(R.string.app_name); progress.setMessage(getString(R.string.please_wait)); progress.show(); new Thread(new Runnable() { @Override public void run() { Looper.prepare(); try { PayloadUtil.getInstance(MainActivity2.this).restoreWalletfromJSON(new CharSequenceX(AccessFactory.getInstance(MainActivity2.this).getGUID() + pin)); if (progress != null && progress.isShowing()) { progress.dismiss(); progress = null; } AccessFactory.getInstance(MainActivity2.this).setIsLoggedIn(true); TimeOutUtil.getInstance().updatePin(); AppUtil.getInstance(MainActivity2.this).restartApp(); } catch (MnemonicException.MnemonicLengthException mle) { mle.printStackTrace(); } catch (DecoderException de) { de.printStackTrace(); } finally { if (progress != null && progress.isShowing()) { progress.dismiss(); progress = null; } } Looper.loop(); } }).start(); } private void exchangeRateThread() { final Handler handler = new Handler(); new Thread(new Runnable() { @Override public void run() { Looper.prepare(); String response = null; try { response = WebUtil.getInstance(null).getURL(WebUtil.LBC_EXCHANGE_URL); ExchangeRateFactory.getInstance(MainActivity2.this).setDataLBC(response); ExchangeRateFactory.getInstance(MainActivity2.this).parseLBC(); } catch(Exception e) { e.printStackTrace(); } response = null; try { response = WebUtil.getInstance(null).getURL(WebUtil.BTCe_EXCHANGE_URL + "btc_usd"); ExchangeRateFactory.getInstance(MainActivity2.this).setDataBTCe(response); ExchangeRateFactory.getInstance(MainActivity2.this).parseBTCe(); } catch(Exception e) { e.printStackTrace(); } response = null; try { response = WebUtil.getInstance(null).getURL(WebUtil.BTCe_EXCHANGE_URL + "btc_rur"); ExchangeRateFactory.getInstance(MainActivity2.this).setDataBTCe(response); ExchangeRateFactory.getInstance(MainActivity2.this).parseBTCe(); } catch(Exception e) { e.printStackTrace(); } response = null; try { response = WebUtil.getInstance(null).getURL(WebUtil.BTCe_EXCHANGE_URL + "btc_eur"); ExchangeRateFactory.getInstance(MainActivity2.this).setDataBTCe(response); ExchangeRateFactory.getInstance(MainActivity2.this).parseBTCe(); } catch(Exception e) { e.printStackTrace(); } response = null; try { response = WebUtil.getInstance(null).getURL(WebUtil.BFX_EXCHANGE_URL); ExchangeRateFactory.getInstance(MainActivity2.this).setDataBFX(response); ExchangeRateFactory.getInstance(MainActivity2.this).parseBFX(); } catch(Exception e) { e.printStackTrace(); } handler.post(new Runnable() { @Override public void run() { ; } }); Looper.loop(); } }).start(); } private void doAppInit(boolean isDial, final String strUri, final String strPCode) { if((strUri != null || strPCode != null) && AccessFactory.getInstance(MainActivity2.this).isLoggedIn()) { progress = new ProgressDialog(MainActivity2.this); progress.setCancelable(false); progress.setTitle(R.string.app_name); progress.setMessage(getText(R.string.please_wait)); progress.show(); new Thread(new Runnable() { @Override public void run() { Looper.prepare(); APIFactory.getInstance(MainActivity2.this).initWallet(); if (progress != null && progress.isShowing()) { progress.dismiss(); progress = null; } Intent intent = new Intent(MainActivity2.this, SendActivity.class); intent.putExtra("uri", strUri); intent.putExtra("pcode", strPCode); startActivity(intent); Looper.loop(); } }).start(); } else if(AccessFactory.getInstance(MainActivity2.this).getGUID().length() < 1 || !PayloadUtil.getInstance(MainActivity2.this).walletFileExists()) { AccessFactory.getInstance(MainActivity2.this).setIsLoggedIn(false); if(AppUtil.getInstance(MainActivity2.this).isSideLoaded()) { doSelectNet(); } else { initDialog(); } } else if(isDial && AccessFactory.getInstance(MainActivity2.this).validateHash(PrefsUtil.getInstance(MainActivity2.this).getValue(PrefsUtil.ACCESS_HASH, ""), AccessFactory.getInstance(MainActivity2.this).getGUID(), new CharSequenceX(AccessFactory.getInstance(MainActivity2.this).getPIN()), AESUtil.DefaultPBKDF2Iterations)) { TimeOutUtil.getInstance().updatePin(); launchFromDialer(AccessFactory.getInstance(MainActivity2.this).getPIN()); } else if(TimeOutUtil.getInstance().isTimedOut()) { AccessFactory.getInstance(MainActivity2.this).setIsLoggedIn(false); validatePIN(strUri == null ? null : strUri); } else if(AccessFactory.getInstance(MainActivity2.this).isLoggedIn() && !TimeOutUtil.getInstance().isTimedOut()) { TimeOutUtil.getInstance().updatePin(); loadedBalanceFragment = true; Intent intent = new Intent(MainActivity2.this, BalanceActivity.class); intent.putExtra("notifTx", true); intent.putExtra("fetch", true); startActivity(intent); } else { AccessFactory.getInstance(MainActivity2.this).setIsLoggedIn(false); validatePIN(strUri == null ? null : strUri); } } private void doAccountSelection() { if(!PayloadUtil.getInstance(MainActivity2.this).walletFileExists()) { return; } account_selections = new String[] { getString(R.string.total), getString(R.string.account_Samourai), getString(R.string.account_shuffling), }; adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_dropdown_item, account_selections); if(account_selections.length > 1) { SamouraiWallet.getInstance().setShowTotalBalance(true); } else { SamouraiWallet.getInstance().setShowTotalBalance(false); } } private void doSelectNet() { AlertDialog.Builder dlg = new AlertDialog.Builder(this) .setTitle(R.string.app_name) .setMessage(R.string.select_network) .setCancelable(false) .setPositiveButton(R.string.MainNet, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); PrefsUtil.getInstance(MainActivity2.this).removeValue(PrefsUtil.TESTNET); SamouraiWallet.getInstance().setCurrentNetworkParams(MainNetParams.get()); initDialog(); } }) .setNegativeButton(R.string.TestNet, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); PrefsUtil.getInstance(MainActivity2.this).setValue(PrefsUtil.TESTNET, true); SamouraiWallet.getInstance().setCurrentNetworkParams(TestNet3Params.get()); initDialog(); } }); if(!isFinishing()) { dlg.show(); } } }
do SIM switch test in MainActivity2
app/src/main/java/com/samourai/wallet/MainActivity2.java
do SIM switch test in MainActivity2
Java
apache-2.0
e914414807ec5ef73c64ce84fff2d7b68c5f2b06
0
apache/openwebbeans,apache/openwebbeans,apache/openwebbeans
/* * 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.webbeans.web.context; import org.apache.webbeans.annotation.DestroyedLiteral; import org.apache.webbeans.annotation.InitializedLiteral; import org.apache.webbeans.config.OWBLogConst; import org.apache.webbeans.config.WebBeansContext; import org.apache.webbeans.context.AbstractContextsService; import org.apache.webbeans.context.ApplicationContext; import org.apache.webbeans.context.ConversationContext; import org.apache.webbeans.context.DependentContext; import org.apache.webbeans.context.RequestContext; import org.apache.webbeans.context.SessionContext; import org.apache.webbeans.context.SingletonContext; import org.apache.webbeans.conversation.ConversationImpl; import org.apache.webbeans.conversation.ConversationManager; import org.apache.webbeans.el.ELContextStore; import org.apache.webbeans.logger.WebBeansLoggerFacade; import org.apache.webbeans.spi.FailOverService; import org.apache.webbeans.util.WebBeansUtil; import org.apache.webbeans.web.intercept.RequestScopedBeanInterceptorHandler; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.ContextException; import javax.enterprise.context.Conversation; import javax.enterprise.context.ConversationScoped; import javax.enterprise.context.Dependent; import javax.enterprise.context.RequestScoped; import javax.enterprise.context.SessionScoped; import javax.enterprise.context.spi.Context; import javax.inject.Singleton; import javax.servlet.ServletContext; import javax.servlet.ServletRequestEvent; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.lang.annotation.Annotation; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; /** * Web container {@link org.apache.webbeans.spi.ContextsService} * implementation. */ public class WebContextsService extends AbstractContextsService { /**Logger instance*/ private static final Logger logger = WebBeansLoggerFacade.getLogger(WebContextsService.class); /**Current request context*/ private static ThreadLocal<RequestContext> requestContexts = null; /**Current session context*/ private static ThreadLocal<SessionContext> sessionContexts = null; /** * This applicationContext will be used for all non servlet-request threads */ private ApplicationContext sharedApplicationContext ; private SingletonContext sharedSingletonContext; /**Current conversation context*/ private static ThreadLocal<ConversationContext> conversationContexts = null; /**Current dependent context*/ private static DependentContext dependentContext; /**Current application contexts*/ private static Map<ServletContext, ApplicationContext> currentApplicationContexts = new ConcurrentHashMap<ServletContext, ApplicationContext>(); /**Current singleton contexts*/ private static Map<ServletContext, SingletonContext> currentSingletonContexts = new ConcurrentHashMap<ServletContext, SingletonContext>(); private static Map<ClassLoader, ServletContext> classLoaderToServletContextMapping = new ConcurrentHashMap<ClassLoader, ServletContext>(); /**Session context manager*/ private final SessionContextManager sessionCtxManager = new SessionContextManager(); /**Conversation context manager*/ private final ConversationManager conversationManager; private boolean supportsConversation = false; protected FailOverService failoverService = null; private WebBeansContext webBeansContext; /**Initialize thread locals*/ static { requestContexts = new ThreadLocal<RequestContext>(); sessionContexts = new ThreadLocal<SessionContext>(); conversationContexts = new ThreadLocal<ConversationContext>(); //Dependent context is always active dependentContext = new DependentContext(); dependentContext.setActive(true); } /** * Removes the ThreadLocals from the ThreadMap to prevent memory leaks. */ public static void removeThreadLocals() { requestContexts.remove(); sessionContexts.remove(); conversationContexts.remove(); RequestScopedBeanInterceptorHandler.removeThreadLocals(); } /** * Creates a new instance. */ public WebContextsService(WebBeansContext webBeansContext) { this.webBeansContext = webBeansContext; supportsConversation = webBeansContext.getOpenWebBeansConfiguration().supportsConversation(); failoverService = webBeansContext.getService(FailOverService.class); conversationManager = webBeansContext.getConversationManager(); sharedApplicationContext = new ApplicationContext(); sharedApplicationContext.setActive(true); } public SessionContextManager getSessionContextManager() { return sessionCtxManager; } /** * {@inheritDoc} */ @Override public void init(Object initializeObject) { //Start application context startContext(ApplicationScoped.class, initializeObject); //Start signelton context startContext(Singleton.class, initializeObject); } /** * {@inheritDoc} */ @Override public void destroy(Object destroyObject) { //Destroy application context endContext(ApplicationScoped.class, destroyObject); // we also need to destroy the shared ApplicationContext sharedApplicationContext.destroy(); //Destroy singleton context endContext(Singleton.class, destroyObject); if (sharedSingletonContext != null) { sharedSingletonContext.destroy(); } //Clear saved contexts related with //this servlet context currentApplicationContexts.clear(); currentSingletonContexts.clear(); //Thread local values to null requestContexts.set(null); sessionContexts.set(null); conversationContexts.set(null); //Remove thread locals //for preventing memory leaks requestContexts.remove(); sessionContexts.remove(); conversationContexts.remove(); } /** * {@inheritDoc} */ @Override public void endContext(Class<? extends Annotation> scopeType, Object endParameters) { if(scopeType.equals(RequestScoped.class)) { destroyRequestContext((ServletRequestEvent)endParameters); } else if(scopeType.equals(SessionScoped.class)) { destroySessionContext((HttpSession)endParameters); } else if(scopeType.equals(ApplicationScoped.class)) { destroyApplicationContext((ServletContext)endParameters); } else if(supportsConversation && scopeType.equals(ConversationScoped.class)) { if (endParameters != null && endParameters instanceof HttpSession) { destoryAllConversationsForSession((HttpSession) endParameters); } destroyConversationContext(); } else if(scopeType.equals(Dependent.class)) { //Do nothing } else if (scopeType.equals(Singleton.class)) { destroySingletonContext((ServletContext)endParameters); } } /** * {@inheritDoc} */ @Override public Context getCurrentContext(Class<? extends Annotation> scopeType) { if(scopeType.equals(RequestScoped.class)) { return getRequestContext(); } else if(scopeType.equals(SessionScoped.class)) { return getSessionContext(); } else if(scopeType.equals(ApplicationScoped.class)) { ServletContext servletContext = classLoaderToServletContextMapping.get(WebBeansUtil.getCurrentClassLoader()); if (servletContext == null) { return null; } return currentApplicationContexts.get(servletContext); } else if(supportsConversation && scopeType.equals(ConversationScoped.class)) { return getConversationContext(); } else if(scopeType.equals(Dependent.class)) { return dependentContext; } else if (scopeType.equals(Singleton.class)) { ServletContext servletContext = classLoaderToServletContextMapping.get(WebBeansUtil.getCurrentClassLoader()); if (servletContext == null) { return null; } return currentSingletonContexts.get(servletContext); } return null; } /** * {@inheritDoc} */ @Override public void startContext(Class<? extends Annotation> scopeType, Object startParameter) throws ContextException { if(scopeType.equals(RequestScoped.class)) { initRequestContext((ServletRequestEvent)startParameter); } else if(scopeType.equals(SessionScoped.class)) { initSessionContext((HttpSession)startParameter); } else if(scopeType.equals(ApplicationScoped.class)) { initApplicationContext((ServletContext)startParameter); } else if(supportsConversation && scopeType.equals(ConversationScoped.class)) { initConversationContext((ConversationContext)startParameter); } else if(scopeType.equals(Dependent.class)) { //Do nothing } else if (scopeType.equals(Singleton.class)) { initSingletonContext((ServletContext)startParameter); } } /** * {@inheritDoc} */ @Override public boolean supportsContext(Class<? extends Annotation> scopeType) { if(scopeType.equals(RequestScoped.class) || scopeType.equals(SessionScoped.class) || scopeType.equals(ApplicationScoped.class) || scopeType.equals(Dependent.class) || scopeType.equals(Singleton.class) || (scopeType.equals(ConversationScoped.class) && supportsConversation)) { return true; } return false; } /** * Initialize requext context with the given request object. * @param event http servlet request event */ private void initRequestContext(ServletRequestEvent event) { RequestContext rq = new ServletRequestContext(); rq.setActive(true); requestContexts.set(rq);// set thread local if(event != null) { HttpServletRequest request = (HttpServletRequest) event.getServletRequest(); ((ServletRequestContext)rq).setServletRequest(request); if (request != null) { //Re-initialize thread local for session HttpSession session = request.getSession(false); if(session != null) { initSessionContext(session); } //Init thread local application context initApplicationContext(event.getServletContext()); //Init thread local singleton context initSingletonContext(event.getServletContext()); webBeansContext.getBeanManagerImpl().fireEvent(request, InitializedLiteral.INSTANCE_REQUEST_SCOPED); } } else { //Init thread local application context initApplicationContext(null); //Init thread local singleton context initSingletonContext(null); webBeansContext.getBeanManagerImpl().fireEvent(new Object(), InitializedLiteral.INSTANCE_REQUEST_SCOPED); } } /** * Destroys the request context and all of its components. * @param requestEvent http servlet request object */ private void destroyRequestContext(ServletRequestEvent requestEvent) { // cleanup open conversations first if (supportsConversation) { cleanupConversations(); } //Get context RequestContext context = getRequestContext(); //Destroy context if (context != null) { context.destroy(); } // clean up the EL caches after each request ELContextStore elStore = ELContextStore.getInstance(false); if (elStore != null) { elStore.destroyELContextStore(); } //Clear thread locals requestContexts.set(null); requestContexts.remove(); RequestScopedBeanInterceptorHandler.removeThreadLocals(); Object payload = requestEvent != null && requestEvent.getServletRequest() != null ? requestEvent.getServletRequest() : new Object(); webBeansContext.getBeanManagerImpl().fireEvent(payload, DestroyedLiteral.INSTANCE_REQUEST_SCOPED); } private void cleanupConversations() { ConversationContext conversationContext = getConversationContext(); if (conversationContext == null) { return; } Conversation conversation = conversationManager.getConversationBeanReference(); if (conversation == null) { return; } if (conversation.isTransient()) { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "Destroying the transient conversation context with cid : [{0}]", conversation.getId()); } destroyConversationContext(); conversationManager.removeConversation(conversation); // in case end() was called } else { //Conversation must be used by one thread at a time ConversationImpl owbConversation = (ConversationImpl)conversation; owbConversation.updateTimeOut(); //Other threads can now access propogated conversation. owbConversation.iDontUseItAnymore(); } } /** * Creates the session context at the session start. * @param session http session object */ private void initSessionContext(HttpSession session) { SessionContext currentSessionContext; if (session == null) { // no session -> create a dummy SessionContext // this is handy if you create asynchronous tasks or // batches which use a 'admin' user. currentSessionContext = new SessionContext(); webBeansContext.getBeanManagerImpl().fireEvent(new Object(), InitializedLiteral.INSTANCE_SESSION_SCOPED); } else { String sessionId = session.getId(); //Current context currentSessionContext = sessionCtxManager.getSessionContextWithSessionId(sessionId); //No current context if (currentSessionContext == null) { currentSessionContext = new SessionContext(); sessionCtxManager.addNewSessionContext(sessionId, currentSessionContext); webBeansContext.getBeanManagerImpl().fireEvent(session, InitializedLiteral.INSTANCE_SESSION_SCOPED); } } //Activate currentSessionContext.setActive(true); //Set thread local sessionContexts.set(currentSessionContext); } /** * Destroys the session context and all of its components at the end of the * session. * @param session http session object */ private void destroySessionContext(HttpSession session) { if (session != null) { //Get current session context SessionContext context = sessionContexts.get(); if (context == null) { initSessionContext(session); context = sessionContexts.get(); } //Destroy context if (context != null) { context.destroy(); } //Clear thread locals sessionContexts.set(null); sessionContexts.remove(); //Remove session from manager sessionCtxManager.removeSessionContextWithSessionId(session.getId()); } } /** * Creates the application context at the application startup * @param servletContext servlet context object */ private void initApplicationContext(ServletContext servletContext) { if (servletContext != null && currentApplicationContexts.containsKey(servletContext)) { return; } if (sharedApplicationContext != null && servletContext == null) { return; } ApplicationContext newApplicationContext = new ApplicationContext(); newApplicationContext.setActive(true); if (servletContext != null) { currentApplicationContexts.put(servletContext, newApplicationContext); ClassLoader currentClassLoader = WebBeansUtil.getCurrentClassLoader(); if (!classLoaderToServletContextMapping.containsKey(currentClassLoader)) { classLoaderToServletContextMapping.put(currentClassLoader, servletContext); } } if (sharedApplicationContext == null) { sharedApplicationContext = newApplicationContext; } webBeansContext.getBeanManagerImpl().fireEvent(servletContext != null ? servletContext : new Object(), InitializedLiteral.INSTANCE_APPLICATION_SCOPED); } /** * Destroys the application context and all of its components at the end of * the application. * @param servletContext servlet context object */ private void destroyApplicationContext(ServletContext servletContext) { //look for thread local //this can be set by initRequestContext ApplicationContext context = null; //Looking the context from saved context //This is used in real web applications if(servletContext != null) { context = currentApplicationContexts.get(servletContext); } //using in tests if(context == null) { context = this.sharedApplicationContext; } //Destroy context if(context != null) { context.destroy(); } //Remove from saved contexts if(servletContext != null) { currentApplicationContexts.remove(servletContext); } //destroyDependents all sessions Collection<SessionContext> allSessionContexts = sessionCtxManager.getAllSessionContexts().values(); if (allSessionContexts != null && allSessionContexts.size() > 0) { for (SessionContext sessionContext : allSessionContexts) { sessionContexts.set(sessionContext); sessionContext.destroy(); sessionContexts.set(null); sessionContexts.remove(); } //Clear map allSessionContexts.clear(); } //destroyDependents all conversations Collection<ConversationContext> allConversationContexts = conversationManager.getAllConversationContexts().values(); if (allConversationContexts != null && allConversationContexts.size() > 0) { for (ConversationContext conversationContext : allConversationContexts) { conversationContexts.set(conversationContext); conversationContext.destroy(); conversationContexts.set(null); conversationContexts.remove(); } //Clear conversations allConversationContexts.clear(); } // this is needed to get rid of ApplicationScoped beans which are cached inside the proxies... webBeansContext.getBeanManagerImpl().clearCacheProxies(); classLoaderToServletContextMapping.remove(WebBeansUtil.getCurrentClassLoader()); webBeansContext.getBeanManagerImpl().fireEvent(servletContext != null ? servletContext : new Object(), DestroyedLiteral.INSTANCE_APPLICATION_SCOPED); } /** * Initialize singleton context. * @param servletContext servlet context */ private void initSingletonContext(ServletContext servletContext) { if (servletContext != null && currentSingletonContexts.containsKey(servletContext)) { return; } if (currentSingletonContexts != null && servletContext == null) { return; } SingletonContext newSingletonContext = new SingletonContext(); newSingletonContext.setActive(true); if (servletContext != null) { currentSingletonContexts.put(servletContext, newSingletonContext); ClassLoader currentClassLoader = WebBeansUtil.getCurrentClassLoader(); if (!classLoaderToServletContextMapping.containsKey(currentClassLoader)) { classLoaderToServletContextMapping.put(currentClassLoader, servletContext); } } if (sharedSingletonContext == null) { sharedSingletonContext = newSingletonContext; } webBeansContext.getBeanManagerImpl().fireEvent(servletContext != null ? servletContext : new Object(), InitializedLiteral.INSTANCE_SINGLETON_SCOPED); } /** * Destroy singleton context. * @param servletContext servlet context */ private void destroySingletonContext(ServletContext servletContext) { SingletonContext context = null; //look for saved context if(servletContext != null) { context = currentSingletonContexts.get(servletContext); } //using in tests if(context == null) { context = this.sharedSingletonContext; } //context is not null //destroyDependents it if(context != null) { context.destroy(); } //remove it from saved contexts if(servletContext != null) { currentSingletonContexts.remove(servletContext); } classLoaderToServletContextMapping.remove(WebBeansUtil.getCurrentClassLoader()); webBeansContext.getBeanManagerImpl().fireEvent(servletContext != null ? servletContext : new Object(), DestroyedLiteral.INSTANCE_SINGLETON_SCOPED); } /** * Initialize conversation context. * @param context context */ private void initConversationContext(ConversationContext context) { if (context == null) { if(conversationContexts.get() == null) { ConversationContext newContext = new ConversationContext(); newContext.setActive(true); conversationContexts.set(newContext); } else { conversationContexts.get().setActive(true); } webBeansContext.getBeanManagerImpl().fireEvent(new Object(), InitializedLiteral.INSTANCE_SINGLETON_SCOPED); } else { context.setActive(true); conversationContexts.set(context); } } /** * Destroy conversation context. */ private void destroyConversationContext() { ConversationContext context = getConversationContext(); if (context != null) { context.destroy(); webBeansContext.getBeanManagerImpl().fireEvent(new Object(), DestroyedLiteral.INSTANCE_SINGLETON_SCOPED); } conversationContexts.set(null); conversationContexts.remove(); } /** * Workaround for OWB-841 * * @param session The current {@link HttpSession} */ private void destoryAllConversationsForSession(HttpSession session) { Map<Conversation, ConversationContext> conversations = conversationManager.getAndRemoveConversationMapWithSessionId(session.getId()); for (Entry<Conversation, ConversationContext> entry : conversations.entrySet()) { conversationContexts.set(entry.getValue()); entry.getValue().destroy(); conversationContexts.set(null); conversationContexts.remove(); } } /** * Get current request ctx. * @return request context */ private RequestContext getRequestContext() { return requestContexts.get(); } /** * Get current session ctx. * @return session context */ private SessionContext getSessionContext() { SessionContext context = sessionContexts.get(); if (null == context) { lazyStartSessionContext(); context = sessionContexts.get(); } return context; } /** * Get current conversation ctx. * @return conversation context */ private ConversationContext getConversationContext() { return conversationContexts.get(); } private Context lazyStartSessionContext() { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, ">lazyStartSessionContext"); } Context webContext = null; Context context = getCurrentContext(RequestScoped.class); if (context instanceof ServletRequestContext) { ServletRequestContext requestContext = (ServletRequestContext) context; HttpServletRequest servletRequest = requestContext.getServletRequest(); if (null != servletRequest) { // this could be null if there is no active request context try { HttpSession currentSession = servletRequest.getSession(); initSessionContext(currentSession); if (failoverService != null && failoverService.isSupportFailOver()) { failoverService.sessionIsInUse(currentSession); } if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "Lazy SESSION context initialization SUCCESS"); } } catch (Exception e) { logger.log(Level.SEVERE, WebBeansLoggerFacade.constructMessage(OWBLogConst.ERROR_0013, e)); } } else { logger.log(Level.WARNING, "Could NOT lazily initialize session context because NO active request context"); } } else { logger.log(Level.WARNING, "Could NOT lazily initialize session context because of "+context+" RequestContext"); } if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "<lazyStartSessionContext "+ webContext); } return webContext; } /** * This might be needed when you aim to start a new thread in a WebApp. * @param scopeType */ @Override public void activateContext(Class<? extends Annotation> scopeType) { if (scopeType.equals(SessionScoped.class)) { // getSessionContext() implicitely creates and binds the SessionContext // to the current Thread if it doesn't yet exist. getSessionContext().setActive(true); } else { super.activateContext(scopeType); } } }
webbeans-web/src/main/java/org/apache/webbeans/web/context/WebContextsService.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.webbeans.web.context; import org.apache.webbeans.config.OWBLogConst; import org.apache.webbeans.config.WebBeansContext; import org.apache.webbeans.context.AbstractContextsService; import org.apache.webbeans.context.ApplicationContext; import org.apache.webbeans.context.ConversationContext; import org.apache.webbeans.context.DependentContext; import org.apache.webbeans.context.RequestContext; import org.apache.webbeans.context.SessionContext; import org.apache.webbeans.context.SingletonContext; import org.apache.webbeans.conversation.ConversationImpl; import org.apache.webbeans.conversation.ConversationManager; import org.apache.webbeans.el.ELContextStore; import org.apache.webbeans.logger.WebBeansLoggerFacade; import org.apache.webbeans.spi.FailOverService; import org.apache.webbeans.util.WebBeansUtil; import org.apache.webbeans.web.intercept.RequestScopedBeanInterceptorHandler; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.ContextException; import javax.enterprise.context.Conversation; import javax.enterprise.context.ConversationScoped; import javax.enterprise.context.Dependent; import javax.enterprise.context.RequestScoped; import javax.enterprise.context.SessionScoped; import javax.enterprise.context.spi.Context; import javax.inject.Singleton; import javax.servlet.ServletContext; import javax.servlet.ServletRequestEvent; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.lang.annotation.Annotation; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; /** * Web container {@link org.apache.webbeans.spi.ContextsService} * implementation. */ public class WebContextsService extends AbstractContextsService { /**Logger instance*/ private static final Logger logger = WebBeansLoggerFacade.getLogger(WebContextsService.class); /**Current request context*/ private static ThreadLocal<RequestContext> requestContexts = null; /**Current session context*/ private static ThreadLocal<SessionContext> sessionContexts = null; /** * This applicationContext will be used for all non servlet-request threads */ private ApplicationContext sharedApplicationContext ; private SingletonContext sharedSingletonContext; /**Current conversation context*/ private static ThreadLocal<ConversationContext> conversationContexts = null; /**Current dependent context*/ private static DependentContext dependentContext; /**Current application contexts*/ private static Map<ServletContext, ApplicationContext> currentApplicationContexts = new ConcurrentHashMap<ServletContext, ApplicationContext>(); /**Current singleton contexts*/ private static Map<ServletContext, SingletonContext> currentSingletonContexts = new ConcurrentHashMap<ServletContext, SingletonContext>(); private static Map<ClassLoader, ServletContext> classLoaderToServletContextMapping = new ConcurrentHashMap<ClassLoader, ServletContext>(); /**Session context manager*/ private final SessionContextManager sessionCtxManager = new SessionContextManager(); /**Conversation context manager*/ private final ConversationManager conversationManager; private boolean supportsConversation = false; protected FailOverService failoverService = null; private WebBeansContext webBeansContext; /**Initialize thread locals*/ static { requestContexts = new ThreadLocal<RequestContext>(); sessionContexts = new ThreadLocal<SessionContext>(); conversationContexts = new ThreadLocal<ConversationContext>(); //Dependent context is always active dependentContext = new DependentContext(); dependentContext.setActive(true); } /** * Removes the ThreadLocals from the ThreadMap to prevent memory leaks. */ public static void removeThreadLocals() { requestContexts.remove(); sessionContexts.remove(); conversationContexts.remove(); RequestScopedBeanInterceptorHandler.removeThreadLocals(); } /** * Creates a new instance. */ public WebContextsService(WebBeansContext webBeansContext) { this.webBeansContext = webBeansContext; supportsConversation = webBeansContext.getOpenWebBeansConfiguration().supportsConversation(); failoverService = webBeansContext.getService(FailOverService.class); conversationManager = webBeansContext.getConversationManager(); sharedApplicationContext = new ApplicationContext(); sharedApplicationContext.setActive(true); } public SessionContextManager getSessionContextManager() { return sessionCtxManager; } /** * {@inheritDoc} */ @Override public void init(Object initializeObject) { //Start application context startContext(ApplicationScoped.class, initializeObject); //Start signelton context startContext(Singleton.class, initializeObject); } /** * {@inheritDoc} */ @Override public void destroy(Object destroyObject) { //Destroy application context endContext(ApplicationScoped.class, destroyObject); // we also need to destroy the shared ApplicationContext sharedApplicationContext.destroy(); //Destroy singleton context endContext(Singleton.class, destroyObject); if (sharedSingletonContext != null) { sharedSingletonContext.destroy(); } //Clear saved contexts related with //this servlet context currentApplicationContexts.clear(); currentSingletonContexts.clear(); //Thread local values to null requestContexts.set(null); sessionContexts.set(null); conversationContexts.set(null); //Remove thread locals //for preventing memory leaks requestContexts.remove(); sessionContexts.remove(); conversationContexts.remove(); } /** * {@inheritDoc} */ @Override public void endContext(Class<? extends Annotation> scopeType, Object endParameters) { if(scopeType.equals(RequestScoped.class)) { destroyRequestContext((ServletRequestEvent)endParameters); } else if(scopeType.equals(SessionScoped.class)) { destroySessionContext((HttpSession)endParameters); } else if(scopeType.equals(ApplicationScoped.class)) { destroyApplicationContext((ServletContext)endParameters); } else if(supportsConversation && scopeType.equals(ConversationScoped.class)) { if (endParameters != null && endParameters instanceof HttpSession) { destoryAllConversationsForSession((HttpSession) endParameters); } destroyConversationContext(); } else if(scopeType.equals(Dependent.class)) { //Do nothing } else if (scopeType.equals(Singleton.class)) { destroySingletonContext((ServletContext)endParameters); } } /** * {@inheritDoc} */ @Override public Context getCurrentContext(Class<? extends Annotation> scopeType) { if(scopeType.equals(RequestScoped.class)) { return getRequestContext(); } else if(scopeType.equals(SessionScoped.class)) { return getSessionContext(); } else if(scopeType.equals(ApplicationScoped.class)) { ServletContext servletContext = classLoaderToServletContextMapping.get(WebBeansUtil.getCurrentClassLoader()); if (servletContext == null) { return null; } return currentApplicationContexts.get(servletContext); } else if(supportsConversation && scopeType.equals(ConversationScoped.class)) { return getConversationContext(); } else if(scopeType.equals(Dependent.class)) { return dependentContext; } else if (scopeType.equals(Singleton.class)) { ServletContext servletContext = classLoaderToServletContextMapping.get(WebBeansUtil.getCurrentClassLoader()); if (servletContext == null) { return null; } return currentSingletonContexts.get(servletContext); } return null; } /** * {@inheritDoc} */ @Override public void startContext(Class<? extends Annotation> scopeType, Object startParameter) throws ContextException { if(scopeType.equals(RequestScoped.class)) { initRequestContext((ServletRequestEvent)startParameter); } else if(scopeType.equals(SessionScoped.class)) { initSessionContext((HttpSession)startParameter); } else if(scopeType.equals(ApplicationScoped.class)) { initApplicationContext((ServletContext)startParameter); } else if(supportsConversation && scopeType.equals(ConversationScoped.class)) { initConversationContext((ConversationContext)startParameter); } else if(scopeType.equals(Dependent.class)) { //Do nothing } else if (scopeType.equals(Singleton.class)) { initSingletonContext((ServletContext)startParameter); } } /** * {@inheritDoc} */ @Override public boolean supportsContext(Class<? extends Annotation> scopeType) { if(scopeType.equals(RequestScoped.class) || scopeType.equals(SessionScoped.class) || scopeType.equals(ApplicationScoped.class) || scopeType.equals(Dependent.class) || scopeType.equals(Singleton.class) || (scopeType.equals(ConversationScoped.class) && supportsConversation)) { return true; } return false; } /** * Initialize requext context with the given request object. * @param event http servlet request event */ private void initRequestContext(ServletRequestEvent event) { RequestContext rq = new ServletRequestContext(); rq.setActive(true); requestContexts.set(rq);// set thread local if(event != null) { HttpServletRequest request = (HttpServletRequest) event.getServletRequest(); ((ServletRequestContext)rq).setServletRequest(request); if (request != null) { //Re-initialize thread local for session HttpSession session = request.getSession(false); if(session != null) { initSessionContext(session); } //Init thread local application context initApplicationContext(event.getServletContext()); //Init thread local singleton context initSingletonContext(event.getServletContext()); } } else { //Init thread local application context initApplicationContext(null); //Init thread local singleton context initSingletonContext(null); } } /** * Destroys the request context and all of its components. * @param request http servlet request object */ private void destroyRequestContext(ServletRequestEvent request) { // cleanup open conversations first if (supportsConversation) { cleanupConversations(); } //Get context RequestContext context = getRequestContext(); //Destroy context if (context != null) { context.destroy(); } // clean up the EL caches after each request ELContextStore elStore = ELContextStore.getInstance(false); if (elStore != null) { elStore.destroyELContextStore(); } //Clear thread locals requestContexts.set(null); requestContexts.remove(); RequestScopedBeanInterceptorHandler.removeThreadLocals(); } private void cleanupConversations() { ConversationContext conversationContext = getConversationContext(); if (conversationContext == null) { return; } Conversation conversation = conversationManager.getConversationBeanReference(); if (conversation == null) { return; } if (conversation.isTransient()) { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "Destroying the transient conversation context with cid : [{0}]", conversation.getId()); } destroyConversationContext(); conversationManager.removeConversation(conversation); // in case end() was called } else { //Conversation must be used by one thread at a time ConversationImpl owbConversation = (ConversationImpl)conversation; owbConversation.updateTimeOut(); //Other threads can now access propogated conversation. owbConversation.iDontUseItAnymore(); } } /** * Creates the session context at the session start. * @param session http session object */ private void initSessionContext(HttpSession session) { SessionContext currentSessionContext; if (session == null) { // no session -> create a dummy SessionContext // this is handy if you create asynchronous tasks or // batches which use a 'admin' user. currentSessionContext = new SessionContext(); } else { String sessionId = session.getId(); //Current context currentSessionContext = sessionCtxManager.getSessionContextWithSessionId(sessionId); //No current context if (currentSessionContext == null) { currentSessionContext = new SessionContext(); sessionCtxManager.addNewSessionContext(sessionId, currentSessionContext); } } //Activate currentSessionContext.setActive(true); //Set thread local sessionContexts.set(currentSessionContext); } /** * Destroys the session context and all of its components at the end of the * session. * @param session http session object */ private void destroySessionContext(HttpSession session) { if (session != null) { //Get current session context SessionContext context = sessionContexts.get(); if (context == null) { initSessionContext(session); context = sessionContexts.get(); } //Destroy context if (context != null) { context.destroy(); } //Clear thread locals sessionContexts.set(null); sessionContexts.remove(); //Remove session from manager sessionCtxManager.removeSessionContextWithSessionId(session.getId()); } } /** * Creates the application context at the application startup * @param servletContext servlet context object */ private void initApplicationContext(ServletContext servletContext) { if (servletContext != null && currentApplicationContexts.containsKey(servletContext)) { return; } if (sharedApplicationContext != null && servletContext == null) { return; } ApplicationContext newApplicationContext = new ApplicationContext(); newApplicationContext.setActive(true); if (servletContext != null) { currentApplicationContexts.put(servletContext, newApplicationContext); ClassLoader currentClassLoader = WebBeansUtil.getCurrentClassLoader(); if (!classLoaderToServletContextMapping.containsKey(currentClassLoader)) { classLoaderToServletContextMapping.put(currentClassLoader, servletContext); } } if (sharedApplicationContext == null) { sharedApplicationContext = newApplicationContext; } } /** * Destroys the application context and all of its components at the end of * the application. * @param servletContext servlet context object */ private void destroyApplicationContext(ServletContext servletContext) { //look for thread local //this can be set by initRequestContext ApplicationContext context = null; //Looking the context from saved context //This is used in real web applications if(servletContext != null) { context = currentApplicationContexts.get(servletContext); } //using in tests if(context == null) { context = this.sharedApplicationContext; } //Destroy context if(context != null) { context.destroy(); } //Remove from saved contexts if(servletContext != null) { currentApplicationContexts.remove(servletContext); } //destroyDependents all sessions Collection<SessionContext> allSessionContexts = sessionCtxManager.getAllSessionContexts().values(); if (allSessionContexts != null && allSessionContexts.size() > 0) { for (SessionContext sessionContext : allSessionContexts) { sessionContexts.set(sessionContext); sessionContext.destroy(); sessionContexts.set(null); sessionContexts.remove(); } //Clear map allSessionContexts.clear(); } //destroyDependents all conversations Collection<ConversationContext> allConversationContexts = conversationManager.getAllConversationContexts().values(); if (allConversationContexts != null && allConversationContexts.size() > 0) { for (ConversationContext conversationContext : allConversationContexts) { conversationContexts.set(conversationContext); conversationContext.destroy(); conversationContexts.set(null); conversationContexts.remove(); } //Clear conversations allConversationContexts.clear(); } // this is needed to get rid of ApplicationScoped beans which are cached inside the proxies... webBeansContext.getBeanManagerImpl().clearCacheProxies(); classLoaderToServletContextMapping.remove(WebBeansUtil.getCurrentClassLoader()); } /** * Initialize singleton context. * @param servletContext servlet context */ private void initSingletonContext(ServletContext servletContext) { if (servletContext != null && currentSingletonContexts.containsKey(servletContext)) { return; } if (currentSingletonContexts != null && servletContext == null) { return; } SingletonContext newSingletonContext = new SingletonContext(); newSingletonContext.setActive(true); if (servletContext != null) { currentSingletonContexts.put(servletContext, newSingletonContext); ClassLoader currentClassLoader = WebBeansUtil.getCurrentClassLoader(); if (!classLoaderToServletContextMapping.containsKey(currentClassLoader)) { classLoaderToServletContextMapping.put(currentClassLoader, servletContext); } } if (sharedSingletonContext == null) { sharedSingletonContext = newSingletonContext; } } /** * Destroy singleton context. * @param servletContext servlet context */ private void destroySingletonContext(ServletContext servletContext) { SingletonContext context = null; //look for saved context if(servletContext != null) { context = currentSingletonContexts.get(servletContext); } //using in tests if(context == null) { context = this.sharedSingletonContext; } //context is not null //destroyDependents it if(context != null) { context.destroy(); } //remove it from saved contexts if(servletContext != null) { currentSingletonContexts.remove(servletContext); } classLoaderToServletContextMapping.remove(WebBeansUtil.getCurrentClassLoader()); } /** * Initialize conversation context. * @param context context */ private void initConversationContext(ConversationContext context) { if (context == null) { if(conversationContexts.get() == null) { ConversationContext newContext = new ConversationContext(); newContext.setActive(true); conversationContexts.set(newContext); } else { conversationContexts.get().setActive(true); } } else { context.setActive(true); conversationContexts.set(context); } } /** * Destroy conversation context. */ private void destroyConversationContext() { ConversationContext context = getConversationContext(); if (context != null) { context.destroy(); } conversationContexts.set(null); conversationContexts.remove(); } /** * Workaround for OWB-841 * * @param session The current {@link HttpSession} */ private void destoryAllConversationsForSession(HttpSession session) { Map<Conversation, ConversationContext> conversations = conversationManager.getAndRemoveConversationMapWithSessionId(session.getId()); for (Entry<Conversation, ConversationContext> entry : conversations.entrySet()) { conversationContexts.set(entry.getValue()); entry.getValue().destroy(); conversationContexts.set(null); conversationContexts.remove(); } } /** * Get current request ctx. * @return request context */ private RequestContext getRequestContext() { return requestContexts.get(); } /** * Get current session ctx. * @return session context */ private SessionContext getSessionContext() { SessionContext context = sessionContexts.get(); if (null == context) { lazyStartSessionContext(); context = sessionContexts.get(); } return context; } /** * Get current conversation ctx. * @return conversation context */ private ConversationContext getConversationContext() { return conversationContexts.get(); } private Context lazyStartSessionContext() { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, ">lazyStartSessionContext"); } Context webContext = null; Context context = getCurrentContext(RequestScoped.class); if (context instanceof ServletRequestContext) { ServletRequestContext requestContext = (ServletRequestContext) context; HttpServletRequest servletRequest = requestContext.getServletRequest(); if (null != servletRequest) { // this could be null if there is no active request context try { HttpSession currentSession = servletRequest.getSession(); initSessionContext(currentSession); if (failoverService != null && failoverService.isSupportFailOver()) { failoverService.sessionIsInUse(currentSession); } if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "Lazy SESSION context initialization SUCCESS"); } } catch (Exception e) { logger.log(Level.SEVERE, WebBeansLoggerFacade.constructMessage(OWBLogConst.ERROR_0013, e)); } } else { logger.log(Level.WARNING, "Could NOT lazily initialize session context because NO active request context"); } } else { logger.log(Level.WARNING, "Could NOT lazily initialize session context because of "+context+" RequestContext"); } if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "<lazyStartSessionContext "+ webContext); } return webContext; } /** * This might be needed when you aim to start a new thread in a WebApp. * @param scopeType */ @Override public void activateContext(Class<? extends Annotation> scopeType) { if (scopeType.equals(SessionScoped.class)) { // getSessionContext() implicitely creates and binds the SessionContext // to the current Thread if it doesn't yet exist. getSessionContext().setActive(true); } else { super.activateContext(scopeType); } } }
OWB-1025 implement @Initialized and @Destroyed also for WebContextsService git-svn-id: 6e2e506005f11016269006bf59d22f905406eeba@1672995 13f79535-47bb-0310-9956-ffa450edef68
webbeans-web/src/main/java/org/apache/webbeans/web/context/WebContextsService.java
OWB-1025 implement @Initialized and @Destroyed also for WebContextsService
Java
apache-2.0
14a03b1dd47d710ad1ead30986fb626aac1f32fb
0
jeremylong/DependencyCheck,jeremylong/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,stefanneuhaus/DependencyCheck,stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck
package org.owasp.dependencycheck.analyzer; import org.junit.Assert; import org.junit.Test; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Modifier; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Objects; import java.util.Properties; import java.util.Set; import java.util.stream.Collectors; public class DependencyCheckPropertiesTest { @Test public void should_each_analyzer_have_default_enabled_property() throws IOException, InstantiationException, IllegalAccessException { String packageName = "org.owasp.dependencycheck.analyzer"; Set<Class<AbstractAnalyzer>> analyzerImplementations = findAllAnalyzerImplementations(packageName); Set<String> analyzerEnabledSettingKeys = new HashSet<>(); for (Class<AbstractAnalyzer> analyzerClass : analyzerImplementations) { AbstractAnalyzer analyzer = analyzerClass.newInstance(); String enabledKey = analyzer.getAnalyzerEnabledSettingKey(); analyzerEnabledSettingKeys.add(enabledKey); } Properties properties = new Properties(); Path propertiesPath = Paths.get("src", "main", "resources", "dependencycheck.properties"); try (FileInputStream fis = new FileInputStream(propertiesPath.toFile())) { properties.load(fis); } Assert.assertFalse(analyzerEnabledSettingKeys.isEmpty()); Set<String> absentKeys = analyzerEnabledSettingKeys.stream() .filter(key -> !properties.containsKey(key)) .collect(Collectors.toSet()); Assert.assertTrue(absentKeys.isEmpty()); } public Set<Class<AbstractAnalyzer>> findAllAnalyzerImplementations(String packageName) throws IOException { Set<Class<?>> packageClasses = findAllClasses(packageName); Set<Class<AbstractAnalyzer>> analyzers = new HashSet<>(); for (Class<?> clazz : packageClasses) { if (isAnalyzerImplementation(clazz)) { // We can safely cast due to call to isAnalyzerImplementation() @SuppressWarnings("unchecked") Class<AbstractAnalyzer> abstractAnalyzer = (Class<AbstractAnalyzer>) clazz; analyzers.add(abstractAnalyzer); } } return analyzers; } private boolean isAnalyzerImplementation(Class<?> clazz) { if (isAnAbstractClass(clazz) || isATestAnalyzer(clazz)) { return false; } return AbstractAnalyzer.class.isAssignableFrom(clazz); } private boolean isAnAbstractClass(Class<?> clazz) { return Modifier.isAbstract(clazz.getModifiers()); } private boolean isATestAnalyzer(Class<?> clazz) { return clazz == AbstractSuppressionAnalyzerTest.AbstractSuppressionAnalyzerImpl.class; } public Set<Class<?>> findAllClasses(String packageName) throws IOException { String parsedPackageName = packageName.replaceAll("[.]", File.separator); Set<Class<?>> classes = new HashSet<>(); Enumeration<URL> resources = ClassLoader.getSystemClassLoader().getResources(parsedPackageName); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); classes.addAll(getClasses(resource, packageName)); } return classes; } private Set<Class<?>> getClasses(URL resource, String packageName) throws IOException { if (Objects.nonNull(resource)) { try (InputStream is = resource.openStream(); InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8); BufferedReader reader = new BufferedReader(isr)) { return tryGetClasses(packageName, reader); } } return Collections.emptySet(); } private Set<Class<?>> tryGetClasses(String packageName, BufferedReader reader) { return reader.lines() .filter(line -> line.endsWith(".class")) .map(line -> getClass(line, packageName)) .collect(Collectors.toSet()); } private Class<?> getClass(String className, String packageName) { try { return tryGetClass(className, packageName); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(e); } } private Class<?> tryGetClass(String className, String packageName) throws ClassNotFoundException { return Class.forName(packageName + "." + className.substring(0, className.lastIndexOf('.'))); } }
core/src/test/java/org/owasp/dependencycheck/analyzer/DependencyCheckPropertiesTest.java
package org.owasp.dependencycheck.analyzer; import org.junit.Assert; import org.junit.Test; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Modifier; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Objects; import java.util.Properties; import java.util.Set; import java.util.stream.Collectors; public class DependencyCheckPropertiesTest { @Test public void should_each_analyzer_have_default_enabled_property() throws IOException, InstantiationException, IllegalAccessException { String packageName = "org.owasp.dependencycheck.analyzer"; Set<Class<AbstractAnalyzer>> analyzerImplementations = findAllAnalyzerImplementations(packageName); Set<String> analyzerEnabledSettingKeys = new HashSet<>(); for (Class<AbstractAnalyzer> analyzerClass : analyzerImplementations) { AbstractAnalyzer analyzer = analyzerClass.newInstance(); String enabledKey = analyzer.getAnalyzerEnabledSettingKey(); analyzerEnabledSettingKeys.add(enabledKey); } Properties properties = new Properties(); Path propertiesPath = Paths.get("src", "main", "resources", "dependencycheck.properties"); try (FileInputStream fis = new FileInputStream(propertiesPath.toFile())) { properties.load(fis); } Assert.assertFalse(analyzerEnabledSettingKeys.isEmpty()); Set<String> absentKeys = analyzerEnabledSettingKeys.stream() .filter(key -> !properties.containsKey(key)) .collect(Collectors.toSet()); Assert.assertTrue(absentKeys.isEmpty()); } public Set<Class<AbstractAnalyzer>> findAllAnalyzerImplementations(String packageName) throws IOException { Set<Class<?>> packageClasses = findAllClasses(packageName); Set<Class<AbstractAnalyzer>> analyzers = new HashSet<>(); for (Class<?> clazz : packageClasses) { if (isAnalyzerImplementation(clazz)) { // We can safely cast due to call to isAnalyzerImplementation() @SuppressWarnings("unchecked") Class<AbstractAnalyzer> abstractAnalyzer = (Class<AbstractAnalyzer>) clazz; analyzers.add(abstractAnalyzer); } } return analyzers; } private boolean isAnalyzerImplementation(Class<?> clazz) { if (isAnAbstractClass(clazz) || isATestAnalyzer(clazz)) { return false; } return AbstractAnalyzer.class.isAssignableFrom(clazz); } private boolean isAnAbstractClass(Class<?> clazz) { return Modifier.isAbstract(clazz.getModifiers()); } private boolean isATestAnalyzer(Class<?> clazz) { return clazz == AbstractSuppressionAnalyzerTest.AbstractSuppressionAnalyzerImpl.class; } public Set<Class<?>> findAllClasses(String packageName) throws IOException { String parsedPackageName = packageName.replaceAll("[.]", File.separator); Set<Class<?>> classes = new HashSet<>(); Enumeration<URL> resources = ClassLoader.getSystemClassLoader().getResources(parsedPackageName); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); classes.addAll(getClasses(resource, packageName)); } return classes; } private Set<Class<?>> getClasses(URL resource, String packageName) throws IOException { if (Objects.nonNull(resource)) { try (InputStream is = resource.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader reader = new BufferedReader(isr)) { return tryGetClasses(packageName, reader); } } return Collections.emptySet(); } private Set<Class<?>> tryGetClasses(String packageName, BufferedReader reader) { return reader.lines() .filter(line -> line.endsWith(".class")) .map(line -> getClass(line, packageName)) .collect(Collectors.toSet()); } private Class<?> getClass(String className, String packageName) { try { return tryGetClass(className, packageName); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(e); } } private Class<?> tryGetClass(String className, String packageName) throws ClassNotFoundException { return Class.forName(packageName + "." + className.substring(0, className.lastIndexOf('.'))); } }
CID-338792 Specify encoding of analyzer files
core/src/test/java/org/owasp/dependencycheck/analyzer/DependencyCheckPropertiesTest.java
CID-338792 Specify encoding of analyzer files
Java
apache-2.0
f51f360183b438f17070e35e9e43bb187a5939c5
0
mohanaraosv/commons-ognl,apache/commons-ognl,apache/commons-ognl,mohanaraosv/commons-ognl
package org.apache.commons.ognl; /* * 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. */ import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Implementation of PropertyAccessor that uses numbers and dynamic subscripts as properties to index into Lists. * * @author Luke Blanshard ([email protected]) * @author Drew Davidson ([email protected]) */ public class ListPropertyAccessor extends ObjectPropertyAccessor implements PropertyAccessor { @Override public Object getProperty( Map<String, Object> context, Object target, Object name ) throws OgnlException { List<?> list = (List<?>) target; if ( name instanceof String ) { Object result = null; if ( name.equals( "size" ) ) { result = Integer.valueOf( list.size() ); } else { if ( name.equals( "iterator" ) ) { result = list.iterator(); } else { if ( name.equals( "isEmpty" ) || name.equals( "empty" ) ) { result = list.isEmpty() ? Boolean.TRUE : Boolean.FALSE; } else { result = super.getProperty( context, target, name ); } } } return result; } if ( name instanceof Number ) { return list.get( ( (Number) name ).intValue() ); } if ( name instanceof DynamicSubscript ) { int len = list.size(); switch ( ( (DynamicSubscript) name ).getFlag() ) { case DynamicSubscript.FIRST: { return len > 0 ? list.get( 0 ) : null; } case DynamicSubscript.MID: { return len > 0 ? list.get( len / 2 ) : null; } case DynamicSubscript.LAST: { return len > 0 ? list.get( len - 1 ) : null; } case DynamicSubscript.ALL: { return new ArrayList<Object>( list ); } } } throw new NoSuchPropertyException( target, name ); } @Override public void setProperty( Map<String, Object> context, Object target, Object name, Object value ) throws OgnlException { if ( name instanceof String && ( (String) name ).indexOf( "$" ) < 0 ) { super.setProperty( context, target, name, value ); return; } @SuppressWarnings( "unchecked" ) // check performed by the invoker List<Object> list = (List<Object>) target; if ( name instanceof Number ) { list.set( ( (Number) name ).intValue(), value ); return; } if ( name instanceof DynamicSubscript ) { int len = list.size(); switch ( ( (DynamicSubscript) name ).getFlag() ) { case DynamicSubscript.FIRST: if ( len > 0 ) { list.set( 0, value ); } return; case DynamicSubscript.MID: if ( len > 0 ) { list.set( len / 2, value ); } return; case DynamicSubscript.LAST: if ( len > 0 ) { list.set( len - 1, value ); } return; case DynamicSubscript.ALL: { if ( !( value instanceof Collection ) ) { throw new OgnlException( "Value must be a collection" ); } list.clear(); list.addAll( (Collection<?>) value ); return; } } } throw new NoSuchPropertyException( target, name ); } @Override public Class<?> getPropertyClass( OgnlContext context, Object target, Object index ) { if ( index instanceof String ) { String key = ( (String) index ).replaceAll( "\"", "" ); if ( key.equals( "size" ) ) { return int.class; } if ( key.equals( "iterator" ) ) { return Iterator.class; } if ( key.equals( "isEmpty" ) || key.equals( "empty" ) ) { return boolean.class; } return super.getPropertyClass( context, target, index ); } if ( index instanceof Number ) return Object.class; return null; } @Override public String getSourceAccessor( OgnlContext context, Object target, Object index ) { String indexStr = index.toString().replaceAll( "\"", "" ); if ( String.class.isInstance( index ) ) { if ( indexStr.equals( "size" ) ) { context.setCurrentAccessor( List.class ); context.setCurrentType( int.class ); return ".size()"; } if ( indexStr.equals( "iterator" ) ) { context.setCurrentAccessor( List.class ); context.setCurrentType( Iterator.class ); return ".iterator()"; } if ( indexStr.equals( "isEmpty" ) || indexStr.equals( "empty" ) ) { context.setCurrentAccessor( List.class ); context.setCurrentType( boolean.class ); return ".isEmpty()"; } } // TODO: This feels really inefficient, must be some better way // check if the index string represents a method on a custom class implementing java.util.List instead.. if ( context.getCurrentObject() != null && !Number.class.isInstance( context.getCurrentObject() ) ) { try { Method m = OgnlRuntime.getReadMethod( target.getClass(), indexStr ); if ( m != null ) { return super.getSourceAccessor( context, target, index ); } } catch ( Throwable t ) { throw OgnlOps.castToRuntime( t ); } } context.setCurrentAccessor( List.class ); // need to convert to primitive for list index access // System.out.println("Curent type: " + context.getCurrentType() + " current object type " + // context.getCurrentObject().getClass()); if ( !context.getCurrentType().isPrimitive() && Number.class.isAssignableFrom( context.getCurrentType() ) ) { indexStr += "." + OgnlRuntime.getNumericValueGetter( context.getCurrentType() ); } else if ( context.getCurrentObject() != null && Number.class.isAssignableFrom( context.getCurrentObject().getClass() ) && !context.getCurrentType().isPrimitive() ) { // means it needs to be cast first as well String toString = String.class.isInstance( index ) && context.getCurrentType() != Object.class ? "" : ".toString()"; indexStr = "org.apache.commons.ognl.OgnlOps#getIntValue(" + indexStr + toString + ")"; } context.setCurrentType( Object.class ); return ".get(" + indexStr + ")"; } @Override public String getSourceSetter( OgnlContext context, Object target, Object index ) { String indexStr = index.toString().replaceAll( "\"", "" ); // TODO: This feels really inefficient, must be some better way // check if the index string represents a method on a custom class implementing java.util.List instead.. /* * System.out.println("Listpropertyaccessor setter using index: " + index + " and current object: " + * context.getCurrentObject() + " number is current object? " + * Number.class.isInstance(context.getCurrentObject())); */ if ( context.getCurrentObject() != null && !Number.class.isInstance( context.getCurrentObject() ) ) { try { Method m = OgnlRuntime.getWriteMethod( target.getClass(), indexStr ); if ( m != null || !context.getCurrentType().isPrimitive() ) { System.out.println( "super source setter returned: " + super.getSourceSetter( context, target, index ) ); return super.getSourceSetter( context, target, index ); } } catch ( Throwable t ) { throw OgnlOps.castToRuntime( t ); } } /* * if (String.class.isInstance(index)) { context.setCurrentAccessor(List.class); return ""; } */ context.setCurrentAccessor( List.class ); // need to convert to primitive for list index access if ( !context.getCurrentType().isPrimitive() && Number.class.isAssignableFrom( context.getCurrentType() ) ) { indexStr += "." + OgnlRuntime.getNumericValueGetter( context.getCurrentType() ); } else if ( context.getCurrentObject() != null && Number.class.isAssignableFrom( context.getCurrentObject().getClass() ) && !context.getCurrentType().isPrimitive() ) { // means it needs to be cast first as well String toString = String.class.isInstance( index ) && context.getCurrentType() != Object.class ? "" : ".toString()"; indexStr = "org.apache.commons.ognl.OgnlOps#getIntValue(" + indexStr + toString + ")"; } context.setCurrentType( Object.class ); return ".set(" + indexStr + ", $3)"; } }
src/main/java/org/apache/commons/ognl/ListPropertyAccessor.java
package org.apache.commons.ognl; /* * 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. */ import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Implementation of PropertyAccessor that uses numbers and dynamic subscripts as properties to index into Lists. * * @author Luke Blanshard ([email protected]) * @author Drew Davidson ([email protected]) */ public class ListPropertyAccessor extends ObjectPropertyAccessor implements PropertyAccessor { @Override public Object getProperty( Map<String, Object> context, Object target, Object name ) throws OgnlException { List<?> list = (List<?>) target; if ( name instanceof String ) { Object result = null; if ( name.equals( "size" ) ) { result = Integer.valueOf( list.size() ); } else { if ( name.equals( "iterator" ) ) { result = list.iterator(); } else { if ( name.equals( "isEmpty" ) || name.equals( "empty" ) ) { result = list.isEmpty() ? Boolean.TRUE : Boolean.FALSE; } else { result = super.getProperty( context, target, name ); } } } return result; } if ( name instanceof Number ) { return list.get( ( (Number) name ).intValue() ); } if ( name instanceof DynamicSubscript ) { int len = list.size(); switch ( ( (DynamicSubscript) name ).getFlag() ) { case DynamicSubscript.FIRST: { return len > 0 ? list.get( 0 ) : null; } case DynamicSubscript.MID: { return len > 0 ? list.get( len / 2 ) : null; } case DynamicSubscript.LAST: { return len > 0 ? list.get( len - 1 ) : null; } case DynamicSubscript.ALL: { return new ArrayList( list ); } } } throw new NoSuchPropertyException( target, name ); } @Override public void setProperty( Map<String, Object> context, Object target, Object name, Object value ) throws OgnlException { if ( name instanceof String && ( (String) name ).indexOf( "$" ) < 0 ) { super.setProperty( context, target, name, value ); return; } @SuppressWarnings( "unchecked" ) // check performed by the invoker List<Object> list = (List<Object>) target; if ( name instanceof Number ) { list.set( ( (Number) name ).intValue(), value ); return; } if ( name instanceof DynamicSubscript ) { int len = list.size(); switch ( ( (DynamicSubscript) name ).getFlag() ) { case DynamicSubscript.FIRST: if ( len > 0 ) { list.set( 0, value ); } return; case DynamicSubscript.MID: if ( len > 0 ) { list.set( len / 2, value ); } return; case DynamicSubscript.LAST: if ( len > 0 ) { list.set( len - 1, value ); } return; case DynamicSubscript.ALL: { if ( !( value instanceof Collection ) ) { throw new OgnlException( "Value must be a collection" ); } list.clear(); list.addAll( (Collection<?>) value ); return; } } } throw new NoSuchPropertyException( target, name ); } @Override public Class<?> getPropertyClass( OgnlContext context, Object target, Object index ) { if ( index instanceof String ) { String key = ( (String) index ).replaceAll( "\"", "" ); if ( key.equals( "size" ) ) { return int.class; } if ( key.equals( "iterator" ) ) { return Iterator.class; } if ( key.equals( "isEmpty" ) || key.equals( "empty" ) ) { return boolean.class; } return super.getPropertyClass( context, target, index ); } if ( index instanceof Number ) return Object.class; return null; } @Override public String getSourceAccessor( OgnlContext context, Object target, Object index ) { String indexStr = index.toString().replaceAll( "\"", "" ); if ( String.class.isInstance( index ) ) { if ( indexStr.equals( "size" ) ) { context.setCurrentAccessor( List.class ); context.setCurrentType( int.class ); return ".size()"; } if ( indexStr.equals( "iterator" ) ) { context.setCurrentAccessor( List.class ); context.setCurrentType( Iterator.class ); return ".iterator()"; } if ( indexStr.equals( "isEmpty" ) || indexStr.equals( "empty" ) ) { context.setCurrentAccessor( List.class ); context.setCurrentType( boolean.class ); return ".isEmpty()"; } } // TODO: This feels really inefficient, must be some better way // check if the index string represents a method on a custom class implementing java.util.List instead.. if ( context.getCurrentObject() != null && !Number.class.isInstance( context.getCurrentObject() ) ) { try { Method m = OgnlRuntime.getReadMethod( target.getClass(), indexStr ); if ( m != null ) { return super.getSourceAccessor( context, target, index ); } } catch ( Throwable t ) { throw OgnlOps.castToRuntime( t ); } } context.setCurrentAccessor( List.class ); // need to convert to primitive for list index access // System.out.println("Curent type: " + context.getCurrentType() + " current object type " + // context.getCurrentObject().getClass()); if ( !context.getCurrentType().isPrimitive() && Number.class.isAssignableFrom( context.getCurrentType() ) ) { indexStr += "." + OgnlRuntime.getNumericValueGetter( context.getCurrentType() ); } else if ( context.getCurrentObject() != null && Number.class.isAssignableFrom( context.getCurrentObject().getClass() ) && !context.getCurrentType().isPrimitive() ) { // means it needs to be cast first as well String toString = String.class.isInstance( index ) && context.getCurrentType() != Object.class ? "" : ".toString()"; indexStr = "org.apache.commons.ognl.OgnlOps#getIntValue(" + indexStr + toString + ")"; } context.setCurrentType( Object.class ); return ".get(" + indexStr + ")"; } @Override public String getSourceSetter( OgnlContext context, Object target, Object index ) { String indexStr = index.toString().replaceAll( "\"", "" ); // TODO: This feels really inefficient, must be some better way // check if the index string represents a method on a custom class implementing java.util.List instead.. /* * System.out.println("Listpropertyaccessor setter using index: " + index + " and current object: " + * context.getCurrentObject() + " number is current object? " + * Number.class.isInstance(context.getCurrentObject())); */ if ( context.getCurrentObject() != null && !Number.class.isInstance( context.getCurrentObject() ) ) { try { Method m = OgnlRuntime.getWriteMethod( target.getClass(), indexStr ); if ( m != null || !context.getCurrentType().isPrimitive() ) { System.out.println( "super source setter returned: " + super.getSourceSetter( context, target, index ) ); return super.getSourceSetter( context, target, index ); } } catch ( Throwable t ) { throw OgnlOps.castToRuntime( t ); } } /* * if (String.class.isInstance(index)) { context.setCurrentAccessor(List.class); return ""; } */ context.setCurrentAccessor( List.class ); // need to convert to primitive for list index access if ( !context.getCurrentType().isPrimitive() && Number.class.isAssignableFrom( context.getCurrentType() ) ) { indexStr += "." + OgnlRuntime.getNumericValueGetter( context.getCurrentType() ); } else if ( context.getCurrentObject() != null && Number.class.isAssignableFrom( context.getCurrentObject().getClass() ) && !context.getCurrentType().isPrimitive() ) { // means it needs to be cast first as well String toString = String.class.isInstance( index ) && context.getCurrentType() != Object.class ? "" : ".toString()"; indexStr = "org.apache.commons.ognl.OgnlOps#getIntValue(" + indexStr + toString + ")"; } context.setCurrentType( Object.class ); return ".set(" + indexStr + ", $3)"; } }
fixed ArrayList raw type git-svn-id: 3629b0064825e9d7230d3d0196b9ea5edc1472c8@1125940 13f79535-47bb-0310-9956-ffa450edef68
src/main/java/org/apache/commons/ognl/ListPropertyAccessor.java
fixed ArrayList raw type
Java
apache-2.0
57920b0e63055cfbe4f092fb39697ccde407d36f
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.instrument.MeterRegistry; import io.micrometer.core.instrument.composite.CompositeMeterRegistry; import io.micrometer.jmx.JmxMeterRegistry; import io.micrometer.prometheus.PrometheusMeterRegistry; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @SpringBootTest(classes = CompositeMeterRegistryConfigurationTest.MetricsApp.class) @TestPropertySource(properties = { "management.metrics.export.jmx.enabled=true", "management.metrics.export.prometheus.enabled=true", }) public class CompositeMeterRegistryConfigurationTest { @Autowired private MeterRegistry registry; @Test public void compositeRegistryIsCreated() { assertThat(registry).isInstanceOf(CompositeMeterRegistry.class); assertThat(((CompositeMeterRegistry) registry).getRegistries()) .hasAtLeastOneElementOfType(JmxMeterRegistry.class) .hasAtLeastOneElementOfType(PrometheusMeterRegistry.class); } @SpringBootApplication(scanBasePackages = "ignored") static class MetricsApp { } }
micrometer-spring-legacy/src/test/java/io/micrometer/spring/autoconfigure/CompositeMeterRegistryConfigurationTest.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.instrument.MeterRegistry; import io.micrometer.core.instrument.MockClock; import io.micrometer.core.instrument.composite.CompositeMeterRegistry; import io.micrometer.datadog.DatadogConfig; import io.micrometer.datadog.DatadogMeterRegistry; import io.micrometer.jmx.JmxMeterRegistry; import io.micrometer.prometheus.PrometheusMeterRegistry; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @SpringBootTest(classes = CompositeMeterRegistryConfigurationTest.MetricsApp.class) @TestPropertySource(properties = { "management.metrics.export.jmx.enabled=true", "management.metrics.export.prometheus.enabled=true", }) public class CompositeMeterRegistryConfigurationTest { @Autowired private MeterRegistry registry; @Test public void compositeRegistryIsCreated() { assertThat(registry).isInstanceOf(CompositeMeterRegistry.class); assertThat(((CompositeMeterRegistry) registry).getRegistries()) .hasAtLeastOneElementOfType(JmxMeterRegistry.class) .hasAtLeastOneElementOfType(PrometheusMeterRegistry.class); } @SpringBootApplication(scanBasePackages = "ignored") static class MetricsApp { } }
Fix remove unused imports
micrometer-spring-legacy/src/test/java/io/micrometer/spring/autoconfigure/CompositeMeterRegistryConfigurationTest.java
Fix remove unused imports
Java
apache-2.0
4f5d072a28ecca654eabbc9a88f5a18a51c4e0b3
0
adejanovski/cassandra,project-zerus/cassandra,jrwest/cassandra,asias/cassandra,swps/cassandra,project-zerus/cassandra,leomrocha/cassandra,carlyeks/cassandra,spodkowinski/cassandra,mashuai/Cassandra-Research,DikangGu/cassandra,codefollower/Cassandra-Research,driftx/cassandra,GabrielNicolasAvellaneda/cassandra,rackerlabs/cloudmetrics-cassandra,miguel0afd/cassandra-cqlMod,sbtourist/cassandra,tongjixianing/projects,aweisberg/cassandra,nakomis/cassandra,jeromatron/cassandra,matthewtt/cassandra_read,jasobrown/cassandra,ptnapoleon/cassandra,helena/cassandra,rmarchei/cassandra,rdio/cassandra,jeffjirsa/cassandra,jsanda/cassandra,jrwest/cassandra,asias/cassandra,Bj0rnen/cassandra,macintoshio/cassandra,jasonstack/cassandra,ollie314/cassandra,jasobrown/cassandra,DavidHerzogTU-Berlin/cassandra,ollie314/cassandra,stef1927/cassandra,ibmsoe/cassandra,sivikt/cassandra,pkdevbox/cassandra,jasonwee/cassandra,carlyeks/cassandra,guanxi55nba/db-improvement,fengshao0907/cassandra-1,beobal/cassandra,jrwest/cassandra,nitsanw/cassandra,phact/cassandra,GabrielNicolasAvellaneda/cassandra,spodkowinski/cassandra,jsanda/cassandra,stef1927/cassandra,LatencyUtils/cassandra-stress2,taigetco/cassandra_read,pauloricardomg/cassandra,tjake/cassandra,yonglehou/cassandra,weideng1/cassandra,jeffjirsa/cassandra,Jollyplum/cassandra,beobal/cassandra,rackerlabs/cloudmetrics-cassandra,hhorii/cassandra,josh-mckenzie/cassandra,fengshao0907/Cassandra-Research,bcoverston/apache-hosted-cassandra,knifewine/cassandra,guanxi55nba/key-value-store,instaclustr/cassandra,aureagle/cassandra,dkua/cassandra,clohfink/cassandra,likaiwalkman/cassandra,rackerlabs/cloudmetrics-cassandra,exoscale/cassandra,guanxi55nba/key-value-store,mike-tr-adamson/cassandra,Jollyplum/cassandra,whitepages/cassandra,fengshao0907/Cassandra-Research,scylladb/scylla-tools-java,guard163/cassandra,asias/cassandra,snazy/cassandra,qinjin/mdtc-cassandra,leomrocha/cassandra,tommystendahl/cassandra,pauloricardomg/cassandra,darach/cassandra,DikangGu/cassandra,dongjiaqiang/cassandra,emolsson/cassandra,likaiwalkman/cassandra,adejanovski/cassandra,michaelmior/cassandra,christian-esken/cassandra,yukim/cassandra,adelapena/cassandra,jbellis/cassandra,mt0803/cassandra,codefollower/Cassandra-Research,a-buck/cassandra,scylladb/scylla-tools-java,mkjellman/cassandra,jasobrown/cassandra,Stratio/stratio-cassandra,ifesdjeen/cassandra,chaordic/cassandra,pauloricardomg/cassandra,krummas/cassandra,phact/cassandra,blambov/cassandra,pcmanus/cassandra,shawnkumar/cstargraph,EnigmaCurry/cassandra,pcmanus/cassandra,weipinghe/cassandra,nakomis/cassandra,jkni/cassandra,darach/cassandra,guanxi55nba/key-value-store,pofallon/cassandra,apache/cassandra,kgreav/cassandra,emolsson/cassandra,rmarchei/cassandra,scaledata/cassandra,iamaleksey/cassandra,dkua/cassandra,MasahikoSawada/cassandra,xiongzheng/Cassandra-Research,codefollower/Cassandra-Research,mshuler/cassandra,bpupadhyaya/cassandra,mashuai/Cassandra-Research,thelastpickle/cassandra,josh-mckenzie/cassandra,ejankan/cassandra,scylladb/scylla-tools-java,HidemotoNakada/cassandra-udf,Imran-C/cassandra,bdeggleston/cassandra,caidongyun/cassandra,ptnapoleon/cassandra,mgmuscari/cassandra-cdh4,mambocab/cassandra,pkdevbox/cassandra,jeffjirsa/cassandra,josh-mckenzie/cassandra,DavidHerzogTU-Berlin/cassandra,scylladb/scylla-tools-java,regispl/cassandra,cooldoger/cassandra,ibmsoe/cassandra,sivikt/cassandra,boneill42/cassandra,tjake/cassandra,nutbunnies/cassandra,lalithsuresh/cassandra-c3,guanxi55nba/db-improvement,weipinghe/cassandra,pofallon/cassandra,vramaswamy456/cassandra,apache/cassandra,bpupadhyaya/cassandra,pauloricardomg/cassandra,tongjixianing/projects,wreda/cassandra,mshuler/cassandra,jeromatron/cassandra,mkjellman/cassandra,WorksApplications/cassandra,lalithsuresh/cassandra-c3,yanbit/cassandra,xiongzheng/Cassandra-Research,ejankan/cassandra,vaibhi9/cassandra,carlyeks/cassandra,mheffner/cassandra-1,AtwooTM/cassandra,Stratio/stratio-cassandra,blerer/cassandra,mike-tr-adamson/cassandra,caidongyun/cassandra,jasonwee/cassandra,tongjixianing/projects,cooldoger/cassandra,clohfink/cassandra,sharvanath/cassandra,strapdata/cassandra,heiko-braun/cassandra,aboudreault/cassandra,knifewine/cassandra,driftx/cassandra,bcoverston/cassandra,a-buck/cassandra,rdio/cassandra,jasonstack/cassandra,mkjellman/cassandra,sluk3r/cassandra,Jaumo/cassandra,nvoron23/cassandra,DICL/cassandra,MasahikoSawada/cassandra,Imran-C/cassandra,sriki77/cassandra,yangzhe1991/cassandra,DICL/cassandra,spodkowinski/cassandra,driftx/cassandra,michaelsembwever/cassandra,RyanMagnusson/cassandra,yanbit/cassandra,blambov/cassandra,a-buck/cassandra,pcmanus/cassandra,kgreav/cassandra,sharvanath/cassandra,blambov/cassandra,ibmsoe/cassandra,mheffner/cassandra-1,Stratio/stratio-cassandra,miguel0afd/cassandra-cqlMod,beobal/cassandra,mkjellman/cassandra,bdeggleston/cassandra,tommystendahl/cassandra,RyanMagnusson/cassandra,yukim/cassandra,aarushi12002/cassandra,MasahikoSawada/cassandra,bmel/cassandra,GabrielNicolasAvellaneda/cassandra,dkua/cassandra,mashuai/Cassandra-Research,helena/cassandra,pallavi510/cassandra,Instagram/cassandra,hengxin/cassandra,aboudreault/cassandra,sriki77/cassandra,josh-mckenzie/cassandra,fengshao0907/cassandra-1,knifewine/cassandra,modempachev4/kassandra,xiongzheng/Cassandra-Research,HidemotoNakada/cassandra-udf,mshuler/cassandra,nakomis/cassandra,aweisberg/cassandra,bcoverston/cassandra,hengxin/cassandra,snazy/cassandra,mheffner/cassandra-1,yangzhe1991/cassandra,AtwooTM/cassandra,michaelmior/cassandra,wreda/cassandra,ollie314/cassandra,heiko-braun/cassandra,exoscale/cassandra,sluk3r/cassandra,yonglehou/cassandra,modempachev4/kassandra,JeremiahDJordan/cassandra,Bj0rnen/cassandra,thobbs/cassandra,vaibhi9/cassandra,macintoshio/cassandra,pofallon/cassandra,DICL/cassandra,yhnishi/cassandra,WorksApplications/cassandra,blerer/cassandra,aboudreault/cassandra,szhou1234/cassandra,dprguiuc/Cassandra-Wasef,ifesdjeen/cassandra,dongjiaqiang/cassandra,project-zerus/cassandra,ptnapoleon/cassandra,weideng1/cassandra,weideng1/cassandra,iburmistrov/Cassandra,pkdevbox/cassandra,iburmistrov/Cassandra,jkni/cassandra,sedulam/CASSANDRA-12201,krummas/cassandra,pcn/cassandra-1,qinjin/mdtc-cassandra,LatencyUtils/cassandra-stress2,michaelsembwever/cassandra,Jollyplum/cassandra,ptuckey/cassandra,strapdata/cassandra,iburmistrov/Cassandra,jbellis/cassandra,exoscale/cassandra,miguel0afd/cassandra-cqlMod,mgmuscari/cassandra-cdh4,whitepages/cassandra,tommystendahl/cassandra,DikangGu/cassandra,bmel/cassandra,ejankan/cassandra,matthewtt/cassandra_read,jasonwee/cassandra,jbellis/cassandra,chbatey/cassandra-1,pallavi510/cassandra,rmarchei/cassandra,sharvanath/cassandra,sluk3r/cassandra,JeremiahDJordan/cassandra,Instagram/cassandra,Bj0rnen/cassandra,newrelic-forks/cassandra,blerer/cassandra,blambov/cassandra,adelapena/cassandra,helena/cassandra,WorksApplications/cassandra,sivikt/cassandra,kangkot/stratio-cassandra,regispl/cassandra,gdusbabek/cassandra,swps/cassandra,tommystendahl/cassandra,iamaleksey/cassandra,Stratio/cassandra,strapdata/cassandra,taigetco/cassandra_read,apache/cassandra,heiko-braun/cassandra,snazy/cassandra,christian-esken/cassandra,rogerchina/cassandra,newrelic-forks/cassandra,EnigmaCurry/cassandra,yonglehou/cassandra,dongjiaqiang/cassandra,sedulam/CASSANDRA-12201,chbatey/cassandra-1,ifesdjeen/cassandra,boneill42/cassandra,yukim/cassandra,rdio/cassandra,guanxi55nba/db-improvement,cooldoger/cassandra,mike-tr-adamson/cassandra,likaiwalkman/cassandra,kangkot/stratio-cassandra,pthomaid/cassandra,pcn/cassandra-1,joesiewert/cassandra,bcoverston/apache-hosted-cassandra,rogerchina/cassandra,mike-tr-adamson/cassandra,kangkot/stratio-cassandra,jeromatron/cassandra,gdusbabek/cassandra,fengshao0907/cassandra-1,christian-esken/cassandra,blerer/cassandra,jsanda/cassandra,strapdata/cassandra,jeffjirsa/cassandra,shawnkumar/cstargraph,rogerchina/cassandra,Imran-C/cassandra,matthewtt/cassandra_read,belliottsmith/cassandra,chaordic/cassandra,HidemotoNakada/cassandra-udf,iamaleksey/cassandra,belliottsmith/cassandra,jrwest/cassandra,michaelmior/cassandra,guard163/cassandra,szhou1234/cassandra,yhnishi/cassandra,vaibhi9/cassandra,aureagle/cassandra,bcoverston/cassandra,dprguiuc/Cassandra-Wasef,kangkot/stratio-cassandra,dprguiuc/Cassandra-Wasef,cooldoger/cassandra,hhorii/cassandra,shawnkumar/cstargraph,sayanh/ViewMaintenanceCassandra,qinjin/mdtc-cassandra,aarushi12002/cassandra,yukim/cassandra,szhou1234/cassandra,sbtourist/cassandra,Jaumo/cassandra,aweisberg/cassandra,weipinghe/cassandra,bpupadhyaya/cassandra,yhnishi/cassandra,stef1927/cassandra,kgreav/cassandra,bcoverston/cassandra,Stratio/cassandra,iamaleksey/cassandra,leomrocha/cassandra,macintoshio/cassandra,juiceblender/cassandra,sayanh/ViewMaintenanceCassandra,WorksApplications/cassandra,adelapena/cassandra,nitsanw/cassandra,Instagram/cassandra,LatencyUtils/cassandra-stress2,hhorii/cassandra,EnigmaCurry/cassandra,bcoverston/apache-hosted-cassandra,DavidHerzogTU-Berlin/cassandraToRun,bmel/cassandra,whitepages/cassandra,michaelsembwever/cassandra,jasonstack/cassandra,taigetco/cassandra_read,thelastpickle/cassandra,aweisberg/cassandra,belliottsmith/cassandra,clohfink/cassandra,adelapena/cassandra,bdeggleston/cassandra,scaledata/cassandra,juiceblender/cassandra,sayanh/ViewMaintenanceCassandra,tjake/cassandra,mt0803/cassandra,DavidHerzogTU-Berlin/cassandraToRun,instaclustr/cassandra,chbatey/cassandra-1,sayanh/ViewMaintenanceSupport,nutbunnies/cassandra,michaelsembwever/cassandra,szhou1234/cassandra,Stratio/stratio-cassandra,nvoron23/cassandra,caidongyun/cassandra,mgmuscari/cassandra-cdh4,thobbs/cassandra,darach/cassandra,phact/cassandra,clohfink/cassandra,ben-manes/cassandra,snazy/cassandra,Jaumo/cassandra,Stratio/cassandra,mt0803/cassandra,pthomaid/cassandra,ifesdjeen/cassandra,yanbit/cassandra,boneill42/cassandra,Stratio/stratio-cassandra,hengxin/cassandra,newrelic-forks/cassandra,thelastpickle/cassandra,instaclustr/cassandra,kangkot/stratio-cassandra,spodkowinski/cassandra,jasobrown/cassandra,ptuckey/cassandra,apache/cassandra,instaclustr/cassandra,sbtourist/cassandra,bdeggleston/cassandra,driftx/cassandra,mambocab/cassandra,belliottsmith/cassandra,AtwooTM/cassandra,nitsanw/cassandra,swps/cassandra,tjake/cassandra,juiceblender/cassandra,Instagram/cassandra,joesiewert/cassandra,pallavi510/cassandra,vramaswamy456/cassandra,ben-manes/cassandra,krummas/cassandra,joesiewert/cassandra,RyanMagnusson/cassandra,mambocab/cassandra,regispl/cassandra,pthomaid/cassandra,beobal/cassandra,mshuler/cassandra,pcn/cassandra-1,yangzhe1991/cassandra,adejanovski/cassandra,sriki77/cassandra,lalithsuresh/cassandra-c3,aarushi12002/cassandra,gdusbabek/cassandra,nvoron23/cassandra,vramaswamy456/cassandra,DavidHerzogTU-Berlin/cassandraToRun,wreda/cassandra,ptuckey/cassandra,nlalevee/cassandra,juiceblender/cassandra,thelastpickle/cassandra,sayanh/ViewMaintenanceSupport,jkni/cassandra,krummas/cassandra,nlalevee/cassandra,ben-manes/cassandra,stef1927/cassandra,fengshao0907/Cassandra-Research,kgreav/cassandra,sedulam/CASSANDRA-12201,guard163/cassandra,scaledata/cassandra,JeremiahDJordan/cassandra,DavidHerzogTU-Berlin/cassandra,nutbunnies/cassandra,modempachev4/kassandra,thobbs/cassandra,chaordic/cassandra,nlalevee/cassandra,aureagle/cassandra,emolsson/cassandra
/* * 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.cassandra.tools; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.lang.management.MemoryUsage; import java.net.ConnectException; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.DecimalFormat; import java.util.concurrent.ExecutionException; import java.util.Map.Entry; import java.util.*; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Maps; import org.apache.commons.cli.*; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.service.CacheServiceMBean; import org.apache.cassandra.service.PBSPredictionResult; import org.apache.cassandra.service.PBSPredictorMBean; import org.apache.cassandra.service.StorageProxyMBean; import org.apache.cassandra.concurrent.JMXEnabledThreadPoolExecutorMBean; import org.apache.cassandra.db.ColumnFamilyStoreMBean; import org.apache.cassandra.db.Table; import org.apache.cassandra.db.compaction.CompactionManagerMBean; import org.apache.cassandra.db.compaction.OperationType; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.exceptions.InvalidRequestException; import org.apache.cassandra.io.util.FileUtils; import org.apache.cassandra.locator.EndpointSnitchInfoMBean; import org.apache.cassandra.net.MessagingServiceMBean; import org.apache.cassandra.service.CacheServiceMBean; import org.apache.cassandra.service.StorageProxyMBean; import org.apache.cassandra.utils.EstimatedHistogram; import org.apache.cassandra.utils.Pair; import org.yaml.snakeyaml.Loader; import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; public class NodeCmd { private static final Pair<String, String> SNAPSHOT_COLUMNFAMILY_OPT = Pair.create("cf", "column-family"); private static final Pair<String, String> HOST_OPT = Pair.create("h", "host"); private static final Pair<String, String> PORT_OPT = Pair.create("p", "port"); private static final Pair<String, String> USERNAME_OPT = Pair.create("u", "username"); private static final Pair<String, String> PASSWORD_OPT = Pair.create("pw", "password"); private static final Pair<String, String> TAG_OPT = Pair.create("t", "tag"); private static final Pair<String, String> TOKENS_OPT = Pair.create("T", "tokens"); private static final Pair<String, String> PRIMARY_RANGE_OPT = Pair.create("pr", "partitioner-range"); private static final Pair<String, String> SNAPSHOT_REPAIR_OPT = Pair.create("snapshot", "with-snapshot"); private static final Pair<String, String> LOCAL_DC_REPAIR_OPT = Pair.create("local", "in-local-dc"); private static final String DEFAULT_HOST = "127.0.0.1"; private static final int DEFAULT_PORT = 7199; private static final ToolOptions options = new ToolOptions(); private final NodeProbe probe; static { options.addOption(SNAPSHOT_COLUMNFAMILY_OPT, true, "only take a snapshot of the specified column family"); options.addOption(HOST_OPT, true, "node hostname or ip address"); options.addOption(PORT_OPT, true, "remote jmx agent port number"); options.addOption(USERNAME_OPT, true, "remote jmx agent username"); options.addOption(PASSWORD_OPT, true, "remote jmx agent password"); options.addOption(TAG_OPT, true, "optional name to give a snapshot"); options.addOption(TOKENS_OPT, false, "display all tokens"); options.addOption(PRIMARY_RANGE_OPT, false, "only repair the first range returned by the partitioner for the node"); options.addOption(SNAPSHOT_REPAIR_OPT, false, "repair one node at a time using snapshots"); options.addOption(LOCAL_DC_REPAIR_OPT, false, "only repair against nodes in the same datacenter"); } public NodeCmd(NodeProbe probe) { this.probe = probe; } private enum NodeCommand { CFHISTOGRAMS, CFSTATS, CLEANUP, CLEARSNAPSHOT, COMPACT, COMPACTIONSTATS, DECOMMISSION, DISABLEGOSSIP, DISABLETHRIFT, DRAIN, ENABLEGOSSIP, ENABLETHRIFT, FLUSH, GETCOMPACTIONTHRESHOLD, GETENDPOINTS, GETSSTABLES, GOSSIPINFO, INFO, INVALIDATEKEYCACHE, INVALIDATEROWCACHE, JOIN, MOVE, NETSTATS, PROXYHISTOGRAMS, REBUILD, REFRESH, REMOVETOKEN, REMOVENODE, REPAIR, RING, SCRUB, SETCACHECAPACITY, SETCOMPACTIONTHRESHOLD, SETCOMPACTIONTHROUGHPUT, SETSTREAMTHROUGHPUT, SETTRACEPROBABILITY, SNAPSHOT, STATUS, STATUSTHRIFT, STOP, TPSTATS, UPGRADESSTABLES, VERSION, DESCRIBERING, RANGEKEYSAMPLE, REBUILD_INDEX, RESETLOCALSCHEMA, PREDICTCONSISTENCY } /** * Prints usage information to stdout. */ private static void printUsage() { HelpFormatter hf = new HelpFormatter(); StringBuilder header = new StringBuilder(512); header.append("\nAvailable commands\n"); final NodeToolHelp ntHelp = loadHelp(); for(NodeToolHelp.NodeToolCommand cmd : ntHelp.commands) addCmdHelp(header, cmd); String usage = String.format("java %s --host <arg> <command>%n", NodeCmd.class.getName()); hf.printHelp(usage, "", options, ""); System.out.println(header.toString()); } private static NodeToolHelp loadHelp() { final InputStream is = NodeCmd.class.getClassLoader().getResourceAsStream("org/apache/cassandra/tools/NodeToolHelp.yaml"); assert is != null; try { final Constructor constructor = new Constructor(NodeToolHelp.class); TypeDescription desc = new TypeDescription(NodeToolHelp.class); desc.putListPropertyType("commands", NodeToolHelp.NodeToolCommand.class); final Yaml yaml = new Yaml(new Loader(constructor)); return (NodeToolHelp)yaml.load(is); } finally { FileUtils.closeQuietly(is); } } private static void addCmdHelp(StringBuilder sb, NodeToolHelp.NodeToolCommand cmd) { sb.append(" ").append(cmd.name); // Ghetto indentation (trying, but not too hard, to not look too bad) if (cmd.name.length() <= 20) for (int i = cmd.name.length(); i < 22; ++i) sb.append(" "); sb.append(" - ").append(cmd.help); } /** * Write a textual representation of the Cassandra ring. * * @param outs * the stream to write to */ public void printRing(PrintStream outs, String keyspace) { Map<String, String> tokensToEndpoints = probe.getTokenToEndpointMap(); LinkedHashMultimap<String, String> endpointsToTokens = LinkedHashMultimap.create(); for (Map.Entry<String, String> entry : tokensToEndpoints.entrySet()) endpointsToTokens.put(entry.getValue(), entry.getKey()); String format = "%-16s%-12s%-7s%-8s%-16s%-20s%-44s%n"; // Calculate per-token ownership of the ring Map<InetAddress, Float> ownerships; boolean keyspaceSelected; try { ownerships = probe.effectiveOwnership(keyspace); keyspaceSelected = true; } catch (ConfigurationException ex) { ownerships = probe.getOwnership(); outs.printf("Note: Ownership information does not include topology; for complete information, specify a keyspace%n"); keyspaceSelected = false; } try { outs.println(); Map<String, Map<InetAddress, Float>> perDcOwnerships = Maps.newLinkedHashMap(); // get the different datasets and map to tokens for (Map.Entry<InetAddress, Float> ownership : ownerships.entrySet()) { String dc = probe.getEndpointSnitchInfoProxy().getDatacenter(ownership.getKey().getHostAddress()); if (!perDcOwnerships.containsKey(dc)) perDcOwnerships.put(dc, new LinkedHashMap<InetAddress, Float>()); perDcOwnerships.get(dc).put(ownership.getKey(), ownership.getValue()); } for (Map.Entry<String, Map<InetAddress, Float>> entry : perDcOwnerships.entrySet()) printDc(outs, format, entry.getKey(), endpointsToTokens, keyspaceSelected, entry.getValue()); } catch (UnknownHostException e) { throw new RuntimeException(e); } } private void printDc(PrintStream outs, String format, String dc, LinkedHashMultimap<String, String> endpointsToTokens, boolean keyspaceSelected, Map<InetAddress, Float> filteredOwnerships) { Collection<String> liveNodes = probe.getLiveNodes(); Collection<String> deadNodes = probe.getUnreachableNodes(); Collection<String> joiningNodes = probe.getJoiningNodes(); Collection<String> leavingNodes = probe.getLeavingNodes(); Collection<String> movingNodes = probe.getMovingNodes(); Map<String, String> loadMap = probe.getLoadMap(); outs.println("Datacenter: " + dc); outs.println("=========="); // get the total amount of replicas for this dc and the last token in this dc's ring List<String> tokens = new ArrayList<String>(); float totalReplicas = 0f; String lastToken = ""; for (Map.Entry<InetAddress, Float> entry : filteredOwnerships.entrySet()) { tokens.addAll(endpointsToTokens.get(entry.getKey().getHostAddress())); lastToken = tokens.get(tokens.size() - 1); totalReplicas += entry.getValue(); } if (keyspaceSelected) outs.print("Replicas: " + (int) totalReplicas + "\n\n"); outs.printf(format, "Address", "Rack", "Status", "State", "Load", "Owns", "Token"); if (filteredOwnerships.size() > 1) outs.printf(format, "", "", "", "", "", "", lastToken); else outs.println(); for (Map.Entry<InetAddress, Float> entry : filteredOwnerships.entrySet()) { String endpoint = entry.getKey().getHostAddress(); for (String token : endpointsToTokens.get(endpoint)) { String rack; try { rack = probe.getEndpointSnitchInfoProxy().getRack(endpoint); } catch (UnknownHostException e) { rack = "Unknown"; } String status = liveNodes.contains(endpoint) ? "Up" : deadNodes.contains(endpoint) ? "Down" : "?"; String state = "Normal"; if (joiningNodes.contains(endpoint)) state = "Joining"; else if (leavingNodes.contains(endpoint)) state = "Leaving"; else if (movingNodes.contains(endpoint)) state = "Moving"; String load = loadMap.containsKey(endpoint) ? loadMap.get(endpoint) : "?"; String owns = new DecimalFormat("##0.00%").format(entry.getValue()); outs.printf(format, endpoint, rack, status, state, load, owns, token); } } outs.println(); } private class ClusterStatus { String kSpace = null, format = null; Collection<String> joiningNodes, leavingNodes, movingNodes, liveNodes, unreachableNodes; Map<String, String> loadMap, hostIDMap, tokensToEndpoints; EndpointSnitchInfoMBean epSnitchInfo; PrintStream outs; ClusterStatus(PrintStream outs, String kSpace) { this.kSpace = kSpace; this.outs = outs; joiningNodes = probe.getJoiningNodes(); leavingNodes = probe.getLeavingNodes(); movingNodes = probe.getMovingNodes(); loadMap = probe.getLoadMap(); tokensToEndpoints = probe.getTokenToEndpointMap(); liveNodes = probe.getLiveNodes(); unreachableNodes = probe.getUnreachableNodes(); hostIDMap = probe.getHostIdMap(); epSnitchInfo = probe.getEndpointSnitchInfoProxy(); } private void printStatusLegend() { outs.println("Status=Up/Down"); outs.println("|/ State=Normal/Leaving/Joining/Moving"); } private Map<String, Map<InetAddress, Float>> getOwnershipByDc(Map<InetAddress, Float> ownerships) throws UnknownHostException { Map<String, Map<InetAddress, Float>> ownershipByDc = Maps.newLinkedHashMap(); EndpointSnitchInfoMBean epSnitchInfo = probe.getEndpointSnitchInfoProxy(); for (Map.Entry<InetAddress, Float> ownership : ownerships.entrySet()) { String dc = epSnitchInfo.getDatacenter(ownership.getKey().getHostAddress()); if (!ownershipByDc.containsKey(dc)) ownershipByDc.put(dc, new LinkedHashMap<InetAddress, Float>()); ownershipByDc.get(dc).put(ownership.getKey(), ownership.getValue()); } return ownershipByDc; } private String getFormat(boolean hasEffectiveOwns, boolean isTokenPerNode) { if (format == null) { StringBuffer buf = new StringBuffer(); buf.append("%s%s %-16s %-9s "); // status, address, and load if (!isTokenPerNode) buf.append("%-6s "); // "Tokens" if (hasEffectiveOwns) buf.append("%-16s "); // "Owns (effective)" else buf.append("%-5s "); // "Owns buf.append("%-36s "); // Host ID if (isTokenPerNode) buf.append("%-39s "); // token buf.append("%s%n"); // "Rack" format = buf.toString(); } return format; } private void printNode(String endpoint, Float owns, Map<InetAddress, Float> ownerships, boolean hasEffectiveOwns, boolean isTokenPerNode) throws UnknownHostException { String status, state, load, strOwns, hostID, rack, fmt; fmt = getFormat(hasEffectiveOwns, isTokenPerNode); if (liveNodes.contains(endpoint)) status = "U"; else if (unreachableNodes.contains(endpoint)) status = "D"; else status = "?"; if (joiningNodes.contains(endpoint)) state = "J"; else if (leavingNodes.contains(endpoint)) state = "L"; else if (movingNodes.contains(endpoint)) state = "M"; else state = "N"; load = loadMap.containsKey(endpoint) ? loadMap.get(endpoint) : "?"; strOwns = new DecimalFormat("##0.0%").format(ownerships.get(InetAddress.getByName(endpoint))); hostID = hostIDMap.get(endpoint); rack = epSnitchInfo.getRack(endpoint); if (isTokenPerNode) { outs.printf(fmt, status, state, endpoint, load, strOwns, hostID, probe.getTokens(endpoint).get(0), rack); } else { int tokens = probe.getTokens(endpoint).size(); outs.printf(fmt, status, state, endpoint, load, tokens, strOwns, hostID, rack); } } private void printNodesHeader(boolean hasEffectiveOwns, boolean isTokenPerNode) { String fmt = getFormat(hasEffectiveOwns, isTokenPerNode); String owns = hasEffectiveOwns ? "Owns (effective)" : "Owns"; if (isTokenPerNode) outs.printf(fmt, "-", "-", "Address", "Load", owns, "Host ID", "Token", "Rack"); else outs.printf(fmt, "-", "-", "Address", "Load", "Tokens", owns, "Host ID", "Rack"); } void print() throws UnknownHostException { Map<InetAddress, Float> ownerships; boolean hasEffectiveOwns = false, isTokenPerNode = true; try { ownerships = probe.effectiveOwnership(kSpace); hasEffectiveOwns = true; } catch (ConfigurationException e) { ownerships = probe.getOwnership(); } // More tokens then nodes (aka vnodes)? if (new HashSet<String>(tokensToEndpoints.values()).size() < tokensToEndpoints.keySet().size()) isTokenPerNode = false; // Datacenters for (Map.Entry<String, Map<InetAddress, Float>> dc : getOwnershipByDc(ownerships).entrySet()) { String dcHeader = String.format("Datacenter: %s%n", dc.getKey()); outs.printf(dcHeader); for (int i=0; i < (dcHeader.length() - 1); i++) outs.print('='); outs.println(); printStatusLegend(); printNodesHeader(hasEffectiveOwns, isTokenPerNode); // Nodes for (Map.Entry<InetAddress, Float> entry : dc.getValue().entrySet()) printNode(entry.getKey().getHostAddress(), entry.getValue(), ownerships, hasEffectiveOwns, isTokenPerNode); } } } /** Writes a table of cluster-wide node information to a PrintStream * @throws UnknownHostException */ public void printClusterStatus(PrintStream outs, String keyspace) throws UnknownHostException { new ClusterStatus(outs, keyspace).print(); } public void printThreadPoolStats(PrintStream outs) { outs.printf("%-25s%10s%10s%15s%10s%18s%n", "Pool Name", "Active", "Pending", "Completed", "Blocked", "All time blocked"); Iterator<Map.Entry<String, JMXEnabledThreadPoolExecutorMBean>> threads = probe.getThreadPoolMBeanProxies(); while (threads.hasNext()) { Entry<String, JMXEnabledThreadPoolExecutorMBean> thread = threads.next(); String poolName = thread.getKey(); JMXEnabledThreadPoolExecutorMBean threadPoolProxy = thread.getValue(); outs.printf("%-25s%10s%10s%15s%10s%18s%n", poolName, threadPoolProxy.getActiveCount(), threadPoolProxy.getPendingTasks(), threadPoolProxy.getCompletedTasks(), threadPoolProxy.getCurrentlyBlockedTasks(), threadPoolProxy.getTotalBlockedTasks()); } outs.printf("%n%-20s%10s%n", "Message type", "Dropped"); for (Entry<String, Integer> entry : probe.getDroppedMessages().entrySet()) outs.printf("%-20s%10s%n", entry.getKey(), entry.getValue()); } /** * Write node information. * * @param outs the stream to write to */ public void printInfo(PrintStream outs, ToolCommandLine cmd) { boolean gossipInitialized = probe.isInitialized(); List<String> toks = probe.getTokens(); // If there is just 1 token, print it now like we always have, otherwise, // require that -T/--tokens be passed (that output is potentially verbose). if (toks.size() == 1) outs.printf("%-17s: %s%n", "Token", toks.get(0)); else if (!cmd.hasOption(TOKENS_OPT.left)) outs.printf("%-17s: (invoke with -T/--tokens to see all %d tokens)%n", "Token", toks.size()); outs.printf("%-17s: %s%n", "ID", probe.getLocalHostId()); outs.printf("%-17s: %s%n", "Gossip active", gossipInitialized); outs.printf("%-17s: %s%n", "Thrift active", probe.isThriftServerRunning()); outs.printf("%-17s: %s%n", "Load", probe.getLoadString()); if (gossipInitialized) outs.printf("%-17s: %s%n", "Generation No", probe.getCurrentGenerationNumber()); else outs.printf("%-17s: %s%n", "Generation No", 0); // Uptime long secondsUp = probe.getUptime() / 1000; outs.printf("%-17s: %d%n", "Uptime (seconds)", secondsUp); // Memory usage MemoryUsage heapUsage = probe.getHeapMemoryUsage(); double memUsed = (double)heapUsage.getUsed() / (1024 * 1024); double memMax = (double)heapUsage.getMax() / (1024 * 1024); outs.printf("%-17s: %.2f / %.2f%n", "Heap Memory (MB)", memUsed, memMax); // Data Center/Rack outs.printf("%-17s: %s%n", "Data Center", probe.getDataCenter()); outs.printf("%-17s: %s%n", "Rack", probe.getRack()); // Exceptions outs.printf("%-17s: %s%n", "Exceptions", probe.getExceptionCount()); CacheServiceMBean cacheService = probe.getCacheServiceMBean(); // Key Cache: Hits, Requests, RecentHitRate, SavePeriodInSeconds outs.printf("%-17s: size %d (bytes), capacity %d (bytes), %d hits, %d requests, %.3f recent hit rate, %d save period in seconds%n", "Key Cache", cacheService.getKeyCacheSize(), cacheService.getKeyCacheCapacityInBytes(), cacheService.getKeyCacheHits(), cacheService.getKeyCacheRequests(), cacheService.getKeyCacheRecentHitRate(), cacheService.getKeyCacheSavePeriodInSeconds()); // Row Cache: Hits, Requests, RecentHitRate, SavePeriodInSeconds outs.printf("%-17s: size %d (bytes), capacity %d (bytes), %d hits, %d requests, %.3f recent hit rate, %d save period in seconds%n", "Row Cache", cacheService.getRowCacheSize(), cacheService.getRowCacheCapacityInBytes(), cacheService.getRowCacheHits(), cacheService.getRowCacheRequests(), cacheService.getRowCacheRecentHitRate(), cacheService.getRowCacheSavePeriodInSeconds()); if (toks.size() > 1 && cmd.hasOption(TOKENS_OPT.left)) { for (String tok : toks) outs.printf("%-17s: %s%n", "Token", tok); } } public void printReleaseVersion(PrintStream outs) { outs.println("ReleaseVersion: " + probe.getReleaseVersion()); } public void printNetworkStats(final InetAddress addr, PrintStream outs) { outs.printf("Mode: %s%n", probe.getOperationMode()); Set<InetAddress> hosts = addr == null ? probe.getStreamDestinations() : new HashSet<InetAddress>(){{add(addr);}}; if (hosts.size() == 0) outs.println("Not sending any streams."); for (InetAddress host : hosts) { try { List<String> files = probe.getFilesDestinedFor(host); if (files.size() > 0) { outs.printf("Streaming to: %s%n", host); for (String file : files) outs.printf(" %s%n", file); } else { outs.printf(" Nothing streaming to %s%n", host); } } catch (IOException ex) { outs.printf(" Error retrieving file data for %s%n", host); } } hosts = addr == null ? probe.getStreamSources() : new HashSet<InetAddress>(){{add(addr); }}; if (hosts.size() == 0) outs.println("Not receiving any streams."); for (InetAddress host : hosts) { try { List<String> files = probe.getIncomingFiles(host); if (files.size() > 0) { outs.printf("Streaming from: %s%n", host); for (String file : files) outs.printf(" %s%n", file); } else { outs.printf(" Nothing streaming from %s%n", host); } } catch (IOException ex) { outs.printf(" Error retrieving file data for %s%n", host); } } MessagingServiceMBean ms = probe.msProxy; outs.printf("%-25s", "Pool Name"); outs.printf("%10s", "Active"); outs.printf("%10s", "Pending"); outs.printf("%15s%n", "Completed"); int pending; long completed; pending = 0; for (int n : ms.getCommandPendingTasks().values()) pending += n; completed = 0; for (long n : ms.getCommandCompletedTasks().values()) completed += n; outs.printf("%-25s%10s%10s%15s%n", "Commands", "n/a", pending, completed); pending = 0; for (int n : ms.getResponsePendingTasks().values()) pending += n; completed = 0; for (long n : ms.getResponseCompletedTasks().values()) completed += n; outs.printf("%-25s%10s%10s%15s%n", "Responses", "n/a", pending, completed); } public void printCompactionStats(PrintStream outs) { int compactionThroughput = probe.getCompactionThroughput(); CompactionManagerMBean cm = probe.getCompactionManagerProxy(); outs.println("pending tasks: " + cm.getPendingTasks()); if (cm.getCompactions().size() > 0) outs.printf("%25s%16s%16s%16s%16s%10s%10s%n", "compaction type", "keyspace", "column family", "completed", "total", "unit", "progress"); long remainingBytes = 0; for (Map<String, String> c : cm.getCompactions()) { String percentComplete = new Long(c.get("total")) == 0 ? "n/a" : new DecimalFormat("0.00").format((double) new Long(c.get("completed")) / new Long(c.get("total")) * 100) + "%"; outs.printf("%25s%16s%16s%16s%16s%10s%10s%n", c.get("taskType"), c.get("keyspace"), c.get("columnfamily"), c.get("completed"), c.get("total"), c.get("unit"), percentComplete); if (c.get("taskType").equals(OperationType.COMPACTION.toString())) remainingBytes += (new Long(c.get("total")) - new Long(c.get("completed"))); } long remainingTimeInSecs = compactionThroughput == 0 || remainingBytes == 0 ? -1 : (remainingBytes) / (long) (1024L * 1024L * compactionThroughput); String remainingTime = remainingTimeInSecs < 0 ? "n/a" : String.format("%dh%02dm%02ds", remainingTimeInSecs / 3600, (remainingTimeInSecs % 3600) / 60, (remainingTimeInSecs % 60)); outs.printf("%25s%10s%n", "Active compaction remaining time : ", remainingTime); } public void printColumnFamilyStats(PrintStream outs) { Map <String, List <ColumnFamilyStoreMBean>> cfstoreMap = new HashMap <String, List <ColumnFamilyStoreMBean>>(); // get a list of column family stores Iterator<Map.Entry<String, ColumnFamilyStoreMBean>> cfamilies = probe.getColumnFamilyStoreMBeanProxies(); while (cfamilies.hasNext()) { Entry<String, ColumnFamilyStoreMBean> entry = cfamilies.next(); String tableName = entry.getKey(); ColumnFamilyStoreMBean cfsProxy = entry.getValue(); if (!cfstoreMap.containsKey(tableName)) { List<ColumnFamilyStoreMBean> columnFamilies = new ArrayList<ColumnFamilyStoreMBean>(); columnFamilies.add(cfsProxy); cfstoreMap.put(tableName, columnFamilies); } else { cfstoreMap.get(tableName).add(cfsProxy); } } // print out the table statistics for (Entry<String, List<ColumnFamilyStoreMBean>> entry : cfstoreMap.entrySet()) { String tableName = entry.getKey(); List<ColumnFamilyStoreMBean> columnFamilies = entry.getValue(); long tableReadCount = 0; long tableWriteCount = 0; int tablePendingTasks = 0; double tableTotalReadTime = 0.0f; double tableTotalWriteTime = 0.0f; outs.println("Keyspace: " + tableName); for (ColumnFamilyStoreMBean cfstore : columnFamilies) { long writeCount = cfstore.getWriteCount(); long readCount = cfstore.getReadCount(); if (readCount > 0) { tableReadCount += readCount; tableTotalReadTime += cfstore.getTotalReadLatencyMicros(); } if (writeCount > 0) { tableWriteCount += writeCount; tableTotalWriteTime += cfstore.getTotalWriteLatencyMicros(); } tablePendingTasks += cfstore.getPendingTasks(); } double tableReadLatency = tableReadCount > 0 ? tableTotalReadTime / tableReadCount / 1000 : Double.NaN; double tableWriteLatency = tableWriteCount > 0 ? tableTotalWriteTime / tableWriteCount / 1000 : Double.NaN; outs.println("\tRead Count: " + tableReadCount); outs.println("\tRead Latency: " + String.format("%s", tableReadLatency) + " ms."); outs.println("\tWrite Count: " + tableWriteCount); outs.println("\tWrite Latency: " + String.format("%s", tableWriteLatency) + " ms."); outs.println("\tPending Tasks: " + tablePendingTasks); // print out column family statistics for this table for (ColumnFamilyStoreMBean cfstore : columnFamilies) { outs.println("\t\tColumn Family: " + cfstore.getColumnFamilyName()); outs.println("\t\tSSTable count: " + cfstore.getLiveSSTableCount()); int[] leveledSStables = cfstore.getSSTableCountPerLevel(); if (leveledSStables != null) { outs.print("\t\tSSTables in each level: ["); for (int level = 0; level < leveledSStables.length; level++) { int count = leveledSStables[level]; outs.print(count); long maxCount = 4L; // for L0 if (level > 0) maxCount = (long) Math.pow(10, level); // show max threshold for level when exceeded if (count > maxCount) outs.print("/" + maxCount); if (level < leveledSStables.length - 1) outs.print(", "); else outs.println("]"); } } outs.println("\t\tSpace used (live): " + cfstore.getLiveDiskSpaceUsed()); outs.println("\t\tSpace used (total): " + cfstore.getTotalDiskSpaceUsed()); outs.println("\t\tNumber of Keys (estimate): " + cfstore.estimateKeys()); outs.println("\t\tMemtable Columns Count: " + cfstore.getMemtableColumnsCount()); outs.println("\t\tMemtable Data Size: " + cfstore.getMemtableDataSize()); outs.println("\t\tMemtable Switch Count: " + cfstore.getMemtableSwitchCount()); outs.println("\t\tRead Count: " + cfstore.getReadCount()); outs.println("\t\tRead Latency: " + String.format("%01.3f", cfstore.getRecentReadLatencyMicros() / 1000) + " ms."); outs.println("\t\tWrite Count: " + cfstore.getWriteCount()); outs.println("\t\tWrite Latency: " + String.format("%01.3f", cfstore.getRecentWriteLatencyMicros() / 1000) + " ms."); outs.println("\t\tPending Tasks: " + cfstore.getPendingTasks()); outs.println("\t\tBloom Filter False Positives: " + cfstore.getBloomFilterFalsePositives()); outs.println("\t\tBloom Filter False Ratio: " + String.format("%01.5f", cfstore.getRecentBloomFilterFalseRatio())); outs.println("\t\tBloom Filter Space Used: " + cfstore.getBloomFilterDiskSpaceUsed()); outs.println("\t\tCompacted row minimum size: " + cfstore.getMinRowSize()); outs.println("\t\tCompacted row maximum size: " + cfstore.getMaxRowSize()); outs.println("\t\tCompacted row mean size: " + cfstore.getMeanRowSize()); outs.println(""); } outs.println("----------------"); } } public void printRemovalStatus(PrintStream outs) { outs.println("RemovalStatus: " + probe.getRemovalStatus()); } private void printCfHistograms(String keySpace, String columnFamily, PrintStream output) { ColumnFamilyStoreMBean store = this.probe.getCfsProxy(keySpace, columnFamily); // default is 90 offsets long[] offsets = new EstimatedHistogram().getBucketOffsets(); long[] rrlh = store.getRecentReadLatencyHistogramMicros(); long[] rwlh = store.getRecentWriteLatencyHistogramMicros(); long[] sprh = store.getRecentSSTablesPerReadHistogram(); long[] ersh = store.getEstimatedRowSizeHistogram(); long[] ecch = store.getEstimatedColumnCountHistogram(); output.println(String.format("%s/%s histograms", keySpace, columnFamily)); output.println(String.format("%-10s%10s%18s%18s%18s%18s", "Offset", "SSTables", "Write Latency", "Read Latency", "Row Size", "Column Count")); for (int i = 0; i < offsets.length; i++) { output.println(String.format("%-10d%10s%18s%18s%18s%18s", offsets[i], (i < sprh.length ? sprh[i] : "0"), (i < rwlh.length ? rwlh[i] : "0"), (i < rrlh.length ? rrlh[i] : "0"), (i < ersh.length ? ersh[i] : "0"), (i < ecch.length ? ecch[i] : "0"))); } } private void printProxyHistograms(PrintStream output) { StorageProxyMBean sp = this.probe.getSpProxy(); long[] offsets = new EstimatedHistogram().getBucketOffsets(); long[] rrlh = sp.getRecentReadLatencyHistogramMicros(); long[] rwlh = sp.getRecentWriteLatencyHistogramMicros(); long[] rrnglh = sp.getRecentRangeLatencyHistogramMicros(); output.println("proxy histograms"); output.println(String.format("%-10s%18s%18s%18s", "Offset", "Read Latency", "Write Latency", "Range Latency")); for (int i = 0; i < offsets.length; i++) { output.println(String.format("%-10d%18s%18s%18s", offsets[i], (i < rrlh.length ? rrlh[i] : "0"), (i < rwlh.length ? rwlh[i] : "0"), (i < rrnglh.length ? rrnglh[i] : "0"))); } } private void printEndPoints(String keySpace, String cf, String key, PrintStream output) { List<InetAddress> endpoints = this.probe.getEndpoints(keySpace, cf, key); for (InetAddress anEndpoint : endpoints) { output.println(anEndpoint.getHostAddress()); } } private void printSSTables(String keyspace, String cf, String key, PrintStream output) { List<String> sstables = this.probe.getSSTables(keyspace, cf, key); for (String sstable : sstables) { output.println(sstable); } } private void printIsThriftServerRunning(PrintStream outs) { outs.println(probe.isThriftServerRunning() ? "running" : "not running"); } public void predictConsistency(Integer replicationFactor, Integer timeAfterWrite, Integer numVersions, Float percentileLatency, PrintStream output) { PBSPredictorMBean predictorMBean = probe.getPBSPredictorMBean(); for(int r = 1; r <= replicationFactor; ++r) { for(int w = 1; w <= replicationFactor; ++w) { if(w+r > replicationFactor+1) continue; try { PBSPredictionResult result = predictorMBean.doPrediction(replicationFactor, r, w, timeAfterWrite, numVersions, percentileLatency); if(r == 1 && w == 1) { output.printf("%dms after a given write, with maximum version staleness of k=%d%n", timeAfterWrite, numVersions); } output.printf("N=%d, R=%d, W=%d%n", replicationFactor, r, w); output.printf("Probability of consistent reads: %f%n", result.getConsistencyProbability()); output.printf("Average read latency: %fms (%.3fth %%ile %dms)%n", result.getAverageReadLatency(), result.getPercentileReadLatencyPercentile()*100, result.getPercentileReadLatencyValue()); output.printf("Average write latency: %fms (%.3fth %%ile %dms)%n%n", result.getAverageWriteLatency(), result.getPercentileWriteLatencyPercentile()*100, result.getPercentileWriteLatencyValue()); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); return; } } } } public static void main(String[] args) throws IOException, InterruptedException, ConfigurationException, ParseException { CommandLineParser parser = new PosixParser(); ToolCommandLine cmd = null; try { cmd = new ToolCommandLine(parser.parse(options, args)); } catch (ParseException p) { badUse(p.getMessage()); } String host = cmd.hasOption(HOST_OPT.left) ? cmd.getOptionValue(HOST_OPT.left) : DEFAULT_HOST; int port = DEFAULT_PORT; String portNum = cmd.getOptionValue(PORT_OPT.left); if (portNum != null) { try { port = Integer.parseInt(portNum); } catch (NumberFormatException e) { throw new ParseException("Port must be a number"); } } String username = cmd.getOptionValue(USERNAME_OPT.left); String password = cmd.getOptionValue(PASSWORD_OPT.left); NodeProbe probe = null; try { probe = username == null ? new NodeProbe(host, port) : new NodeProbe(host, port, username, password); } catch (IOException ioe) { Throwable inner = findInnermostThrowable(ioe); if (inner instanceof ConnectException) { System.err.printf("Failed to connect to '%s:%d': %s%n", host, port, inner.getMessage()); System.exit(1); } else if (inner instanceof UnknownHostException) { System.err.printf("Cannot resolve '%s': unknown host%n", host); System.exit(1); } else { err(ioe, "Error connecting to remote JMX agent!"); } } try { NodeCommand command = null; try { command = cmd.getCommand(); } catch (IllegalArgumentException e) { badUse(e.getMessage()); } NodeCmd nodeCmd = new NodeCmd(probe); // Execute the requested command. String[] arguments = cmd.getCommandArguments(); String tag; String columnFamilyName = null; switch (command) { case RING : if (arguments.length > 0) { nodeCmd.printRing(System.out, arguments[0]); } else { nodeCmd.printRing(System.out, null); }; break; case INFO : nodeCmd.printInfo(System.out, cmd); break; case CFSTATS : nodeCmd.printColumnFamilyStats(System.out); break; case TPSTATS : nodeCmd.printThreadPoolStats(System.out); break; case VERSION : nodeCmd.printReleaseVersion(System.out); break; case COMPACTIONSTATS : nodeCmd.printCompactionStats(System.out); break; case DISABLEGOSSIP : probe.stopGossiping(); break; case ENABLEGOSSIP : probe.startGossiping(); break; case DISABLETHRIFT : probe.stopThriftServer(); break; case ENABLETHRIFT : probe.startThriftServer(); break; case STATUSTHRIFT : nodeCmd.printIsThriftServerRunning(System.out); break; case RESETLOCALSCHEMA: probe.resetLocalSchema(); break; case STATUS : if (arguments.length > 0) nodeCmd.printClusterStatus(System.out, arguments[0]); else nodeCmd.printClusterStatus(System.out, null); break; case DECOMMISSION : if (arguments.length > 0) { System.err.println("Decommission will decommission the node you are connected to and does not take arguments!"); System.exit(1); } probe.decommission(); break; case DRAIN : try { probe.drain(); } catch (ExecutionException ee) { err(ee, "Error occured during flushing"); } break; case NETSTATS : if (arguments.length > 0) { nodeCmd.printNetworkStats(InetAddress.getByName(arguments[0]), System.out); } else { nodeCmd.printNetworkStats(null, System.out); } break; case SNAPSHOT : columnFamilyName = cmd.getOptionValue(SNAPSHOT_COLUMNFAMILY_OPT.left); /* FALL THRU */ case CLEARSNAPSHOT : tag = cmd.getOptionValue(TAG_OPT.left); handleSnapshots(command, tag, arguments, columnFamilyName, probe); break; case MOVE : if (arguments.length != 1) { badUse("Missing token argument for move."); } try { probe.move(arguments[0]); } catch (UnsupportedOperationException uoerror) { System.err.println(uoerror.getMessage()); System.exit(1); } break; case JOIN: if (probe.isJoined()) { System.err.println("This node has already joined the ring."); System.exit(1); } probe.joinRing(); break; case SETCOMPACTIONTHROUGHPUT : if (arguments.length != 1) { badUse("Missing value argument."); } probe.setCompactionThroughput(Integer.parseInt(arguments[0])); break; case SETSTREAMTHROUGHPUT : if (arguments.length != 1) { badUse("Missing value argument."); } probe.setStreamThroughput(Integer.parseInt(arguments[0])); break; case SETTRACEPROBABILITY : if (arguments.length != 1) { badUse("Missing value argument."); } probe.setTraceProbability(Double.parseDouble(arguments[0])); break; case REBUILD : if (arguments.length > 1) { badUse("Too many arguments."); } probe.rebuild(arguments.length == 1 ? arguments[0] : null); break; case REMOVETOKEN : System.err.println("Warn: removetoken is deprecated, please use removenode instead"); case REMOVENODE : if (arguments.length != 1) { badUse("Missing an argument for removenode (either status, force, or an ID)"); } else if (arguments[0].equals("status")) { nodeCmd.printRemovalStatus(System.out); } else if (arguments[0].equals("force")) { nodeCmd.printRemovalStatus(System.out); probe.forceRemoveCompletion(); } else { probe.removeNode(arguments[0]); } break; case INVALIDATEKEYCACHE : probe.invalidateKeyCache(); break; case INVALIDATEROWCACHE : probe.invalidateRowCache(); break; case CLEANUP : case COMPACT : case REPAIR : case FLUSH : case SCRUB : case UPGRADESSTABLES : optionalKSandCFs(command, cmd, arguments, probe); break; case GETCOMPACTIONTHRESHOLD : if (arguments.length != 2) { badUse("getcompactionthreshold requires ks and cf args."); } probe.getCompactionThreshold(System.out, arguments[0], arguments[1]); break; case CFHISTOGRAMS : if (arguments.length != 2) { badUse("cfhistograms requires ks and cf args"); } nodeCmd.printCfHistograms(arguments[0], arguments[1], System.out); break; case SETCACHECAPACITY : if (arguments.length != 2) { badUse("setcachecapacity requires key-cache-capacity, and row-cache-capacity args."); } probe.setCacheCapacities(Integer.parseInt(arguments[0]), Integer.parseInt(arguments[1])); break; case SETCOMPACTIONTHRESHOLD : if (arguments.length != 4) { badUse("setcompactionthreshold requires ks, cf, min, and max threshold args."); } int minthreshold = Integer.parseInt(arguments[2]); int maxthreshold = Integer.parseInt(arguments[3]); if ((minthreshold < 0) || (maxthreshold < 0)) { badUse("Thresholds must be positive integers"); } if (minthreshold > maxthreshold) { badUse("Min threshold cannot be greater than max."); } if (minthreshold < 2 && maxthreshold != 0) { badUse("Min threshold must be at least 2"); } probe.setCompactionThreshold(arguments[0], arguments[1], minthreshold, maxthreshold); break; case GETENDPOINTS : if (arguments.length != 3) { badUse("getendpoints requires ks, cf and key args"); } nodeCmd.printEndPoints(arguments[0], arguments[1], arguments[2], System.out); break; case PROXYHISTOGRAMS : if (arguments.length != 0) { badUse("proxyhistograms does not take arguments"); } nodeCmd.printProxyHistograms(System.out); break; case GETSSTABLES: if (arguments.length != 3) { badUse("getsstables requires ks, cf and key args"); } nodeCmd.printSSTables(arguments[0], arguments[1], arguments[2], System.out); break; case REFRESH: if (arguments.length != 2) { badUse("load_new_sstables requires ks and cf args"); } probe.loadNewSSTables(arguments[0], arguments[1]); break; case REBUILD_INDEX: if (arguments.length < 2) { badUse("rebuild_index requires ks and cf args"); } if (arguments.length >= 3) probe.rebuildIndex(arguments[0], arguments[1], arguments[2].split(",")); else probe.rebuildIndex(arguments[0], arguments[1]); break; case GOSSIPINFO : nodeCmd.printGossipInfo(System.out); break; case STOP: if (arguments.length != 1) { badUse("stop requires a type."); } probe.stop(arguments[0].toUpperCase()); break; case DESCRIBERING : if (arguments.length != 1) { badUse("Missing keyspace argument for describering."); } nodeCmd.printDescribeRing(arguments[0], System.out); break; case RANGEKEYSAMPLE : nodeCmd.printRangeKeySample(System.out); break; case PREDICTCONSISTENCY: if (arguments.length < 2) { badUse("Requires replication factor and time"); } int numVersions = 1; if (arguments.length == 3) { numVersions = Integer.parseInt(arguments[2]); } float percentileLatency = .999f; if (arguments.length == 4) { percentileLatency = Float.parseFloat(arguments[3]); } nodeCmd.predictConsistency(Integer.parseInt(arguments[0]), Integer.parseInt(arguments[1]), numVersions, percentileLatency, System.out); break; default : throw new RuntimeException("Unreachable code."); } } finally { if (probe != null) { try { probe.close(); } catch (IOException ex) { // swallow the exception so the user will see the real one. } } } System.exit(0); } private static Throwable findInnermostThrowable(Throwable ex) { Throwable inner = ex.getCause(); return inner == null ? ex : findInnermostThrowable(inner); } private void printDescribeRing(String keyspaceName, PrintStream out) { out.println("Schema Version:" + probe.getSchemaVersion()); out.println("TokenRange: "); try { for (String tokenRangeString : probe.describeRing(keyspaceName)) { out.println("\t" + tokenRangeString); } } catch (InvalidRequestException e) { err(e, e.getMessage()); } } private void printRangeKeySample(PrintStream outs) { outs.println("RangeKeySample: "); List<String> tokenStrings = this.probe.sampleKeyRange(); for (String tokenString : tokenStrings) { outs.println("\t" + tokenString); } } private void printGossipInfo(PrintStream out) { out.println(probe.getGossipInfo()); } private static void badUse(String useStr) { System.err.println(useStr); printUsage(); System.exit(1); } private static void err(Exception e, String errStr) { System.err.println(errStr); e.printStackTrace(); System.exit(3); } private static void complainNonzeroArgs(String[] args, NodeCommand cmd) { if (args.length > 0) { System.err.println("Too many arguments for command '"+cmd.toString()+"'."); printUsage(); System.exit(1); } } private static void handleSnapshots(NodeCommand nc, String tag, String[] cmdArgs, String columnFamily, NodeProbe probe) throws InterruptedException, IOException { String[] keyspaces = Arrays.copyOfRange(cmdArgs, 0, cmdArgs.length); System.out.print("Requested snapshot for: "); if ( keyspaces.length > 0 ) { for (int i = 0; i < keyspaces.length; i++) System.out.print(keyspaces[i] + " "); } else { System.out.print("all keyspaces "); } if (columnFamily != null) { System.out.print("and column family: " + columnFamily); } System.out.println(); switch (nc) { case SNAPSHOT : if (tag == null || tag.equals("")) tag = new Long(System.currentTimeMillis()).toString(); probe.takeSnapshot(tag, columnFamily, keyspaces); System.out.println("Snapshot directory: " + tag); break; case CLEARSNAPSHOT : probe.clearSnapshot(tag, keyspaces); break; } } private static void optionalKSandCFs(NodeCommand nc, ToolCommandLine cmd, String[] cmdArgs, NodeProbe probe) throws InterruptedException, IOException { // if there is one additional arg, it's the keyspace; more are columnfamilies List<String> keyspaces = cmdArgs.length == 0 ? probe.getKeyspaces() : Arrays.asList(cmdArgs[0]); for (String keyspace : keyspaces) { if (!probe.getKeyspaces().contains(keyspace)) { System.err.println("Keyspace [" + keyspace + "] does not exist."); System.exit(1); } } // second loop so we're less likely to die halfway through due to invalid keyspace for (String keyspace : keyspaces) { String[] columnFamilies = cmdArgs.length <= 1 ? new String[0] : Arrays.copyOfRange(cmdArgs, 1, cmdArgs.length); switch (nc) { case REPAIR : boolean snapshot = cmd.hasOption(SNAPSHOT_REPAIR_OPT.left); boolean localDC = cmd.hasOption(LOCAL_DC_REPAIR_OPT.left); if (cmd.hasOption(PRIMARY_RANGE_OPT.left)) probe.forceTableRepairPrimaryRange(keyspace, snapshot, localDC, columnFamilies); else probe.forceTableRepair(keyspace, snapshot, localDC, columnFamilies); break; case FLUSH : try { probe.forceTableFlush(keyspace, columnFamilies); } catch (ExecutionException ee) { err(ee, "Error occured during flushing"); } break; case COMPACT : try { probe.forceTableCompaction(keyspace, columnFamilies); } catch (ExecutionException ee) { err(ee, "Error occured during compaction"); } break; case CLEANUP : if (keyspace.equals(Table.SYSTEM_KS)) { break; } // Skip cleanup on system cfs. try { probe.forceTableCleanup(keyspace, columnFamilies); } catch (ExecutionException ee) { err(ee, "Error occured during cleanup"); } break; case SCRUB : try { probe.scrub(keyspace, columnFamilies); } catch (ExecutionException ee) { err(ee, "Error occured while scrubbing keyspace " + keyspace); } break; case UPGRADESSTABLES : try { probe.upgradeSSTables(keyspace, columnFamilies); } catch (ExecutionException ee) { err(ee, "Error occured while upgrading the sstables for keyspace " + keyspace); } break; default: throw new RuntimeException("Unreachable code."); } } } private static class ToolOptions extends Options { public void addOption(Pair<String, String> opts, boolean hasArgument, String description) { addOption(opts, hasArgument, description, false); } public void addOption(Pair<String, String> opts, boolean hasArgument, String description, boolean required) { addOption(opts.left, opts.right, hasArgument, description, required); } public void addOption(String opt, String longOpt, boolean hasArgument, String description, boolean required) { Option option = new Option(opt, longOpt, hasArgument, description); option.setRequired(required); addOption(option); } } private static class ToolCommandLine { private final CommandLine commandLine; public ToolCommandLine(CommandLine commands) { commandLine = commands; } public Option[] getOptions() { return commandLine.getOptions(); } public boolean hasOption(String opt) { return commandLine.hasOption(opt); } public String getOptionValue(String opt) { return commandLine.getOptionValue(opt); } public NodeCommand getCommand() { if (commandLine.getArgs().length == 0) throw new IllegalArgumentException("Command was not specified."); String command = commandLine.getArgs()[0]; try { return NodeCommand.valueOf(command.toUpperCase()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Unrecognized command: " + command); } } public String[] getCommandArguments() { List params = commandLine.getArgList(); if (params.size() < 2) // command parameters are empty return new String[0]; String[] toReturn = new String[params.size() - 1]; for (int i = 1; i < params.size(); i++) toReturn[i - 1] = (String) params.get(i); return toReturn; } } }
src/java/org/apache/cassandra/tools/NodeCmd.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.cassandra.tools; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.lang.management.MemoryUsage; import java.net.ConnectException; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.DecimalFormat; import java.util.concurrent.ExecutionException; import java.util.Map.Entry; import java.util.*; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Maps; import org.apache.commons.cli.*; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.service.CacheServiceMBean; import org.apache.cassandra.service.PBSPredictionResult; import org.apache.cassandra.service.PBSPredictorMBean; import org.apache.cassandra.service.StorageProxyMBean; import org.apache.cassandra.concurrent.JMXEnabledThreadPoolExecutorMBean; import org.apache.cassandra.db.ColumnFamilyStoreMBean; import org.apache.cassandra.db.Table; import org.apache.cassandra.db.compaction.CompactionManagerMBean; import org.apache.cassandra.db.compaction.OperationType; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.exceptions.InvalidRequestException; import org.apache.cassandra.io.util.FileUtils; import org.apache.cassandra.locator.EndpointSnitchInfoMBean; import org.apache.cassandra.net.MessagingServiceMBean; import org.apache.cassandra.service.CacheServiceMBean; import org.apache.cassandra.service.StorageProxyMBean; import org.apache.cassandra.utils.EstimatedHistogram; import org.apache.cassandra.utils.Pair; import org.yaml.snakeyaml.Loader; import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; public class NodeCmd { private static final Pair<String, String> SNAPSHOT_COLUMNFAMILY_OPT = Pair.create("cf", "column-family"); private static final Pair<String, String> HOST_OPT = Pair.create("h", "host"); private static final Pair<String, String> PORT_OPT = Pair.create("p", "port"); private static final Pair<String, String> USERNAME_OPT = Pair.create("u", "username"); private static final Pair<String, String> PASSWORD_OPT = Pair.create("pw", "password"); private static final Pair<String, String> TAG_OPT = Pair.create("t", "tag"); private static final Pair<String, String> TOKENS_OPT = Pair.create("T", "tokens"); private static final Pair<String, String> PRIMARY_RANGE_OPT = Pair.create("pr", "partitioner-range"); private static final Pair<String, String> SNAPSHOT_REPAIR_OPT = Pair.create("snapshot", "with-snapshot"); private static final Pair<String, String> LOCAL_DC_REPAIR_OPT = Pair.create("local", "in-local-dc"); private static final String DEFAULT_HOST = "127.0.0.1"; private static final int DEFAULT_PORT = 7199; private static final ToolOptions options = new ToolOptions(); private final NodeProbe probe; static { options.addOption(SNAPSHOT_COLUMNFAMILY_OPT, true, "only take a snapshot of the specified column family"); options.addOption(HOST_OPT, true, "node hostname or ip address"); options.addOption(PORT_OPT, true, "remote jmx agent port number"); options.addOption(USERNAME_OPT, true, "remote jmx agent username"); options.addOption(PASSWORD_OPT, true, "remote jmx agent password"); options.addOption(TAG_OPT, true, "optional name to give a snapshot"); options.addOption(TOKENS_OPT, false, "display all tokens"); options.addOption(PRIMARY_RANGE_OPT, false, "only repair the first range returned by the partitioner for the node"); options.addOption(SNAPSHOT_REPAIR_OPT, false, "repair one node at a time using snapshots"); options.addOption(LOCAL_DC_REPAIR_OPT, false, "only repair against nodes in the same datacenter"); } public NodeCmd(NodeProbe probe) { this.probe = probe; } private enum NodeCommand { CFHISTOGRAMS, CFSTATS, CLEANUP, CLEARSNAPSHOT, COMPACT, COMPACTIONSTATS, DECOMMISSION, DISABLEGOSSIP, DISABLETHRIFT, DRAIN, ENABLEGOSSIP, ENABLETHRIFT, FLUSH, GETCOMPACTIONTHRESHOLD, GETENDPOINTS, GETSSTABLES, GOSSIPINFO, INFO, INVALIDATEKEYCACHE, INVALIDATEROWCACHE, JOIN, MOVE, NETSTATS, PROXYHISTOGRAMS, REBUILD, REFRESH, REMOVETOKEN, REMOVENODE, REPAIR, RING, SCRUB, SETCACHECAPACITY, SETCOMPACTIONTHRESHOLD, SETCOMPACTIONTHROUGHPUT, SETSTREAMTHROUGHPUT, SETTRACEPROBABILITY, SNAPSHOT, STATUS, STATUSTHRIFT, STOP, TPSTATS, UPGRADESSTABLES, VERSION, DESCRIBERING, RANGEKEYSAMPLE, REBUILD_INDEX, RESETLOCALSCHEMA, PREDICTCONSISTENCY } /** * Prints usage information to stdout. */ private static void printUsage() { HelpFormatter hf = new HelpFormatter(); StringBuilder header = new StringBuilder(512); header.append("\nAvailable commands\n"); final NodeToolHelp ntHelp = loadHelp(); for(NodeToolHelp.NodeToolCommand cmd : ntHelp.commands) addCmdHelp(header, cmd); String usage = String.format("java %s --host <arg> <command>%n", NodeCmd.class.getName()); hf.printHelp(usage, "", options, ""); System.out.println(header.toString()); } private static NodeToolHelp loadHelp() { final InputStream is = NodeCmd.class.getClassLoader().getResourceAsStream("org/apache/cassandra/tools/NodeToolHelp.yaml"); assert is != null; try { final Constructor constructor = new Constructor(NodeToolHelp.class); TypeDescription desc = new TypeDescription(NodeToolHelp.class); desc.putListPropertyType("commands", NodeToolHelp.NodeToolCommand.class); final Yaml yaml = new Yaml(new Loader(constructor)); return (NodeToolHelp)yaml.load(is); } finally { FileUtils.closeQuietly(is); } } private static void addCmdHelp(StringBuilder sb, NodeToolHelp.NodeToolCommand cmd) { sb.append(" ").append(cmd.name); // Ghetto indentation (trying, but not too hard, to not look too bad) if (cmd.name.length() <= 20) for (int i = cmd.name.length(); i < 22; ++i) sb.append(" "); sb.append(" - ").append(cmd.help); } /** * Write a textual representation of the Cassandra ring. * * @param outs * the stream to write to */ public void printRing(PrintStream outs, String keyspace) { Map<String, String> tokensToEndpoints = probe.getTokenToEndpointMap(); LinkedHashMultimap<String, String> endpointsToTokens = LinkedHashMultimap.create(); for (Map.Entry<String, String> entry : tokensToEndpoints.entrySet()) endpointsToTokens.put(entry.getValue(), entry.getKey()); String format = "%-16s%-12s%-7s%-8s%-16s%-20s%-44s%n"; // Calculate per-token ownership of the ring Map<InetAddress, Float> ownerships; boolean keyspaceSelected; try { ownerships = probe.effectiveOwnership(keyspace); keyspaceSelected = true; } catch (ConfigurationException ex) { ownerships = probe.getOwnership(); outs.printf("Note: Ownership information does not include topology; for complete information, specify a keyspace%n"); keyspaceSelected = false; } try { outs.println(); Map<String, Map<InetAddress, Float>> perDcOwnerships = Maps.newLinkedHashMap(); // get the different datasets and map to tokens for (Map.Entry<InetAddress, Float> ownership : ownerships.entrySet()) { String dc = probe.getEndpointSnitchInfoProxy().getDatacenter(ownership.getKey().getHostAddress()); if (!perDcOwnerships.containsKey(dc)) perDcOwnerships.put(dc, new LinkedHashMap<InetAddress, Float>()); perDcOwnerships.get(dc).put(ownership.getKey(), ownership.getValue()); } for (Map.Entry<String, Map<InetAddress, Float>> entry : perDcOwnerships.entrySet()) printDc(outs, format, entry.getKey(), endpointsToTokens, keyspaceSelected, entry.getValue()); } catch (UnknownHostException e) { throw new RuntimeException(e); } } private void printDc(PrintStream outs, String format, String dc, LinkedHashMultimap<String, String> endpointsToTokens, boolean keyspaceSelected, Map<InetAddress, Float> filteredOwnerships) { Collection<String> liveNodes = probe.getLiveNodes(); Collection<String> deadNodes = probe.getUnreachableNodes(); Collection<String> joiningNodes = probe.getJoiningNodes(); Collection<String> leavingNodes = probe.getLeavingNodes(); Collection<String> movingNodes = probe.getMovingNodes(); Map<String, String> loadMap = probe.getLoadMap(); outs.println("Datacenter: " + dc); outs.println("=========="); // get the total amount of replicas for this dc and the last token in this dc's ring List<String> tokens = new ArrayList<String>(); float totalReplicas = 0f; String lastToken = ""; for (Map.Entry<InetAddress, Float> entry : filteredOwnerships.entrySet()) { tokens.addAll(endpointsToTokens.get(entry.getKey().getHostAddress())); lastToken = tokens.get(tokens.size() - 1); totalReplicas += entry.getValue(); } if (keyspaceSelected) outs.print("Replicas: " + (int) totalReplicas + "\n\n"); outs.printf(format, "Address", "Rack", "Status", "State", "Load", "Owns", "Token"); if (filteredOwnerships.size() > 1) outs.printf(format, "", "", "", "", "", "", lastToken); else outs.println(); for (Map.Entry<InetAddress, Float> entry : filteredOwnerships.entrySet()) { String endpoint = entry.getKey().getHostAddress(); for (String token : endpointsToTokens.get(endpoint)) { String rack; try { rack = probe.getEndpointSnitchInfoProxy().getRack(endpoint); } catch (UnknownHostException e) { rack = "Unknown"; } String status = liveNodes.contains(endpoint) ? "Up" : deadNodes.contains(endpoint) ? "Down" : "?"; String state = "Normal"; if (joiningNodes.contains(endpoint)) state = "Joining"; else if (leavingNodes.contains(endpoint)) state = "Leaving"; else if (movingNodes.contains(endpoint)) state = "Moving"; String load = loadMap.containsKey(endpoint) ? loadMap.get(endpoint) : "?"; String owns = new DecimalFormat("##0.00%").format(entry.getValue()); outs.printf(format, endpoint, rack, status, state, load, owns, token); } } outs.println(); } private class ClusterStatus { String kSpace = null, format = null; Collection<String> joiningNodes, leavingNodes, movingNodes, liveNodes, unreachableNodes; Map<String, String> loadMap, hostIDMap, tokensToEndpoints; EndpointSnitchInfoMBean epSnitchInfo; PrintStream outs; ClusterStatus(PrintStream outs, String kSpace) { this.kSpace = kSpace; this.outs = outs; joiningNodes = probe.getJoiningNodes(); leavingNodes = probe.getLeavingNodes(); movingNodes = probe.getMovingNodes(); loadMap = probe.getLoadMap(); tokensToEndpoints = probe.getTokenToEndpointMap(); liveNodes = probe.getLiveNodes(); unreachableNodes = probe.getUnreachableNodes(); hostIDMap = probe.getHostIdMap(); epSnitchInfo = probe.getEndpointSnitchInfoProxy(); } private void printStatusLegend() { outs.println("Status=Up/Down"); outs.println("|/ State=Normal/Leaving/Joining/Moving"); } private Map<String, Map<InetAddress, Float>> getOwnershipByDc(Map<InetAddress, Float> ownerships) throws UnknownHostException { Map<String, Map<InetAddress, Float>> ownershipByDc = Maps.newLinkedHashMap(); EndpointSnitchInfoMBean epSnitchInfo = probe.getEndpointSnitchInfoProxy(); for (Map.Entry<InetAddress, Float> ownership : ownerships.entrySet()) { String dc = epSnitchInfo.getDatacenter(ownership.getKey().getHostAddress()); if (!ownershipByDc.containsKey(dc)) ownershipByDc.put(dc, new LinkedHashMap<InetAddress, Float>()); ownershipByDc.get(dc).put(ownership.getKey(), ownership.getValue()); } return ownershipByDc; } private String getFormat(boolean hasEffectiveOwns, boolean isTokenPerNode) { if (format == null) { StringBuffer buf = new StringBuffer(); buf.append("%s%s %-16s %-9s "); // status, address, and load if (!isTokenPerNode) buf.append("%-6s "); // "Tokens" if (hasEffectiveOwns) buf.append("%-16s "); // "Owns (effective)" else buf.append("%-5s "); // "Owns buf.append("%-36s "); // Host ID if (isTokenPerNode) buf.append("%-39s "); // token buf.append("%s%n"); // "Rack" format = buf.toString(); } return format; } private void printNode(String endpoint, Float owns, Map<InetAddress, Float> ownerships, boolean hasEffectiveOwns, boolean isTokenPerNode) throws UnknownHostException { String status, state, load, strOwns, hostID, rack, fmt; fmt = getFormat(hasEffectiveOwns, isTokenPerNode); if (liveNodes.contains(endpoint)) status = "U"; else if (unreachableNodes.contains(endpoint)) status = "D"; else status = "?"; if (joiningNodes.contains(endpoint)) state = "J"; else if (leavingNodes.contains(endpoint)) state = "L"; else if (movingNodes.contains(endpoint)) state = "M"; else state = "N"; load = loadMap.containsKey(endpoint) ? loadMap.get(endpoint) : "?"; strOwns = new DecimalFormat("##0.0%").format(ownerships.get(InetAddress.getByName(endpoint))); hostID = hostIDMap.get(endpoint); rack = epSnitchInfo.getRack(endpoint); if (isTokenPerNode) { outs.printf(fmt, status, state, endpoint, load, strOwns, hostID, probe.getTokens(endpoint).get(0), rack); } else { int tokens = probe.getTokens(endpoint).size(); outs.printf(fmt, status, state, endpoint, load, tokens, strOwns, hostID, rack); } } private void printNodesHeader(boolean hasEffectiveOwns, boolean isTokenPerNode) { String fmt = getFormat(hasEffectiveOwns, isTokenPerNode); String owns = hasEffectiveOwns ? "Owns (effective)" : "Owns"; if (isTokenPerNode) outs.printf(fmt, "-", "-", "Address", "Load", owns, "Host ID", "Token", "Rack"); else outs.printf(fmt, "-", "-", "Address", "Load", "Tokens", owns, "Host ID", "Rack"); } void print() throws UnknownHostException { Map<InetAddress, Float> ownerships; boolean hasEffectiveOwns = false, isTokenPerNode = true; try { ownerships = probe.effectiveOwnership(kSpace); hasEffectiveOwns = true; } catch (ConfigurationException e) { ownerships = probe.getOwnership(); } // More tokens then nodes (aka vnodes)? if (new HashSet<String>(tokensToEndpoints.values()).size() < tokensToEndpoints.keySet().size()) isTokenPerNode = false; // Datacenters for (Map.Entry<String, Map<InetAddress, Float>> dc : getOwnershipByDc(ownerships).entrySet()) { String dcHeader = String.format("Datacenter: %s%n", dc.getKey()); outs.printf(dcHeader); for (int i=0; i < (dcHeader.length() - 1); i++) outs.print('='); outs.println(); printStatusLegend(); printNodesHeader(hasEffectiveOwns, isTokenPerNode); // Nodes for (Map.Entry<InetAddress, Float> entry : dc.getValue().entrySet()) printNode(entry.getKey().getHostAddress(), entry.getValue(), ownerships, hasEffectiveOwns, isTokenPerNode); } } } /** Writes a table of cluster-wide node information to a PrintStream * @throws UnknownHostException */ public void printClusterStatus(PrintStream outs, String keyspace) throws UnknownHostException { new ClusterStatus(outs, keyspace).print(); } public void printThreadPoolStats(PrintStream outs) { outs.printf("%-25s%10s%10s%15s%10s%18s%n", "Pool Name", "Active", "Pending", "Completed", "Blocked", "All time blocked"); Iterator<Map.Entry<String, JMXEnabledThreadPoolExecutorMBean>> threads = probe.getThreadPoolMBeanProxies(); while (threads.hasNext()) { Entry<String, JMXEnabledThreadPoolExecutorMBean> thread = threads.next(); String poolName = thread.getKey(); JMXEnabledThreadPoolExecutorMBean threadPoolProxy = thread.getValue(); outs.printf("%-25s%10s%10s%15s%10s%18s%n", poolName, threadPoolProxy.getActiveCount(), threadPoolProxy.getPendingTasks(), threadPoolProxy.getCompletedTasks(), threadPoolProxy.getCurrentlyBlockedTasks(), threadPoolProxy.getTotalBlockedTasks()); } outs.printf("%n%-20s%10s%n", "Message type", "Dropped"); for (Entry<String, Integer> entry : probe.getDroppedMessages().entrySet()) outs.printf("%-20s%10s%n", entry.getKey(), entry.getValue()); } /** * Write node information. * * @param outs the stream to write to */ public void printInfo(PrintStream outs, ToolCommandLine cmd) { boolean gossipInitialized = probe.isInitialized(); List<String> toks = probe.getTokens(); // If there is just 1 token, print it now like we always have, otherwise, // require that -T/--tokens be passed (that output is potentially verbose). if (toks.size() == 1) outs.printf("%-17s: %s%n", "Token", toks.get(0)); else if (!cmd.hasOption(TOKENS_OPT.left)) outs.printf("%-17s: (invoke with -T/--tokens to see all %d tokens)%n", "Token", toks.size()); outs.printf("%-17s: %s%n", "ID", probe.getLocalHostId()); outs.printf("%-17s: %s%n", "Gossip active", gossipInitialized); outs.printf("%-17s: %s%n", "Thrift active", probe.isThriftServerRunning()); outs.printf("%-17s: %s%n", "Load", probe.getLoadString()); if (gossipInitialized) outs.printf("%-17s: %s%n", "Generation No", probe.getCurrentGenerationNumber()); else outs.printf("%-17s: %s%n", "Generation No", 0); // Uptime long secondsUp = probe.getUptime() / 1000; outs.printf("%-17s: %d%n", "Uptime (seconds)", secondsUp); // Memory usage MemoryUsage heapUsage = probe.getHeapMemoryUsage(); double memUsed = (double)heapUsage.getUsed() / (1024 * 1024); double memMax = (double)heapUsage.getMax() / (1024 * 1024); outs.printf("%-17s: %.2f / %.2f%n", "Heap Memory (MB)", memUsed, memMax); // Data Center/Rack outs.printf("%-17s: %s%n", "Data Center", probe.getDataCenter()); outs.printf("%-17s: %s%n", "Rack", probe.getRack()); // Exceptions outs.printf("%-17s: %s%n", "Exceptions", probe.getExceptionCount()); CacheServiceMBean cacheService = probe.getCacheServiceMBean(); // Key Cache: Hits, Requests, RecentHitRate, SavePeriodInSeconds outs.printf("%-17s: size %d (bytes), capacity %d (bytes), %d hits, %d requests, %.3f recent hit rate, %d save period in seconds%n", "Key Cache", cacheService.getKeyCacheSize(), cacheService.getKeyCacheCapacityInBytes(), cacheService.getKeyCacheHits(), cacheService.getKeyCacheRequests(), cacheService.getKeyCacheRecentHitRate(), cacheService.getKeyCacheSavePeriodInSeconds()); // Row Cache: Hits, Requests, RecentHitRate, SavePeriodInSeconds outs.printf("%-17s: size %d (bytes), capacity %d (bytes), %d hits, %d requests, %.3f recent hit rate, %d save period in seconds%n", "Row Cache", cacheService.getRowCacheSize(), cacheService.getRowCacheCapacityInBytes(), cacheService.getRowCacheHits(), cacheService.getRowCacheRequests(), cacheService.getRowCacheRecentHitRate(), cacheService.getRowCacheSavePeriodInSeconds()); if (toks.size() > 1 && cmd.hasOption(TOKENS_OPT.left)) { for (String tok : toks) outs.printf("%-17s: %s%n", "Token", tok); } } public void printReleaseVersion(PrintStream outs) { outs.println("ReleaseVersion: " + probe.getReleaseVersion()); } public void printNetworkStats(final InetAddress addr, PrintStream outs) { outs.printf("Mode: %s%n", probe.getOperationMode()); Set<InetAddress> hosts = addr == null ? probe.getStreamDestinations() : new HashSet<InetAddress>(){{add(addr);}}; if (hosts.size() == 0) outs.println("Not sending any streams."); for (InetAddress host : hosts) { try { List<String> files = probe.getFilesDestinedFor(host); if (files.size() > 0) { outs.printf("Streaming to: %s%n", host); for (String file : files) outs.printf(" %s%n", file); } else { outs.printf(" Nothing streaming to %s%n", host); } } catch (IOException ex) { outs.printf(" Error retrieving file data for %s%n", host); } } hosts = addr == null ? probe.getStreamSources() : new HashSet<InetAddress>(){{add(addr); }}; if (hosts.size() == 0) outs.println("Not receiving any streams."); for (InetAddress host : hosts) { try { List<String> files = probe.getIncomingFiles(host); if (files.size() > 0) { outs.printf("Streaming from: %s%n", host); for (String file : files) outs.printf(" %s%n", file); } else { outs.printf(" Nothing streaming from %s%n", host); } } catch (IOException ex) { outs.printf(" Error retrieving file data for %s%n", host); } } MessagingServiceMBean ms = probe.msProxy; outs.printf("%-25s", "Pool Name"); outs.printf("%10s", "Active"); outs.printf("%10s", "Pending"); outs.printf("%15s%n", "Completed"); int pending; long completed; pending = 0; for (int n : ms.getCommandPendingTasks().values()) pending += n; completed = 0; for (long n : ms.getCommandCompletedTasks().values()) completed += n; outs.printf("%-25s%10s%10s%15s%n", "Commands", "n/a", pending, completed); pending = 0; for (int n : ms.getResponsePendingTasks().values()) pending += n; completed = 0; for (long n : ms.getResponseCompletedTasks().values()) completed += n; outs.printf("%-25s%10s%10s%15s%n", "Responses", "n/a", pending, completed); } public void printCompactionStats(PrintStream outs) { int compactionThroughput = probe.getCompactionThroughput(); CompactionManagerMBean cm = probe.getCompactionManagerProxy(); outs.println("pending tasks: " + cm.getPendingTasks()); if (cm.getCompactions().size() > 0) outs.printf("%25s%16s%16s%16s%16s%10s%10s%n", "compaction type", "keyspace", "column family", "completed", "total", "unit", "progress"); long remainingBytes = 0; for (Map<String, String> c : cm.getCompactions()) { String percentComplete = new Long(c.get("total")) == 0 ? "n/a" : new DecimalFormat("0.00").format((double) new Long(c.get("completed")) / new Long(c.get("total")) * 100) + "%"; outs.printf("%25s%16s%16s%16s%16s%10s%10s%n", c.get("taskType"), c.get("keyspace"), c.get("columnfamily"), c.get("completed"), c.get("total"), c.get("unit"), percentComplete); if (c.get("taskType").equals(OperationType.COMPACTION.toString())) remainingBytes += (new Long(c.get("total")) - new Long(c.get("completed"))); } long remainingTimeInSecs = compactionThroughput == 0 || remainingBytes == 0 ? -1 : (remainingBytes) / (long) (1024L * 1024L * compactionThroughput); String remainingTime = remainingTimeInSecs < 0 ? "n/a" : String.format("%dh%02dm%02ds", remainingTimeInSecs / 3600, (remainingTimeInSecs % 3600) / 60, (remainingTimeInSecs % 60)); outs.printf("%25s%10s%n", "Active compaction remaining time : ", remainingTime); } public void printColumnFamilyStats(PrintStream outs) { Map <String, List <ColumnFamilyStoreMBean>> cfstoreMap = new HashMap <String, List <ColumnFamilyStoreMBean>>(); // get a list of column family stores Iterator<Map.Entry<String, ColumnFamilyStoreMBean>> cfamilies = probe.getColumnFamilyStoreMBeanProxies(); while (cfamilies.hasNext()) { Entry<String, ColumnFamilyStoreMBean> entry = cfamilies.next(); String tableName = entry.getKey(); ColumnFamilyStoreMBean cfsProxy = entry.getValue(); if (!cfstoreMap.containsKey(tableName)) { List<ColumnFamilyStoreMBean> columnFamilies = new ArrayList<ColumnFamilyStoreMBean>(); columnFamilies.add(cfsProxy); cfstoreMap.put(tableName, columnFamilies); } else { cfstoreMap.get(tableName).add(cfsProxy); } } // print out the table statistics for (Entry<String, List<ColumnFamilyStoreMBean>> entry : cfstoreMap.entrySet()) { String tableName = entry.getKey(); List<ColumnFamilyStoreMBean> columnFamilies = entry.getValue(); long tableReadCount = 0; long tableWriteCount = 0; int tablePendingTasks = 0; double tableTotalReadTime = 0.0f; double tableTotalWriteTime = 0.0f; outs.println("Keyspace: " + tableName); for (ColumnFamilyStoreMBean cfstore : columnFamilies) { long writeCount = cfstore.getWriteCount(); long readCount = cfstore.getReadCount(); if (readCount > 0) { tableReadCount += readCount; tableTotalReadTime += cfstore.getTotalReadLatencyMicros(); } if (writeCount > 0) { tableWriteCount += writeCount; tableTotalWriteTime += cfstore.getTotalWriteLatencyMicros(); } tablePendingTasks += cfstore.getPendingTasks(); } double tableReadLatency = tableReadCount > 0 ? tableTotalReadTime / tableReadCount / 1000 : Double.NaN; double tableWriteLatency = tableWriteCount > 0 ? tableTotalWriteTime / tableWriteCount / 1000 : Double.NaN; outs.println("\tRead Count: " + tableReadCount); outs.println("\tRead Latency: " + String.format("%s", tableReadLatency) + " ms."); outs.println("\tWrite Count: " + tableWriteCount); outs.println("\tWrite Latency: " + String.format("%s", tableWriteLatency) + " ms."); outs.println("\tPending Tasks: " + tablePendingTasks); // print out column family statistics for this table for (ColumnFamilyStoreMBean cfstore : columnFamilies) { outs.println("\t\tColumn Family: " + cfstore.getColumnFamilyName()); outs.println("\t\tSSTable count: " + cfstore.getLiveSSTableCount()); int[] leveledSStables = cfstore.getSSTableCountPerLevel(); if (leveledSStables != null) { outs.print("\t\tSSTables in each level: ["); for (int level = 0; level < leveledSStables.length; level++) { int count = leveledSStables[level]; outs.print(count); long maxCount = 4L; // for L0 if (level > 0) maxCount = (long) Math.pow(10, level); // show max threshold for level when exceeded if (count > maxCount) outs.print("/" + maxCount); if (level < leveledSStables.length - 1) outs.print(", "); else outs.println("]"); } } outs.println("\t\tSpace used (live): " + cfstore.getLiveDiskSpaceUsed()); outs.println("\t\tSpace used (total): " + cfstore.getTotalDiskSpaceUsed()); outs.println("\t\tNumber of Keys (estimate): " + cfstore.estimateKeys()); outs.println("\t\tMemtable Columns Count: " + cfstore.getMemtableColumnsCount()); outs.println("\t\tMemtable Data Size: " + cfstore.getMemtableDataSize()); outs.println("\t\tMemtable Switch Count: " + cfstore.getMemtableSwitchCount()); outs.println("\t\tRead Count: " + cfstore.getReadCount()); outs.println("\t\tRead Latency: " + String.format("%01.3f", cfstore.getRecentReadLatencyMicros() / 1000) + " ms."); outs.println("\t\tWrite Count: " + cfstore.getWriteCount()); outs.println("\t\tWrite Latency: " + String.format("%01.3f", cfstore.getRecentWriteLatencyMicros() / 1000) + " ms."); outs.println("\t\tPending Tasks: " + cfstore.getPendingTasks()); outs.println("\t\tBloom Filter False Positives: " + cfstore.getBloomFilterFalsePositives()); outs.println("\t\tBloom Filter False Ratio: " + String.format("%01.5f", cfstore.getRecentBloomFilterFalseRatio())); outs.println("\t\tBloom Filter Space Used: " + cfstore.getBloomFilterDiskSpaceUsed()); outs.println("\t\tCompacted row minimum size: " + cfstore.getMinRowSize()); outs.println("\t\tCompacted row maximum size: " + cfstore.getMaxRowSize()); outs.println("\t\tCompacted row mean size: " + cfstore.getMeanRowSize()); outs.println(""); } outs.println("----------------"); } } public void printRemovalStatus(PrintStream outs) { outs.println("RemovalStatus: " + probe.getRemovalStatus()); } private void printCfHistograms(String keySpace, String columnFamily, PrintStream output) { ColumnFamilyStoreMBean store = this.probe.getCfsProxy(keySpace, columnFamily); // default is 90 offsets long[] offsets = new EstimatedHistogram().getBucketOffsets(); long[] rrlh = store.getRecentReadLatencyHistogramMicros(); long[] rwlh = store.getRecentWriteLatencyHistogramMicros(); long[] sprh = store.getRecentSSTablesPerReadHistogram(); long[] ersh = store.getEstimatedRowSizeHistogram(); long[] ecch = store.getEstimatedColumnCountHistogram(); output.println(String.format("%s/%s histograms", keySpace, columnFamily)); output.println(String.format("%-10s%10s%18s%18s%18s%18s", "Offset", "SSTables", "Write Latency", "Read Latency", "Row Size", "Column Count")); for (int i = 0; i < offsets.length; i++) { output.println(String.format("%-10d%10s%18s%18s%18s%18s", offsets[i], (i < sprh.length ? sprh[i] : "0"), (i < rwlh.length ? rwlh[i] : "0"), (i < rrlh.length ? rrlh[i] : "0"), (i < ersh.length ? ersh[i] : "0"), (i < ecch.length ? ecch[i] : "0"))); } } private void printProxyHistograms(PrintStream output) { StorageProxyMBean sp = this.probe.getSpProxy(); long[] offsets = new EstimatedHistogram().getBucketOffsets(); long[] rrlh = sp.getRecentReadLatencyHistogramMicros(); long[] rwlh = sp.getRecentWriteLatencyHistogramMicros(); long[] rrnglh = sp.getRecentRangeLatencyHistogramMicros(); output.println("proxy histograms"); output.println(String.format("%-10s%18s%18s%18s", "Offset", "Read Latency", "Write Latency", "Range Latency")); for (int i = 0; i < offsets.length; i++) { output.println(String.format("%-10d%18s%18s%18s", offsets[i], (i < rrlh.length ? rrlh[i] : "0"), (i < rwlh.length ? rwlh[i] : "0"), (i < rrnglh.length ? rrnglh[i] : "0"))); } } private void printEndPoints(String keySpace, String cf, String key, PrintStream output) { List<InetAddress> endpoints = this.probe.getEndpoints(keySpace, cf, key); for (InetAddress anEndpoint : endpoints) { output.println(anEndpoint.getHostAddress()); } } private void printSSTables(String keyspace, String cf, String key, PrintStream output) { List<String> sstables = this.probe.getSSTables(keyspace, cf, key); for (String sstable : sstables) { output.println(sstable); } } private void printIsThriftServerRunning(PrintStream outs) { outs.println(probe.isThriftServerRunning() ? "running" : "not running"); } public void predictConsistency(Integer replicationFactor, Integer timeAfterWrite, Integer numVersions, Float percentileLatency, PrintStream output) { PBSPredictorMBean predictorMBean = probe.getPBSPredictorMBean(); for(int r = 1; r <= replicationFactor; ++r) { for(int w = 1; w <= replicationFactor; ++w) { if(w+r > replicationFactor+1) continue; try { PBSPredictionResult result = predictorMBean.doPrediction(replicationFactor, r, w, timeAfterWrite, numVersions, percentileLatency); if(r == 1 && w == 1) { output.printf("%dms after a given write, with maximum version staleness of k=%d\n", timeAfterWrite, numVersions); } output.printf("N=%d, R=%d, W=%d\n", replicationFactor, r, w); output.printf("Probability of consistent reads: %f\n", result.getConsistencyProbability()); output.printf("Average read latency: %fms (%.3fth %%ile %dms)\n", result.getAverageReadLatency(), result.getPercentileReadLatencyPercentile()*100, result.getPercentileReadLatencyValue()); output.printf("Average write latency: %fms (%.3fth %%ile %dms)\n\n", result.getAverageWriteLatency(), result.getPercentileWriteLatencyPercentile()*100, result.getPercentileWriteLatencyValue()); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); return; } } } } public static void main(String[] args) throws IOException, InterruptedException, ConfigurationException, ParseException { CommandLineParser parser = new PosixParser(); ToolCommandLine cmd = null; try { cmd = new ToolCommandLine(parser.parse(options, args)); } catch (ParseException p) { badUse(p.getMessage()); } String host = cmd.hasOption(HOST_OPT.left) ? cmd.getOptionValue(HOST_OPT.left) : DEFAULT_HOST; int port = DEFAULT_PORT; String portNum = cmd.getOptionValue(PORT_OPT.left); if (portNum != null) { try { port = Integer.parseInt(portNum); } catch (NumberFormatException e) { throw new ParseException("Port must be a number"); } } String username = cmd.getOptionValue(USERNAME_OPT.left); String password = cmd.getOptionValue(PASSWORD_OPT.left); NodeProbe probe = null; try { probe = username == null ? new NodeProbe(host, port) : new NodeProbe(host, port, username, password); } catch (IOException ioe) { Throwable inner = findInnermostThrowable(ioe); if (inner instanceof ConnectException) { System.err.printf("Failed to connect to '%s:%d': %s%n", host, port, inner.getMessage()); System.exit(1); } else if (inner instanceof UnknownHostException) { System.err.printf("Cannot resolve '%s': unknown host%n", host); System.exit(1); } else { err(ioe, "Error connecting to remote JMX agent!"); } } try { NodeCommand command = null; try { command = cmd.getCommand(); } catch (IllegalArgumentException e) { badUse(e.getMessage()); } NodeCmd nodeCmd = new NodeCmd(probe); // Execute the requested command. String[] arguments = cmd.getCommandArguments(); String tag; String columnFamilyName = null; switch (command) { case RING : if (arguments.length > 0) { nodeCmd.printRing(System.out, arguments[0]); } else { nodeCmd.printRing(System.out, null); }; break; case INFO : nodeCmd.printInfo(System.out, cmd); break; case CFSTATS : nodeCmd.printColumnFamilyStats(System.out); break; case TPSTATS : nodeCmd.printThreadPoolStats(System.out); break; case VERSION : nodeCmd.printReleaseVersion(System.out); break; case COMPACTIONSTATS : nodeCmd.printCompactionStats(System.out); break; case DISABLEGOSSIP : probe.stopGossiping(); break; case ENABLEGOSSIP : probe.startGossiping(); break; case DISABLETHRIFT : probe.stopThriftServer(); break; case ENABLETHRIFT : probe.startThriftServer(); break; case STATUSTHRIFT : nodeCmd.printIsThriftServerRunning(System.out); break; case RESETLOCALSCHEMA: probe.resetLocalSchema(); break; case STATUS : if (arguments.length > 0) nodeCmd.printClusterStatus(System.out, arguments[0]); else nodeCmd.printClusterStatus(System.out, null); break; case DECOMMISSION : if (arguments.length > 0) { System.err.println("Decommission will decommission the node you are connected to and does not take arguments!"); System.exit(1); } probe.decommission(); break; case DRAIN : try { probe.drain(); } catch (ExecutionException ee) { err(ee, "Error occured during flushing"); } break; case NETSTATS : if (arguments.length > 0) { nodeCmd.printNetworkStats(InetAddress.getByName(arguments[0]), System.out); } else { nodeCmd.printNetworkStats(null, System.out); } break; case SNAPSHOT : columnFamilyName = cmd.getOptionValue(SNAPSHOT_COLUMNFAMILY_OPT.left); /* FALL THRU */ case CLEARSNAPSHOT : tag = cmd.getOptionValue(TAG_OPT.left); handleSnapshots(command, tag, arguments, columnFamilyName, probe); break; case MOVE : if (arguments.length != 1) { badUse("Missing token argument for move."); } try { probe.move(arguments[0]); } catch (UnsupportedOperationException uoerror) { System.err.println(uoerror.getMessage()); System.exit(1); } break; case JOIN: if (probe.isJoined()) { System.err.println("This node has already joined the ring."); System.exit(1); } probe.joinRing(); break; case SETCOMPACTIONTHROUGHPUT : if (arguments.length != 1) { badUse("Missing value argument."); } probe.setCompactionThroughput(Integer.parseInt(arguments[0])); break; case SETSTREAMTHROUGHPUT : if (arguments.length != 1) { badUse("Missing value argument."); } probe.setStreamThroughput(Integer.parseInt(arguments[0])); break; case SETTRACEPROBABILITY : if (arguments.length != 1) { badUse("Missing value argument."); } probe.setTraceProbability(Double.parseDouble(arguments[0])); break; case REBUILD : if (arguments.length > 1) { badUse("Too many arguments."); } probe.rebuild(arguments.length == 1 ? arguments[0] : null); break; case REMOVETOKEN : System.err.println("Warn: removetoken is deprecated, please use removenode instead"); case REMOVENODE : if (arguments.length != 1) { badUse("Missing an argument for removenode (either status, force, or an ID)"); } else if (arguments[0].equals("status")) { nodeCmd.printRemovalStatus(System.out); } else if (arguments[0].equals("force")) { nodeCmd.printRemovalStatus(System.out); probe.forceRemoveCompletion(); } else { probe.removeNode(arguments[0]); } break; case INVALIDATEKEYCACHE : probe.invalidateKeyCache(); break; case INVALIDATEROWCACHE : probe.invalidateRowCache(); break; case CLEANUP : case COMPACT : case REPAIR : case FLUSH : case SCRUB : case UPGRADESSTABLES : optionalKSandCFs(command, cmd, arguments, probe); break; case GETCOMPACTIONTHRESHOLD : if (arguments.length != 2) { badUse("getcompactionthreshold requires ks and cf args."); } probe.getCompactionThreshold(System.out, arguments[0], arguments[1]); break; case CFHISTOGRAMS : if (arguments.length != 2) { badUse("cfhistograms requires ks and cf args"); } nodeCmd.printCfHistograms(arguments[0], arguments[1], System.out); break; case SETCACHECAPACITY : if (arguments.length != 2) { badUse("setcachecapacity requires key-cache-capacity, and row-cache-capacity args."); } probe.setCacheCapacities(Integer.parseInt(arguments[0]), Integer.parseInt(arguments[1])); break; case SETCOMPACTIONTHRESHOLD : if (arguments.length != 4) { badUse("setcompactionthreshold requires ks, cf, min, and max threshold args."); } int minthreshold = Integer.parseInt(arguments[2]); int maxthreshold = Integer.parseInt(arguments[3]); if ((minthreshold < 0) || (maxthreshold < 0)) { badUse("Thresholds must be positive integers"); } if (minthreshold > maxthreshold) { badUse("Min threshold cannot be greater than max."); } if (minthreshold < 2 && maxthreshold != 0) { badUse("Min threshold must be at least 2"); } probe.setCompactionThreshold(arguments[0], arguments[1], minthreshold, maxthreshold); break; case GETENDPOINTS : if (arguments.length != 3) { badUse("getendpoints requires ks, cf and key args"); } nodeCmd.printEndPoints(arguments[0], arguments[1], arguments[2], System.out); break; case PROXYHISTOGRAMS : if (arguments.length != 0) { badUse("proxyhistograms does not take arguments"); } nodeCmd.printProxyHistograms(System.out); break; case GETSSTABLES: if (arguments.length != 3) { badUse("getsstables requires ks, cf and key args"); } nodeCmd.printSSTables(arguments[0], arguments[1], arguments[2], System.out); break; case REFRESH: if (arguments.length != 2) { badUse("load_new_sstables requires ks and cf args"); } probe.loadNewSSTables(arguments[0], arguments[1]); break; case REBUILD_INDEX: if (arguments.length < 2) { badUse("rebuild_index requires ks and cf args"); } if (arguments.length >= 3) probe.rebuildIndex(arguments[0], arguments[1], arguments[2].split(",")); else probe.rebuildIndex(arguments[0], arguments[1]); break; case GOSSIPINFO : nodeCmd.printGossipInfo(System.out); break; case STOP: if (arguments.length != 1) { badUse("stop requires a type."); } probe.stop(arguments[0].toUpperCase()); break; case DESCRIBERING : if (arguments.length != 1) { badUse("Missing keyspace argument for describering."); } nodeCmd.printDescribeRing(arguments[0], System.out); break; case RANGEKEYSAMPLE : nodeCmd.printRangeKeySample(System.out); break; case PREDICTCONSISTENCY: if (arguments.length < 2) { badUse("Requires replication factor and time"); } int numVersions = 1; if (arguments.length == 3) { numVersions = Integer.parseInt(arguments[2]); } float percentileLatency = .999f; if (arguments.length == 4) { percentileLatency = Float.parseFloat(arguments[3]); } nodeCmd.predictConsistency(Integer.parseInt(arguments[0]), Integer.parseInt(arguments[1]), numVersions, percentileLatency, System.out); break; default : throw new RuntimeException("Unreachable code."); } } finally { if (probe != null) { try { probe.close(); } catch (IOException ex) { // swallow the exception so the user will see the real one. } } } System.exit(0); } private static Throwable findInnermostThrowable(Throwable ex) { Throwable inner = ex.getCause(); return inner == null ? ex : findInnermostThrowable(inner); } private void printDescribeRing(String keyspaceName, PrintStream out) { out.println("Schema Version:" + probe.getSchemaVersion()); out.println("TokenRange: "); try { for (String tokenRangeString : probe.describeRing(keyspaceName)) { out.println("\t" + tokenRangeString); } } catch (InvalidRequestException e) { err(e, e.getMessage()); } } private void printRangeKeySample(PrintStream outs) { outs.println("RangeKeySample: "); List<String> tokenStrings = this.probe.sampleKeyRange(); for (String tokenString : tokenStrings) { outs.println("\t" + tokenString); } } private void printGossipInfo(PrintStream out) { out.println(probe.getGossipInfo()); } private static void badUse(String useStr) { System.err.println(useStr); printUsage(); System.exit(1); } private static void err(Exception e, String errStr) { System.err.println(errStr); e.printStackTrace(); System.exit(3); } private static void complainNonzeroArgs(String[] args, NodeCommand cmd) { if (args.length > 0) { System.err.println("Too many arguments for command '"+cmd.toString()+"'."); printUsage(); System.exit(1); } } private static void handleSnapshots(NodeCommand nc, String tag, String[] cmdArgs, String columnFamily, NodeProbe probe) throws InterruptedException, IOException { String[] keyspaces = Arrays.copyOfRange(cmdArgs, 0, cmdArgs.length); System.out.print("Requested snapshot for: "); if ( keyspaces.length > 0 ) { for (int i = 0; i < keyspaces.length; i++) System.out.print(keyspaces[i] + " "); } else { System.out.print("all keyspaces "); } if (columnFamily != null) { System.out.print("and column family: " + columnFamily); } System.out.println(); switch (nc) { case SNAPSHOT : if (tag == null || tag.equals("")) tag = new Long(System.currentTimeMillis()).toString(); probe.takeSnapshot(tag, columnFamily, keyspaces); System.out.println("Snapshot directory: " + tag); break; case CLEARSNAPSHOT : probe.clearSnapshot(tag, keyspaces); break; } } private static void optionalKSandCFs(NodeCommand nc, ToolCommandLine cmd, String[] cmdArgs, NodeProbe probe) throws InterruptedException, IOException { // if there is one additional arg, it's the keyspace; more are columnfamilies List<String> keyspaces = cmdArgs.length == 0 ? probe.getKeyspaces() : Arrays.asList(cmdArgs[0]); for (String keyspace : keyspaces) { if (!probe.getKeyspaces().contains(keyspace)) { System.err.println("Keyspace [" + keyspace + "] does not exist."); System.exit(1); } } // second loop so we're less likely to die halfway through due to invalid keyspace for (String keyspace : keyspaces) { String[] columnFamilies = cmdArgs.length <= 1 ? new String[0] : Arrays.copyOfRange(cmdArgs, 1, cmdArgs.length); switch (nc) { case REPAIR : boolean snapshot = cmd.hasOption(SNAPSHOT_REPAIR_OPT.left); boolean localDC = cmd.hasOption(LOCAL_DC_REPAIR_OPT.left); if (cmd.hasOption(PRIMARY_RANGE_OPT.left)) probe.forceTableRepairPrimaryRange(keyspace, snapshot, localDC, columnFamilies); else probe.forceTableRepair(keyspace, snapshot, localDC, columnFamilies); break; case FLUSH : try { probe.forceTableFlush(keyspace, columnFamilies); } catch (ExecutionException ee) { err(ee, "Error occured during flushing"); } break; case COMPACT : try { probe.forceTableCompaction(keyspace, columnFamilies); } catch (ExecutionException ee) { err(ee, "Error occured during compaction"); } break; case CLEANUP : if (keyspace.equals(Table.SYSTEM_KS)) { break; } // Skip cleanup on system cfs. try { probe.forceTableCleanup(keyspace, columnFamilies); } catch (ExecutionException ee) { err(ee, "Error occured during cleanup"); } break; case SCRUB : try { probe.scrub(keyspace, columnFamilies); } catch (ExecutionException ee) { err(ee, "Error occured while scrubbing keyspace " + keyspace); } break; case UPGRADESSTABLES : try { probe.upgradeSSTables(keyspace, columnFamilies); } catch (ExecutionException ee) { err(ee, "Error occured while upgrading the sstables for keyspace " + keyspace); } break; default: throw new RuntimeException("Unreachable code."); } } } private static class ToolOptions extends Options { public void addOption(Pair<String, String> opts, boolean hasArgument, String description) { addOption(opts, hasArgument, description, false); } public void addOption(Pair<String, String> opts, boolean hasArgument, String description, boolean required) { addOption(opts.left, opts.right, hasArgument, description, required); } public void addOption(String opt, String longOpt, boolean hasArgument, String description, boolean required) { Option option = new Option(opt, longOpt, hasArgument, description); option.setRequired(required); addOption(option); } } private static class ToolCommandLine { private final CommandLine commandLine; public ToolCommandLine(CommandLine commands) { commandLine = commands; } public Option[] getOptions() { return commandLine.getOptions(); } public boolean hasOption(String opt) { return commandLine.hasOption(opt); } public String getOptionValue(String opt) { return commandLine.getOptionValue(opt); } public NodeCommand getCommand() { if (commandLine.getArgs().length == 0) throw new IllegalArgumentException("Command was not specified."); String command = commandLine.getArgs()[0]; try { return NodeCommand.valueOf(command.toUpperCase()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Unrecognized command: " + command); } } public String[] getCommandArguments() { List params = commandLine.getArgList(); if (params.size() < 2) // command parameters are empty return new String[0]; String[] toReturn = new String[params.size() - 1]; for (int i = 1; i < params.size(); i++) toReturn[i - 1] = (String) params.get(i); return toReturn; } } }
use %n rather than \n in printf calls
src/java/org/apache/cassandra/tools/NodeCmd.java
use %n rather than \n in printf calls
Java
apache-2.0
9281106066d52300289617eb95fa3134f93ab765
0
venicegeo/pz-access,venicegeo/pz-access,venicegeo/pz-access,venicegeo/pz-access
/** * Copyright 2016, RadiantBlue Technologies, 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 access.messaging; import java.io.IOException; import java.util.Arrays; import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.PostConstruct; import messaging.job.JobMessageFactory; import messaging.job.KafkaClientFactory; import model.data.DataResource; import model.job.Job; import model.job.JobProgress; import model.job.type.AccessJob; import model.status.StatusUpdate; import org.apache.kafka.clients.consumer.Consumer; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.common.errors.WakeupException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import access.database.MongoAccessor; import access.database.model.Deployment; import access.deploy.Deployer; import access.deploy.Leaser; import com.fasterxml.jackson.databind.ObjectMapper; import com.mongodb.MongoException; /** * Worker class that listens for Access Jobs being passed in through the * Dispatcher. Handles the Access Jobs by standing up services, retrieving * files, or other various forms of Access for data. * * This component assumes that the data intended to be accessed is already * ingested into the Piazza system; either by the Ingest component or other * components that are capable of inserting data into Piazza. * * @author Patrick.Doody * */ @Component public class AccessWorker { private static final String ACCESS_TOPIC_NAME = "access"; @Autowired private Deployer deployer; @Autowired private Leaser leaser; @Autowired private MongoAccessor accessor; @Value("${kafka.host}") private String KAFKA_HOST; @Value("${kafka.port}") private String KAFKA_PORT; @Value("${kafka.group}") private String KAFKA_GROUP; private Producer<String, String> producer; private Consumer<String, String> consumer; private final AtomicBoolean closed = new AtomicBoolean(false); /** * Worker class that listens for and processes Access messages. */ public AccessWorker() { } /** * */ @PostConstruct public void initialize() { // Initialize the Kafka consumer/producer producer = KafkaClientFactory.getProducer(KAFKA_HOST, KAFKA_PORT); consumer = KafkaClientFactory.getConsumer(KAFKA_HOST, KAFKA_PORT, KAFKA_GROUP); // Listen for events TODO: Talk to Sonny about moving to @Async method Thread pollThread = new Thread() { public void run() { listen(); } }; pollThread.start(); } /** * Listens for Kafka Access messages for creating Deployments for Access of * Resources */ public void listen() { try { consumer.subscribe(Arrays.asList(ACCESS_TOPIC_NAME)); while (!closed.get()) { ConsumerRecords<String, String> consumerRecords = consumer.poll(1000); // Handle new Messages on this topic. for (ConsumerRecord<String, String> consumerRecord : consumerRecords) { System.out.println("Processing Access Message " + consumerRecord.topic() + " with key " + consumerRecord.key()); try { ObjectMapper mapper = new ObjectMapper(); Job job = mapper.readValue(consumerRecord.value(), Job.class); AccessJob accessJob = (AccessJob) job.jobType; // Update Status that this Job is being processed JobProgress jobProgress = new JobProgress(0); StatusUpdate statusUpdate = new StatusUpdate(StatusUpdate.STATUS_RUNNING, jobProgress); producer.send(JobMessageFactory.getUpdateStatusMessage(consumerRecord.key(), statusUpdate)); // Depending on how the user wants to Access the // Resource switch (accessJob.getDeploymentType()) { case AccessJob.ACCESS_TYPE_FILE: // TODO: Return FTP link? S3 link? Stream the bytes? break; case AccessJob.ACCESS_TYPE_GEOSERVER: // Check if a Deployment already exists boolean exists = deployer.doesDeploymentExist(accessJob.getResourceId()); if (exists) { // If it does, then renew the Lease on the // existing deployment. Deployment deployment = accessor.getDeploymentByResourceId(accessJob.getResourceId()); leaser.renewDeploymentLease(deployment); } else { // Get the data and deploy it DataResource dataToDeploy = accessor.getData(accessJob.getResourceId()); Deployment deployment = deployer.createDeployment(dataToDeploy); // Get a lease for the new deployment. leaser.getDeploymentLease(deployment); } break; } // Update Job Status to complete for this Job. statusUpdate = new StatusUpdate(StatusUpdate.STATUS_SUCCESS); statusUpdate.setResult(null /* TODO: Set the result! */); producer.send(JobMessageFactory.getUpdateStatusMessage(consumerRecord.key(), statusUpdate)); } catch (IOException jsonException) { System.out.println("Error Parsing Access Job Message."); jsonException.printStackTrace(); } catch (MongoException mongoException) { System.out.println("Error Accessing Mongo Database: " + mongoException.getMessage()); mongoException.printStackTrace(); } catch (Exception exception) { System.out.println("An unexpected error occurred while processing the Job Message: " + exception.getMessage()); exception.printStackTrace(); } } } } catch (WakeupException exception) { // Ignore exception if closing if (!closed.get()) { throw exception; } } finally { consumer.close(); } } }
src/main/java/access/messaging/AccessWorker.java
package access.messaging; import java.io.IOException; import java.util.Arrays; import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.PostConstruct; import messaging.job.JobMessageFactory; import messaging.job.KafkaClientFactory; import model.job.Job; import model.job.JobProgress; import model.job.type.AccessJob; import model.status.StatusUpdate; import org.apache.kafka.clients.consumer.Consumer; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.common.errors.WakeupException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import access.database.MongoAccessor; import access.database.model.Deployment; import access.deploy.Deployer; import access.deploy.Leaser; import com.fasterxml.jackson.databind.ObjectMapper; import com.mongodb.MongoException; /** * Worker class that listens for Access Jobs being passed in through the * Dispatcher. Handles the Access Jobs by standing up services, retrieving * files, or other various forms of Access for data. * * This component assumes that the data intended to be accessed is already * ingested into the Piazza system; either by the Ingest component or other * components that are capable of inserting data into Piazza. * * @author Patrick.Doody * */ @Component public class AccessWorker { private static final String ACCESS_TOPIC_NAME = "access"; @Autowired private Deployer deployer; @Autowired private Leaser leaser; @Autowired private MongoAccessor accessor; @Value("${kafka.host}") private String KAFKA_HOST; @Value("${kafka.port}") private String KAFKA_PORT; @Value("${kafka.group}") private String KAFKA_GROUP; private Producer<String, String> producer; private Consumer<String, String> consumer; private final AtomicBoolean closed = new AtomicBoolean(false); /** * Worker class that listens for and processes Access messages. */ public AccessWorker() { } /** * */ @PostConstruct public void initialize() { // Initialize the Kafka consumer/producer producer = KafkaClientFactory.getProducer(KAFKA_HOST, KAFKA_PORT); consumer = KafkaClientFactory.getConsumer(KAFKA_HOST, KAFKA_PORT, KAFKA_GROUP); // Listen for events TODO: Talk to Sonny about moving to @Async method Thread pollThread = new Thread() { public void run() { listen(); } }; pollThread.start(); } /** * Listens for Kafka Access messages for creating Deployments for Access of * Resources */ public void listen() { try { consumer.subscribe(Arrays.asList(ACCESS_TOPIC_NAME)); while (!closed.get()) { ConsumerRecords<String, String> consumerRecords = consumer.poll(1000); // Handle new Messages on this topic. for (ConsumerRecord<String, String> consumerRecord : consumerRecords) { System.out.println("Processing Access Message " + consumerRecord.topic() + " with key " + consumerRecord.key()); try { ObjectMapper mapper = new ObjectMapper(); Job job = mapper.readValue(consumerRecord.value(), Job.class); AccessJob accessJob = (AccessJob) job.jobType; // Update Status that this Job is being processed JobProgress jobProgress = new JobProgress(0); StatusUpdate statusUpdate = new StatusUpdate(StatusUpdate.STATUS_RUNNING, jobProgress); producer.send(JobMessageFactory.getUpdateStatusMessage(consumerRecord.key(), statusUpdate)); // Depending on how the user wants to Access the // Resource switch (accessJob.getDeploymentType()) { case AccessJob.ACCESS_TYPE_FILE: // TODO: Return FTP link? S3 link? Stream the bytes? break; case AccessJob.ACCESS_TYPE_GEOSERVER: // Check if a Deployment already exists boolean exists = deployer.doesDeploymentExist(accessJob.getResourceId()); if (exists) { // If it does, then renew the Lease on the // existing deployment. Deployment deployment = accessor.getDeploymentByResourceId(accessJob.getResourceId()); leaser.renewDeploymentLease(deployment); } else { Deployment deployment = deployer.createDeployment(accessor.getData(accessJob .getResourceId())); // Get a lease for the new deployment. leaser.getDeploymentLease(deployment); } break; } // Update Job Status to complete for this Job. jobProgress.percentComplete = 100; statusUpdate = new StatusUpdate(StatusUpdate.STATUS_SUCCESS, jobProgress); producer.send(JobMessageFactory.getUpdateStatusMessage(consumerRecord.key(), statusUpdate)); } catch (IOException jsonException) { System.out.println("Error Parsing Access Job Message."); jsonException.printStackTrace(); } catch (MongoException mongoException) { System.out.println("Error committing Resources to Mongo Collections: " + mongoException.getMessage()); mongoException.printStackTrace(); } catch (Exception exception) { System.out.println("An unexpected error occurred while processing the Job Message: " + exception.getMessage()); exception.printStackTrace(); } } } } catch (WakeupException exception) { // Ignore exception if closing if (!closed.get()) { throw exception; } } finally { consumer.close(); } } }
Add license text
src/main/java/access/messaging/AccessWorker.java
Add license text
Java
apache-2.0
f14aeeb182eaf6304e7ffc060195abf59b276001
0
qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit
// Copyright (C) 2015 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.gpg; import static com.google.common.base.Preconditions.checkState; import static java.nio.charset.StandardCharsets.UTF_8; import static org.eclipse.jgit.lib.Constants.OBJ_BLOB; import com.google.common.base.Preconditions; import com.google.common.io.ByteStreams; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.bouncycastle.bcpg.ArmoredInputStream; import org.bouncycastle.bcpg.ArmoredOutputStream; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.openpgp.PGPPublicKeyRing; import org.bouncycastle.openpgp.PGPPublicKeyRingCollection; import org.bouncycastle.openpgp.PGPSignature; import org.bouncycastle.openpgp.bc.BcPGPObjectFactory; import org.bouncycastle.openpgp.operator.bc.BcPGPContentVerifierBuilderProvider; import org.eclipse.jgit.errors.IncorrectObjectTypeException; import org.eclipse.jgit.errors.MissingObjectException; import org.eclipse.jgit.lib.CommitBuilder; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectInserter; import org.eclipse.jgit.lib.ObjectReader; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.RefUpdate; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.notes.Note; import org.eclipse.jgit.notes.NoteMap; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.util.NB; /** * Store of GPG public keys in git notes. * * <p>Keys are stored in filenames based on their hex key ID, padded out to 40 characters to match * the length of a SHA-1. (This is to easily reuse existing fanout code in {@link NoteMap}, and may * be changed later after an appropriate transition.) * * <p>The contents of each file is an ASCII armored stream containing one or more public key rings * matching the ID. Multiple keys are supported because forging a key ID is possible, but such a key * cannot be used to verify signatures produced with the correct key. * * <p>Subkeys are mapped to the master GPG key in the same NoteMap. * * <p>No additional checks are performed on the key after reading; callers should only trust keys * after checking with a {@link PublicKeyChecker}. */ public class PublicKeyStore implements AutoCloseable { private static final ObjectId EMPTY_TREE = ObjectId.fromString("4b825dc642cb6eb9a060e54bf8d69288fbee4904"); /** Ref where GPG public keys are stored. */ public static final String REFS_GPG_KEYS = "refs/meta/gpg-keys"; /** * Choose the public key that produced a signature. * * <p> * * @param keyRings candidate keys. * @param sig signature object. * @param data signed payload. * @return the key chosen from {@code keyRings} that was able to verify the signature, or {@code * null} if none was found. * @throws PGPException if an error occurred verifying the signature. */ public static PGPPublicKey getSigner( Iterable<PGPPublicKeyRing> keyRings, PGPSignature sig, byte[] data) throws PGPException { for (PGPPublicKeyRing kr : keyRings) { // Possibly return a signing subkey in case it differs from the master public key PGPPublicKey k = kr.getPublicKey(sig.getKeyID()); if (k == null) { throw new IllegalStateException( "No public key found for ID: " + keyIdToString(sig.getKeyID())); } sig.init(new BcPGPContentVerifierBuilderProvider(), k); sig.update(data); if (sig.verify()) { // If the signature was made using a subkey, return the main public key. // This enables further validity checks, like user ID checks, that can only // be performed using the master public key. return kr.getPublicKey(); } } return null; } /** * Choose the public key that produced a certification. * * <p> * * @param keyRings candidate keys. * @param sig signature object. * @param userId user ID being certified. * @param key key being certified. * @return the key chosen from {@code keyRings} that was able to verify the certification, or * {@code null} if none was found. * @throws PGPException if an error occurred verifying the certification. */ public static PGPPublicKey getSigner( Iterable<PGPPublicKeyRing> keyRings, PGPSignature sig, String userId, PGPPublicKey key) throws PGPException { for (PGPPublicKeyRing kr : keyRings) { PGPPublicKey k = kr.getPublicKey(); sig.init(new BcPGPContentVerifierBuilderProvider(), k); if (sig.verifyCertification(userId, key)) { return k; } } return null; } private final Repository repo; private ObjectReader reader; private RevCommit tip; private NoteMap notes; private Map<Fingerprint, PGPPublicKeyRing> toAdd; private Set<Fingerprint> toRemove; /** @param repo repository to read keys from. */ public PublicKeyStore(Repository repo) { this.repo = repo; toAdd = new HashMap<>(); toRemove = new HashSet<>(); } @Override public void close() { reset(); } private void reset() { if (reader != null) { reader.close(); reader = null; notes = null; } } private void load() throws IOException { reset(); reader = repo.newObjectReader(); Ref ref = repo.getRefDatabase().exactRef(REFS_GPG_KEYS); if (ref == null) { return; } try (RevWalk rw = new RevWalk(reader)) { tip = rw.parseCommit(ref.getObjectId()); notes = NoteMap.read(reader, tip); } } /** * Read public keys with the given key ID. * * <p>Keys should not be trusted unless checked with {@link PublicKeyChecker}. * * <p>Multiple calls to this method use the same state of the key ref; to reread the ref, call * {@link #close()} first. * * @param keyId key ID. * @return any keys found that could be successfully parsed. * @throws PGPException if an error occurred parsing the key data. * @throws IOException if an error occurred reading the repository data. */ public PGPPublicKeyRingCollection get(long keyId) throws PGPException, IOException { return new PGPPublicKeyRingCollection(get(keyId, null)); } /** * Read public key with the given fingerprint. * * <p>Keys should not be trusted unless checked with {@link PublicKeyChecker}. * * <p>Multiple calls to this method use the same state of the key ref; to reread the ref, call * {@link #close()} first. * * @param fingerprint key fingerprint. * @return the key if found, or {@code null}. * @throws PGPException if an error occurred parsing the key data. * @throws IOException if an error occurred reading the repository data. */ public PGPPublicKeyRing get(byte[] fingerprint) throws PGPException, IOException { List<PGPPublicKeyRing> keyRings = get(Fingerprint.getId(fingerprint), fingerprint); return !keyRings.isEmpty() ? keyRings.get(0) : null; } private List<PGPPublicKeyRing> get(long keyId, byte[] fp) throws IOException { if (reader == null) { load(); } if (notes == null) { return Collections.emptyList(); } return get(keyObjectId(keyId), fp); } private List<PGPPublicKeyRing> get(ObjectId keyObjectId, byte[] fp) throws IOException { Note note = notes.getNote(keyObjectId); if (note == null) { return Collections.emptyList(); } return readKeysFromNote(note, fp); } private List<PGPPublicKeyRing> readKeysFromNote(Note note, byte[] fp) throws IOException, MissingObjectException, IncorrectObjectTypeException { boolean foundAtLeastOneKey = false; List<PGPPublicKeyRing> keys = new ArrayList<>(); ObjectId data = note.getData(); try (InputStream stream = reader.open(data, OBJ_BLOB).openStream()) { byte[] bytes = ByteStreams.toByteArray(stream); InputStream in = new ByteArrayInputStream(bytes); while (true) { @SuppressWarnings("unchecked") Iterator<Object> it = new BcPGPObjectFactory(new ArmoredInputStream(in)).iterator(); if (!it.hasNext()) { break; } foundAtLeastOneKey = true; Object obj = it.next(); if (obj instanceof PGPPublicKeyRing) { PGPPublicKeyRing kr = (PGPPublicKeyRing) obj; if (fp == null || Arrays.equals(fp, kr.getPublicKey().getFingerprint())) { keys.add(kr); } } checkState(!it.hasNext(), "expected one PGP object per ArmoredInputStream"); } if (foundAtLeastOneKey) { return keys; } // Subkey handling String id = new String(bytes, UTF_8); Preconditions.checkArgument(ObjectId.isId(id), "Not valid SHA1: " + id); return get(ObjectId.fromString(id), fp); } } public void rebuildSubkeyMasterKeyMap() throws MissingObjectException, IncorrectObjectTypeException, IOException, PGPException { if (reader == null) { load(); } if (notes != null) { try (ObjectInserter ins = repo.newObjectInserter()) { for (Note note : notes) { for (PGPPublicKeyRing keyRing : new PGPPublicKeyRingCollection(readKeysFromNote(note, null))) { long masterKeyId = keyRing.getPublicKey().getKeyID(); ObjectId masterKeyObjectId = keyObjectId(masterKeyId); saveSubkeyMapping(ins, keyRing, masterKeyId, masterKeyObjectId); } } } } } /** * Add a public key to the store. * * <p>Multiple calls may be made to buffer keys in memory, and they are not saved until {@link * #save(CommitBuilder)} is called. * * @param keyRing a key ring containing exactly one public master key. */ public void add(PGPPublicKeyRing keyRing) { int numMaster = 0; for (PGPPublicKey key : keyRing) { if (key.isMasterKey()) { numMaster++; } } // We could have an additional sanity check to ensure all subkeys belong to // this master key, but that requires doing actual signature verification // here. The alternative is insane but harmless. if (numMaster != 1) { throw new IllegalArgumentException("Exactly 1 master key is required, found " + numMaster); } Fingerprint fp = new Fingerprint(keyRing.getPublicKey().getFingerprint()); toAdd.put(fp, keyRing); toRemove.remove(fp); } /** * Remove a public key from the store. * * <p>Multiple calls may be made to buffer deletes in memory, and they are not saved until {@link * #save(CommitBuilder)} is called. * * @param fingerprint the fingerprint of the key to remove. */ public void remove(byte[] fingerprint) { Fingerprint fp = new Fingerprint(fingerprint); toAdd.remove(fp); toRemove.add(fp); } /** * Save pending keys to the store. * * <p>One commit is created and the ref updated. The pending list is cleared if and only if the * ref update succeeds, which allows for easy retries in case of lock failure. * * @param cb commit builder with at least author and identity populated; tree and parent are * ignored. * @return result of the ref update. */ public RefUpdate.Result save(CommitBuilder cb) throws PGPException, IOException { if (toAdd.isEmpty() && toRemove.isEmpty()) { return RefUpdate.Result.NO_CHANGE; } if (reader == null) { load(); } if (notes == null) { notes = NoteMap.newEmptyMap(); } ObjectId newTip; try (ObjectInserter ins = repo.newObjectInserter()) { for (PGPPublicKeyRing keyRing : toAdd.values()) { saveToNotes(ins, keyRing); } for (Fingerprint fp : toRemove) { deleteFromNotes(ins, fp); } cb.setTreeId(notes.writeTree(ins)); if (cb.getTreeId().equals(tip != null ? tip.getTree() : EMPTY_TREE)) { return RefUpdate.Result.NO_CHANGE; } if (tip != null) { cb.setParentId(tip); } if (cb.getMessage() == null) { int n = toAdd.size() + toRemove.size(); cb.setMessage(String.format("Update %d public key%s", n, n != 1 ? "s" : "")); } newTip = ins.insert(cb); ins.flush(); } RefUpdate ru = repo.updateRef(PublicKeyStore.REFS_GPG_KEYS); ru.setExpectedOldObjectId(tip); ru.setNewObjectId(newTip); ru.setRefLogIdent(cb.getCommitter()); ru.setRefLogMessage("Store public keys", true); RefUpdate.Result result = ru.update(); reset(); switch (result) { case FAST_FORWARD: case NEW: case NO_CHANGE: toAdd.clear(); toRemove.clear(); break; case FORCED: case IO_FAILURE: case LOCK_FAILURE: case NOT_ATTEMPTED: case REJECTED: case REJECTED_CURRENT_BRANCH: case RENAMED: case REJECTED_MISSING_OBJECT: case REJECTED_OTHER_REASON: default: break; } return result; } private void saveToNotes(ObjectInserter ins, PGPPublicKeyRing keyRing) throws PGPException, IOException { long masterKeyId = keyRing.getPublicKey().getKeyID(); PGPPublicKeyRingCollection existing = get(masterKeyId); List<PGPPublicKeyRing> toWrite = new ArrayList<>(existing.size() + 1); boolean replaced = false; for (PGPPublicKeyRing kr : existing) { if (sameKey(keyRing, kr)) { toWrite.add(keyRing); replaced = true; } else { toWrite.add(kr); } } if (!replaced) { toWrite.add(keyRing); } ObjectId masterKeyObjectId = keyObjectId(masterKeyId); notes.set(masterKeyObjectId, ins.insert(OBJ_BLOB, keysToArmored(toWrite))); saveSubkeyMapping(ins, keyRing, masterKeyId, masterKeyObjectId); } private void saveSubkeyMapping( ObjectInserter ins, PGPPublicKeyRing keyRing, long masterKeyId, ObjectId masterKeyObjectId) throws IOException { // Subkey handling byte[] masterKeyBytes = masterKeyObjectId.name().getBytes(UTF_8); ObjectId masterKeyObject = null; for (PGPPublicKey key : keyRing) { long subKeyId = key.getKeyID(); // Skip master public key if (masterKeyId == subKeyId) { continue; } // Insert master key object only once for all subkeys if (masterKeyObject == null) { masterKeyObject = ins.insert(OBJ_BLOB, masterKeyBytes); } ObjectId subkeyObjectId = keyObjectId(subKeyId); Preconditions.checkArgument( notes.get(subkeyObjectId) == null || notes.get(subkeyObjectId).equals(masterKeyObject), "Master key differs for subkey: " + subkeyObjectId.name()); notes.set(subkeyObjectId, masterKeyObject); } } private void deleteFromNotes(ObjectInserter ins, Fingerprint fp) throws PGPException, IOException { long keyId = fp.getId(); PGPPublicKeyRingCollection existing = get(keyId); List<PGPPublicKeyRing> toWrite = new ArrayList<>(existing.size()); for (PGPPublicKeyRing kr : existing) { if (!fp.equalsBytes(kr.getPublicKey().getFingerprint())) { toWrite.add(kr); } } if (toWrite.size() == existing.size()) { return; } ObjectId keyObjectId = keyObjectId(keyId); if (!toWrite.isEmpty()) { notes.set(keyObjectId, ins.insert(OBJ_BLOB, keysToArmored(toWrite))); } else { PGPPublicKeyRing keyRing = get(fp.get()); for (PGPPublicKey key : keyRing) { long subKeyId = key.getKeyID(); // Skip master public key if (keyId == subKeyId) { continue; } notes.remove(keyObjectId(subKeyId)); } notes.remove(keyObjectId); } } private static boolean sameKey(PGPPublicKeyRing kr1, PGPPublicKeyRing kr2) { return Arrays.equals(kr1.getPublicKey().getFingerprint(), kr2.getPublicKey().getFingerprint()); } private static byte[] keysToArmored(List<PGPPublicKeyRing> keys) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(4096 * keys.size()); for (PGPPublicKeyRing kr : keys) { try (ArmoredOutputStream aout = new ArmoredOutputStream(out)) { kr.encode(aout); } } return out.toByteArray(); } public static String keyToString(PGPPublicKey key) { Iterator<String> it = key.getUserIDs(); return String.format( "%s %s(%s)", keyIdToString(key.getKeyID()), it.hasNext() ? it.next() + " " : "", Fingerprint.toString(key.getFingerprint())); } public static String keyIdToString(long keyId) { // Match key ID format from gpg --list-keys. return String.format("%08X", (int) keyId); } static ObjectId keyObjectId(long keyId) { byte[] buf = new byte[Constants.OBJECT_ID_LENGTH]; NB.encodeInt64(buf, 0, keyId); return ObjectId.fromRaw(buf); } }
java/com/google/gerrit/gpg/PublicKeyStore.java
// Copyright (C) 2015 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.gpg; import static com.google.common.base.Preconditions.checkState; import static java.nio.charset.StandardCharsets.UTF_8; import static org.eclipse.jgit.lib.Constants.OBJ_BLOB; import com.google.common.base.Preconditions; import com.google.common.io.ByteStreams; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.bouncycastle.bcpg.ArmoredInputStream; import org.bouncycastle.bcpg.ArmoredOutputStream; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.openpgp.PGPPublicKeyRing; import org.bouncycastle.openpgp.PGPPublicKeyRingCollection; import org.bouncycastle.openpgp.PGPSignature; import org.bouncycastle.openpgp.bc.BcPGPObjectFactory; import org.bouncycastle.openpgp.operator.bc.BcPGPContentVerifierBuilderProvider; import org.eclipse.jgit.errors.IncorrectObjectTypeException; import org.eclipse.jgit.errors.MissingObjectException; import org.eclipse.jgit.lib.CommitBuilder; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectInserter; import org.eclipse.jgit.lib.ObjectReader; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.RefUpdate; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.notes.Note; import org.eclipse.jgit.notes.NoteMap; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.util.NB; /** * Store of GPG public keys in git notes. * * <p>Keys are stored in filenames based on their hex key ID, padded out to 40 characters to match * the length of a SHA-1. (This is to easily reuse existing fanout code in {@link NoteMap}, and may * be changed later after an appropriate transition.) * * <p>The contents of each file is an ASCII armored stream containing one or more public key rings * matching the ID. Multiple keys are supported because forging a key ID is possible, but such a key * cannot be used to verify signatures produced with the correct key. * * <p>Subkeys are mapped to the master GPG key in the same NoteMap. * * <p>No additional checks are performed on the key after reading; callers should only trust keys * after checking with a {@link PublicKeyChecker}. */ public class PublicKeyStore implements AutoCloseable { private static final ObjectId EMPTY_TREE = ObjectId.fromString("4b825dc642cb6eb9a060e54bf8d69288fbee4904"); /** Ref where GPG public keys are stored. */ public static final String REFS_GPG_KEYS = "refs/meta/gpg-keys"; /** * Choose the public key that produced a signature. * * <p> * * @param keyRings candidate keys. * @param sig signature object. * @param data signed payload. * @return the key chosen from {@code keyRings} that was able to verify the signature, or {@code * null} if none was found. * @throws PGPException if an error occurred verifying the signature. */ public static PGPPublicKey getSigner( Iterable<PGPPublicKeyRing> keyRings, PGPSignature sig, byte[] data) throws PGPException { for (PGPPublicKeyRing kr : keyRings) { // Possibly return a signing subkey in case it differs from the master public key PGPPublicKey k = kr.getPublicKey(sig.getKeyID()); if (k == null) { throw new IllegalStateException( "No public key found for ID: " + keyIdToString(sig.getKeyID())); } sig.init(new BcPGPContentVerifierBuilderProvider(), k); sig.update(data); if (sig.verify()) { // If the signature was made using a subkey, return the main public key. // This enables further validity checks, like user ID checks, that can only // be performed using the master public key. return kr.getPublicKey(); } } return null; } /** * Choose the public key that produced a certification. * * <p> * * @param keyRings candidate keys. * @param sig signature object. * @param userId user ID being certified. * @param key key being certified. * @return the key chosen from {@code keyRings} that was able to verify the certification, or * {@code null} if none was found. * @throws PGPException if an error occurred verifying the certification. */ public static PGPPublicKey getSigner( Iterable<PGPPublicKeyRing> keyRings, PGPSignature sig, String userId, PGPPublicKey key) throws PGPException { for (PGPPublicKeyRing kr : keyRings) { PGPPublicKey k = kr.getPublicKey(); sig.init(new BcPGPContentVerifierBuilderProvider(), k); if (sig.verifyCertification(userId, key)) { return k; } } return null; } private final Repository repo; private ObjectReader reader; private RevCommit tip; private NoteMap notes; private Map<Fingerprint, PGPPublicKeyRing> toAdd; private Set<Fingerprint> toRemove; /** @param repo repository to read keys from. */ public PublicKeyStore(Repository repo) { this.repo = repo; toAdd = new HashMap<>(); toRemove = new HashSet<>(); } @Override public void close() { reset(); } private void reset() { if (reader != null) { reader.close(); reader = null; notes = null; } } private void load() throws IOException { reset(); reader = repo.newObjectReader(); Ref ref = repo.getRefDatabase().exactRef(REFS_GPG_KEYS); if (ref == null) { return; } try (RevWalk rw = new RevWalk(reader)) { tip = rw.parseCommit(ref.getObjectId()); notes = NoteMap.read(reader, tip); } } /** * Read public keys with the given key ID. * * <p>Keys should not be trusted unless checked with {@link PublicKeyChecker}. * * <p>Multiple calls to this method use the same state of the key ref; to reread the ref, call * {@link #close()} first. * * @param keyId key ID. * @return any keys found that could be successfully parsed. * @throws PGPException if an error occurred parsing the key data. * @throws IOException if an error occurred reading the repository data. */ public PGPPublicKeyRingCollection get(long keyId) throws PGPException, IOException { return new PGPPublicKeyRingCollection(get(keyId, null)); } /** * Read public key with the given fingerprint. * * <p>Keys should not be trusted unless checked with {@link PublicKeyChecker}. * * <p>Multiple calls to this method use the same state of the key ref; to reread the ref, call * {@link #close()} first. * * @param fingerprint key fingerprint. * @return the key if found, or {@code null}. * @throws PGPException if an error occurred parsing the key data. * @throws IOException if an error occurred reading the repository data. */ public PGPPublicKeyRing get(byte[] fingerprint) throws PGPException, IOException { List<PGPPublicKeyRing> keyRings = get(Fingerprint.getId(fingerprint), fingerprint); return !keyRings.isEmpty() ? keyRings.get(0) : null; } private List<PGPPublicKeyRing> get(long keyId, byte[] fp) throws IOException { if (reader == null) { load(); } if (notes == null) { return Collections.emptyList(); } return get(keyObjectId(keyId), fp); } private List<PGPPublicKeyRing> get(ObjectId keyObjectId, byte[] fp) throws IOException { Note note = notes.getNote(keyObjectId); if (note == null) { return Collections.emptyList(); } return readKeysFromNote(note, fp); } private List<PGPPublicKeyRing> readKeysFromNote(Note note, byte[] fp) throws IOException, MissingObjectException, IncorrectObjectTypeException { boolean foundAtLeastOneKey = false; List<PGPPublicKeyRing> keys = new ArrayList<>(); ObjectId data = note.getData(); try (InputStream stream = reader.open(data, OBJ_BLOB).openStream()) { byte[] bytes = ByteStreams.toByteArray(stream); InputStream in = new ByteArrayInputStream(bytes); while (true) { @SuppressWarnings("unchecked") Iterator<Object> it = new BcPGPObjectFactory(new ArmoredInputStream(in)).iterator(); if (!it.hasNext()) { break; } foundAtLeastOneKey = true; Object obj = it.next(); if (obj instanceof PGPPublicKeyRing) { PGPPublicKeyRing kr = (PGPPublicKeyRing) obj; if (fp == null || Arrays.equals(fp, kr.getPublicKey().getFingerprint())) { keys.add(kr); } } checkState(!it.hasNext(), "expected one PGP object per ArmoredInputStream"); } if (foundAtLeastOneKey) { return keys; } // Subkey handling String id = new String(bytes, UTF_8); Preconditions.checkArgument(ObjectId.isId(id), "Not valid SHA1: " + id); return get(ObjectId.fromString(id), fp); } } public void rebuildSubkeyMasterKeyMap() throws MissingObjectException, IncorrectObjectTypeException, IOException, PGPException { if (reader == null) { load(); } if (notes != null) { try (ObjectInserter ins = repo.newObjectInserter()) { for (Note note : notes) { for (PGPPublicKeyRing keyRing : new PGPPublicKeyRingCollection(readKeysFromNote(note, null))) { long masterKeyId = keyRing.getPublicKey().getKeyID(); ObjectId masterKeyObjectId = keyObjectId(masterKeyId); saveSubkeyMaping(ins, keyRing, masterKeyId, masterKeyObjectId); } } } } } /** * Add a public key to the store. * * <p>Multiple calls may be made to buffer keys in memory, and they are not saved until {@link * #save(CommitBuilder)} is called. * * @param keyRing a key ring containing exactly one public master key. */ public void add(PGPPublicKeyRing keyRing) { int numMaster = 0; for (PGPPublicKey key : keyRing) { if (key.isMasterKey()) { numMaster++; } } // We could have an additional sanity check to ensure all subkeys belong to // this master key, but that requires doing actual signature verification // here. The alternative is insane but harmless. if (numMaster != 1) { throw new IllegalArgumentException("Exactly 1 master key is required, found " + numMaster); } Fingerprint fp = new Fingerprint(keyRing.getPublicKey().getFingerprint()); toAdd.put(fp, keyRing); toRemove.remove(fp); } /** * Remove a public key from the store. * * <p>Multiple calls may be made to buffer deletes in memory, and they are not saved until {@link * #save(CommitBuilder)} is called. * * @param fingerprint the fingerprint of the key to remove. */ public void remove(byte[] fingerprint) { Fingerprint fp = new Fingerprint(fingerprint); toAdd.remove(fp); toRemove.add(fp); } /** * Save pending keys to the store. * * <p>One commit is created and the ref updated. The pending list is cleared if and only if the * ref update succeeds, which allows for easy retries in case of lock failure. * * @param cb commit builder with at least author and identity populated; tree and parent are * ignored. * @return result of the ref update. */ public RefUpdate.Result save(CommitBuilder cb) throws PGPException, IOException { if (toAdd.isEmpty() && toRemove.isEmpty()) { return RefUpdate.Result.NO_CHANGE; } if (reader == null) { load(); } if (notes == null) { notes = NoteMap.newEmptyMap(); } ObjectId newTip; try (ObjectInserter ins = repo.newObjectInserter()) { for (PGPPublicKeyRing keyRing : toAdd.values()) { saveToNotes(ins, keyRing); } for (Fingerprint fp : toRemove) { deleteFromNotes(ins, fp); } cb.setTreeId(notes.writeTree(ins)); if (cb.getTreeId().equals(tip != null ? tip.getTree() : EMPTY_TREE)) { return RefUpdate.Result.NO_CHANGE; } if (tip != null) { cb.setParentId(tip); } if (cb.getMessage() == null) { int n = toAdd.size() + toRemove.size(); cb.setMessage(String.format("Update %d public key%s", n, n != 1 ? "s" : "")); } newTip = ins.insert(cb); ins.flush(); } RefUpdate ru = repo.updateRef(PublicKeyStore.REFS_GPG_KEYS); ru.setExpectedOldObjectId(tip); ru.setNewObjectId(newTip); ru.setRefLogIdent(cb.getCommitter()); ru.setRefLogMessage("Store public keys", true); RefUpdate.Result result = ru.update(); reset(); switch (result) { case FAST_FORWARD: case NEW: case NO_CHANGE: toAdd.clear(); toRemove.clear(); break; case FORCED: case IO_FAILURE: case LOCK_FAILURE: case NOT_ATTEMPTED: case REJECTED: case REJECTED_CURRENT_BRANCH: case RENAMED: case REJECTED_MISSING_OBJECT: case REJECTED_OTHER_REASON: default: break; } return result; } private void saveToNotes(ObjectInserter ins, PGPPublicKeyRing keyRing) throws PGPException, IOException { long masterKeyId = keyRing.getPublicKey().getKeyID(); PGPPublicKeyRingCollection existing = get(masterKeyId); List<PGPPublicKeyRing> toWrite = new ArrayList<>(existing.size() + 1); boolean replaced = false; for (PGPPublicKeyRing kr : existing) { if (sameKey(keyRing, kr)) { toWrite.add(keyRing); replaced = true; } else { toWrite.add(kr); } } if (!replaced) { toWrite.add(keyRing); } ObjectId masterKeyObjectId = keyObjectId(masterKeyId); notes.set(masterKeyObjectId, ins.insert(OBJ_BLOB, keysToArmored(toWrite))); saveSubkeyMaping(ins, keyRing, masterKeyId, masterKeyObjectId); } private void saveSubkeyMaping( ObjectInserter ins, PGPPublicKeyRing keyRing, long masterKeyId, ObjectId masterKeyObjectId) throws IOException { // Subkey handling byte[] masterKeyBytes = masterKeyObjectId.name().getBytes(UTF_8); ObjectId masterKeyObject = null; for (PGPPublicKey key : keyRing) { long subKeyId = key.getKeyID(); // Skip master public key if (masterKeyId == subKeyId) { continue; } // Insert master key object only once for all subkeys if (masterKeyObject == null) { masterKeyObject = ins.insert(OBJ_BLOB, masterKeyBytes); } ObjectId subkeyObjectId = keyObjectId(subKeyId); Preconditions.checkArgument( notes.get(subkeyObjectId) == null || notes.get(subkeyObjectId).equals(masterKeyObject), "Master key differs for subkey: " + subkeyObjectId.name()); notes.set(subkeyObjectId, masterKeyObject); } } private void deleteFromNotes(ObjectInserter ins, Fingerprint fp) throws PGPException, IOException { long keyId = fp.getId(); PGPPublicKeyRingCollection existing = get(keyId); List<PGPPublicKeyRing> toWrite = new ArrayList<>(existing.size()); for (PGPPublicKeyRing kr : existing) { if (!fp.equalsBytes(kr.getPublicKey().getFingerprint())) { toWrite.add(kr); } } if (toWrite.size() == existing.size()) { return; } ObjectId keyObjectId = keyObjectId(keyId); if (!toWrite.isEmpty()) { notes.set(keyObjectId, ins.insert(OBJ_BLOB, keysToArmored(toWrite))); } else { PGPPublicKeyRing keyRing = get(fp.get()); for (PGPPublicKey key : keyRing) { long subKeyId = key.getKeyID(); // Skip master public key if (keyId == subKeyId) { continue; } notes.remove(keyObjectId(subKeyId)); } notes.remove(keyObjectId); } } private static boolean sameKey(PGPPublicKeyRing kr1, PGPPublicKeyRing kr2) { return Arrays.equals(kr1.getPublicKey().getFingerprint(), kr2.getPublicKey().getFingerprint()); } private static byte[] keysToArmored(List<PGPPublicKeyRing> keys) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(4096 * keys.size()); for (PGPPublicKeyRing kr : keys) { try (ArmoredOutputStream aout = new ArmoredOutputStream(out)) { kr.encode(aout); } } return out.toByteArray(); } public static String keyToString(PGPPublicKey key) { Iterator<String> it = key.getUserIDs(); return String.format( "%s %s(%s)", keyIdToString(key.getKeyID()), it.hasNext() ? it.next() + " " : "", Fingerprint.toString(key.getFingerprint())); } public static String keyIdToString(long keyId) { // Match key ID format from gpg --list-keys. return String.format("%08X", (int) keyId); } static ObjectId keyObjectId(long keyId) { byte[] buf = new byte[Constants.OBJECT_ID_LENGTH]; NB.encodeInt64(buf, 0, keyId); return ObjectId.fromRaw(buf); } }
PublicKeyStore: Fix typo in method name Change-Id: I66abc5dda40ebb5eb2c032e26886207930121786
java/com/google/gerrit/gpg/PublicKeyStore.java
PublicKeyStore: Fix typo in method name
Java
apache-2.0
f0dfb20f378e6628a9d9bcbe10ca0e56cecdb743
0
felixb/websms-api
/* * Copyright (C) 2010 Felix Bechstein * * This file is part of WebSMS. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; If not, see <http://www.gnu.org/licenses/>. */ package de.ub0r.android.websms.connector.common; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.cookie.Cookie; import org.apache.http.cookie.CookieOrigin; import org.apache.http.cookie.MalformedCookieException; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.cookie.BrowserCompatSpec; import org.apache.http.impl.cookie.CookieSpecBase; import org.apache.http.message.BasicNameValuePair; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; /** * General Utils calls. * * @author flx */ public final class Utils { /** Tag for output. */ private static final String TAG = "utl"; /** Standard buffer size. */ public static final int BUFSIZE = 32768; /** HTTP Response 200. */ public static final int HTTP_SERVICE_OK = 200; /** HTTP Response 401. */ public static final int HTTP_SERVICE_UNAUTHORIZED = 401; /** HTTP Response 500. */ public static final int HTTP_SERVICE_500 = 500; /** HTTP Response 503. */ public static final int HTTP_SERVICE_UNAVAILABLE = 503; /** Default port for HTTP. */ private static final int PORT_HTTP = 80; /** Default port for HTTPS. */ private static final int PORT_HTTPS = 443; /** Preference's name: use default sender. */ public static final String PREFS_USE_DEFAULT_SENDER = "use_default_sender"; /** Preference's name: custom sender. */ public static final String PREFS_CUSTOM_SENDER = "custom_sender"; /** Resturn only matching line in stream2str(). */ public static final int ONLY_MATCHING_LINE = -2; /** * No Constructor needed here. */ private Utils() { return; } /** * Get custom sender from preferences by users choice. Else: default sender * is selected. * * @param context * {@link Context} * @param defSender * default Sender * @return selected Sender */ public static String getSender(final Context context, // . final String defSender) { if (context == null) { return defSender; } final SharedPreferences p = PreferenceManager .getDefaultSharedPreferences(context); if (p.getBoolean(PREFS_USE_DEFAULT_SENDER, true)) { return defSender; } final String s = p.getString(PREFS_CUSTOM_SENDER, ""); if (s == null || s.length() == 0) { return defSender; } return s; } /** * Parse a String of "name <number>, name <number>, number, ..." to an array * of "name <number>". * * @param recipients * recipients * @return array of recipients */ public static String[] parseRecipients(final String recipients) { String s = recipients.trim(); if (s.endsWith(",")) { s = s.substring(0, s.length() - 1); } ArrayList<String> ret = new ArrayList<String>(); String[] ss = s.split(","); final int l = ss.length; String r = null; String rr; for (int i = 0; i < l; i++) { rr = ss[i]; if (r == null) { r = rr; } else { r += "," + rr; } if (rr.contains("0") || rr.contains("1") || rr.contains("2") || rr.contains("3") || rr.contains("4") || rr.contains("5") || rr.contains("6") || rr.contains("7") || rr.contains("8") || rr.contains("9")) { r = r.trim(); final String na = getRecipientsName(r); final String nu = cleanRecipient(getRecipientsNumber(r)); if (na != null && na.trim().length() > 0) { r = na + " <" + nu + ">"; } else { r = nu; } ret.add(r); r = null; } } return ret.toArray(new String[0]); } /** * Join an array of recipients separated with separator. * * @param recipients * recipients * @param separator * separator * @return joined recipients */ public static String joinRecipients(final String[] recipients, final String separator) { if (recipients == null) { return null; } final int e = recipients.length; if (e == 0) { return null; } final StringBuilder buf = new StringBuilder(recipients[0]); for (int i = 1; i < e; i++) { buf.append(separator); buf.append(recipients[i]); } return buf.toString(); } /** * Join an array of recipients separated with separator, stripped to only * contain numbers. * * @param recipients * recipients * @param separator * separator * @param oldFormat * Use old international format. E.g. 0049, not +49. * @return joined recipients */ public static String joinRecipientsNumbers(final String[] recipients, final String separator, final boolean oldFormat) { if (recipients == null) { return null; } final int e = recipients.length; if (e == 0) { return null; } final StringBuilder buf = new StringBuilder(); if (oldFormat) { buf.append(international2oldformat(// . getRecipientsNumber(recipients[0]))); } else { buf.append(getRecipientsNumber(recipients[0])); } for (int i = 1; i < e; i++) { buf.append(separator); if (oldFormat) { buf.append(international2oldformat(// . getRecipientsNumber(recipients[i]))); } else { buf.append(getRecipientsNumber(recipients[i])); } } return buf.toString(); } /** * Get a recipient's number. * * @param recipient * recipient * @return recipient's number */ public static String getRecipientsNumber(final String recipient) { final int i = recipient.lastIndexOf('<'); if (i >= 0) { final int j = recipient.indexOf('>', i); if (j > 0) { return recipient.substring(i + 1, j); } } return recipient; } /** * Get a recipient's name. * * @param recipient * recipient * @return recipient's name */ public static String getRecipientsName(final String recipient) { final int i = recipient.lastIndexOf('<'); if (i > 0) { return recipient.substring(0, i - 1).trim(); } return recipient; } /** * Clean recipient's phone number from [ -.()<>]. * * @param recipient * recipient's mobile number * @return clean number */ public static String cleanRecipient(final String recipient) { if (recipient == null) { return ""; } return recipient.replaceAll("[^+0-9]", "").trim(); } /** * Convert international number to national. * * @param defPrefix * default prefix * @param number * international number * @return national number */ public static String international2national(final String defPrefix, final String number) { if (number.startsWith(defPrefix)) { return '0' + number.substring(defPrefix.length()); } else if (number.startsWith("00" + defPrefix.substring(1))) { return '0' + number.substring(defPrefix.length() + 1); } return number; } /** * Convert national number to international. Old format internationals were * converted to new format. * * @param defPrefix * default prefix * @param number * national number * @return international number */ public static String national2international(final String defPrefix, final String number) { if (number.startsWith("+")) { return number; } else if (number.startsWith("00")) { return "+" + number.substring(2); } else if (number.startsWith("0")) { return defPrefix + number.substring(1); } return defPrefix + number; } /** * Convert national number to international. * * @param defPrefix * default prefix * @param number * national numbers * @return international numbers */ public static String[] national2international(final String defPrefix, final String[] number) { final int l = number.length; String[] n = new String[l]; for (int i = 0; i < l; i++) { n[i] = national2international(defPrefix, getRecipientsNumber(number[i])); } return n; } /** * Convert international number to old format. Eg. +49123 to 0049123 * * @param number * international number starting with + * @return international number in old format starting with 00 */ public static String international2oldformat(final String number) { if (number.startsWith("+")) { return "00" + number.substring(1); } return number; } /** * Get a fresh HTTP-Connection. * * @param url * URL to open * @param cookies * cookies to transmit * @param postData * post data * @param userAgent * user agent * @param referer * referer * @return the connection * @throws IOException * IOException */ public static HttpResponse getHttpClient(final String url, final ArrayList<Cookie> cookies, final ArrayList<BasicNameValuePair> postData, final String userAgent, final String referer) throws IOException { Log.d(TAG, "HTTPClient URL: " + url); final DefaultHttpClient client = new DefaultHttpClient(); HttpRequestBase request; if (postData == null) { request = new HttpGet(url); } else { request = new HttpPost(url); ((HttpPost) request).setEntity(new UrlEncodedFormEntity(postData, "ISO-8859-15")); // TODO make it as parameter Log.d(TAG, "HTTPClient POST: " + postData); } if (referer != null) { request.setHeader("Referer", referer); Log.d(TAG, "HTTPClient REF: " + referer); } if (userAgent != null) { request.setHeader("User-Agent", userAgent); Log.d(TAG, "HTTPClient AGENT: " + userAgent); } if (cookies != null && cookies.size() > 0) { final CookieSpecBase cookieSpecBase = new BrowserCompatSpec(); for (final Header cookieHeader : cookieSpecBase .formatCookies(cookies)) { // Setting the cookie request.setHeader(cookieHeader); Log.d(TAG, "HTTPClient COOKIE: " + cookieHeader); } } return client.execute(request); } /** * Update cookies from response. * * @param cookies * old {@link Cookie} list * @param headers * {@link Header}s from {@link HttpResponse} * @param url * requested URL * @throws URISyntaxException * malformed URI * @throws MalformedCookieException * malformed {@link Cookie} */ public static void updateCookies(final ArrayList<Cookie> cookies, final Header[] headers, final String url) throws URISyntaxException, MalformedCookieException { final URI uri = new URI(url); int port = uri.getPort(); if (port < 0) { if (url.startsWith("https")) { port = PORT_HTTPS; } else { port = PORT_HTTP; } } final CookieOrigin origin = new CookieOrigin(uri.getHost(), port, uri .getPath(), false); final CookieSpecBase cookieSpecBase = new BrowserCompatSpec(); String name; String value; for (final Header header : headers) { for (final Cookie cookie : cookieSpecBase.parse(header, origin)) { // THE cookie name = cookie.getName(); value = cookie.getValue(); if (value == null || value.equals("")) { continue; } for (final Cookie c : cookies) { if (name.equals(c.getName())) { cookies.remove(c); cookies.add(cookie); name = null; break; } } if (name != null) { cookies.add(cookie); } } } } /** * Read {@link InputStream} and convert it into {@link String}. * * @param is * {@link InputStream} to read from * @return {@link String} holding all the bytes from the {@link InputStream} * @throws IOException * IOException */ public static String stream2str(final InputStream is) throws IOException { return stream2str(is, 0, -1, null); } /** * Read {@link InputStream} and convert it into {@link String}. * * @param is * {@link InputStream} to read from param charset to read the * {@link InputStream}. Can be null. * @param charset * charset to be used to read {@link InputStream}. Can be null. * @return {@link String} holding all the bytes from the {@link InputStream} * @throws IOException * IOException */ public static String stream2str(final InputStream is, final String charset) throws IOException { return stream2str(is, 0, -1, null); } /** * Read {@link InputStream} and convert it into {@link String}. * * @param is * {@link InputStream} to read from * @param start * first characters of stream that should be fetched. Set to 0, * if nothing should be skipped. * @param end * last characters of stream that should be fetched. This method * might read some more characters. Set to -1 if all characters * should be read. * @return {@link String} holding all the bytes from the {@link InputStream} * @throws IOException * IOException */ public static String stream2str(final InputStream is, final int start, final int end) throws IOException { return stream2str(is, null, start, end); } /** * Read {@link InputStream} and convert it into {@link String}. * * @param is * {@link InputStream} to read from param charset to read the * {@link InputStream}. Can be null. * @param charset * charset to be used to read {@link InputStream}. Can be null. * @param start * first characters of stream that should be fetched. Set to 0, * if nothing should be skipped. * @param end * last characters of stream that should be fetched. This method * might read some more characters. Set to -1 if all characters * should be read. * @return {@link String} holding all the bytes from the {@link InputStream} * @throws IOException * IOException */ public static String stream2str(final InputStream is, final String charset, final int start, final int end) throws IOException { return stream2str(is, charset, start, end, null); } /** * Read {@link InputStream} and convert it into {@link String}. * * @param is * {@link InputStream} to read from * @param start * first characters of stream that should be fetched. Set to 0, * if nothing should be skipped. * @param end * last characters of stream that should be fetched. This method * might read some more characters. Set to -1 if all characters * should be read. * @param pattern * start reading at this pattern, set end = -2 to return only the * line, matching this pattern * @return {@link String} holding all the bytes from the {@link InputStream} * @throws IOException * IOException */ public static String stream2str(final InputStream is, final int start, final int end, final String pattern) throws IOException { return stream2str(is, null, start, end, pattern); } /** * Read {@link InputStream} and convert it into {@link String}. * * @param is * {@link InputStream} to read from * @param charset * charset to be used to read {@link InputStream}. Can be null. * @param start * first characters of stream that should be fetched. Set to 0, * if nothing should be skipped. * @param end * last characters of stream that should be fetched. This method * might read some more characters. Set to -1 if all characters * should be read. * @param pattern * start reading at this pattern, set end = -2 to return only the * line, matching this pattern * @return {@link String} holding all the bytes from the {@link InputStream} * @throws IOException * IOException */ public static String stream2str(final InputStream is, final String charset, final int start, final int end, final String pattern) throws IOException { boolean foundPattern = false; if (pattern == null) { foundPattern = true; } InputStreamReader r; if (charset == null) { r = new InputStreamReader(is); } else { r = new InputStreamReader(is, charset); } final BufferedReader bufferedReader = new BufferedReader(r, BUFSIZE); final StringBuilder data = new StringBuilder(); String line = null; long totalSkipped = 0; long skipped = 0; while (start > totalSkipped) { skipped = bufferedReader.skip(start - totalSkipped); if (skipped == 0) { break; } totalSkipped += skipped; } skipped = 0; while ((line = bufferedReader.readLine()) != null) { skipped += line.length() + 1; if (!foundPattern) { if (line.indexOf(pattern) >= 0) { if (end == ONLY_MATCHING_LINE) { return line; } foundPattern = true; Log.d(TAG, "skipped: " + skipped); } } if (foundPattern) { data.append(line + "\n"); } if (end >= 0 && skipped > (end - start)) { break; } } bufferedReader.close(); if (!foundPattern) { return null; } return data.toString(); } /** * Generate MD5 Hash from String. * * @param s * input * @return hash */ public static String md5(final String s) { try { // Create MD5 Hash final MessageDigest digest = java.security.MessageDigest .getInstance("MD5"); digest.update(s.getBytes()); final byte[] messageDigest = digest.digest(); // Create Hex String final StringBuilder hexString = new StringBuilder(32); int b; for (int i = 0; i < messageDigest.length; i++) { b = 0xFF & messageDigest[i]; if (b < 0x10) { hexString.append('0' + Integer.toHexString(b)); } else { hexString.append(Integer.toHexString(b)); } } return hexString.toString(); } catch (final NoSuchAlgorithmException e) { Log.e(TAG, null, e); } return ""; } }
src/de/ub0r/android/websms/connector/common/Utils.java
/* * Copyright (C) 2010 Felix Bechstein * * This file is part of WebSMS. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; If not, see <http://www.gnu.org/licenses/>. */ package de.ub0r.android.websms.connector.common; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.cookie.Cookie; import org.apache.http.cookie.CookieOrigin; import org.apache.http.cookie.MalformedCookieException; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.cookie.BrowserCompatSpec; import org.apache.http.impl.cookie.CookieSpecBase; import org.apache.http.message.BasicNameValuePair; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; /** * General Utils calls. * * @author flx */ public final class Utils { /** Tag for output. */ private static final String TAG = "utl"; /** Standard buffer size. */ public static final int BUFSIZE = 32768; /** HTTP Response 200. */ public static final int HTTP_SERVICE_OK = 200; /** HTTP Response 401. */ public static final int HTTP_SERVICE_UNAUTHORIZED = 401; /** HTTP Response 500. */ public static final int HTTP_SERVICE_500 = 500; /** HTTP Response 503. */ public static final int HTTP_SERVICE_UNAVAILABLE = 503; /** Default port for HTTP. */ private static final int PORT_HTTP = 80; /** Default port for HTTPS. */ private static final int PORT_HTTPS = 443; /** Preference's name: use default sender. */ public static final String PREFS_USE_DEFAULT_SENDER = "use_default_sender"; /** Preference's name: custom sender. */ public static final String PREFS_CUSTOM_SENDER = "custom_sender"; /** Resturn only matching line in stream2str(). */ public static final int ONLY_MATCHING_LINE = -2; /** * No Constructor needed here. */ private Utils() { return; } /** * Get custom sender from preferences by users choice. Else: default sender * is selected. * * @param context * {@link Context} * @param defSender * default Sender * @return selected Sender */ public static String getSender(final Context context, // . final String defSender) { if (context == null) { return defSender; } final SharedPreferences p = PreferenceManager .getDefaultSharedPreferences(context); if (p.getBoolean(PREFS_USE_DEFAULT_SENDER, true)) { return defSender; } final String s = p.getString(PREFS_CUSTOM_SENDER, ""); if (s == null || s.length() == 0) { return defSender; } return s; } /** * Parse a String of "name <number>, name <number>, number, ..." to an array * of "name <number>". * * @param recipients * recipients * @return array of recipients */ public static String[] parseRecipients(final String recipients) { String s = recipients.trim(); if (s.endsWith(",")) { s = s.substring(0, s.length() - 1); } ArrayList<String> ret = new ArrayList<String>(); String[] ss = s.split(","); final int l = ss.length; String r = null; String rr; for (int i = 0; i < l; i++) { rr = ss[i]; if (r == null) { r = rr; } else { r += "," + rr; } if (rr.contains("0") || rr.contains("1") || rr.contains("2") || rr.contains("3") || rr.contains("4") || rr.contains("5") || rr.contains("6") || rr.contains("7") || rr.contains("8") || rr.contains("9")) { r = r.trim(); final String na = getRecipientsName(r); final String nu = cleanRecipient(getRecipientsNumber(r)); if (na != null && na.trim().length() > 0) { r = na + " <" + nu + ">"; } else { r = nu; } ret.add(r); r = null; } } return ret.toArray(new String[0]); } /** * Join an array of recipients separated with separator. * * @param recipients * recipients * @param separator * separator * @return joined recipients */ public static String joinRecipients(final String[] recipients, final String separator) { if (recipients == null) { return null; } final int e = recipients.length; if (e == 0) { return null; } final StringBuilder buf = new StringBuilder(recipients[0]); for (int i = 1; i < e; i++) { buf.append(separator); buf.append(recipients[i]); } return buf.toString(); } /** * Join an array of recipients separated with separator, stripped to only * contain numbers. * * @param recipients * recipients * @param separator * separator * @param oldFormat * Use old international format. E.g. 0049, not +49. * @return joined recipients */ public static String joinRecipientsNumbers(final String[] recipients, final String separator, final boolean oldFormat) { if (recipients == null) { return null; } final int e = recipients.length; if (e == 0) { return null; } final StringBuilder buf = new StringBuilder(); if (oldFormat) { buf.append(international2oldformat(// . getRecipientsNumber(recipients[0]))); } else { buf.append(getRecipientsNumber(recipients[0])); } for (int i = 1; i < e; i++) { buf.append(separator); if (oldFormat) { buf.append(international2oldformat(// . getRecipientsNumber(recipients[i]))); } else { buf.append(getRecipientsNumber(recipients[i])); } } return buf.toString(); } /** * Get a recipient's number. * * @param recipient * recipient * @return recipient's number */ public static String getRecipientsNumber(final String recipient) { final int i = recipient.lastIndexOf('<'); if (i >= 0) { final int j = recipient.indexOf('>', i); if (j > 0) { return recipient.substring(i + 1, j); } } return recipient; } /** * Get a recipient's name. * * @param recipient * recipient * @return recipient's name */ public static String getRecipientsName(final String recipient) { final int i = recipient.lastIndexOf('<'); if (i >= 0) { return recipient.substring(0, i - 1).trim(); } return recipient; } /** * Clean recipient's phone number from [ -.()<>]. * * @param recipient * recipient's mobile number * @return clean number */ public static String cleanRecipient(final String recipient) { if (recipient == null) { return ""; } return recipient.replaceAll("[^+0-9]", "").trim(); } /** * Convert international number to national. * * @param defPrefix * default prefix * @param number * international number * @return national number */ public static String international2national(final String defPrefix, final String number) { if (number.startsWith(defPrefix)) { return '0' + number.substring(defPrefix.length()); } else if (number.startsWith("00" + defPrefix.substring(1))) { return '0' + number.substring(defPrefix.length() + 1); } return number; } /** * Convert national number to international. Old format internationals were * converted to new format. * * @param defPrefix * default prefix * @param number * national number * @return international number */ public static String national2international(final String defPrefix, final String number) { if (number.startsWith("+")) { return number; } else if (number.startsWith("00")) { return "+" + number.substring(2); } else if (number.startsWith("0")) { return defPrefix + number.substring(1); } return defPrefix + number; } /** * Convert national number to international. * * @param defPrefix * default prefix * @param number * national numbers * @return international numbers */ public static String[] national2international(final String defPrefix, final String[] number) { final int l = number.length; String[] n = new String[l]; for (int i = 0; i < l; i++) { n[i] = national2international(defPrefix, getRecipientsNumber(number[i])); } return n; } /** * Convert international number to old format. Eg. +49123 to 0049123 * * @param number * international number starting with + * @return international number in old format starting with 00 */ public static String international2oldformat(final String number) { if (number.startsWith("+")) { return "00" + number.substring(1); } return number; } /** * Get a fresh HTTP-Connection. * * @param url * URL to open * @param cookies * cookies to transmit * @param postData * post data * @param userAgent * user agent * @param referer * referer * @return the connection * @throws IOException * IOException */ public static HttpResponse getHttpClient(final String url, final ArrayList<Cookie> cookies, final ArrayList<BasicNameValuePair> postData, final String userAgent, final String referer) throws IOException { Log.d(TAG, "HTTPClient URL: " + url); final DefaultHttpClient client = new DefaultHttpClient(); HttpRequestBase request; if (postData == null) { request = new HttpGet(url); } else { request = new HttpPost(url); ((HttpPost) request).setEntity(new UrlEncodedFormEntity(postData, "ISO-8859-15")); // TODO make it as parameter Log.d(TAG, "HTTPClient POST: " + postData); } if (referer != null) { request.setHeader("Referer", referer); Log.d(TAG, "HTTPClient REF: " + referer); } if (userAgent != null) { request.setHeader("User-Agent", userAgent); Log.d(TAG, "HTTPClient AGENT: " + userAgent); } if (cookies != null && cookies.size() > 0) { final CookieSpecBase cookieSpecBase = new BrowserCompatSpec(); for (final Header cookieHeader : cookieSpecBase .formatCookies(cookies)) { // Setting the cookie request.setHeader(cookieHeader); Log.d(TAG, "HTTPClient COOKIE: " + cookieHeader); } } return client.execute(request); } /** * Update cookies from response. * * @param cookies * old {@link Cookie} list * @param headers * {@link Header}s from {@link HttpResponse} * @param url * requested URL * @throws URISyntaxException * malformed URI * @throws MalformedCookieException * malformed {@link Cookie} */ public static void updateCookies(final ArrayList<Cookie> cookies, final Header[] headers, final String url) throws URISyntaxException, MalformedCookieException { final URI uri = new URI(url); int port = uri.getPort(); if (port < 0) { if (url.startsWith("https")) { port = PORT_HTTPS; } else { port = PORT_HTTP; } } final CookieOrigin origin = new CookieOrigin(uri.getHost(), port, uri .getPath(), false); final CookieSpecBase cookieSpecBase = new BrowserCompatSpec(); String name; String value; for (final Header header : headers) { for (final Cookie cookie : cookieSpecBase.parse(header, origin)) { // THE cookie name = cookie.getName(); value = cookie.getValue(); if (value == null || value.equals("")) { continue; } for (final Cookie c : cookies) { if (name.equals(c.getName())) { cookies.remove(c); cookies.add(cookie); name = null; break; } } if (name != null) { cookies.add(cookie); } } } } /** * Read {@link InputStream} and convert it into {@link String}. * * @param is * {@link InputStream} to read from * @return {@link String} holding all the bytes from the {@link InputStream} * @throws IOException * IOException */ public static String stream2str(final InputStream is) throws IOException { return stream2str(is, 0, -1, null); } /** * Read {@link InputStream} and convert it into {@link String}. * * @param is * {@link InputStream} to read from param charset to read the * {@link InputStream}. Can be null. * @param charset * charset to be used to read {@link InputStream}. Can be null. * @return {@link String} holding all the bytes from the {@link InputStream} * @throws IOException * IOException */ public static String stream2str(final InputStream is, final String charset) throws IOException { return stream2str(is, 0, -1, null); } /** * Read {@link InputStream} and convert it into {@link String}. * * @param is * {@link InputStream} to read from * @param start * first characters of stream that should be fetched. Set to 0, * if nothing should be skipped. * @param end * last characters of stream that should be fetched. This method * might read some more characters. Set to -1 if all characters * should be read. * @return {@link String} holding all the bytes from the {@link InputStream} * @throws IOException * IOException */ public static String stream2str(final InputStream is, final int start, final int end) throws IOException { return stream2str(is, null, start, end); } /** * Read {@link InputStream} and convert it into {@link String}. * * @param is * {@link InputStream} to read from param charset to read the * {@link InputStream}. Can be null. * @param charset * charset to be used to read {@link InputStream}. Can be null. * @param start * first characters of stream that should be fetched. Set to 0, * if nothing should be skipped. * @param end * last characters of stream that should be fetched. This method * might read some more characters. Set to -1 if all characters * should be read. * @return {@link String} holding all the bytes from the {@link InputStream} * @throws IOException * IOException */ public static String stream2str(final InputStream is, final String charset, final int start, final int end) throws IOException { return stream2str(is, charset, start, end, null); } /** * Read {@link InputStream} and convert it into {@link String}. * * @param is * {@link InputStream} to read from * @param start * first characters of stream that should be fetched. Set to 0, * if nothing should be skipped. * @param end * last characters of stream that should be fetched. This method * might read some more characters. Set to -1 if all characters * should be read. * @param pattern * start reading at this pattern, set end = -2 to return only the * line, matching this pattern * @return {@link String} holding all the bytes from the {@link InputStream} * @throws IOException * IOException */ public static String stream2str(final InputStream is, final int start, final int end, final String pattern) throws IOException { return stream2str(is, null, start, end, pattern); } /** * Read {@link InputStream} and convert it into {@link String}. * * @param is * {@link InputStream} to read from * @param charset * charset to be used to read {@link InputStream}. Can be null. * @param start * first characters of stream that should be fetched. Set to 0, * if nothing should be skipped. * @param end * last characters of stream that should be fetched. This method * might read some more characters. Set to -1 if all characters * should be read. * @param pattern * start reading at this pattern, set end = -2 to return only the * line, matching this pattern * @return {@link String} holding all the bytes from the {@link InputStream} * @throws IOException * IOException */ public static String stream2str(final InputStream is, final String charset, final int start, final int end, final String pattern) throws IOException { boolean foundPattern = false; if (pattern == null) { foundPattern = true; } InputStreamReader r; if (charset == null) { r = new InputStreamReader(is); } else { r = new InputStreamReader(is, charset); } final BufferedReader bufferedReader = new BufferedReader(r, BUFSIZE); final StringBuilder data = new StringBuilder(); String line = null; long totalSkipped = 0; long skipped = 0; while (start > totalSkipped) { skipped = bufferedReader.skip(start - totalSkipped); if (skipped == 0) { break; } totalSkipped += skipped; } skipped = 0; while ((line = bufferedReader.readLine()) != null) { skipped += line.length() + 1; if (!foundPattern) { if (line.indexOf(pattern) >= 0) { if (end == ONLY_MATCHING_LINE) { return line; } foundPattern = true; Log.d(TAG, "skipped: " + skipped); } } if (foundPattern) { data.append(line + "\n"); } if (end >= 0 && skipped > (end - start)) { break; } } bufferedReader.close(); if (!foundPattern) { return null; } return data.toString(); } /** * Generate MD5 Hash from String. * * @param s * input * @return hash */ public static String md5(final String s) { try { // Create MD5 Hash final MessageDigest digest = java.security.MessageDigest .getInstance("MD5"); digest.update(s.getBytes()); final byte[] messageDigest = digest.digest(); // Create Hex String final StringBuilder hexString = new StringBuilder(32); int b; for (int i = 0; i < messageDigest.length; i++) { b = 0xFF & messageDigest[i]; if (b < 0x10) { hexString.append('0' + Integer.toHexString(b)); } else { hexString.append(Integer.toHexString(b)); } } return hexString.toString(); } catch (final NoSuchAlgorithmException e) { Log.e(TAG, null, e); } return ""; } }
fix StringIndexOutOfBoundsException
src/de/ub0r/android/websms/connector/common/Utils.java
fix StringIndexOutOfBoundsException
Java
apache-2.0
2d42fb13b0b3c54b4f7007b8796882aeb91be6b7
0
elytra/Teckle
/* * Copyright 2017 Benjamin K (darkevilmac) * * 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.elytradev.teckle; import com.elytradev.teckle.common.TeckleMod; import java.util.Random; /** * Very important to the function of the mod, DO NOT REMOVE! */ public class CorrelatedHint { private static final String[] nonsense = { "kill a puppy!", "cuddle?", "sell our souls?", "use the slide whistle?", "use ASM on NullPointerException?", "reinvent the wheel?", "switch to Geico?", "think about everything that could go wrong?", "pass out?", "drown.", "install a rootkit.", "fly away.", "learn rocket science." }; static { int index = new Random().nextInt(nonsense.length); TeckleMod.LOG.info("Why don't we just go " + nonsense[index]); } }
src/main/java/com/elytradev/teckle/CorrelatedHint.java
/* * Copyright 2017 Benjamin K (darkevilmac) * * 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.elytradev.teckle; import com.elytradev.teckle.common.TeckleMod; import java.util.Random; /** * Very important to the function of the mod, DO NOT REMOVE! */ public class CorrelatedHint { private static final String[] nonsense = { "kill a puppy!", "cuddle?", "sell our souls?", "use the slide whistle?", "use ASM on NullPointerException?", "reinvent the wheel?", "switch to Geico?", "think about everything that could go wrong?", "pass out?", "drown." }; static { int index = new Random().nextInt(nonsense.length); TeckleMod.LOG.info("Why don't we just go " + nonsense[index]); } }
Improve mod interop.
src/main/java/com/elytradev/teckle/CorrelatedHint.java
Improve mod interop.
Java
apache-2.0
886a5b17669e7c1d4a04688b8fdb4c18cc38d574
0
liduanw/bitherj,liduanw/bitherj,bither/bitherj,bither/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 net.bither.bitherj.AbstractApp; import net.bither.bitherj.crypto.ECKey; import net.bither.bitherj.crypto.TransactionSignature; import net.bither.bitherj.db.AbstractDb; import net.bither.bitherj.exception.PasswordException; import net.bither.bitherj.exception.TxBuilderException; import net.bither.bitherj.script.Script; import net.bither.bitherj.script.ScriptBuilder; import net.bither.bitherj.script.ScriptChunk; import net.bither.bitherj.utils.PrivateKeyUtil; import net.bither.bitherj.utils.QRCodeUtil; import net.bither.bitherj.utils.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongycastle.crypto.params.KeyParameter; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import javax.annotation.Nonnull; public class Address implements Comparable<Address> { private static final Logger log = LoggerFactory.getLogger(Address.class); public static final String KEY_SPLIT_STRING = ":"; public static final String PUBLIC_KEY_FILE_NAME_SUFFIX = ".pub"; protected String encryptPrivKey; protected byte[] pubKey; protected String address; protected boolean hasPrivKey; protected boolean syncComplete = false; private long mSortTime; private long balance = 0; private boolean isFromXRandom; public Address(String address, byte[] pubKey, long sortTime, boolean isSyncComplete, boolean isFromXRandom, boolean hasPrivKey) { this.hasPrivKey = hasPrivKey; this.encryptPrivKey = null; this.address = address; this.pubKey = pubKey; this.mSortTime = sortTime; this.syncComplete = isSyncComplete; this.isFromXRandom = isFromXRandom; this.updateBalance(); } public Address(String address, byte[] pubKey, String encryptString, boolean isFromXRandom) { this.encryptPrivKey = encryptString; this.address = address; this.pubKey = pubKey; this.hasPrivKey = !Utils.isEmpty(encryptString); this.updateBalance(); this.isFromXRandom = isFromXRandom; } public int txCount() { return AbstractDb.txProvider.txCount(this.address); } public List<Tx> getRecentlyTxsWithConfirmationCntLessThan(int confirmationCnt, int limit) { List<Tx> txList = new ArrayList<Tx>(); int blockNo = BlockChain.getInstance().getLastBlock().getBlockNo() - confirmationCnt + 1; for (Tx tx : AbstractDb.txProvider.getRecentlyTxsByAddress(this.address, blockNo, limit)) { txList.add(tx); } return txList; } public List<Tx> getTxs() { List<Tx> txs = AbstractDb.txProvider.getTxAndDetailByAddress(this.address); Collections.sort(txs); return txs; } @Override public int compareTo(@Nonnull Address address) { return -1 * Long.valueOf(getmSortTime()).compareTo(Long.valueOf(address.getmSortTime())); } public void updateBalance() { long balance = 0; List<Tx> txs = this.getTxs(); Set<byte[]> invalidTx = new HashSet<byte[]>(); Set<OutPoint> spentOut = new HashSet<OutPoint>(); Set<OutPoint> unspendOut = new HashSet<OutPoint>(); for (int i = txs.size() - 1; i >= 0; i--) { Set<OutPoint> spent = new HashSet<OutPoint>(); Tx tx = txs.get(i); Set<byte[]> inHashes = new HashSet<byte[]>(); for (In in : tx.getIns()) { spent.add(new OutPoint(in.getPrevTxHash(), in.getPrevOutSn())); inHashes.add(in.getPrevTxHash()); } if (tx.getBlockNo() == Tx.TX_UNCONFIRMED && (this.isIntersects(spent, spentOut) || this.isIntersects(inHashes, invalidTx))) { invalidTx.add(tx.getTxHash()); continue; } spentOut.addAll(spent); for (Out out : tx.getOuts()) { if (Utils.compareString(this.getAddress(), out.getOutAddress())) { unspendOut.add(new OutPoint(tx.getTxHash(), out.getOutSn())); balance += out.getOutValue(); } } spent.clear(); spent.addAll(unspendOut); spent.retainAll(spentOut); for (OutPoint o : spent) { Tx tx1 = AbstractDb.txProvider.getTxDetailByTxHash(o.getTxHash()); unspendOut.remove(o); balance -= tx1.getOuts().get(o.getOutSn()).getOutValue(); } } this.balance = balance; } private boolean isIntersects(Set set1, Set set2) { Set result = new HashSet(); result.addAll(set1); result.retainAll(set2); return !result.isEmpty(); } public long getBalance() { return balance; } private long getDeltaBalance() { long oldBalance = this.balance; this.updateBalance(); return this.balance - oldBalance; } public void notificatTx(Tx tx, Tx.TxNotificationType txNotificationType) { long deltaBalance = getDeltaBalance(); AbstractApp.notificationService.notificatTx(this, tx, txNotificationType, deltaBalance); } public void setBlockHeight(List<byte[]> txHashes, int height) { notificatTx(null, Tx.TxNotificationType.txDoubleSpend); } public void removeTx(byte[] txHash) { AbstractDb.txProvider.remove(txHash); } public boolean initTxs(List<Tx> txs) { AbstractDb.txProvider.addTxs(txs); if (txs.size() > 0) { notificatTx(null, Tx.TxNotificationType.txFromApi); } return true; } public byte[] getPubKey() { return this.pubKey; } public String getAddress() { return this.address; } public boolean hasPrivKey() { return this.hasPrivKey; } public boolean isSyncComplete() { return this.syncComplete; } public void setSyncComplete(boolean isSyncComplete) { this.syncComplete = isSyncComplete; } public boolean isFromXRandom() { return this.isFromXRandom; } public void setFromXRandom(boolean isFromXRAndom) { this.isFromXRandom = isFromXRAndom; } public void savePrivateKey() throws IOException { String privateKeyFullFileName = Utils.format(BitherjSettings.PRIVATE_KEY_FILE_NAME, Utils.getPrivateDir(), getAddress()); Utils.writeFile(this.encryptPrivKey, new File(privateKeyFullFileName)); } public void savePubKey(long sortTime) throws IOException { if (hasPrivKey()) { savePubKey(Utils.getPrivateDir().getAbsolutePath(), sortTime); } else { savePubKey(Utils.getWatchOnlyDir().getAbsolutePath(), sortTime); } } private void savePubKey(String dir, long sortTime) throws IOException { this.mSortTime = sortTime; String watchOnlyFullFileName = Utils.format(BitherjSettings.WATCH_ONLY_FILE_NAME, dir, getAddress()); String watchOnlyContent = Utils.format("%s:%s:%s%s", Utils.bytesToHexString(this.pubKey), getSyncCompleteString(), Long.toString(this.mSortTime), getXRandomString()); log.debug("address content " + watchOnlyContent); Utils.writeFile(watchOnlyContent, new File(watchOnlyFullFileName)); } public void updatePubkey() throws IOException { if (hasPrivKey()) { updatePubKey(Utils.getPrivateDir().getAbsolutePath()); } else { updatePubKey(Utils.getWatchOnlyDir().getAbsolutePath()); } } private void updatePubKey(String dir) throws IOException { String watchOnlyFullFileName = Utils.format(BitherjSettings.WATCH_ONLY_FILE_NAME, dir, getAddress()); String watchOnlyContent = Utils.format("%s:%s:%s%s", Utils.bytesToHexString(this.pubKey), getSyncCompleteString(), Long.toString(this.mSortTime), getXRandomString()); log.debug("address content " + watchOnlyContent); Utils.writeFile(watchOnlyContent, new File(watchOnlyFullFileName)); } private String getSyncCompleteString() { return isSyncComplete() ? "1" : "0"; } private String getXRandomString() { return isFromXRandom() ? ":" + QRCodeUtil.XRANDOM_FLAG : ""; } public void removeWatchOnly() { String watchOnlyFullFileName = Utils.format(BitherjSettings.WATCH_ONLY_FILE_NAME, Utils.getWatchOnlyDir(), getAddress()); Utils.removeFile(new File(watchOnlyFullFileName)); } @Override public boolean equals(Object o) { if (o instanceof Address) { Address other = (Address) o; return Utils.compareString(getAddress(), other.getAddress()); } return false; } public long getmSortTime() { return mSortTime; } public String getEncryptPrivKey() { if (this.hasPrivKey) { if (Utils.isEmpty(this.encryptPrivKey)) { String privateKeyFullFileName = Utils.format(BitherjSettings .PRIVATE_KEY_FILE_NAME, Utils.getPrivateDir(), getAddress()); this.encryptPrivKey = Utils.readFile(new File(privateKeyFullFileName)); if (this.encryptPrivKey == null) { //todo backup? } //dispaly new version qrcode this.encryptPrivKey = QRCodeUtil.getNewVersionEncryptPrivKey(this.encryptPrivKey); } return this.encryptPrivKey; } else { return null; } } public void setEncryptPrivKey(String encryptPrivKey) { this.encryptPrivKey = encryptPrivKey; this.hasPrivKey = true; } public Tx buildTx(List<Long> amounts, List<String> addresses) throws TxBuilderException { return TxBuilder.getInstance().buildTx(this, amounts, addresses); } public Tx buildTx(long amount, String address) throws TxBuilderException { List<Long> amounts = new ArrayList<Long>(); amounts.add(amount); List<String> addresses = new ArrayList<String>(); addresses.add(address); return buildTx(amounts, addresses); } public List<Tx> getRecentlyTxs(int confirmationCnt, int limit) { int blockNo = BlockChain.getInstance().lastBlock.getBlockNo() - confirmationCnt + 1; return AbstractDb.txProvider.getRecentlyTxsByAddress(this.address, blockNo, limit); } public String getShortAddress() { return Utils.shortenAddress(getAddress()); } public List<String> signStrHashes(List<String> unsignedInHashes, CharSequence passphrase) { ArrayList<byte[]> hashes = new ArrayList<byte[]>(); for (String h : unsignedInHashes) { hashes.add(Utils.hexStringToByteArray(h)); } List<byte[]> resultHashes = signHashes(hashes, passphrase); ArrayList<String> resultStrs = new ArrayList<String>(); for (byte[] h : resultHashes) { resultStrs.add(Utils.bytesToHexString(h)); } return resultStrs; } public List<byte[]> signHashes(List<byte[]> unsignedInHashes, CharSequence passphrase) throws PasswordException { ECKey key = PrivateKeyUtil.getECKeyFromSingleString(this.getEncryptPrivKey(), passphrase); if (key == null) { throw new PasswordException("do not decrypt eckey"); } KeyParameter assKey = key.getKeyCrypter().deriveKey(passphrase); List<byte[]> result = new ArrayList<byte[]>(); for (byte[] unsignedInHash : unsignedInHashes) { TransactionSignature signature = new TransactionSignature(key.sign(unsignedInHash, assKey), TransactionSignature.SigHash.ALL, false); result.add(ScriptBuilder.createInputScript(signature, key).getProgram()); } return result; } public void signTx(Tx tx, CharSequence passphrase) { tx.signWithSignatures(this.signHashes(tx.getUnsignedInHashes(), passphrase)); } public boolean checkRValues() { //TODO checkRValueForAddress return new Random().nextInt() % 2 == 0; } public boolean checkRValuesForTx(Tx tx) { HashSet<byte[]> rs = new HashSet<byte[]>(); for (In in : tx.getIns()) { Script script = new Script(in.getInSignature()); for (ScriptChunk chunk : script.getChunks()) { if (chunk.isPushData() && chunk.opcode == 71) { TransactionSignature signature = TransactionSignature.decodeFromBitcoin(chunk .data, false); rs.add(signature.r.toByteArray()); } } } //TODO checkRValueForTx return new Random().nextInt() % 2 == 0; } }
bitherj/src/main/java/net/bither/bitherj/core/Address.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 net.bither.bitherj.AbstractApp; import net.bither.bitherj.crypto.ECKey; import net.bither.bitherj.crypto.TransactionSignature; import net.bither.bitherj.db.AbstractDb; import net.bither.bitherj.exception.PasswordException; import net.bither.bitherj.exception.TxBuilderException; import net.bither.bitherj.script.ScriptBuilder; import net.bither.bitherj.utils.PrivateKeyUtil; import net.bither.bitherj.utils.QRCodeUtil; import net.bither.bitherj.utils.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongycastle.crypto.params.KeyParameter; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.annotation.Nonnull; public class Address implements Comparable<Address> { private static final Logger log = LoggerFactory.getLogger(Address.class); public static final String KEY_SPLIT_STRING = ":"; public static final String PUBLIC_KEY_FILE_NAME_SUFFIX = ".pub"; protected String encryptPrivKey; protected byte[] pubKey; protected String address; protected boolean hasPrivKey; protected boolean syncComplete = false; private long mSortTime; private long balance = 0; private boolean isFromXRandom; public Address(String address, byte[] pubKey, long sortTime, boolean isSyncComplete, boolean isFromXRandom, boolean hasPrivKey) { this.hasPrivKey = hasPrivKey; this.encryptPrivKey = null; this.address = address; this.pubKey = pubKey; this.mSortTime = sortTime; this.syncComplete = isSyncComplete; this.isFromXRandom = isFromXRandom; this.updateBalance(); } public Address(String address, byte[] pubKey, String encryptString, boolean isFromXRandom) { this.encryptPrivKey = encryptString; this.address = address; this.pubKey = pubKey; this.hasPrivKey = !Utils.isEmpty(encryptString); this.updateBalance(); this.isFromXRandom = isFromXRandom; } public int txCount() { return AbstractDb.txProvider.txCount(this.address); } public List<Tx> getRecentlyTxsWithConfirmationCntLessThan(int confirmationCnt, int limit) { List<Tx> txList = new ArrayList<Tx>(); int blockNo = BlockChain.getInstance().getLastBlock().getBlockNo() - confirmationCnt + 1; for (Tx tx : AbstractDb.txProvider.getRecentlyTxsByAddress(this.address, blockNo, limit)) { txList.add(tx); } return txList; } public List<Tx> getTxs() { List<Tx> txs = AbstractDb.txProvider.getTxAndDetailByAddress(this.address); Collections.sort(txs); return txs; } @Override public int compareTo(@Nonnull Address address) { return -1 * Long.valueOf(getmSortTime()).compareTo(Long.valueOf(address.getmSortTime())); } public void updateBalance() { long balance = 0; List<Tx> txs = this.getTxs(); Set<byte[]> invalidTx = new HashSet<byte[]>(); Set<OutPoint> spentOut = new HashSet<OutPoint>(); Set<OutPoint> unspendOut = new HashSet<OutPoint>(); for (int i = txs.size() - 1; i >= 0; i--) { Set<OutPoint> spent = new HashSet<OutPoint>(); Tx tx = txs.get(i); Set<byte[]> inHashes = new HashSet<byte[]>(); for (In in : tx.getIns()) { spent.add(new OutPoint(in.getPrevTxHash(), in.getPrevOutSn())); inHashes.add(in.getPrevTxHash()); } if (tx.getBlockNo() == Tx.TX_UNCONFIRMED && (this.isIntersects(spent, spentOut) || this.isIntersects(inHashes, invalidTx))) { invalidTx.add(tx.getTxHash()); continue; } spentOut.addAll(spent); for (Out out : tx.getOuts()) { if (Utils.compareString(this.getAddress(), out.getOutAddress())) { unspendOut.add(new OutPoint(tx.getTxHash(), out.getOutSn())); balance += out.getOutValue(); } } spent.clear(); spent.addAll(unspendOut); spent.retainAll(spentOut); for (OutPoint o : spent) { Tx tx1 = AbstractDb.txProvider.getTxDetailByTxHash(o.getTxHash()); unspendOut.remove(o); balance -= tx1.getOuts().get(o.getOutSn()).getOutValue(); } } this.balance = balance; } private boolean isIntersects(Set set1, Set set2) { Set result = new HashSet(); result.addAll(set1); result.retainAll(set2); return !result.isEmpty(); } public long getBalance() { return balance; } private long getDeltaBalance() { long oldBalance = this.balance; this.updateBalance(); return this.balance - oldBalance; } public void notificatTx(Tx tx, Tx.TxNotificationType txNotificationType) { long deltaBalance = getDeltaBalance(); AbstractApp.notificationService.notificatTx(this, tx, txNotificationType, deltaBalance); } public void setBlockHeight(List<byte[]> txHashes, int height) { notificatTx(null, Tx.TxNotificationType.txDoubleSpend); } public void removeTx(byte[] txHash) { AbstractDb.txProvider.remove(txHash); } public boolean initTxs(List<Tx> txs) { AbstractDb.txProvider.addTxs(txs); if (txs.size() > 0) { notificatTx(null, Tx.TxNotificationType.txFromApi); } return true; } public byte[] getPubKey() { return this.pubKey; } public String getAddress() { return this.address; } public boolean hasPrivKey() { return this.hasPrivKey; } public boolean isSyncComplete() { return this.syncComplete; } public void setSyncComplete(boolean isSyncComplete) { this.syncComplete = isSyncComplete; } public boolean isFromXRandom() { return this.isFromXRandom; } public void setFromXRandom(boolean isFromXRAndom) { this.isFromXRandom = isFromXRAndom; } public void savePrivateKey() throws IOException { String privateKeyFullFileName = Utils.format(BitherjSettings.PRIVATE_KEY_FILE_NAME, Utils.getPrivateDir(), getAddress()); Utils.writeFile(this.encryptPrivKey, new File(privateKeyFullFileName)); } public void savePubKey(long sortTime) throws IOException { if (hasPrivKey()) { savePubKey(Utils.getPrivateDir().getAbsolutePath(), sortTime); } else { savePubKey(Utils.getWatchOnlyDir().getAbsolutePath(), sortTime); } } private void savePubKey(String dir, long sortTime) throws IOException { this.mSortTime = sortTime; String watchOnlyFullFileName = Utils.format(BitherjSettings.WATCH_ONLY_FILE_NAME , dir, getAddress()); String watchOnlyContent = Utils.format("%s:%s:%s%s", Utils.bytesToHexString(this.pubKey), getSyncCompleteString(), Long.toString(this.mSortTime), getXRandomString()); log.debug("address content " + watchOnlyContent); Utils.writeFile(watchOnlyContent, new File(watchOnlyFullFileName)); } public void updatePubkey() throws IOException { if (hasPrivKey()) { updatePubKey(Utils.getPrivateDir().getAbsolutePath()); } else { updatePubKey(Utils.getWatchOnlyDir().getAbsolutePath()); } } private void updatePubKey(String dir) throws IOException { String watchOnlyFullFileName = Utils.format(BitherjSettings.WATCH_ONLY_FILE_NAME , dir, getAddress()); String watchOnlyContent = Utils.format("%s:%s:%s%s", Utils.bytesToHexString(this.pubKey), getSyncCompleteString(), Long.toString(this.mSortTime), getXRandomString()); log.debug("address content " + watchOnlyContent); Utils.writeFile(watchOnlyContent, new File(watchOnlyFullFileName)); } private String getSyncCompleteString() { return isSyncComplete() ? "1" : "0"; } private String getXRandomString() { return isFromXRandom() ? ":" + QRCodeUtil.XRANDOM_FLAG : ""; } public void removeWatchOnly() { String watchOnlyFullFileName = Utils.format(BitherjSettings.WATCH_ONLY_FILE_NAME , Utils.getWatchOnlyDir(), getAddress()); Utils.removeFile(new File(watchOnlyFullFileName)); } @Override public boolean equals(Object o) { if (o instanceof Address) { Address other = (Address) o; return Utils.compareString(getAddress(), other.getAddress()); } return false; } public long getmSortTime() { return mSortTime; } public String getEncryptPrivKey() { if (this.hasPrivKey) { if (Utils.isEmpty(this.encryptPrivKey)) { String privateKeyFullFileName = Utils.format(BitherjSettings.PRIVATE_KEY_FILE_NAME, Utils.getPrivateDir(), getAddress()); this.encryptPrivKey = Utils.readFile(new File(privateKeyFullFileName)); if (this.encryptPrivKey == null) { //todo backup? } //dispaly new version qrcode this.encryptPrivKey = QRCodeUtil.getNewVersionEncryptPrivKey(this.encryptPrivKey); } return this.encryptPrivKey; } else { return null; } } public void setEncryptPrivKey(String encryptPrivKey) { this.encryptPrivKey = encryptPrivKey; this.hasPrivKey = true; } public Tx buildTx(List<Long> amounts, List<String> addresses) throws TxBuilderException { return TxBuilder.getInstance().buildTx(this, amounts, addresses); } public Tx buildTx(long amount, String address) throws TxBuilderException { List<Long> amounts = new ArrayList<Long>(); amounts.add(amount); List<String> addresses = new ArrayList<String>(); addresses.add(address); return buildTx(amounts, addresses); } public List<Tx> getRecentlyTxs(int confirmationCnt, int limit) { int blockNo = BlockChain.getInstance().lastBlock.getBlockNo() - confirmationCnt + 1; return AbstractDb.txProvider.getRecentlyTxsByAddress(this.address, blockNo, limit); } public String getShortAddress() { return Utils.shortenAddress(getAddress()); } public List<String> signStrHashes(List<String> unsignedInHashes, CharSequence passphrase) { ArrayList<byte[]> hashes = new ArrayList<byte[]>(); for (String h : unsignedInHashes) { hashes.add(Utils.hexStringToByteArray(h)); } List<byte[]> resultHashes = signHashes(hashes, passphrase); ArrayList<String> resultStrs = new ArrayList<String>(); for (byte[] h : resultHashes) { resultStrs.add(Utils.bytesToHexString(h)); } return resultStrs; } public List<byte[]> signHashes(List<byte[]> unsignedInHashes, CharSequence passphrase) throws PasswordException { ECKey key = PrivateKeyUtil.getECKeyFromSingleString(this.getEncryptPrivKey(), passphrase); if (key == null) { throw new PasswordException("do not decrypt eckey"); } KeyParameter assKey = key.getKeyCrypter().deriveKey(passphrase); List<byte[]> result = new ArrayList<byte[]>(); for (byte[] unsignedInHash : unsignedInHashes) { TransactionSignature signature = new TransactionSignature(key.sign(unsignedInHash, assKey) , TransactionSignature.SigHash.ALL, false); result.add(ScriptBuilder.createInputScript(signature, key).getProgram()); } return result; } public void signTx(Tx tx, CharSequence passphrase) { tx.signWithSignatures(this.signHashes(tx.getUnsignedInHashes(), passphrase)); } }
edit address
bitherj/src/main/java/net/bither/bitherj/core/Address.java
edit address
Java
apache-2.0
0218047315eb27072aead05d82911b233058034b
0
adichad/lucene-new,adichad/lucene,adichad/lucene,adichad/lucene-new,adichad/lucene-new,adichad/lucene,tokee/lucene,adichad/lucene-new,adichad/lucene,adichad/lucene-new,tokee/lucene,adichad/lucene,tokee/lucene,tokee/lucene
package org.apache.lucene.index; /** * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.search.Similarity; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.Lock; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** IndexReader is an abstract class, providing an interface for accessing an index. Search of an index is done entirely through this abstract interface, so that any subclass which implements it is searchable. <p> Concrete subclasses of IndexReader are usually constructed with a call to one of the static <code>open()</code> methods, e.g. {@link #open(String)}. <p> For efficiency, in this API documents are often referred to via <i>document numbers</i>, non-negative integers which each name a unique document in the index. These document numbers are ephemeral--they may change as documents are added to and deleted from an index. Clients should thus not rely on a given document having the same number between sessions. @author Doug Cutting @version $Id$ */ public abstract class IndexReader { /** * Constructor used if IndexReader is not owner of its directory. * This is used for IndexReaders that are used within other IndexReaders that take care or locking directories. * * @param directory Directory where IndexReader files reside. */ protected IndexReader(Directory directory) { this.directory = directory; } /** * Constructor used if IndexReader is owner of its directory. * If IndexReader is owner of its directory, it locks its directory in case of write operations. * * @param directory Directory where IndexReader files reside. * @param segmentInfos Used for write-l * @param closeDirectory */ IndexReader(Directory directory, SegmentInfos segmentInfos, boolean closeDirectory) { init(directory, segmentInfos, closeDirectory, true); } void init(Directory directory, SegmentInfos segmentInfos, boolean closeDirectory, boolean directoryOwner) { this.directory = directory; this.segmentInfos = segmentInfos; this.directoryOwner = directoryOwner; this.closeDirectory = closeDirectory; } private Directory directory; private boolean directoryOwner; private boolean closeDirectory; private SegmentInfos segmentInfos; private Lock writeLock; private boolean stale; private boolean hasChanges; /** Returns an IndexReader reading the index in an FSDirectory in the named path. */ public static IndexReader open(String path) throws IOException { return open(FSDirectory.getDirectory(path, false), true); } /** Returns an IndexReader reading the index in an FSDirectory in the named path. */ public static IndexReader open(File path) throws IOException { return open(FSDirectory.getDirectory(path, false), true); } /** Returns an IndexReader reading the index in the given Directory. */ public static IndexReader open(final Directory directory) throws IOException { return open(directory, false); } private static IndexReader open(final Directory directory, final boolean closeDirectory) throws IOException { synchronized (directory) { // in- & inter-process sync return (IndexReader)new Lock.With( directory.makeLock(IndexWriter.COMMIT_LOCK_NAME), IndexWriter.COMMIT_LOCK_TIMEOUT) { public Object doBody() throws IOException { SegmentInfos infos = new SegmentInfos(); infos.read(directory); if (infos.size() == 1) { // index is optimized return SegmentReader.get(infos, infos.info(0), closeDirectory); } else { IndexReader[] readers = new IndexReader[infos.size()]; for (int i = 0; i < infos.size(); i++) readers[i] = SegmentReader.get(infos.info(i)); return new MultiReader(directory, infos, closeDirectory, readers); } } }.run(); } } /** Returns the directory this index resides in. */ public Directory directory() { return directory; } /** * Returns the time the index in the named directory was last modified. * * <p>Synchronization of IndexReader and IndexWriter instances is * no longer done via time stamps of the segments file since the time resolution * depends on the hardware platform. Instead, a version number is maintained * within the segments file, which is incremented everytime when the index is * changed.</p> * * @deprecated Replaced by {@link #getCurrentVersion(String)} * */ public static long lastModified(String directory) throws IOException { return lastModified(new File(directory)); } /** * Returns the time the index in the named directory was last modified. * * <p>Synchronization of IndexReader and IndexWriter instances is * no longer done via time stamps of the segments file since the time resolution * depends on the hardware platform. Instead, a version number is maintained * within the segments file, which is incremented everytime when the index is * changed.</p> * * @deprecated Replaced by {@link #getCurrentVersion(File)} * */ public static long lastModified(File directory) throws IOException { return FSDirectory.fileModified(directory, "segments"); } /** * Returns the time the index in the named directory was last modified. * * <p>Synchronization of IndexReader and IndexWriter instances is * no longer done via time stamps of the segments file since the time resolution * depends on the hardware platform. Instead, a version number is maintained * within the segments file, which is incremented everytime when the index is * changed.</p> * * @deprecated Replaced by {@link #getCurrentVersion(Directory)} * */ public static long lastModified(Directory directory) throws IOException { return directory.fileModified("segments"); } /** * Reads version number from segments files. The version number counts the * number of changes of the index. * * @param directory where the index resides. * @return version number. * @throws IOException if segments file cannot be read */ public static long getCurrentVersion(String directory) throws IOException { return getCurrentVersion(new File(directory)); } /** * Reads version number from segments files. The version number counts the * number of changes of the index. * * @param directory where the index resides. * @return version number. * @throws IOException if segments file cannot be read */ public static long getCurrentVersion(File directory) throws IOException { Directory dir = FSDirectory.getDirectory(directory, false); long version = getCurrentVersion(dir); dir.close(); return version; } /** * Reads version number from segments files. The version number counts the * number of changes of the index. * * @param directory where the index resides. * @return version number. * @throws IOException if segments file cannot be read. */ public static long getCurrentVersion(Directory directory) throws IOException { return SegmentInfos.readCurrentVersion(directory); } /** * Return an array of term frequency vectors for the specified document. * The array contains a vector for each vectorized field in the document. * Each vector contains terms and frequencies for all terms in a given vectorized field. * If no such fields existed, the method returns null. The term vectors that are * returned my either be of type TermFreqVector or of type TermPositionsVector if * positions or offsets have been stored. * * @param docNumber document for which term frequency vectors are returned * @return array of term frequency vectors. May be null if no term vectors have been * stored for the specified document. * @throws IOException if index cannot be accessed * @see org.apache.lucene.document.Field.TermVector */ abstract public TermFreqVector[] getTermFreqVectors(int docNumber) throws IOException; /** * Return a term frequency vector for the specified document and field. The * returned vector contains terms and frequencies for the terms in * the specified field of this document, if the field had the storeTermVector * flag set. If termvectors had been stored with positions or offsets, a * TermPositionsVector is returned. * * @param docNumber document for which the term frequency vector is returned * @param field field for which the term frequency vector is returned. * @return term frequency vector May be null if field does not exist in the specified * document or term vector was not stored. * @throws IOException if index cannot be accessed * @see org.apache.lucene.document.Field.TermVector */ abstract public TermFreqVector getTermFreqVector(int docNumber, String field) throws IOException; /** * Returns <code>true</code> if an index exists at the specified directory. * If the directory does not exist or if there is no index in it. * <code>false</code> is returned. * @param directory the directory to check for an index * @return <code>true</code> if an index exists; <code>false</code> otherwise */ public static boolean indexExists(String directory) { return (new File(directory, "segments")).exists(); } /** * Returns <code>true</code> if an index exists at the specified directory. * If the directory does not exist or if there is no index in it. * @param directory the directory to check for an index * @return <code>true</code> if an index exists; <code>false</code> otherwise */ public static boolean indexExists(File directory) { return (new File(directory, "segments")).exists(); } /** * Returns <code>true</code> if an index exists at the specified directory. * If the directory does not exist or if there is no index in it. * @param directory the directory to check for an index * @return <code>true</code> if an index exists; <code>false</code> otherwise * @throws IOException if there is a problem with accessing the index */ public static boolean indexExists(Directory directory) throws IOException { return directory.fileExists("segments"); } /** Returns the number of documents in this index. */ public abstract int numDocs(); /** Returns one greater than the largest possible document number. This may be used to, e.g., determine how big to allocate an array which will have an element for every document number in an index. */ public abstract int maxDoc(); /** Returns the stored fields of the <code>n</code><sup>th</sup> <code>Document</code> in this index. */ public abstract Document document(int n) throws IOException; /** Returns true if document <i>n</i> has been deleted */ public abstract boolean isDeleted(int n); /** Returns true if any documents have been deleted */ public abstract boolean hasDeletions(); /** Returns the byte-encoded normalization factor for the named field of * every document. This is used by the search code to score documents. * * @see Field#setBoost(float) */ public abstract byte[] norms(String field) throws IOException; /** Reads the byte-encoded normalization factor for the named field of every * document. This is used by the search code to score documents. * * @see Field#setBoost(float) */ public abstract void norms(String field, byte[] bytes, int offset) throws IOException; /** Expert: Resets the normalization factor for the named field of the named * document. The norm represents the product of the field's {@link * Field#setBoost(float) boost} and its {@link Similarity#lengthNorm(String, * int) length normalization}. Thus, to preserve the length normalization * values when resetting this, one should base the new value upon the old. * * @see #norms(String) * @see Similarity#decodeNorm(byte) */ public final synchronized void setNorm(int doc, String field, byte value) throws IOException{ if(directoryOwner) aquireWriteLock(); doSetNorm(doc, field, value); hasChanges = true; } /** Implements setNorm in subclass.*/ protected abstract void doSetNorm(int doc, String field, byte value) throws IOException; /** Expert: Resets the normalization factor for the named field of the named * document. * * @see #norms(String) * @see Similarity#decodeNorm(byte) */ public void setNorm(int doc, String field, float value) throws IOException { setNorm(doc, field, Similarity.encodeNorm(value)); } /** Returns an enumeration of all the terms in the index. The enumeration is ordered by Term.compareTo(). Each term is greater than all that precede it in the enumeration. */ public abstract TermEnum terms() throws IOException; /** Returns an enumeration of all terms after a given term. The enumeration is ordered by Term.compareTo(). Each term is greater than all that precede it in the enumeration. */ public abstract TermEnum terms(Term t) throws IOException; /** Returns the number of documents containing the term <code>t</code>. */ public abstract int docFreq(Term t) throws IOException; /** Returns an enumeration of all the documents which contain <code>term</code>. For each document, the document number, the frequency of the term in that document is also provided, for use in search scoring. Thus, this method implements the mapping: <p><ul> Term &nbsp;&nbsp; =&gt; &nbsp;&nbsp; &lt;docNum, freq&gt;<sup>*</sup> </ul> <p>The enumeration is ordered by document number. Each document number is greater than all that precede it in the enumeration. */ public TermDocs termDocs(Term term) throws IOException { TermDocs termDocs = termDocs(); termDocs.seek(term); return termDocs; } /** Returns an unpositioned {@link TermDocs} enumerator. */ public abstract TermDocs termDocs() throws IOException; /** Returns an enumeration of all the documents which contain <code>term</code>. For each document, in addition to the document number and frequency of the term in that document, a list of all of the ordinal positions of the term in the document is available. Thus, this method implements the mapping: <p><ul> Term &nbsp;&nbsp; =&gt; &nbsp;&nbsp; &lt;docNum, freq, &lt;pos<sub>1</sub>, pos<sub>2</sub>, ... pos<sub>freq-1</sub>&gt; &gt;<sup>*</sup> </ul> <p> This positional information faciliates phrase and proximity searching. <p>The enumeration is ordered by document number. Each document number is greater than all that precede it in the enumeration. */ public TermPositions termPositions(Term term) throws IOException { TermPositions termPositions = termPositions(); termPositions.seek(term); return termPositions; } /** Returns an unpositioned {@link TermPositions} enumerator. */ public abstract TermPositions termPositions() throws IOException; /** * Tries to acquire the WriteLock on this directory. * this method is only valid if this IndexReader is directory owner. * * @throws IOException If WriteLock cannot be acquired. */ private void aquireWriteLock() throws IOException { if (stale) throw new IOException("IndexReader out of date and no longer valid for delete, undelete, or setNorm operations"); if (writeLock == null) { Lock writeLock = directory.makeLock(IndexWriter.WRITE_LOCK_NAME); if (!writeLock.obtain(IndexWriter.WRITE_LOCK_TIMEOUT)) // obtain write lock throw new IOException("Index locked for write: " + writeLock); this.writeLock = writeLock; // we have to check whether index has changed since this reader was opened. // if so, this reader is no longer valid for deletion if (SegmentInfos.readCurrentVersion(directory) > segmentInfos.getVersion()) { stale = true; this.writeLock.release(); this.writeLock = null; throw new IOException("IndexReader out of date and no longer valid for delete, undelete, or setNorm operations"); } } } /** Deletes the document numbered <code>docNum</code>. Once a document is deleted it will not appear in TermDocs or TermPostitions enumerations. Attempts to read its field with the {@link #document} method will result in an error. The presence of this document may still be reflected in the {@link #docFreq} statistic, though this will be corrected eventually as the index is further modified. */ public final synchronized void delete(int docNum) throws IOException { if(directoryOwner) aquireWriteLock(); doDelete(docNum); hasChanges = true; } /** Implements deletion of the document numbered <code>docNum</code>. * Applications should call {@link #delete(int)} or {@link #delete(Term)}. */ protected abstract void doDelete(int docNum) throws IOException; /** Deletes all documents containing <code>term</code>. This is useful if one uses a document field to hold a unique ID string for the document. Then to delete such a document, one merely constructs a term with the appropriate field and the unique ID string as its text and passes it to this method. Returns the number of documents deleted. See {@link #delete(int)} for information about when this deletion will become effective. */ public final int delete(Term term) throws IOException { TermDocs docs = termDocs(term); if (docs == null) return 0; int n = 0; try { while (docs.next()) { delete(docs.doc()); n++; } } finally { docs.close(); } return n; } /** Undeletes all documents currently marked as deleted in this index.*/ public final synchronized void undeleteAll() throws IOException{ if(directoryOwner) aquireWriteLock(); doUndeleteAll(); hasChanges = true; } /** Implements actual undeleteAll() in subclass. */ protected abstract void doUndeleteAll() throws IOException; /** * Commit changes resulting from delete, undeleteAll, or setNorm operations * * @throws IOException */ protected final synchronized void commit() throws IOException{ if(hasChanges){ if(directoryOwner){ synchronized (directory) { // in- & inter-process sync new Lock.With(directory.makeLock(IndexWriter.COMMIT_LOCK_NAME), IndexWriter.COMMIT_LOCK_TIMEOUT) { public Object doBody() throws IOException { doCommit(); segmentInfos.write(directory); return null; } }.run(); } if (writeLock != null) { writeLock.release(); // release write lock writeLock = null; } } else doCommit(); } hasChanges = false; } /** Implements commit. */ protected abstract void doCommit() throws IOException; /** * Closes files associated with this index. * Also saves any new deletions to disk. * No other methods should be called after this has been called. */ public final synchronized void close() throws IOException { commit(); doClose(); if(closeDirectory) directory.close(); } /** Implements close. */ protected abstract void doClose() throws IOException; /** Release the write lock, if needed. */ protected void finalize() { if (writeLock != null) { writeLock.release(); // release write lock writeLock = null; } } /** * Returns a list of all unique field names that exist in the index pointed * to by this IndexReader. * @return Collection of Strings indicating the names of the fields * @throws IOException if there is a problem with accessing the index */ public abstract Collection getFieldNames() throws IOException; /** * Returns a list of all unique field names that exist in the index pointed * to by this IndexReader. The boolean argument specifies whether the fields * returned are indexed or not. * @param indexed <code>true</code> if only indexed fields should be returned; * <code>false</code> if only unindexed fields should be returned. * @return Collection of Strings indicating the names of the fields * @throws IOException if there is a problem with accessing the index */ public abstract Collection getFieldNames(boolean indexed) throws IOException; /** * * @param storedTermVector if true, returns only Indexed fields that have term vector info, * else only indexed fields without term vector info * @return Collection of Strings indicating the names of the fields * * @deprecated Replaced by {@link #getIndexedFieldNames (Field.TermVector tvSpec)} */ public Collection getIndexedFieldNames(boolean storedTermVector){ if(storedTermVector){ Set fieldSet = new HashSet(); fieldSet.addAll(getIndexedFieldNames(Field.TermVector.YES)); fieldSet.addAll(getIndexedFieldNames(Field.TermVector.WITH_POSITIONS)); fieldSet.addAll(getIndexedFieldNames(Field.TermVector.WITH_OFFSETS)); fieldSet.addAll(getIndexedFieldNames(Field.TermVector.WITH_POSITIONS_OFFSETS)); return fieldSet; } else return getIndexedFieldNames(Field.TermVector.NO); } /** * Get a list of unique field names that exist in this index, are indexed, and have * the specified term vector information. * * @param tvSpec specifies which term vector information should be available for the fields * @return Collection of Strings indicating the names of the fields */ public abstract Collection getIndexedFieldNames(Field.TermVector tvSpec); /** * Returns <code>true</code> iff the index in the named directory is * currently locked. * @param directory the directory to check for a lock * @throws IOException if there is a problem with accessing the index */ public static boolean isLocked(Directory directory) throws IOException { return directory.makeLock(IndexWriter.WRITE_LOCK_NAME).isLocked() || directory.makeLock(IndexWriter.COMMIT_LOCK_NAME).isLocked(); } /** * Returns <code>true</code> iff the index in the named directory is * currently locked. * @param directory the directory to check for a lock * @throws IOException if there is a problem with accessing the index */ public static boolean isLocked(String directory) throws IOException { Directory dir = FSDirectory.getDirectory(directory, false); boolean result = isLocked(dir); dir.close(); return result; } /** * Forcibly unlocks the index in the named directory. * <P> * Caution: this should only be used by failure recovery code, * when it is known that no other process nor thread is in fact * currently accessing this index. */ public static void unlock(Directory directory) throws IOException { directory.makeLock(IndexWriter.WRITE_LOCK_NAME).release(); directory.makeLock(IndexWriter.COMMIT_LOCK_NAME).release(); } }
src/java/org/apache/lucene/index/IndexReader.java
package org.apache.lucene.index; /** * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.search.Similarity; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.Lock; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** IndexReader is an abstract class, providing an interface for accessing an index. Search of an index is done entirely through this abstract interface, so that any subclass which implements it is searchable. <p> Concrete subclasses of IndexReader are usually constructed with a call to one of the static <code>open()</code> methods, e.g. {@link #open(String)}. <p> For efficiency, in this API documents are often referred to via <i>document numbers</i>, non-negative integers which each name a unique document in the index. These document numbers are ephemeral--they may change as documents are added to and deleted from an index. Clients should thus not rely on a given document having the same number between sessions. @author Doug Cutting @version $Id$ */ public abstract class IndexReader { /** * Constructor used if IndexReader is not owner of its directory. * This is used for IndexReaders that are used within other IndexReaders that take care or locking directories. * * @param directory Directory where IndexReader files reside. */ protected IndexReader(Directory directory) { this.directory = directory; } /** * Constructor used if IndexReader is owner of its directory. * If IndexReader is owner of its directory, it locks its directory in case of write operations. * * @param directory Directory where IndexReader files reside. * @param segmentInfos Used for write-l * @param closeDirectory */ IndexReader(Directory directory, SegmentInfos segmentInfos, boolean closeDirectory) { init(directory, segmentInfos, closeDirectory, true); } void init(Directory directory, SegmentInfos segmentInfos, boolean closeDirectory, boolean directoryOwner) { this.directory = directory; this.segmentInfos = segmentInfos; this.directoryOwner = directoryOwner; this.closeDirectory = closeDirectory; } private Directory directory; private boolean directoryOwner; private boolean closeDirectory; private SegmentInfos segmentInfos; private Lock writeLock; private boolean stale; private boolean hasChanges; /** Returns an IndexReader reading the index in an FSDirectory in the named path. */ public static IndexReader open(String path) throws IOException { return open(FSDirectory.getDirectory(path, false), true); } /** Returns an IndexReader reading the index in an FSDirectory in the named path. */ public static IndexReader open(File path) throws IOException { return open(FSDirectory.getDirectory(path, false), true); } /** Returns an IndexReader reading the index in the given Directory. */ public static IndexReader open(final Directory directory) throws IOException { return open(directory, false); } private static IndexReader open(final Directory directory, final boolean closeDirectory) throws IOException { synchronized (directory) { // in- & inter-process sync return (IndexReader)new Lock.With( directory.makeLock(IndexWriter.COMMIT_LOCK_NAME), IndexWriter.COMMIT_LOCK_TIMEOUT) { public Object doBody() throws IOException { SegmentInfos infos = new SegmentInfos(); infos.read(directory); if (infos.size() == 1) { // index is optimized return SegmentReader.get(infos, infos.info(0), closeDirectory); } else { IndexReader[] readers = new IndexReader[infos.size()]; for (int i = 0; i < infos.size(); i++) readers[i] = SegmentReader.get(infos.info(i)); return new MultiReader(directory, infos, closeDirectory, readers); } } }.run(); } } /** Returns the directory this index resides in. */ public Directory directory() { return directory; } /** * Returns the time the index in the named directory was last modified. * * <p>Synchronization of IndexReader and IndexWriter instances is * no longer done via time stamps of the segments file since the time resolution * depends on the hardware platform. Instead, a version number is maintained * within the segments file, which is incremented everytime when the index is * changed.</p> * * @deprecated Replaced by {@link #getCurrentVersion(String)} * */ public static long lastModified(String directory) throws IOException { return lastModified(new File(directory)); } /** * Returns the time the index in the named directory was last modified. * * <p>Synchronization of IndexReader and IndexWriter instances is * no longer done via time stamps of the segments file since the time resolution * depends on the hardware platform. Instead, a version number is maintained * within the segments file, which is incremented everytime when the index is * changed.</p> * * @deprecated Replaced by {@link #getCurrentVersion(File)} * */ public static long lastModified(File directory) throws IOException { return FSDirectory.fileModified(directory, "segments"); } /** * Returns the time the index in the named directory was last modified. * * <p>Synchronization of IndexReader and IndexWriter instances is * no longer done via time stamps of the segments file since the time resolution * depends on the hardware platform. Instead, a version number is maintained * within the segments file, which is incremented everytime when the index is * changed.</p> * * @deprecated Replaced by {@link #getCurrentVersion(Directory)} * */ public static long lastModified(Directory directory) throws IOException { return directory.fileModified("segments"); } /** * Reads version number from segments files. The version number counts the * number of changes of the index. * * @param directory where the index resides. * @return version number. * @throws IOException if segments file cannot be read */ public static long getCurrentVersion(String directory) throws IOException { return getCurrentVersion(new File(directory)); } /** * Reads version number from segments files. The version number counts the * number of changes of the index. * * @param directory where the index resides. * @return version number. * @throws IOException if segments file cannot be read */ public static long getCurrentVersion(File directory) throws IOException { Directory dir = FSDirectory.getDirectory(directory, false); long version = getCurrentVersion(dir); dir.close(); return version; } /** * Reads version number from segments files. The version number counts the * number of changes of the index. * * @param directory where the index resides. * @return version number. * @throws IOException if segments file cannot be read. */ public static long getCurrentVersion(Directory directory) throws IOException { return SegmentInfos.readCurrentVersion(directory); } /** * Return an array of term frequency vectors for the specified document. * The array contains a vector for each vectorized field in the document. * Each vector contains terms and frequencies for all terms in a given vectorized field. * If no such fields existed, the method returns null. The term vectors that are * returned my either be of type TermFreqVector or of type TermPositionsVector if * positions or offsets have been stored. * * @param docNumber document for which term frequency vectors are returned * @return array of term frequency vectors. May be null if no term vectors have been * stored for the specified document. * @throws IOException if index cannot be accessed * @see org.apache.lucene.document.Field.TermVector */ abstract public TermFreqVector[] getTermFreqVectors(int docNumber) throws IOException; /** * Return a term frequency vector for the specified document and field. The * returned vector contains terms and frequencies for the terms in * the specified field of this document, if the field had the storeTermVector * flag set. If termvectors had been stored with positions or offsets, a * TermPositionsVector is returned. * * @param docNumber document for which the term frequency vector is returned * @param field field for which the term frequency vector is returned. * @return term frequency vector May be null if field does not exist in the specified * document or term vector was not stored. * @throws IOException if index cannot be accessed * @see org.apache.lucene.document.Field.TermVector */ abstract public TermFreqVector getTermFreqVector(int docNumber, String field) throws IOException; /** * Returns <code>true</code> if an index exists at the specified directory. * If the directory does not exist or if there is no index in it. * <code>false</code> is returned. * @param directory the directory to check for an index * @return <code>true</code> if an index exists; <code>false</code> otherwise */ public static boolean indexExists(String directory) { return (new File(directory, "segments")).exists(); } /** * Returns <code>true</code> if an index exists at the specified directory. * If the directory does not exist or if there is no index in it. * @param directory the directory to check for an index * @return <code>true</code> if an index exists; <code>false</code> otherwise */ public static boolean indexExists(File directory) { return (new File(directory, "segments")).exists(); } /** * Returns <code>true</code> if an index exists at the specified directory. * If the directory does not exist or if there is no index in it. * @param directory the directory to check for an index * @return <code>true</code> if an index exists; <code>false</code> otherwise * @throws IOException if there is a problem with accessing the index */ public static boolean indexExists(Directory directory) throws IOException { return directory.fileExists("segments"); } /** Returns the number of documents in this index. */ public abstract int numDocs(); /** Returns one greater than the largest possible document number. This may be used to, e.g., determine how big to allocate an array which will have an element for every document number in an index. */ public abstract int maxDoc(); /** Returns the stored fields of the <code>n</code><sup>th</sup> <code>Document</code> in this index. */ public abstract Document document(int n) throws IOException; /** Returns true if document <i>n</i> has been deleted */ public abstract boolean isDeleted(int n); /** Returns true if any documents have been deleted */ public abstract boolean hasDeletions(); /** Returns the byte-encoded normalization factor for the named field of * every document. This is used by the search code to score documents. * * @see Field#setBoost(float) */ public abstract byte[] norms(String field) throws IOException; /** Reads the byte-encoded normalization factor for the named field of every * document. This is used by the search code to score documents. * * @see Field#setBoost(float) */ public abstract void norms(String field, byte[] bytes, int offset) throws IOException; /** Expert: Resets the normalization factor for the named field of the named * document. The norm represents the product of the field's {@link * Field#setBoost(float) boost} and its {@link Similarity#lengthNorm(String, * int) length normalization}. Thus, to preserve the length normalization * values when resetting this, one should base the new value upon the old. * * @see #norms(String) * @see Similarity#decodeNorm(byte) */ public final synchronized void setNorm(int doc, String field, byte value) throws IOException{ if(directoryOwner) aquireWriteLock(); doSetNorm(doc, field, value); hasChanges = true; } /** Implements setNorm in subclass.*/ protected abstract void doSetNorm(int doc, String field, byte value) throws IOException; /** Expert: Resets the normalization factor for the named field of the named * document. * * @see #norms(String) * @see Similarity#decodeNorm(byte) */ public void setNorm(int doc, String field, float value) throws IOException { setNorm(doc, field, Similarity.encodeNorm(value)); } /** Returns an enumeration of all the terms in the index. The enumeration is ordered by Term.compareTo(). Each term is greater than all that precede it in the enumeration. */ public abstract TermEnum terms() throws IOException; /** Returns an enumeration of all terms after a given term. The enumeration is ordered by Term.compareTo(). Each term is greater than all that precede it in the enumeration. */ public abstract TermEnum terms(Term t) throws IOException; /** Returns the number of documents containing the term <code>t</code>. */ public abstract int docFreq(Term t) throws IOException; /** Returns an enumeration of all the documents which contain <code>term</code>. For each document, the document number, the frequency of the term in that document is also provided, for use in search scoring. Thus, this method implements the mapping: <p><ul> Term &nbsp;&nbsp; =&gt; &nbsp;&nbsp; &lt;docNum, freq&gt;<sup>*</sup> </ul> <p>The enumeration is ordered by document number. Each document number is greater than all that precede it in the enumeration. */ public TermDocs termDocs(Term term) throws IOException { TermDocs termDocs = termDocs(); termDocs.seek(term); return termDocs; } /** Returns an unpositioned {@link TermDocs} enumerator. */ public abstract TermDocs termDocs() throws IOException; /** Returns an enumeration of all the documents which contain <code>term</code>. For each document, in addition to the document number and frequency of the term in that document, a list of all of the ordinal positions of the term in the document is available. Thus, this method implements the mapping: <p><ul> Term &nbsp;&nbsp; =&gt; &nbsp;&nbsp; &lt;docNum, freq, &lt;pos<sub>1</sub>, pos<sub>2</sub>, ... pos<sub>freq-1</sub>&gt; &gt;<sup>*</sup> </ul> <p> This positional information faciliates phrase and proximity searching. <p>The enumeration is ordered by document number. Each document number is greater than all that precede it in the enumeration. */ public TermPositions termPositions(Term term) throws IOException { TermPositions termPositions = termPositions(); termPositions.seek(term); return termPositions; } /** Returns an unpositioned {@link TermPositions} enumerator. */ public abstract TermPositions termPositions() throws IOException; /** * Tries to acquire the WriteLock on this directory. * this method is only valid if this IndexReader is directory owner. * * @throws IOException If WriteLock cannot be acquired. */ private void aquireWriteLock() throws IOException { if (stale) throw new IOException("IndexReader out of date and no longer valid for delete, undelete, or setNorm operations"); if (writeLock == null) { Lock writeLock = directory.makeLock(IndexWriter.WRITE_LOCK_NAME); if (!writeLock.obtain(IndexWriter.WRITE_LOCK_TIMEOUT)) // obtain write lock throw new IOException("Index locked for write: " + writeLock); this.writeLock = writeLock; // we have to check whether index has changed since this reader was opened. // if so, this reader is no longer valid for deletion if (SegmentInfos.readCurrentVersion(directory) > segmentInfos.getVersion()) { stale = true; this.writeLock.release(); this.writeLock = null; throw new IOException("IndexReader out of date and no longer valid for delete, undelete, or setNorm operations"); } } } /** Deletes the document numbered <code>docNum</code>. Once a document is deleted it will not appear in TermDocs or TermPostitions enumerations. Attempts to read its field with the {@link #document} method will result in an error. The presence of this document may still be reflected in the {@link #docFreq} statistic, though this will be corrected eventually as the index is further modified. */ public final synchronized void delete(int docNum) throws IOException { if(directoryOwner) aquireWriteLock(); doDelete(docNum); hasChanges = true; } /** Implements deletion of the document numbered <code>docNum</code>. * Applications should call {@link #delete(int)} or {@link #delete(Term)}. */ protected abstract void doDelete(int docNum) throws IOException; /** Deletes all documents containing <code>term</code>. This is useful if one uses a document field to hold a unique ID string for the document. Then to delete such a document, one merely constructs a term with the appropriate field and the unique ID string as its text and passes it to this method. Returns the number of documents deleted. See {@link #delete(int)} for information about when this deletion will become effective. */ public final int delete(Term term) throws IOException { TermDocs docs = termDocs(term); if (docs == null) return 0; int n = 0; try { while (docs.next()) { delete(docs.doc()); n++; } } finally { docs.close(); } return n; } /** Undeletes all documents currently marked as deleted in this index.*/ public final synchronized void undeleteAll() throws IOException{ if(directoryOwner) aquireWriteLock(); doUndeleteAll(); hasChanges = true; } /** Implements actual undeleteAll() in subclass. */ protected abstract void doUndeleteAll() throws IOException; /** * Commit changes resulting from delete, undeleteAll, or setNorm operations * * @throws IOException */ protected final synchronized void commit() throws IOException{ if(hasChanges){ if(directoryOwner){ synchronized (directory) { // in- & inter-process sync new Lock.With(directory.makeLock(IndexWriter.COMMIT_LOCK_NAME), IndexWriter.COMMIT_LOCK_TIMEOUT) { public Object doBody() throws IOException { doCommit(); segmentInfos.write(directory); return null; } }.run(); } if (writeLock != null) { writeLock.release(); // release write lock writeLock = null; } } else doCommit(); } hasChanges = false; } /** Implements commit. */ protected abstract void doCommit() throws IOException; /** * Closes files associated with this index. * Also saves any new deletions to disk. * No other methods should be called after this has been called. */ public final synchronized void close() throws IOException { commit(); doClose(); if(closeDirectory) directory.close(); } /** Implements close. */ protected abstract void doClose() throws IOException; /** Release the write lock, if needed. */ protected void finalize() { if (writeLock != null) { writeLock.release(); // release write lock writeLock = null; } } /** * Returns a list of all unique field names that exist in the index pointed * to by this IndexReader. * @return Collection of Strings indicating the names of the fields * @throws IOException if there is a problem with accessing the index */ public abstract Collection getFieldNames() throws IOException; /** * Returns a list of all unique field names that exist in the index pointed * to by this IndexReader. The boolean argument specifies whether the fields * returned are indexed or not. * @param indexed <code>true</code> if only indexed fields should be returned; * <code>false</code> if only unindexed fields should be returned. * @return Collection of Strings indicating the names of the fields * @throws IOException if there is a problem with accessing the index */ public abstract Collection getFieldNames(boolean indexed) throws IOException; /** * * @param storedTermVector if true, returns only Indexed fields that have term vector info, * else only indexed fields without term vector info * @return Collection of Strings indicating the names of the fields * * @deprecated Replaced by {@link #getIndexedFieldNames (Field.TermVector tvSpec)} */ public Collection getIndexedFieldNames(boolean storedTermVector){ if(storedTermVector){ Set fieldSet = new HashSet(); fieldSet.addAll(getIndexedFieldNames(Field.TermVector.YES)); fieldSet.addAll(getIndexedFieldNames(Field.TermVector.WITH_POSITIONS)); fieldSet.addAll(getIndexedFieldNames(Field.TermVector.WITH_OFFSETS)); fieldSet.addAll(getIndexedFieldNames(Field.TermVector.WITH_POSITIONS_OFFSETS)); return fieldSet; } else return getIndexedFieldNames(Field.TermVector.NO); } /** * Get a list of unique field names that exist in this index, are indexed, and have * the specified term vector information. * * @param tvSpec specifies which term vector information shoul dbe available for the fields * @return Collection of Strings indicating the names of the fields */ public abstract Collection getIndexedFieldNames(Field.TermVector tvSpec); /** * Returns <code>true</code> iff the index in the named directory is * currently locked. * @param directory the directory to check for a lock * @throws IOException if there is a problem with accessing the index */ public static boolean isLocked(Directory directory) throws IOException { return directory.makeLock(IndexWriter.WRITE_LOCK_NAME).isLocked() || directory.makeLock(IndexWriter.COMMIT_LOCK_NAME).isLocked(); } /** * Returns <code>true</code> iff the index in the named directory is * currently locked. * @param directory the directory to check for a lock * @throws IOException if there is a problem with accessing the index */ public static boolean isLocked(String directory) throws IOException { Directory dir = FSDirectory.getDirectory(directory, false); boolean result = isLocked(dir); dir.close(); return result; } /** * Forcibly unlocks the index in the named directory. * <P> * Caution: this should only be used by failure recovery code, * when it is known that no other process nor thread is in fact * currently accessing this index. */ public static void unlock(Directory directory) throws IOException { directory.makeLock(IndexWriter.WRITE_LOCK_NAME).release(); directory.makeLock(IndexWriter.COMMIT_LOCK_NAME).release(); } }
fix for a typo in a javadoc comment git-svn-id: 4c5078813df38efa56971a28e09a55254294f104@150589 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/lucene/index/IndexReader.java
fix for a typo in a javadoc comment
Java
apache-2.0
9fa11a04d0e59581a7eb1f09f4a5c5c40995f9e4
0
tokee/lucene,adichad/lucene,tokee/lucene,adichad/lucene,tokee/lucene,tokee/lucene,adichad/lucene-new,adichad/lucene-new,adichad/lucene,adichad/lucene-new,adichad/lucene-new,adichad/lucene,adichad/lucene-new,adichad/lucene
package org.apache.lucene.search; /** * Copyright 2005 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.lucene.index.IndexReader; import org.apache.lucene.search.Explanation; import org.apache.lucene.search.Query; import org.apache.lucene.search.Scorer; import org.apache.lucene.search.Searcher; import org.apache.lucene.search.Similarity; import org.apache.lucene.search.Weight; import org.apache.lucene.util.ToStringUtils; /** * A query that matches all documents. * * @author John Wang */ public class MatchAllDocsQuery extends Query { public MatchAllDocsQuery() { } private class MatchAllScorer extends Scorer { final IndexReader reader; int id; final int maxId; final float score; MatchAllScorer(IndexReader reader, Similarity similarity, Weight w) { super(similarity); this.reader = reader; id = -1; maxId = reader.maxDoc() - 1; score = w.getValue(); } public Explanation explain(int doc) { return null; // not called... see MatchAllDocsWeight.explain() } public int doc() { return id; } public boolean next() { while (id < maxId) { id++; if (!reader.isDeleted(id)) { return true; } } return false; } public float score() { return score; } public boolean skipTo(int target) { id = target - 1; return next(); } } private class MatchAllDocsWeight implements Weight { private Searcher searcher; private float queryWeight; private float queryNorm; public MatchAllDocsWeight(Searcher searcher) { this.searcher = searcher; } public String toString() { return "weight(" + MatchAllDocsQuery.this + ")"; } public Query getQuery() { return MatchAllDocsQuery.this; } public float getValue() { return queryWeight; } public float sumOfSquaredWeights() { queryWeight = getBoost(); return queryWeight * queryWeight; } public void normalize(float queryNorm) { this.queryNorm = queryNorm; queryWeight *= this.queryNorm; } public Scorer scorer(IndexReader reader) { return new MatchAllScorer(reader, getSimilarity(searcher), this); } public Explanation explain(IndexReader reader, int doc) { // explain query weight Explanation queryExpl = new Explanation(); queryExpl.setDescription("MatchAllDocsQuery, product of:"); queryExpl.setValue(getValue()); if (getBoost() != 1.0f) { queryExpl.addDetail(new Explanation(getBoost(),"boost")); } queryExpl.addDetail(new Explanation(queryNorm,"queryNorm")); return queryExpl; } } protected Weight createWeight(Searcher searcher) { return new MatchAllDocsWeight(searcher); } public String toString(String field) { StringBuffer buffer = new StringBuffer(); buffer.append("MatchAllDocsQuery"); buffer.append(ToStringUtils.boost(getBoost())); return buffer.toString(); } public boolean equals(Object o) { if (!(o instanceof MatchAllDocsQuery)) return false; MatchAllDocsQuery other = (MatchAllDocsQuery) o; return this.getBoost() == other.getBoost(); } public int hashCode() { return Float.floatToIntBits(getBoost()); } }
src/java/org/apache/lucene/search/MatchAllDocsQuery.java
package org.apache.lucene.search; /** * Copyright 2005 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.lucene.index.IndexReader; import org.apache.lucene.search.Explanation; import org.apache.lucene.search.Query; import org.apache.lucene.search.Scorer; import org.apache.lucene.search.Searcher; import org.apache.lucene.search.Similarity; import org.apache.lucene.search.Weight; import org.apache.lucene.util.ToStringUtils; /** * A query that matches all documents. * * @author John Wang */ public class MatchAllDocsQuery extends Query { public MatchAllDocsQuery() { } private class MatchAllScorer extends Scorer { IndexReader reader; int count; int maxDoc; MatchAllScorer(IndexReader reader, Similarity similarity) { super(similarity); this.reader = reader; count = -1; maxDoc = reader.maxDoc(); } public int doc() { return count; } public Explanation explain(int doc) { Explanation explanation = new Explanation(); explanation.setValue(1.0f); explanation.setDescription("MatchAllDocsQuery"); return explanation; } public boolean next() { while (count < (maxDoc - 1)) { count++; if (!reader.isDeleted(count)) { return true; } } return false; } public float score() { return 1.0f; } public boolean skipTo(int target) { count = target - 1; return next(); } } private class MatchAllDocsWeight implements Weight { private Searcher searcher; public MatchAllDocsWeight(Searcher searcher) { this.searcher = searcher; } public String toString() { return "weight(" + MatchAllDocsQuery.this + ")"; } public Query getQuery() { return MatchAllDocsQuery.this; } public float getValue() { return 1.0f; } public float sumOfSquaredWeights() { return 1.0f; } public void normalize(float queryNorm) { } public Scorer scorer(IndexReader reader) { return new MatchAllScorer(reader, getSimilarity(searcher)); } public Explanation explain(IndexReader reader, int doc) { // explain query weight Explanation queryExpl = new Explanation(); queryExpl.setDescription("MatchAllDocsQuery:"); Explanation boostExpl = new Explanation(getBoost(), "boost"); if (getBoost() != 1.0f) queryExpl.addDetail(boostExpl); queryExpl.setValue(boostExpl.getValue()); return queryExpl; } } protected Weight createWeight(Searcher searcher) { return new MatchAllDocsWeight(searcher); } public String toString(String field) { StringBuffer buffer = new StringBuffer(); buffer.append("MatchAllDocsQuery"); buffer.append(ToStringUtils.boost(getBoost())); return buffer.toString(); } public boolean equals(Object o) { if (!(o instanceof MatchAllDocsQuery)) return false; MatchAllDocsQuery other = (MatchAllDocsQuery) o; return this.getBoost() == other.getBoost(); } public int hashCode() { return Float.floatToIntBits(getBoost()); } }
fix score to include boost and query normalization: LUCENE-450 git-svn-id: 4c5078813df38efa56971a28e09a55254294f104@358089 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/lucene/search/MatchAllDocsQuery.java
fix score to include boost and query normalization: LUCENE-450
Java
apache-2.0
9232ac47360a4ea5f23ff957a3427f8d289fb3b7
0
cosmocode/cosmocode-json
/** * Copyright 2010 CosmoCode GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.cosmocode.json; import org.json.JSONException; import org.json.JSONStringer; import org.json.JSONWriter; import org.json.extension.JSONConstructor; import org.json.extension.JSONEncoder; import de.cosmocode.rendering.AbstractRenderer; import de.cosmocode.rendering.Renderer; import de.cosmocode.rendering.RenderingException; /** * Json based {@link Renderer} implementation. * * @since 2.1 * @author Willi Schoenborn */ @SuppressWarnings("deprecation") public final class JsonRenderer extends AbstractRenderer { private final JSONWriter writer = new JSONStringer(); private final JSONConstructor adapter = JSON.asConstructor(this); @Override protected Renderer unknownValue(Object value) { if (value instanceof JSONEncoder) { try { JSONEncoder.class.cast(value).encodeJSON(adapter); } catch (JSONException e) { throw new RenderingException(e); } return this; } else { return super.unknownValue(value); } } @Override public Renderer list() throws RenderingException { try { writer.array(); } catch (JSONException e) { throw new RenderingException(e); } return this; } @Override public Renderer endList() throws RenderingException { try { writer.endArray(); } catch (JSONException e) { throw new RenderingException(e); } return this; } @Override public Renderer map() throws RenderingException { try { writer.object(); } catch (JSONException e) { throw new RenderingException(e); } return this; } @Override public Renderer endMap() throws RenderingException { try { writer.endObject(); } catch (JSONException e) { throw new RenderingException(e); } return this; } @Override public Renderer key(CharSequence key) throws RenderingException { try { writer.key(key == null ? "null" : key.toString()); } catch (JSONException e) { throw new RenderingException(e); } return this; } @Override public Renderer nullValue() throws RenderingException { try { writer.value(null); } catch (JSONException e) { throw new RenderingException(e); } return this; } @Override public Renderer value(boolean value) throws RenderingException { try { writer.value(value); } catch (JSONException e) { throw new RenderingException(e); } return this; } @Override public Renderer value(long value) throws RenderingException { try { writer.value(value); } catch (JSONException e) { throw new RenderingException(e); } return this; } @Override public Renderer value(double value) throws RenderingException { try { writer.value(value); } catch (JSONException e) { throw new RenderingException(e); } return this; } @Override public Renderer value(CharSequence value) throws RenderingException { try { writer.value(value); } catch (JSONException e) { throw new RenderingException(e); } return this; } @Override public String build() throws RenderingException { return writer.toString(); } }
src/main/java/de/cosmocode/json/JsonRenderer.java
/** * Copyright 2010 CosmoCode GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.cosmocode.json; import org.json.JSONException; import org.json.JSONStringer; import org.json.JSONWriter; import org.json.extension.JSONConstructor; import org.json.extension.JSONEncoder; import de.cosmocode.rendering.AbstractRenderer; import de.cosmocode.rendering.Renderer; import de.cosmocode.rendering.RenderingException; /** * Json based {@link Renderer} implementation. * * @since 2.1 * @author Willi Schoenborn */ @SuppressWarnings("deprecation") public final class JsonRenderer extends AbstractRenderer implements Renderer { private final JSONWriter writer = new JSONStringer(); private final JSONConstructor adapter = JSON.asConstructor(this); @Override protected Renderer unknownValue(Object value) { if (value instanceof JSONEncoder) { try { JSONEncoder.class.cast(value).encodeJSON(adapter); } catch (JSONException e) { throw new RenderingException(e); } return this; } else { return super.unknownValue(value); } } @Override public Renderer list() throws RenderingException { try { writer.array(); } catch (JSONException e) { throw new RenderingException(e); } return this; } @Override public Renderer endList() throws RenderingException { try { writer.endArray(); } catch (JSONException e) { throw new RenderingException(e); } return this; } @Override public Renderer map() throws RenderingException { try { writer.object(); } catch (JSONException e) { throw new RenderingException(e); } return this; } @Override public Renderer endMap() throws RenderingException { try { writer.endObject(); } catch (JSONException e) { throw new RenderingException(e); } return this; } @Override public Renderer key(CharSequence key) throws RenderingException { try { writer.key(key == null ? "null" : key.toString()); } catch (JSONException e) { throw new RenderingException(e); } return this; } @Override public Renderer nullValue() throws RenderingException { try { writer.value(null); } catch (JSONException e) { throw new RenderingException(e); } return this; } @Override public Renderer value(boolean value) throws RenderingException { try { writer.value(value); } catch (JSONException e) { throw new RenderingException(e); } return this; } @Override public Renderer value(long value) throws RenderingException { try { writer.value(value); } catch (JSONException e) { throw new RenderingException(e); } return this; } @Override public Renderer value(double value) throws RenderingException { try { writer.value(value); } catch (JSONException e) { throw new RenderingException(e); } return this; } @Override public Renderer value(CharSequence value) throws RenderingException { try { writer.value(value); } catch (JSONException e) { throw new RenderingException(e); } return this; } @Override public String build() throws RenderingException { return writer.toString(); } }
removed redundant implements clause
src/main/java/de/cosmocode/json/JsonRenderer.java
removed redundant implements clause
Java
apache-2.0
436c224d3f77e6091bc3c2b4938aa249c4320d24
0
venicegeo/pz-ingest,venicegeo/pz-ingest,venicegeo/pz-ingest
/** * Copyright 2016, RadiantBlue Technologies, 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 ingest.utility; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.apache.commons.io.FilenameUtils; import org.geotools.data.DataStore; import org.geotools.data.DataStoreFinder; import org.geotools.data.DefaultTransaction; import org.geotools.data.FeatureSource; import org.geotools.data.Transaction; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.data.simple.SimpleFeatureStore; import org.geotools.geometry.jts.JTS; import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.referencing.CRS; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.referencing.FactoryException; import org.opengis.referencing.NoSuchAuthorityCodeException; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.operation.MathTransform; import org.opengis.referencing.operation.TransformException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import com.amazonaws.AmazonClientException; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.ObjectMetadata; import com.vividsolutions.jts.geom.Envelope; import exception.InvalidInputException; import model.data.DataResource; import model.data.DataType; import model.data.FileRepresentation; import model.data.location.FileAccessFactory; import model.data.location.FileLocation; import model.data.location.S3FileStore; import model.data.type.GeoJsonDataType; import model.data.type.ShapefileDataType; import model.job.metadata.SpatialMetadata; import util.GeoToolsUtil; import util.PiazzaLogger; /** * Utility component for some generic processing efforts. * * @author Sonny.Saniev * */ @Component public class IngestUtilities { @Autowired private PiazzaLogger logger; @Value("${vcap.services.pz-geoserver-efs.credentials.postgres.hostname}") private String POSTGRES_HOST; @Value("${vcap.services.pz-geoserver-efs.credentials.postgres.port}") private String POSTGRES_PORT; @Value("${vcap.services.pz-geoserver-efs.credentials.postgres.database}") private String POSTGRES_DB_NAME; @Value("${vcap.services.pz-geoserver-efs.credentials.postgres.username}") private String POSTGRES_USER; @Value("${vcap.services.pz-geoserver-efs.credentials.postgres.password}") private String POSTGRES_PASSWORD; @Value("${postgres.schema}") private String POSTGRES_SCHEMA; @Value("${vcap.services.pz-blobstore.credentials.access_key_id}") private String AMAZONS3_ACCESS_KEY; @Value("${vcap.services.pz-blobstore.credentials.secret_access_key}") private String AMAZONS3_PRIVATE_KEY; @Value("${vcap.services.pz-blobstore.credentials.bucket}") private String AMAZONS3_BUCKET_NAME; private final static Logger LOGGER = LoggerFactory.getLogger(IngestUtilities.class); /** * Recursive deletion of directory * * @param File * Directory to be deleted * * @return boolean if successful * @throws IOException */ public boolean deleteDirectoryRecursive(File directory) throws IOException { boolean result = false; if (directory.isDirectory()) { File[] files = directory.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { deleteDirectoryRecursive(files[i]); } if (!files[i].delete()) throw new IOException("Unable to delete file " + files[i].getName() + " from " + directory.getAbsolutePath()); } result = directory.delete(); } return result; } /** * Unzip the given zip into output directory. This is only applicable for SHAPEFILES as it includes black/whitelist * for preventing malicious inputs. * * @param zipPath * Zip file full path * @param extractPath * Extracted zip output directory * * @return boolean if successful * @throws IOException */ public void extractZip(String zipPath, String extractPath) throws IOException { byte[] buffer = new byte[1024]; ZipInputStream zipInputStream = null; FileOutputStream outputStream = null; try { // Create output directory File directory = new File(extractPath); if (!directory.exists()) { directory.mkdir(); } // Stream from zip content zipInputStream = new ZipInputStream(new FileInputStream(zipPath)); // Get initial file list entry ZipEntry zipEntry = zipInputStream.getNextEntry(); while (zipEntry != null) { String fileName = zipEntry.getName(); String extension = FilenameUtils.getExtension(fileName); String filePath = String.format("%s%s%s.%s", extractPath, File.separator, "ShapefileData", extension); // Sanitize - blacklist if (filePath.contains("..") || (fileName.contains("/")) || (fileName.contains("\\"))) { logger.log(String.format( "Cannot extract Zip entry %s because it contains a restricted path reference. Characters such as '..' or slashes are disallowed. The initial zip path was %s. This was blocked to prevent a vulnerability.", zipEntry.getName(), zipPath), PiazzaLogger.WARNING); zipInputStream.closeEntry(); zipEntry = zipInputStream.getNextEntry(); continue; } // Sanitize - whitelist if ((filePath.contains(".shp")) || (filePath.contains(".prj")) || (filePath.contains(".shx")) || (filePath.contains(".dbf")) || (filePath.contains(".sbn"))) { File newFile = new File(filePath).getCanonicalFile(); // Create all non existing folders new File(newFile.getParent()).mkdirs(); outputStream = new FileOutputStream(newFile); int length; while ((length = zipInputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); } outputStream.close(); zipInputStream.closeEntry(); zipEntry = zipInputStream.getNextEntry(); } else { zipInputStream.closeEntry(); zipEntry = zipInputStream.getNextEntry(); } } zipInputStream.closeEntry(); zipInputStream.close(); } catch (IOException ex) { String error = "Unable to extract zip: " + zipPath + " to path " + extractPath; LOGGER.error(error, ex); throw new IOException(error); } finally { try { zipInputStream.close(); } catch (Exception exception) { LOGGER.error("Error Closing Resource Stream", exception); } try { outputStream.close(); } catch (Exception exception) { LOGGER.error("Error Closing Resource Stream", exception); } } } /** * Gets the GeoTools Feature Store for the Shapefile. * * @param shapefilePath * The full string path to the expanded *.shp shape file. * @return The GeoTools Shapefile Data Store Feature Source */ public FeatureSource<SimpleFeatureType, SimpleFeature> getShapefileDataStore(String shapefilePath) throws IOException { File shapefile = new File(shapefilePath); Map<String, Object> map = new HashMap<String, Object>(); map.put("url", shapefile.toURI().toURL()); DataStore dataStore = DataStoreFinder.getDataStore(map); String typeName = dataStore.getTypeNames()[0]; FeatureSource<SimpleFeatureType, SimpleFeature> featureSource = dataStore.getFeatureSource(typeName); return featureSource; } /** * Loads the contents of a DataResource into the PostGIS Database. * * @param featureSource * The GeoTools FeatureSource for the ingest information. * @param dataResource * The DataResource object with FeatureSource metadata * @throws IOException */ public void persistFeatures(FeatureSource<SimpleFeatureType, SimpleFeature> featureSource, DataResource dataResource, SimpleFeatureType featureSchema) throws IOException { // Get the dataStore to the postGIS database. DataStore postGisStore = GeoToolsUtil.getPostGisDataStore(POSTGRES_HOST, POSTGRES_PORT, POSTGRES_SCHEMA, POSTGRES_DB_NAME, POSTGRES_USER, POSTGRES_PASSWORD); // Create the schema in the data store String tableName = dataResource.getDataId(); // Associate the table name with the DataResource SimpleFeatureType postGisSchema = GeoToolsUtil.cloneFeatureType(featureSchema, tableName); postGisStore.createSchema(postGisSchema); SimpleFeatureStore postGisFeatureStore = (SimpleFeatureStore) postGisStore.getFeatureSource(tableName); // Commit the features to the data store Transaction transaction = new DefaultTransaction(); try { // Get the features from the FeatureCollection and add to the PostGIS store SimpleFeatureCollection features = (SimpleFeatureCollection) featureSource.getFeatures(); postGisFeatureStore.addFeatures(features); // Commit the changes and clean up transaction.commit(); transaction.close(); } catch (IOException exception) { // Clean up resources transaction.rollback(); transaction.close(); LOGGER.error("Error copying DataResource to PostGIS: " + exception.getMessage(), exception); // Rethrow throw exception; } finally { // Cleanup Data Store postGisStore.dispose(); } } /** * Will copy external AWS S3 file to piazza S3 Bucket * * @param dataResource * @param host * if piazza should host the data */ public void copyS3Source(DataResource dataResource) throws AmazonClientException, InvalidInputException, IOException { // Connect to AWS S3 Bucket. Apply security only if credentials are // present AmazonS3 s3Client = getAwsClient(); // Obtain file input stream FileLocation fileLocation = ((FileRepresentation) dataResource.getDataType()).getLocation(); FileAccessFactory fileFactory = new FileAccessFactory(AMAZONS3_ACCESS_KEY, AMAZONS3_PRIVATE_KEY); InputStream inputStream = fileFactory.getFile(fileLocation); // Write stream directly into an s3 bucket ObjectMetadata metadata = new ObjectMetadata(); String fileKey = String.format("%s-%s", dataResource.getDataId(), fileLocation.getFileName()); s3Client.putObject(AMAZONS3_BUCKET_NAME, fileKey, inputStream, metadata); // Clean up inputStream.close(); } public long getFileSize(DataResource dataResource) throws AmazonClientException, InvalidInputException, IOException { // Obtain file input stream FileLocation fileLocation = ((FileRepresentation) dataResource.getDataType()).getLocation(); FileAccessFactory fileFactory = new FileAccessFactory(AMAZONS3_ACCESS_KEY, AMAZONS3_PRIVATE_KEY); InputStream inputStream = fileFactory.getFile(fileLocation); long counter = inputStream.read(); long numBytes = 0; while (counter >= 0) { counter = inputStream.read(); numBytes++; } return numBytes; } /** * Gets an instance of an S3 client to use. * * @return The S3 client */ public AmazonS3 getAwsClient() { AmazonS3 s3Client; if ((AMAZONS3_ACCESS_KEY.isEmpty()) && (AMAZONS3_PRIVATE_KEY.isEmpty())) { s3Client = new AmazonS3Client(); } else { BasicAWSCredentials credentials = new BasicAWSCredentials(AMAZONS3_ACCESS_KEY, AMAZONS3_PRIVATE_KEY); s3Client = new AmazonS3Client(credentials); } return s3Client; } /** * Searches directory file list for the first shape file and returns the name (non-recursive) * * @param directoryPath * Folder path to search * * @return shape file name found in the directory */ public String findShapeFileName(String directoryPath) throws IOException { File[] files = new File(directoryPath).listFiles(); for (int index = 0; index < files.length; index++) { String fileName = files[index].getName(); if (fileName.toLowerCase(Locale.ROOT).endsWith(".shp")) return fileName; } throw new IOException("No shape file was found inside unzipped directory: " + directoryPath); } /** * Deletes all persistent files for a Data Resource item. This will not remove the entry from MongoDB. That is * handled separately. * * <p> * This will delete files from S3 for rasters/vectors, and for vectors this will also delete the PostGIS table. * </p> * * @param dataResource */ public void deleteDataResourceFiles(DataResource dataResource) throws IOException { // If the DataResource has PostGIS tables to clean DataType dataType = dataResource.getDataType(); if (dataType instanceof ShapefileDataType) { deleteDatabaseTable(((ShapefileDataType) dataType).getDatabaseTableName()); } else if (dataType instanceof GeoJsonDataType) { deleteDatabaseTable(((GeoJsonDataType) dataType).databaseTableName); } // If the Data Resource has S3 files to clean if (dataType instanceof S3FileStore) { S3FileStore fileStore = (S3FileStore) dataType; if (!fileStore.getBucketName().equals(AMAZONS3_BUCKET_NAME)) { // Held by Piazza S3. Delete the data. AmazonS3 client = getAwsClient(); client.deleteObject(fileStore.getBucketName(), fileStore.getFileName()); } } } /** * Based on the input Spatial metadata in native projection, this will reproject to EPSG:4326 and return a newly * created SpatialMetadata object with WGS84/EPSG:4326 projection information for that native bounding box. * * @param spatialMetadata * The native bounding box information * @return Projected (WGS84) bounding box information */ public SpatialMetadata getProjectedSpatialMetadata(SpatialMetadata spatialMetadata) throws NoSuchAuthorityCodeException, FactoryException, TransformException { // Coordinate system inputs to transform CoordinateReferenceSystem sourceCrs = CRS.decode(String.format("EPSG:%s", spatialMetadata.getEpsgCode())); CoordinateReferenceSystem targetCrs = CRS.decode("EPSG:4326"); MathTransform transform = CRS.findMathTransform(sourceCrs, targetCrs); // Build the bounding box geometry to reproject with the transform ReferencedEnvelope envelope = new ReferencedEnvelope(spatialMetadata.getMinX(), spatialMetadata.getMaxX(), spatialMetadata.getMinY(), spatialMetadata.getMaxY(), sourceCrs); // Project Envelope projectedEnvelope = JTS.transform(envelope, transform); // Create a new container and add the information SpatialMetadata projected = new SpatialMetadata(); projected.setMinX(projectedEnvelope.getMinX()); projected.setMinY(projectedEnvelope.getMinY()); projected.setMaxX(projectedEnvelope.getMaxX()); projected.setMaxY(projectedEnvelope.getMaxY()); projected.setEpsgCode(4326); return projected; } /** * Drops a table, by name, in the Piazza database. * * @param tableName * The name of the table to drop. */ public void deleteDatabaseTable(String tableName) throws IOException { // Delete the table DataStore postGisStore = GeoToolsUtil.getPostGisDataStore(POSTGRES_HOST, POSTGRES_PORT, POSTGRES_SCHEMA, POSTGRES_DB_NAME, POSTGRES_USER, POSTGRES_PASSWORD); try { postGisStore.removeSchema(tableName); } catch (IllegalArgumentException exception) { // If this exception is triggered, then its likely the database // table was already deleted. Log that. String error = String.format( "Attempted to delete Table %s from Database for deleting a Data Resource, but the table was not found.", tableName); LOGGER.error(error, exception); logger.log(error, PiazzaLogger.WARNING); } finally { postGisStore.dispose(); } } }
src/main/java/ingest/utility/IngestUtilities.java
/** * Copyright 2016, RadiantBlue Technologies, 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 ingest.utility; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.apache.commons.io.FilenameUtils; import org.geotools.data.DataStore; import org.geotools.data.DataStoreFinder; import org.geotools.data.DefaultTransaction; import org.geotools.data.FeatureSource; import org.geotools.data.Transaction; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.data.simple.SimpleFeatureStore; import org.geotools.geometry.jts.JTS; import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.referencing.CRS; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.referencing.FactoryException; import org.opengis.referencing.NoSuchAuthorityCodeException; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.operation.MathTransform; import org.opengis.referencing.operation.TransformException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import com.amazonaws.AmazonClientException; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.ObjectMetadata; import com.vividsolutions.jts.geom.Envelope; import exception.InvalidInputException; import model.data.DataResource; import model.data.DataType; import model.data.FileRepresentation; import model.data.location.FileAccessFactory; import model.data.location.FileLocation; import model.data.location.S3FileStore; import model.data.type.GeoJsonDataType; import model.data.type.ShapefileDataType; import model.job.metadata.SpatialMetadata; import util.GeoToolsUtil; import util.PiazzaLogger; /** * Utility component for some generic processing efforts. * * @author Sonny.Saniev * */ @Component public class IngestUtilities { @Autowired private PiazzaLogger logger; @Value("${vcap.services.pz-geoserver-efs.credentials.postgres.hostname}") private String POSTGRES_HOST; @Value("${vcap.services.pz-geoserver-efs.credentials.postgres.port}") private String POSTGRES_PORT; @Value("${vcap.services.pz-geoserver-efs.credentials.postgres.database}") private String POSTGRES_DB_NAME; @Value("${vcap.services.pz-geoserver-efs.credentials.postgres.username}") private String POSTGRES_USER; @Value("${vcap.services.pz-geoserver-efs.credentials.postgres.password}") private String POSTGRES_PASSWORD; @Value("${postgres.schema}") private String POSTGRES_SCHEMA; @Value("${vcap.services.pz-blobstore.credentials.access_key_id}") private String AMAZONS3_ACCESS_KEY; @Value("${vcap.services.pz-blobstore.credentials.secret_access_key}") private String AMAZONS3_PRIVATE_KEY; @Value("${vcap.services.pz-blobstore.credentials.bucket}") private String AMAZONS3_BUCKET_NAME; private final static Logger LOGGER = LoggerFactory.getLogger(IngestUtilities.class); /** * Recursive deletion of directory * * @param File * Directory to be deleted * * @return boolean if successful * @throws IOException */ public boolean deleteDirectoryRecursive(File directory) throws IOException { boolean result = false; if (directory.isDirectory()) { File[] files = directory.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { deleteDirectoryRecursive(files[i]); } if (!files[i].delete()) throw new IOException("Unable to delete file " + files[i].getName() + " from " + directory.getAbsolutePath()); } result = directory.delete(); } return result; } /** * Unzip the given zip into output directory. This is only applicable for SHAPEFILES as it includes black/whitelist * for preventing malicious inputs. * * @param zipPath * Zip file full path * @param extractPath * Extracted zip output directory * * @return boolean if successful * @throws IOException */ public void extractZip(String zipPath, String extractPath) throws IOException { byte[] buffer = new byte[1024]; ZipInputStream zipInputStream = null; FileOutputStream outputStream = null; try { // Create output directory File directory = new File(extractPath); if (!directory.exists()) { directory.mkdir(); } // Stream from zip content zipInputStream = new ZipInputStream(new FileInputStream(zipPath)); // Get initial file list entry ZipEntry zipEntry = zipInputStream.getNextEntry(); while (zipEntry != null) { String fileName = zipEntry.getName(); String extension = FilenameUtils.getExtension(fileName); String filePath = String.format("%s%s%s.%s", extractPath, File.separator, "ShapefileData", extension); // Sanitize - blacklist if (filePath.contains("..") || (fileName.contains("/")) || (fileName.contains("\\"))) { logger.log(String.format( "Cannot extract Zip entry %s because it contains a restricted path reference. Characters such as '..' or slashes are disallowed. The initial zip path was %s. This was blocked to prevent a vulnerability.", zipEntry.getName(), zipPath), PiazzaLogger.WARNING); zipInputStream.closeEntry(); zipEntry = zipInputStream.getNextEntry(); continue; } // Sanitize - whitelist if ((filePath.contains(".shp")) || (filePath.contains(".prj")) || (filePath.contains(".shx")) || (filePath.contains(".dbf")) || (filePath.contains(".sbn"))) { File newFile = new File(filePath).getCanonicalFile(); // Create all non existing folders new File(newFile.getParent()).mkdirs(); outputStream = new FileOutputStream(newFile); int length; while ((length = zipInputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); } outputStream.close(); zipInputStream.closeEntry(); zipEntry = zipInputStream.getNextEntry(); } else { zipInputStream.closeEntry(); zipEntry = zipInputStream.getNextEntry(); } } zipInputStream.closeEntry(); zipInputStream.close(); } catch (IOException ex) { String error = "Unable to extract zip: " + zipPath + " to path " + extractPath; LOGGER.error(error, ex); throw new IOException(error); } finally { try { zipInputStream.close(); } catch (Exception exception) { LOGGER.error("Error Closing Resource Stream", exception); } try { outputStream.close(); } catch (Exception exception) { LOGGER.error("Error Closing Resource Stream", exception); } } } /** * Gets the GeoTools Feature Store for the Shapefile. * * @param shapefilePath * The full string path to the expanded *.shp shape file. * @return The GeoTools Shapefile Data Store Feature Source */ public FeatureSource<SimpleFeatureType, SimpleFeature> getShapefileDataStore(String shapefilePath) throws IOException { File shapefile = new File(shapefilePath); Map<String, Object> map = new HashMap<String, Object>(); map.put("url", shapefile.toURI().toURL()); DataStore dataStore = DataStoreFinder.getDataStore(map); String typeName = dataStore.getTypeNames()[0]; FeatureSource<SimpleFeatureType, SimpleFeature> featureSource = dataStore.getFeatureSource(typeName); return featureSource; } /** * Loads the contents of a DataResource into the PostGIS Database. * * @param featureSource * The GeoTools FeatureSource for the ingest information. * @param dataResource * The DataResource object with FeatureSource metadata * @throws IOException */ public void persistFeatures(FeatureSource<SimpleFeatureType, SimpleFeature> featureSource, DataResource dataResource, SimpleFeatureType featureSchema) throws IOException { // Get the dataStore to the postGIS database. DataStore postGisStore = GeoToolsUtil.getPostGisDataStore(POSTGRES_HOST, POSTGRES_PORT, POSTGRES_SCHEMA, POSTGRES_DB_NAME, POSTGRES_USER, POSTGRES_PASSWORD); LOGGER.info(String.format("Connecting to PostGIS at host %s on port %s to persist DataResource Id %s", POSTGRES_HOST, POSTGRES_PORT, dataResource.getDataId())); // Create the schema in the data store String tableName = dataResource.getDataId(); // Associate the table name with the DataResource SimpleFeatureType postGisSchema = GeoToolsUtil.cloneFeatureType(featureSchema, tableName); postGisStore.createSchema(postGisSchema); SimpleFeatureStore postGisFeatureStore = (SimpleFeatureStore) postGisStore.getFeatureSource(tableName); // Commit the features to the data store Transaction transaction = new DefaultTransaction(); try { // Get the features from the FeatureCollection and add to the PostGIS store SimpleFeatureCollection features = (SimpleFeatureCollection) featureSource.getFeatures(); postGisFeatureStore.addFeatures(features); // Commit the changes and clean up transaction.commit(); transaction.close(); } catch (IOException exception) { // Clean up resources transaction.rollback(); transaction.close(); LOGGER.error("Error copying DataResource to PostGIS: " + exception.getMessage(), exception); // Rethrow throw exception; } finally { // Cleanup Data Store postGisStore.dispose(); } } /** * Will copy external AWS S3 file to piazza S3 Bucket * * @param dataResource * @param host * if piazza should host the data */ public void copyS3Source(DataResource dataResource) throws AmazonClientException, InvalidInputException, IOException { // Connect to AWS S3 Bucket. Apply security only if credentials are // present AmazonS3 s3Client = getAwsClient(); // Obtain file input stream FileLocation fileLocation = ((FileRepresentation) dataResource.getDataType()).getLocation(); FileAccessFactory fileFactory = new FileAccessFactory(AMAZONS3_ACCESS_KEY, AMAZONS3_PRIVATE_KEY); InputStream inputStream = fileFactory.getFile(fileLocation); // Write stream directly into an s3 bucket ObjectMetadata metadata = new ObjectMetadata(); String fileKey = String.format("%s-%s", dataResource.getDataId(), fileLocation.getFileName()); s3Client.putObject(AMAZONS3_BUCKET_NAME, fileKey, inputStream, metadata); // Clean up inputStream.close(); } public long getFileSize(DataResource dataResource) throws AmazonClientException, InvalidInputException, IOException { // Obtain file input stream FileLocation fileLocation = ((FileRepresentation) dataResource.getDataType()).getLocation(); FileAccessFactory fileFactory = new FileAccessFactory(AMAZONS3_ACCESS_KEY, AMAZONS3_PRIVATE_KEY); InputStream inputStream = fileFactory.getFile(fileLocation); long counter = inputStream.read(); long numBytes = 0; while (counter >= 0) { counter = inputStream.read(); numBytes++; } return numBytes; } /** * Gets an instance of an S3 client to use. * * @return The S3 client */ public AmazonS3 getAwsClient() { AmazonS3 s3Client; if ((AMAZONS3_ACCESS_KEY.isEmpty()) && (AMAZONS3_PRIVATE_KEY.isEmpty())) { s3Client = new AmazonS3Client(); } else { BasicAWSCredentials credentials = new BasicAWSCredentials(AMAZONS3_ACCESS_KEY, AMAZONS3_PRIVATE_KEY); s3Client = new AmazonS3Client(credentials); } return s3Client; } /** * Searches directory file list for the first shape file and returns the name (non-recursive) * * @param directoryPath * Folder path to search * * @return shape file name found in the directory */ public String findShapeFileName(String directoryPath) throws IOException { File[] files = new File(directoryPath).listFiles(); for (int index = 0; index < files.length; index++) { String fileName = files[index].getName(); if (fileName.toLowerCase(Locale.ROOT).endsWith(".shp")) return fileName; } throw new IOException("No shape file was found inside unzipped directory: " + directoryPath); } /** * Deletes all persistent files for a Data Resource item. This will not remove the entry from MongoDB. That is * handled separately. * * <p> * This will delete files from S3 for rasters/vectors, and for vectors this will also delete the PostGIS table. * </p> * * @param dataResource */ public void deleteDataResourceFiles(DataResource dataResource) throws IOException { // If the DataResource has PostGIS tables to clean DataType dataType = dataResource.getDataType(); if (dataType instanceof ShapefileDataType) { deleteDatabaseTable(((ShapefileDataType) dataType).getDatabaseTableName()); } else if (dataType instanceof GeoJsonDataType) { deleteDatabaseTable(((GeoJsonDataType) dataType).databaseTableName); } // If the Data Resource has S3 files to clean if (dataType instanceof S3FileStore) { S3FileStore fileStore = (S3FileStore) dataType; if (!fileStore.getBucketName().equals(AMAZONS3_BUCKET_NAME)) { // Held by Piazza S3. Delete the data. AmazonS3 client = getAwsClient(); client.deleteObject(fileStore.getBucketName(), fileStore.getFileName()); } } } /** * Based on the input Spatial metadata in native projection, this will reproject to EPSG:4326 and return a newly * created SpatialMetadata object with WGS84/EPSG:4326 projection information for that native bounding box. * * @param spatialMetadata * The native bounding box information * @return Projected (WGS84) bounding box information */ public SpatialMetadata getProjectedSpatialMetadata(SpatialMetadata spatialMetadata) throws NoSuchAuthorityCodeException, FactoryException, TransformException { // Coordinate system inputs to transform CoordinateReferenceSystem sourceCrs = CRS.decode(String.format("EPSG:%s", spatialMetadata.getEpsgCode())); CoordinateReferenceSystem targetCrs = CRS.decode("EPSG:4326"); MathTransform transform = CRS.findMathTransform(sourceCrs, targetCrs); // Build the bounding box geometry to reproject with the transform ReferencedEnvelope envelope = new ReferencedEnvelope(spatialMetadata.getMinX(), spatialMetadata.getMaxX(), spatialMetadata.getMinY(), spatialMetadata.getMaxY(), sourceCrs); // Project Envelope projectedEnvelope = JTS.transform(envelope, transform); // Create a new container and add the information SpatialMetadata projected = new SpatialMetadata(); projected.setMinX(projectedEnvelope.getMinX()); projected.setMinY(projectedEnvelope.getMinY()); projected.setMaxX(projectedEnvelope.getMaxX()); projected.setMaxY(projectedEnvelope.getMaxY()); projected.setEpsgCode(4326); return projected; } /** * Drops a table, by name, in the Piazza database. * * @param tableName * The name of the table to drop. */ public void deleteDatabaseTable(String tableName) throws IOException { // Delete the table DataStore postGisStore = GeoToolsUtil.getPostGisDataStore(POSTGRES_HOST, POSTGRES_PORT, POSTGRES_SCHEMA, POSTGRES_DB_NAME, POSTGRES_USER, POSTGRES_PASSWORD); try { postGisStore.removeSchema(tableName); } catch (IllegalArgumentException exception) { // If this exception is triggered, then its likely the database // table was already deleted. Log that. String error = String.format( "Attempted to delete Table %s from Database for deleting a Data Resource, but the table was not found.", tableName); LOGGER.error(error, exception); logger.log(error, PiazzaLogger.WARNING); } finally { postGisStore.dispose(); } } }
8957 SonarQube Coverage
src/main/java/ingest/utility/IngestUtilities.java
8957 SonarQube Coverage
Java
apache-2.0
33710dd48c6b1e97cf62113d03d300b58cdcb7af
0
wikimedia/apps-android-commons,wikimedia/apps-android-commons,nicolas-raoul/apps-android-commons,maskaravivek/apps-android-commons,misaochan/apps-android-commons,psh/apps-android-commons,commons-app/apps-android-commons,tobias47n9e/apps-android-commons,RSBat/apps-android-commons,sandarumk/apps-android-commons,neslihanturan/apps-android-commons,tobias47n9e/apps-android-commons,misaochan/apps-android-commons,tobias47n9e/apps-android-commons,nicolas-raoul/apps-android-commons,misaochan/apps-android-commons,domdomegg/apps-android-commons,misaochan/apps-android-commons,maskaravivek/apps-android-commons,wikimedia/apps-android-commons,psh/apps-android-commons,whym/apps-android-commons,sandarumk/apps-android-commons,misaochan/apps-android-commons,maskaravivek/apps-android-commons,whym/apps-android-commons,commons-app/apps-android-commons,misaochan/apps-android-commons,whym/apps-android-commons,akaita/apps-android-commons,commons-app/apps-android-commons,dbrant/apps-android-commons,nicolas-raoul/apps-android-commons,RSBat/apps-android-commons,akaita/apps-android-commons,commons-app/apps-android-commons,akaita/apps-android-commons,neslihanturan/apps-android-commons,RSBat/apps-android-commons,psh/apps-android-commons,neslihanturan/apps-android-commons,neslihanturan/apps-android-commons,domdomegg/apps-android-commons,psh/apps-android-commons,domdomegg/apps-android-commons,nicolas-raoul/apps-android-commons,whym/apps-android-commons,dbrant/apps-android-commons,sandarumk/apps-android-commons,maskaravivek/apps-android-commons,neslihanturan/apps-android-commons,domdomegg/apps-android-commons,commons-app/apps-android-commons,dbrant/apps-android-commons,dbrant/apps-android-commons,psh/apps-android-commons,domdomegg/apps-android-commons,maskaravivek/apps-android-commons
package fr.free.nrw.commons.category; import android.os.AsyncTask; import android.text.TextUtils; import android.util.Log; import android.view.View; import org.mediawiki.api.ApiResult; import org.mediawiki.api.MWApi; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.Iterator; import fr.free.nrw.commons.CommonsApplication; /** * Sends asynchronous queries to the Commons MediaWiki API to retrieve categories that are close to * the keyword typed in by the user. The 'srsearch' action-specific parameter is used for this * purpose. This class should be subclassed in CategorizationFragment.java to aggregate the results. */ public class MethodAUpdater extends AsyncTask<Void, Void, ArrayList<String>> { private String filter; private static final String TAG = MethodAUpdater.class.getName(); CategorizationFragment catFragment; public MethodAUpdater(CategorizationFragment catFragment) { this.catFragment = catFragment; } @Override protected void onPreExecute() { super.onPreExecute(); filter = catFragment.categoriesFilter.getText().toString(); catFragment.categoriesSearchInProgress.setVisibility(View.VISIBLE); catFragment.categoriesNotFoundView.setVisibility(View.GONE); catFragment.categoriesSkip.setVisibility(View.GONE); } /** * Remove categories that contain a year in them (starting with 19__ or 20__), except for this year * and previous year * Rationale: https://github.com/commons-app/apps-android-commons/issues/47 * @param items Unfiltered list of categories * @return Filtered category list */ private ArrayList<String> filterYears(ArrayList<String> items) { Iterator<String> iterator; //Check for current and previous year to exclude these categories from removal Calendar now = Calendar.getInstance(); int year = now.get(Calendar.YEAR); String yearInString = String.valueOf(year); Log.d(TAG, "Year: " + yearInString); int prevYear = year - 1; String prevYearInString = String.valueOf(prevYear); Log.d(TAG, "Previous year: " + prevYearInString); //Copy to Iterator to prevent ConcurrentModificationException when removing item for(iterator = items.iterator(); iterator.hasNext();) { String s = iterator.next(); //Check if s contains a 4-digit word anywhere within the string (.* is wildcard) //And that s does not equal the current year or previous year if(s.matches(".*(19|20)\\d{2}.*") && !s.contains(yearInString) && !s.contains(prevYearInString)) { Log.d(TAG, "Filtering out year " + s); iterator.remove(); } } Log.d(TAG, "Items: " + items.toString()); return items; } @Override protected ArrayList<String> doInBackground(Void... voids) { //otherwise if user has typed something in that isn't in cache, search API for matching categories MWApi api = CommonsApplication.createMWApi(); ApiResult result; ArrayList<String> categories = new ArrayList<String>(); //URL https://commons.wikimedia.org/w/api.php?action=query&format=xml&list=search&srwhat=text&srenablerewrites=1&srnamespace=14&srlimit=10&srsearch= try { result = api.action("query") .param("format", "xml") .param("list", "search") .param("srwhat", "text") .param("srnamespace", "14") .param("srlimit", catFragment.SEARCH_CATS_LIMIT) .param("srsearch", filter) .get(); Log.d(TAG, "Method A URL filter" + result.toString()); } catch (IOException e) { Log.e(TAG, "IO Exception: ", e); //Return empty arraylist return categories; } ArrayList<ApiResult> categoryNodes = result.getNodes("/api/query/search/p/@title"); for(ApiResult categoryNode: categoryNodes) { String cat = categoryNode.getDocument().getTextContent(); String catString = cat.replace("Category:", ""); categories.add(catString); } Log.d(TAG, "Found categories from Method A search, waiting for filter"); ArrayList<String> filteredItems = new ArrayList<String>(filterYears(categories)); return filteredItems; } }
app/src/main/java/fr/free/nrw/commons/category/MethodAUpdater.java
package fr.free.nrw.commons.category; import android.os.AsyncTask; import android.text.TextUtils; import android.util.Log; import android.view.View; import org.mediawiki.api.ApiResult; import org.mediawiki.api.MWApi; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.Iterator; import fr.free.nrw.commons.CommonsApplication; /** * Sends asynchronous queries to the Commons MediaWiki API to retrieve categories that are close to * the keyword typed in by the user. The 'srsearch' action-specific parameter is used for this * purpose. This class should be subclassed in CategorizationFragment.java to aggregate the results. */ public class MethodAUpdater extends AsyncTask<Void, Void, ArrayList<String>> { private String filter; private static final String TAG = MethodAUpdater.class.getName(); CategorizationFragment catFragment; public MethodAUpdater(CategorizationFragment catFragment) { this.catFragment = catFragment; } @Override protected void onPreExecute() { super.onPreExecute(); filter = catFragment.categoriesFilter.getText().toString(); catFragment.categoriesSearchInProgress.setVisibility(View.VISIBLE); catFragment.categoriesNotFoundView.setVisibility(View.GONE); catFragment.categoriesSkip.setVisibility(View.GONE); } /** * Remove categories that contain a year in them (starting with 19__ or 20__), except for this year * and previous year * Rationale: https://github.com/commons-app/apps-android-commons/issues/47 * @param items Unfiltered list of categories * @return Filtered category list */ private ArrayList<String> filterYears(ArrayList<String> items) { Iterator<String> iterator; //Check for current and previous year to exclude these categories from removal Calendar now = Calendar.getInstance(); int year = now.get(Calendar.YEAR); String yearInString = String.valueOf(year); Log.d(TAG, "Year: " + yearInString); int prevYear = year - 1; String prevYearInString = String.valueOf(prevYear); Log.d(TAG, "Previous year: " + prevYearInString); //Copy to Iterator to prevent ConcurrentModificationException when removing item for(iterator = items.iterator(); iterator.hasNext();) { String s = iterator.next(); //Check if s contains a 4-digit word anywhere within the string (.* is wildcard) //And that s does not equal the current year or previous year if(s.matches(".*(19|20)\\d{2}.*") && !s.contains(yearInString) && !s.contains(prevYearInString)) { Log.d(TAG, "Filtering out year " + s); iterator.remove(); } } Log.d(TAG, "Items: " + items.toString()); return items; } @Override protected ArrayList<String> doInBackground(Void... voids) { //If user hasn't typed anything in yet, get GPS and recent items if(TextUtils.isEmpty(filter)) { ArrayList<String> mergedItems = new ArrayList<String>(catFragment.mergeItems()); Log.d(TAG, "Merged items, waiting for filter"); ArrayList<String> filteredItems = new ArrayList<String>(filterYears(mergedItems)); return filteredItems; } //if user types in something that is in cache, return cached category if(catFragment.categoriesCache.containsKey(filter)) { ArrayList<String> cachedItems = new ArrayList<String>(catFragment.categoriesCache.get(filter)); Log.d(TAG, "Found cache items, waiting for filter"); ArrayList<String> filteredItems = new ArrayList<String>(filterYears(cachedItems)); return filteredItems; } //otherwise if user has typed something in that isn't in cache, search API for matching categories MWApi api = CommonsApplication.createMWApi(); ApiResult result; ArrayList<String> categories = new ArrayList<String>(); //URL https://commons.wikimedia.org/w/api.php?action=query&format=xml&list=search&srwhat=text&srenablerewrites=1&srnamespace=14&srlimit=10&srsearch= try { result = api.action("query") .param("format", "xml") .param("list", "search") .param("srwhat", "text") .param("srnamespace", "14") .param("srlimit", catFragment.SEARCH_CATS_LIMIT) .param("srsearch", filter) .get(); Log.d(TAG, "Method A URL filter" + result.toString()); } catch (IOException e) { Log.e(TAG, "IO Exception: ", e); //Return empty arraylist return categories; } ArrayList<ApiResult> categoryNodes = result.getNodes("/api/query/search/p/@title"); for(ApiResult categoryNode: categoryNodes) { String cat = categoryNode.getDocument().getTextContent(); String catString = cat.replace("Category:", ""); categories.add(catString); } Log.d(TAG, "Found categories from Method A search, waiting for filter"); ArrayList<String> filteredItems = new ArrayList<String>(filterYears(categories)); return filteredItems; } }
Remove unnecessary calls in MethodAUpdater
app/src/main/java/fr/free/nrw/commons/category/MethodAUpdater.java
Remove unnecessary calls in MethodAUpdater
Java
apache-2.0
7caab2ca242b03055cfbe81c578c694523e670bd
0
x-hansong/EasyChat,x-hansong/EasyChat,x-hansong/EasyChat
package com.easychat.service.impl; import com.easychat.exception.BadRequestException; import com.easychat.exception.NotFoundException; import com.easychat.model.entity.FriendRelationship; import com.easychat.model.entity.User; import com.easychat.model.entity.UserTemp; import com.easychat.model.error.ErrorType; import com.easychat.repository.FriendRelationshipRepository; import com.easychat.repository.UserRepository; import com.easychat.service.UserService; import com.easychat.utils.CommonUtils; import com.easychat.utils.JsonUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by yonah on 15-10-18. */ @Service public class UserServiceImpl implements UserService { private UserRepository userRepository; private FriendRelationshipRepository friendRelationshipRepository; private RedisTemplate redisTemplate; static Logger logger = LoggerFactory.getLogger(UserService.class); @Autowired public UserServiceImpl(UserRepository userRepository,FriendRelationshipRepository friendRelationshipRepository) { this.userRepository = userRepository; this.friendRelationshipRepository = friendRelationshipRepository; } /** * 注册处理 * @param json */ @Override public void addUser(String json) throws BadRequestException { Map data = JsonUtils.decode(json, Map.class); String nameTest = (String) data.get("name"); String passwordTest = (String) data.get("password"); if (CommonUtils.checkName(nameTest) && CommonUtils.checkPassword(passwordTest)) { User user = userRepository.findByName(nameTest); if (user == null) { User userTest = new User(); userTest.setName(nameTest); userTest.setPassword(CommonUtils.md5(passwordTest)); String avatar="http://img4q.duitang.com/uploads/item/201503/05/20150305192855_iAFTs.thumb.224_0.jpeg"; userTest.setAvatar(avatar); userTest.setNick(nameTest); userRepository.save(userTest); } else { throw new BadRequestException(ErrorType.DUPLICATE_UNIQUE_PROPERTY_EXISTS, "Entity user requires that property named username be unique"); } } else { throw new BadRequestException(ErrorType.ILLEGAL_ARGUMENT, "invalid username or password"); } } /** * 用户登录 * * @return 用户名和密码正确,创建session并返回. */ @Override public User authenticate(String json) throws BadRequestException, NotFoundException { Map data = JsonUtils.decode(json, Map.class); String name = (String) data.get("name"); String password = CommonUtils.md5((String) data.get("password")); if (name == null || password == null) { throw new BadRequestException(ErrorType.ILLEGAL_ARGUMENT, "invalid input"); } return validateUser(name, password); } /** * 验证账号密码是否正确 * * @param name * @param password * @return User */ private User validateUser(String name, String password) throws NotFoundException, BadRequestException { User user = userRepository.findByName(name); if (user != null){ if (password.equals(user.getPassword())) { return user; } else { throw new BadRequestException(ErrorType.ILLEGAL_ARGUMENT, "invalid username or password"); } } else { throw new NotFoundException(ErrorType.SERVICE_RESOURCE_NOT_FOUND, "the user is not exists"); } } /** * 修改用户信息接口. * * @param name * @param json * @throws BadRequestException */ @Override public void modifyUserInfo(String name, String json) throws BadRequestException ,NotFoundException{ Map<String, Object> data = JsonUtils.decode(json, Map.class); String sex = (String)data.get("sex"); String nick = (String) data.get("nick"); String phone = (String) data.get("phone"); String email = (String) data.get("email"); String avatar = (String) data.get("avatar"); String signInfo = (String) data.get("sign_info"); if (CommonUtils.checkNick(nick)) { if (CommonUtils.checkEmail(email)) { if (CommonUtils.checkSex(sex)) { if (CommonUtils.checkPhone(phone)) { if (CommonUtils.checkSignInfo(signInfo)) { User user = userRepository.findByName(name); if (user == null) throw new NotFoundException(ErrorType.SERVICE_RESOURCE_NOT_FOUND, "the user is not exists"); user.setSex(sex); user.setNick(nick); user.setPhone(phone); user.setEmail(email); user.setAvatar(avatar); user.setSignInfo(signInfo); userRepository.save(user); } else throw new BadRequestException(ErrorType.ILLEGAL_ARGUMENT, "Wrong signInfo input"); } else throw new BadRequestException(ErrorType.ILLEGAL_ARGUMENT, "Wrong phone input"); } else throw new BadRequestException(ErrorType.ILLEGAL_ARGUMENT, "Wrong sex input"); } else throw new BadRequestException(ErrorType.ILLEGAL_ARGUMENT, "Wrong email input"); } else throw new BadRequestException(ErrorType.ILLEGAL_ARGUMENT, "Wrong nick input"); } /** * 获取用户信息 * * @param name * @return * @throws NotFoundException */ public String getUser(String name) throws NotFoundException { User user = userRepository.findByName(name); if (user != null) { Map<String, Object> data = new HashMap<String, Object>(); data.put("id", user.getId()); data.put("name", name); data.put("nick", user.getNick()); data.put("sex", user.getSex()); data.put("phone", user.getPhone()); data.put("email", user.getEmail()); data.put("avatar", user.getAvatar()); data.put("sign_info", user.getSignInfo()); String json = JsonUtils.encode(data); return json; } else{ throw new NotFoundException(ErrorType.SERVICE_RESOURCE_NOT_FOUND, "the user is not exists"); } } /** * 获取所有好友 * @param name * @return * @throws NotFoundException */ @Override public String getFriends(String name) throws NotFoundException { User user = userRepository.findByName(name); //判断用户是否存在 if (user != null){ long uid = user.getId(); logger.debug(uid + ""); List<FriendRelationship> friendRelationshipList = friendRelationshipRepository.findByAid(uid); //判断好友人数是否等于零 if(friendRelationshipList.size() >0 && friendRelationshipList != null){ UserTemp[] friends = new UserTemp[friendRelationshipList.size()]; for(int i = 0 ;i <friendRelationshipList.size() ; i++){ long fid = friendRelationshipList.get(i).getBid(); User friend = userRepository.findOne(fid); friends[i] = new UserTemp(friend); } Map<String,UserTemp[]> map = new HashMap<>(); map.put("friends",friends); String json = JsonUtils.encode(map); return json; }else { return null; } }else{ throw new NotFoundException(ErrorType.SERVICE_RESOURCE_NOT_FOUND, "the user is not exists"); } } /** * 删除好友 * @param userName * @param friendName * @throws NotFoundException */ @Override public void deleteFriend(String userName, String friendName) throws NotFoundException{ User user = userRepository.findByName(userName); //判断用户是否存在 if(user != null){ User friend = userRepository.findByName(friendName); //判断好友是否存在 if(friend !=null){ long uid = user.getId(); long fid = friend.getId(); FriendRelationship uTofFriendRelationship = friendRelationshipRepository.findByAidAndBid(uid,fid); FriendRelationship fTouFriendRelationship = friendRelationshipRepository.findByAidAndBid(fid, uid); //判断双方的好友关系是否存在 if((uTofFriendRelationship != null) && (fTouFriendRelationship !=null)){ friendRelationshipRepository.delete(uTofFriendRelationship); friendRelationshipRepository.delete(fTouFriendRelationship); }else{ throw new NotFoundException(ErrorType.SERVICE_RESOURCE_NOT_FOUND, "they are not friends"); } }else{ throw new NotFoundException(ErrorType.SERVICE_RESOURCE_NOT_FOUND, "the friend is not exists"); } }else{ throw new NotFoundException(ErrorType.SERVICE_RESOURCE_NOT_FOUND, "the user is not exists"); } } /** * 获取好友信息 * * @param name * @return * @throws NotFoundException */ public String getFriendInfo(String name,String friend_name) throws NotFoundException { User user = userRepository.findByName(name); if (user != null) { User friend = userRepository.findByName(friend_name); //判断好友是否存在 if (friend != null) { long uid = user.getId(); long fid = friend.getId(); FriendRelationship uTofFriendRelationship = friendRelationshipRepository.findByAidAndBid(uid, fid); FriendRelationship fTouFriendRelationship = friendRelationshipRepository.findByAidAndBid(fid, uid); //判断双方的好友关系是否存在 if ((uTofFriendRelationship != null) && (fTouFriendRelationship != null)) { UserTemp friendTemp = new UserTemp(friend); String json = JsonUtils.encode(friendTemp); return json; } else throw new NotFoundException(ErrorType.SERVICE_RESOURCE_NOT_FOUND, "they are not friends"); } else throw new NotFoundException(ErrorType.SERVICE_RESOURCE_NOT_FOUND, "the friend is not exists"); } else{ throw new NotFoundException(ErrorType.SERVICE_RESOURCE_NOT_FOUND, "the user is not exists"); } } /** * 获取陌生人信息 * * @param name * @return * @throws NotFoundException */ public String getStrangerInfo(String name,String stranger_name) throws NotFoundException { User user = userRepository.findByName(name); if (user != null) { User person = userRepository.findByName(stranger_name); //判断好友是否存在 if (person != null) { long uid = user.getId(); long fid = person.getId(); FriendRelationship uTofFriendRelationship = friendRelationshipRepository.findByAidAndBid(uid, fid); FriendRelationship fTouFriendRelationship = friendRelationshipRepository.findByAidAndBid(fid, uid); //判断双方的好友关系是否存在 //如果两个人是好友,返回基于好友身份的信息 if ((uTofFriendRelationship != null) && (fTouFriendRelationship != null)) { UserTemp friendTemp = new UserTemp(person); String json = JsonUtils.encode(friendTemp); return json; } //如果两个人不是好友,返回基于陌生人身份的信息 else { Map<String, Object> data = new HashMap<String, Object>(); data.put("name", stranger_name); data.put("nick", person.getNick()); data.put("sex", person.getSex()); data.put("avatar", person.getAvatar()); data.put("sign_info", person.getSignInfo()); String json = JsonUtils.encode(data); return json; } } else throw new NotFoundException(ErrorType.SERVICE_RESOURCE_NOT_FOUND, "the stranger is not exists"); } else { throw new NotFoundException(ErrorType.SERVICE_RESOURCE_NOT_FOUND, "the user is not exists"); } } /** * 添加好友关系 */ @Override public boolean setFriendRelationship(String aName, String bName){ User aUser = userRepository.findByName(aName); User bUser = userRepository.findByName(bName); FriendRelationship relationship = new FriendRelationship(aUser.getId(), bUser.getId()); friendRelationshipRepository.save(relationship); relationship.setAid(bUser.getId()); relationship.setBid(aUser.getId()); friendRelationshipRepository.save(relationship); return true; } }
Server/src/main/java/com/easychat/service/impl/UserServiceImpl.java
package com.easychat.service.impl; import com.easychat.exception.BadRequestException; import com.easychat.exception.NotFoundException; import com.easychat.model.entity.FriendRelationship; import com.easychat.model.entity.User; import com.easychat.model.entity.UserTemp; import com.easychat.model.error.ErrorType; import com.easychat.repository.FriendRelationshipRepository; import com.easychat.repository.UserRepository; import com.easychat.service.UserService; import com.easychat.utils.CommonUtils; import com.easychat.utils.JsonUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by yonah on 15-10-18. */ @Service public class UserServiceImpl implements UserService { private UserRepository userRepository; private FriendRelationshipRepository friendRelationshipRepository; private RedisTemplate redisTemplate; static Logger logger = LoggerFactory.getLogger(UserService.class); @Autowired public UserServiceImpl(UserRepository userRepository,FriendRelationshipRepository friendRelationshipRepository) { this.userRepository = userRepository; this.friendRelationshipRepository = friendRelationshipRepository; } /** * 注册处理 * @param json */ @Override public void addUser(String json) throws BadRequestException { Map data = JsonUtils.decode(json, Map.class); String nameTest = (String) data.get("name"); String passwordTest = (String) data.get("password"); if (CommonUtils.checkName(nameTest) && CommonUtils.checkPassword(passwordTest)) { User user = userRepository.findByName(nameTest); if (user == null) { User userTest = new User(); userTest.setName(nameTest); userTest.setPassword(CommonUtils.md5(passwordTest)); String avatar="http://img4q.duitang.com/uploads/item/201503/05/20150305192855_iAFTs.thumb.224_0.jpeg"; userTest.setAvatar(avatar); userTest.setNick(nameTest); userRepository.save(userTest); } else { throw new BadRequestException(ErrorType.DUPLICATE_UNIQUE_PROPERTY_EXISTS, "Entity user requires that property named username be unique"); } } else { throw new BadRequestException(ErrorType.ILLEGAL_ARGUMENT, "invalid username or password"); } } /** * 用户登录 * * @return 用户名和密码正确,创建session并返回. */ @Override public User authenticate(String json) throws BadRequestException, NotFoundException { Map data = JsonUtils.decode(json, Map.class); String name = (String) data.get("name"); String password = CommonUtils.md5((String) data.get("password")); if (name == null || password == null) { throw new BadRequestException(ErrorType.ILLEGAL_ARGUMENT, "invalid input"); } return validateUser(name, password); } /** * 验证账号密码是否正确 * * @param name * @param password * @return User */ private User validateUser(String name, String password) throws NotFoundException, BadRequestException { User user = userRepository.findByName(name); if (user != null){ if (password.equals(user.getPassword())) { return user; } else { throw new BadRequestException(ErrorType.ILLEGAL_ARGUMENT, "invalid username or password"); } } else { throw new NotFoundException(ErrorType.SERVICE_RESOURCE_NOT_FOUND, "the user is not exists"); } } /** * 修改用户信息接口. * * @param name * @param json * @throws BadRequestException */ @Override public void modifyUserInfo(String name, String json) throws BadRequestException ,NotFoundException{ Map<String, Object> data = JsonUtils.decode(json, Map.class); String sex = (String)data.get("sex"); String nick = (String) data.get("nick"); String phone = (String) data.get("phone"); String email = (String) data.get("email"); String avatar = (String) data.get("avatar"); String signInfo = (String) data.get("sign_info"); if (CommonUtils.checkNick(nick)) { if (CommonUtils.checkEmail(email)) { if (CommonUtils.checkSex(sex)) { if (CommonUtils.checkPhone(phone)) { if (CommonUtils.checkSignInfo(signInfo)) { User user = userRepository.findByName(name); if (user == null) throw new NotFoundException(ErrorType.SERVICE_RESOURCE_NOT_FOUND, "the user is not exists"); user.setSex(sex); user.setNick(nick); user.setPhone(phone); user.setEmail(email); user.setAvatar(avatar); user.setSignInfo(signInfo); userRepository.save(user); } else throw new BadRequestException(ErrorType.ILLEGAL_ARGUMENT, "Wrong signInfo input"); } else throw new BadRequestException(ErrorType.ILLEGAL_ARGUMENT, "Wrong phone input"); } else throw new BadRequestException(ErrorType.ILLEGAL_ARGUMENT, "Wrong sex input"); } else throw new BadRequestException(ErrorType.ILLEGAL_ARGUMENT, "Wrong email input"); } else throw new BadRequestException(ErrorType.ILLEGAL_ARGUMENT, "Wrong nick input"); } /** * 获取用户信息 * * @param name * @return * @throws NotFoundException */ public String getUser(String name) throws NotFoundException { User user = userRepository.findByName(name); if (user != null) { Map<String, Object> data = new HashMap<String, Object>(); data.put("id", user.getId()); data.put("name", name); data.put("nick", user.getNick()); data.put("sex", user.getSex()); data.put("phone", user.getPhone()); data.put("email", user.getEmail()); data.put("avatar", user.getAvatar()); data.put("sign_info", user.getSignInfo()); String json = JsonUtils.encode(data); return json; } else{ throw new NotFoundException(ErrorType.SERVICE_RESOURCE_NOT_FOUND, "the user is not exists"); } } /** * 获取所有好友 * @param name * @return * @throws NotFoundException */ @Override public String getFriends(String name) throws NotFoundException { User user = userRepository.findByName(name); //判断用户是否存在 if (user != null){ long uid = user.getId(); logger.debug(uid + ""); List<FriendRelationship> friendRelationshipList = friendRelationshipRepository.findByAid(uid); //判断好友人数是否等于零 if(friendRelationshipList.size() >0 && friendRelationshipList != null){ UserTemp[] friends = new UserTemp[friendRelationshipList.size()]; for(int i = 0 ;i <friendRelationshipList.size() ; i++){ long fid = friendRelationshipList.get(i).getBid(); User friend = userRepository.findOne(fid); friends[i] = new UserTemp(friend); } Map<String,UserTemp[]> map = new HashMap<>(); map.put("friends",friends); String json = JsonUtils.encode(map); return json; }else { throw new NotFoundException(ErrorType.SERVICE_RESOURCE_NOT_FOUND, "the user has no friend"); } }else{ throw new NotFoundException(ErrorType.SERVICE_RESOURCE_NOT_FOUND, "the user is not exists"); } } /** * 删除好友 * @param userName * @param friendName * @throws NotFoundException */ @Override public void deleteFriend(String userName, String friendName) throws NotFoundException{ User user = userRepository.findByName(userName); //判断用户是否存在 if(user != null){ User friend = userRepository.findByName(friendName); //判断好友是否存在 if(friend !=null){ long uid = user.getId(); long fid = friend.getId(); FriendRelationship uTofFriendRelationship = friendRelationshipRepository.findByAidAndBid(uid,fid); FriendRelationship fTouFriendRelationship = friendRelationshipRepository.findByAidAndBid(fid, uid); //判断双方的好友关系是否存在 if((uTofFriendRelationship != null) && (fTouFriendRelationship !=null)){ friendRelationshipRepository.delete(uTofFriendRelationship); friendRelationshipRepository.delete(fTouFriendRelationship); }else{ throw new NotFoundException(ErrorType.SERVICE_RESOURCE_NOT_FOUND, "they are not friends"); } }else{ throw new NotFoundException(ErrorType.SERVICE_RESOURCE_NOT_FOUND, "the friend is not exists"); } }else{ throw new NotFoundException(ErrorType.SERVICE_RESOURCE_NOT_FOUND, "the user is not exists"); } } /** * 获取好友信息 * * @param name * @return * @throws NotFoundException */ public String getFriendInfo(String name,String friend_name) throws NotFoundException { User user = userRepository.findByName(name); if (user != null) { User friend = userRepository.findByName(friend_name); //判断好友是否存在 if (friend != null) { long uid = user.getId(); long fid = friend.getId(); FriendRelationship uTofFriendRelationship = friendRelationshipRepository.findByAidAndBid(uid, fid); FriendRelationship fTouFriendRelationship = friendRelationshipRepository.findByAidAndBid(fid, uid); //判断双方的好友关系是否存在 if ((uTofFriendRelationship != null) && (fTouFriendRelationship != null)) { UserTemp friendTemp = new UserTemp(friend); String json = JsonUtils.encode(friendTemp); return json; } else throw new NotFoundException(ErrorType.SERVICE_RESOURCE_NOT_FOUND, "they are not friends"); } else throw new NotFoundException(ErrorType.SERVICE_RESOURCE_NOT_FOUND, "the friend is not exists"); } else{ throw new NotFoundException(ErrorType.SERVICE_RESOURCE_NOT_FOUND, "the user is not exists"); } } /** * 获取陌生人信息 * * @param name * @return * @throws NotFoundException */ public String getStrangerInfo(String name,String stranger_name) throws NotFoundException { User user = userRepository.findByName(name); if (user != null) { User person = userRepository.findByName(stranger_name); //判断好友是否存在 if (person != null) { long uid = user.getId(); long fid = person.getId(); FriendRelationship uTofFriendRelationship = friendRelationshipRepository.findByAidAndBid(uid, fid); FriendRelationship fTouFriendRelationship = friendRelationshipRepository.findByAidAndBid(fid, uid); //判断双方的好友关系是否存在 //如果两个人是好友,返回基于好友身份的信息 if ((uTofFriendRelationship != null) && (fTouFriendRelationship != null)) { UserTemp friendTemp = new UserTemp(person); String json = JsonUtils.encode(friendTemp); return json; } //如果两个人不是好友,返回基于陌生人身份的信息 else { Map<String, Object> data = new HashMap<String, Object>(); data.put("name", stranger_name); data.put("nick", person.getNick()); data.put("sex", person.getSex()); data.put("avatar", person.getAvatar()); data.put("sign_info", person.getSignInfo()); String json = JsonUtils.encode(data); return json; } } else throw new NotFoundException(ErrorType.SERVICE_RESOURCE_NOT_FOUND, "the stranger is not exists"); } else { throw new NotFoundException(ErrorType.SERVICE_RESOURCE_NOT_FOUND, "the user is not exists"); } } /** * 添加好友关系 */ @Override public boolean setFriendRelationship(String aName, String bName){ User aUser = userRepository.findByName(aName); User bUser = userRepository.findByName(bName); FriendRelationship relationship = new FriendRelationship(aUser.getId(), bUser.getId()); friendRelationshipRepository.save(relationship); relationship.setAid(bUser.getId()); relationship.setBid(aUser.getId()); friendRelationshipRepository.save(relationship); return true; } }
修改获取用户所有好友接口,当该用户没有好友时,返回null
Server/src/main/java/com/easychat/service/impl/UserServiceImpl.java
修改获取用户所有好友接口,当该用户没有好友时,返回null
Java
apache-2.0
669c856b6715d23ef289139d64f50e82d7f2870b
0
adrapereira/jena,jianglili007/jena,samaitra/jena,tr3vr/jena,kidaa/jena,jianglili007/jena,samaitra/jena,adrapereira/jena,apache/jena,CesarPantoja/jena,samaitra/jena,jianglili007/jena,adrapereira/jena,kamir/jena,adrapereira/jena,kamir/jena,adrapereira/jena,CesarPantoja/jena,jianglili007/jena,apache/jena,kidaa/jena,jianglili007/jena,tr3vr/jena,kidaa/jena,CesarPantoja/jena,atsolakid/jena,apache/jena,kidaa/jena,atsolakid/jena,atsolakid/jena,jianglili007/jena,samaitra/jena,apache/jena,tr3vr/jena,CesarPantoja/jena,adrapereira/jena,kamir/jena,tr3vr/jena,atsolakid/jena,atsolakid/jena,tr3vr/jena,kamir/jena,CesarPantoja/jena,apache/jena,samaitra/jena,samaitra/jena,kidaa/jena,kidaa/jena,atsolakid/jena,apache/jena,adrapereira/jena,tr3vr/jena,samaitra/jena,apache/jena,tr3vr/jena,CesarPantoja/jena,kamir/jena,CesarPantoja/jena,jianglili007/jena,apache/jena,kidaa/jena,atsolakid/jena,kamir/jena,kamir/jena
/* * 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.jena.rdf.model.impl; import org.apache.jena.enhanced.* ; import org.apache.jena.graph.* ; import org.apache.jena.rdf.model.* ; /** An implementation of Bag */ public class BagImpl extends ContainerImpl implements Bag { final static public Implementation factory = new Implementation() { @Override public boolean canWrap( Node n, EnhGraph eg ) { return true; } @Override public EnhNode wrap(Node n,EnhGraph eg) { return new BagImpl(n,eg); } }; /** Creates new BagMem */ public BagImpl( ModelCom model ) { super(model); } public BagImpl( String uri, ModelCom model ) { super(uri, model); } public BagImpl( Resource r, ModelCom m ) { super( r, m ); } public BagImpl( Node n, EnhGraph g ) { super(n,g); } }
jena-core/src/main/java/org/apache/jena/rdf/model/impl/BagImpl.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.jena.rdf.model.impl; import org.apache.jena.enhanced.* ; import org.apache.jena.graph.* ; import org.apache.jena.rdf.model.* ; /** An implementation of Bag */ public class BagImpl extends ContainerImpl implements Bag { @SuppressWarnings("hiding") final static public Implementation factory = new Implementation() { @Override public boolean canWrap( Node n, EnhGraph eg ) { return true; } @Override public EnhNode wrap(Node n,EnhGraph eg) { return new BagImpl(n,eg); } }; /** Creates new BagMem */ public BagImpl( ModelCom model ) { super(model); } public BagImpl( String uri, ModelCom model ) { super(uri, model); } public BagImpl( Resource r, ModelCom m ) { super( r, m ); } public BagImpl( Node n, EnhGraph g ) { super(n,g); } }
JENA-938 : Code cleaning (extract of PR #63)
jena-core/src/main/java/org/apache/jena/rdf/model/impl/BagImpl.java
JENA-938 : Code cleaning (extract of PR #63)
Java
apache-2.0
804f1d9c19d600e5cd94fd554360421d415b5f4a
0
WANdisco/gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,gerrit-review/gerrit,gerrit-review/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,gerrit-review/gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,WANdisco/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,gerrit-review/gerrit,gerrit-review/gerrit,gerrit-review/gerrit,gerrit-review/gerrit,WANdisco/gerrit
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.lucene; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.gerrit.lucene.AbstractLuceneIndex.sortFieldName; import static com.google.gerrit.lucene.LuceneVersionManager.CHANGES_PREFIX; import static com.google.gerrit.server.git.QueueProvider.QueueType.INTERACTIVE; import static com.google.gerrit.server.index.change.ChangeField.CHANGE; import static com.google.gerrit.server.index.change.ChangeField.LEGACY_ID; import static com.google.gerrit.server.index.change.ChangeField.PROJECT; import static com.google.gerrit.server.index.change.IndexRewriter.CLOSED_STATUSES; import static com.google.gerrit.server.index.change.IndexRewriter.OPEN_STATUSES; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import com.google.gerrit.reviewdb.client.Account; import com.google.gerrit.reviewdb.client.Change; import com.google.gerrit.reviewdb.client.PatchSet; import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.reviewdb.server.ReviewDb; import com.google.gerrit.server.StarredChangesUtil; import com.google.gerrit.server.config.GerritServerConfig; import com.google.gerrit.server.config.SitePaths; import com.google.gerrit.server.index.FieldDef.FillArgs; import com.google.gerrit.server.index.IndexExecutor; import com.google.gerrit.server.index.QueryOptions; import com.google.gerrit.server.index.Schema; import com.google.gerrit.server.index.change.ChangeField; import com.google.gerrit.server.index.change.ChangeField.ChangeProtoField; import com.google.gerrit.server.index.change.ChangeField.PatchSetApprovalProtoField; import com.google.gerrit.server.index.change.ChangeField.PatchSetProtoField; import com.google.gerrit.server.index.change.ChangeIndex; import com.google.gerrit.server.index.change.IndexRewriter; import com.google.gerrit.server.query.Predicate; import com.google.gerrit.server.query.QueryParseException; import com.google.gerrit.server.query.change.ChangeData; import com.google.gerrit.server.query.change.ChangeDataSource; import com.google.gwtorm.protobuf.ProtobufCodec; import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.ResultSet; import com.google.inject.Provider; import com.google.inject.assistedinject.Assisted; import com.google.inject.assistedinject.AssistedInject; import org.apache.lucene.document.Document; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexableField; import org.apache.lucene.index.Term; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.SearcherFactory; import org.apache.lucene.search.SearcherManager; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.TopFieldDocs; import org.apache.lucene.store.RAMDirectory; import org.apache.lucene.util.BytesRef; import org.eclipse.jgit.lib.Config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; /** * Secondary index implementation using Apache Lucene. * <p> * Writes are managed using a single {@link IndexWriter} per process, committed * aggressively. Reads use {@link SearcherManager} and periodically refresh, * though there may be some lag between a committed write and it showing up to * other threads' searchers. */ public class LuceneChangeIndex implements ChangeIndex { private static final Logger log = LoggerFactory.getLogger(LuceneChangeIndex.class); public static final String CHANGES_OPEN = "open"; public static final String CHANGES_CLOSED = "closed"; static final String UPDATED_SORT_FIELD = sortFieldName(ChangeField.UPDATED); static final String ID_SORT_FIELD = sortFieldName(ChangeField.LEGACY_ID); private static final String ADDED_FIELD = ChangeField.ADDED.getName(); private static final String APPROVAL_FIELD = ChangeField.APPROVAL.getName(); private static final String CHANGE_FIELD = ChangeField.CHANGE.getName(); private static final String DELETED_FIELD = ChangeField.DELETED.getName(); private static final String MERGEABLE_FIELD = ChangeField.MERGEABLE.getName(); private static final String PATCH_SET_FIELD = ChangeField.PATCH_SET.getName(); private static final String REVIEWEDBY_FIELD = ChangeField.REVIEWEDBY.getName(); private static final String HASHTAG_FIELD = ChangeField.HASHTAG_CASE_AWARE.getName(); private static final String STAR_FIELD = ChangeField.STAR.getName(); @Deprecated private static final String STARREDBY_FIELD = ChangeField.STARREDBY.getName(); static Term idTerm(ChangeData cd) { return QueryBuilder.intTerm(LEGACY_ID.getName(), cd.getId().get()); } static Term idTerm(Change.Id id) { return QueryBuilder.intTerm(LEGACY_ID.getName(), id.get()); } private final FillArgs fillArgs; private final ListeningExecutorService executor; private final Provider<ReviewDb> db; private final ChangeData.Factory changeDataFactory; private final Schema<ChangeData> schema; private final QueryBuilder<ChangeData> queryBuilder; private final ChangeSubIndex openIndex; private final ChangeSubIndex closedIndex; @AssistedInject LuceneChangeIndex( @GerritServerConfig Config cfg, SitePaths sitePaths, @IndexExecutor(INTERACTIVE) ListeningExecutorService executor, Provider<ReviewDb> db, ChangeData.Factory changeDataFactory, FillArgs fillArgs, @Assisted Schema<ChangeData> schema) throws IOException { this.fillArgs = fillArgs; this.executor = executor; this.db = db; this.changeDataFactory = changeDataFactory; this.schema = schema; GerritIndexWriterConfig openConfig = new GerritIndexWriterConfig(cfg, "changes_open"); GerritIndexWriterConfig closedConfig = new GerritIndexWriterConfig(cfg, "changes_closed"); queryBuilder = new QueryBuilder<>(schema, openConfig.getAnalyzer()); SearcherFactory searcherFactory = new SearcherFactory(); if (LuceneIndexModule.isInMemoryTest(cfg)) { openIndex = new ChangeSubIndex(schema, sitePaths, new RAMDirectory(), "ramOpen", openConfig, searcherFactory); closedIndex = new ChangeSubIndex(schema, sitePaths, new RAMDirectory(), "ramClosed", closedConfig, searcherFactory); } else { Path dir = LuceneVersionManager.getDir(sitePaths, CHANGES_PREFIX, schema); openIndex = new ChangeSubIndex(schema, sitePaths, dir.resolve(CHANGES_OPEN), openConfig, searcherFactory); closedIndex = new ChangeSubIndex(schema, sitePaths, dir.resolve(CHANGES_CLOSED), closedConfig, searcherFactory); } } @Override public void close() { MoreExecutors.shutdownAndAwaitTermination( executor, Long.MAX_VALUE, TimeUnit.SECONDS); try { openIndex.close(); } finally { closedIndex.close(); } } @Override public Schema<ChangeData> getSchema() { return schema; } @Override public void replace(ChangeData cd) throws IOException { Term id = LuceneChangeIndex.idTerm(cd); // toDocument is essentially static and doesn't depend on the specific // sub-index, so just pick one. Document doc = openIndex.toDocument(cd, fillArgs); try { if (cd.change().getStatus().isOpen()) { Futures.allAsList( closedIndex.delete(id), openIndex.replace(id, doc)).get(); } else { Futures.allAsList( openIndex.delete(id), closedIndex.replace(id, doc)).get(); } } catch (OrmException | ExecutionException | InterruptedException e) { throw new IOException(e); } } @Override public void delete(Change.Id id) throws IOException { Term idTerm = LuceneChangeIndex.idTerm(id); try { Futures.allAsList( openIndex.delete(idTerm), closedIndex.delete(idTerm)).get(); } catch (ExecutionException | InterruptedException e) { throw new IOException(e); } } @Override public void deleteAll() throws IOException { openIndex.deleteAll(); closedIndex.deleteAll(); } @Override public ChangeDataSource getSource(Predicate<ChangeData> p, QueryOptions opts) throws QueryParseException { Set<Change.Status> statuses = IndexRewriter.getPossibleStatus(p); List<ChangeSubIndex> indexes = Lists.newArrayListWithCapacity(2); if (!Sets.intersection(statuses, OPEN_STATUSES).isEmpty()) { indexes.add(openIndex); } if (!Sets.intersection(statuses, CLOSED_STATUSES).isEmpty()) { indexes.add(closedIndex); } return new QuerySource(indexes, queryBuilder.toQuery(p), opts, getSort()); } @Override public void markReady(boolean ready) throws IOException { // Arbitrary done on open index, as ready bit is set // per index and not sub index openIndex.markReady(ready); } private Sort getSort() { return new Sort( new SortField(UPDATED_SORT_FIELD, SortField.Type.LONG, true), new SortField(ID_SORT_FIELD, SortField.Type.LONG, true)); } public ChangeSubIndex getClosedChangesIndex() { return closedIndex; } private class QuerySource implements ChangeDataSource { private final List<ChangeSubIndex> indexes; private final Query query; private final QueryOptions opts; private final Sort sort; private QuerySource(List<ChangeSubIndex> indexes, Query query, QueryOptions opts, Sort sort) { this.indexes = indexes; this.query = checkNotNull(query, "null query from Lucene"); this.opts = opts; this.sort = sort; } @Override public int getCardinality() { return 10; // TODO(dborowitz): estimate from Lucene? } @Override public boolean hasChange() { return false; } @Override public String toString() { return query.toString(); } @Override public ResultSet<ChangeData> read() throws OrmException { IndexSearcher[] searchers = new IndexSearcher[indexes.size()]; try { int realLimit = opts.start() + opts.limit(); TopFieldDocs[] hits = new TopFieldDocs[indexes.size()]; for (int i = 0; i < indexes.size(); i++) { searchers[i] = indexes.get(i).acquire(); hits[i] = searchers[i].search(query, realLimit, sort); } TopDocs docs = TopDocs.merge(sort, realLimit, hits); List<ChangeData> result = Lists.newArrayListWithCapacity(docs.scoreDocs.length); Set<String> fields = fields(opts); String idFieldName = LEGACY_ID.getName(); for (int i = opts.start(); i < docs.scoreDocs.length; i++) { ScoreDoc sd = docs.scoreDocs[i]; Document doc = searchers[sd.shardIndex].doc(sd.doc, fields); result.add(toChangeData(doc, fields, idFieldName)); } final List<ChangeData> r = Collections.unmodifiableList(result); return new ResultSet<ChangeData>() { @Override public Iterator<ChangeData> iterator() { return r.iterator(); } @Override public List<ChangeData> toList() { return r; } @Override public void close() { // Do nothing. } }; } catch (IOException e) { throw new OrmException(e); } finally { for (int i = 0; i < indexes.size(); i++) { if (searchers[i] != null) { try { indexes.get(i).release(searchers[i]); } catch (IOException e) { log.warn("cannot release Lucene searcher", e); } } } } } } private Set<String> fields(QueryOptions opts) { // Ensure we request enough fields to construct a ChangeData. Set<String> fs = opts.fields(); if (fs.contains(CHANGE.getName())) { // A Change is always sufficient. return fs; } if (!schema.hasField(PROJECT)) { // Schema is not new enough to have project field. Ensure we have ID // field, and call createOnlyWhenNoteDbDisabled from toChangeData below. if (fs.contains(LEGACY_ID.getName())) { return fs; } else { return Sets.union(fs, ImmutableSet.of(LEGACY_ID.getName())); } } // New enough schema to have project field, so ensure that is requested. if (fs.contains(PROJECT.getName()) && fs.contains(LEGACY_ID.getName())) { return fs; } else { return Sets.union(fs, ImmutableSet.of(LEGACY_ID.getName(), PROJECT.getName())); } } private ChangeData toChangeData(Document doc, Set<String> fields, String idFieldName) { ChangeData cd; // Either change or the ID field was guaranteed to be included in the call // to fields() above. BytesRef cb = doc.getBinaryValue(CHANGE_FIELD); if (cb != null) { cd = changeDataFactory.create(db.get(), ChangeProtoField.CODEC.decode(cb.bytes, cb.offset, cb.length)); } else { Change.Id id = new Change.Id(doc.getField(idFieldName).numericValue().intValue()); IndexableField project = doc.getField(PROJECT.getName()); if (project == null) { // Old schema without project field: we can safely assume NoteDb is // disabled. cd = changeDataFactory.createOnlyWhenNoteDbDisabled(db.get(), id); } else { cd = changeDataFactory.create( db.get(), new Project.NameKey(project.stringValue()), id); } } if (fields.contains(PATCH_SET_FIELD)) { decodePatchSets(doc, cd); } if (fields.contains(APPROVAL_FIELD)) { decodeApprovals(doc, cd); } if (fields.contains(ADDED_FIELD) && fields.contains(DELETED_FIELD)) { decodeChangedLines(doc, cd); } if (fields.contains(MERGEABLE_FIELD)) { decodeMergeable(doc, cd); } if (fields.contains(REVIEWEDBY_FIELD)) { decodeReviewedBy(doc, cd); } if (fields.contains(HASHTAG_FIELD)) { decodeHashtags(doc, cd); } if (fields.contains(STARREDBY_FIELD)) { decodeStarredBy(doc, cd); } if (fields.contains(STAR_FIELD)) { decodeStar(doc, cd); } return cd; } private void decodePatchSets(Document doc, ChangeData cd) { List<PatchSet> patchSets = decodeProtos(doc, PATCH_SET_FIELD, PatchSetProtoField.CODEC); if (!patchSets.isEmpty()) { // Will be an empty list for schemas prior to when this field was stored; // this cannot be valid since a change needs at least one patch set. cd.setPatchSets(patchSets); } } private void decodeApprovals(Document doc, ChangeData cd) { cd.setCurrentApprovals( decodeProtos(doc, APPROVAL_FIELD, PatchSetApprovalProtoField.CODEC)); } private void decodeChangedLines(Document doc, ChangeData cd) { IndexableField added = doc.getField(ADDED_FIELD); IndexableField deleted = doc.getField(DELETED_FIELD); if (added != null && deleted != null) { cd.setChangedLines( added.numericValue().intValue(), deleted.numericValue().intValue()); } } private void decodeMergeable(Document doc, ChangeData cd) { String mergeable = doc.get(MERGEABLE_FIELD); if ("1".equals(mergeable)) { cd.setMergeable(true); } else if ("0".equals(mergeable)) { cd.setMergeable(false); } } private void decodeReviewedBy(Document doc, ChangeData cd) { IndexableField[] reviewedBy = doc.getFields(REVIEWEDBY_FIELD); if (reviewedBy.length > 0) { Set<Account.Id> accounts = Sets.newHashSetWithExpectedSize(reviewedBy.length); for (IndexableField r : reviewedBy) { int id = r.numericValue().intValue(); if (reviewedBy.length == 1 && id == ChangeField.NOT_REVIEWED) { break; } accounts.add(new Account.Id(id)); } cd.setReviewedBy(accounts); } } private void decodeHashtags(Document doc, ChangeData cd) { IndexableField[] hashtag = doc.getFields(HASHTAG_FIELD); Set<String> hashtags = Sets.newHashSetWithExpectedSize(hashtag.length); for (IndexableField r : hashtag) { hashtags.add(r.binaryValue().utf8ToString()); } cd.setHashtags(hashtags); } @Deprecated private void decodeStarredBy(Document doc, ChangeData cd) { IndexableField[] starredBy = doc.getFields(STARREDBY_FIELD); Set<Account.Id> accounts = Sets.newHashSetWithExpectedSize(starredBy.length); for (IndexableField r : starredBy) { accounts.add(new Account.Id(r.numericValue().intValue())); } cd.setStarredBy(accounts); } private void decodeStar(Document doc, ChangeData cd) { IndexableField[] star = doc.getFields(STAR_FIELD); Multimap<Account.Id, String> stars = ArrayListMultimap.create(); for (IndexableField r : star) { StarredChangesUtil.StarField starField = StarredChangesUtil.StarField.parse(r.stringValue()); if (starField != null) { stars.put(starField.accountId(), starField.label()); } } cd.setStars(stars); } private static <T> List<T> decodeProtos(Document doc, String fieldName, ProtobufCodec<T> codec) { BytesRef[] bytesRefs = doc.getBinaryValues(fieldName); if (bytesRefs.length == 0) { return Collections.emptyList(); } List<T> result = new ArrayList<>(bytesRefs.length); for (BytesRef r : bytesRefs) { result.add(codec.decode(r.bytes, r.offset, r.length)); } return result; } }
gerrit-lucene/src/main/java/com/google/gerrit/lucene/LuceneChangeIndex.java
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.lucene; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.gerrit.lucene.AbstractLuceneIndex.sortFieldName; import static com.google.gerrit.lucene.LuceneVersionManager.CHANGES_PREFIX; import static com.google.gerrit.server.git.QueueProvider.QueueType.INTERACTIVE; import static com.google.gerrit.server.index.change.ChangeField.CHANGE; import static com.google.gerrit.server.index.change.ChangeField.LEGACY_ID; import static com.google.gerrit.server.index.change.ChangeField.PROJECT; import static com.google.gerrit.server.index.change.IndexRewriter.CLOSED_STATUSES; import static com.google.gerrit.server.index.change.IndexRewriter.OPEN_STATUSES; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.gerrit.reviewdb.client.Account; import com.google.gerrit.reviewdb.client.Change; import com.google.gerrit.reviewdb.client.PatchSet; import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.reviewdb.server.ReviewDb; import com.google.gerrit.server.StarredChangesUtil; import com.google.gerrit.server.config.GerritServerConfig; import com.google.gerrit.server.config.SitePaths; import com.google.gerrit.server.index.FieldDef.FillArgs; import com.google.gerrit.server.index.IndexExecutor; import com.google.gerrit.server.index.QueryOptions; import com.google.gerrit.server.index.Schema; import com.google.gerrit.server.index.change.ChangeField; import com.google.gerrit.server.index.change.ChangeField.ChangeProtoField; import com.google.gerrit.server.index.change.ChangeField.PatchSetApprovalProtoField; import com.google.gerrit.server.index.change.ChangeField.PatchSetProtoField; import com.google.gerrit.server.index.change.ChangeIndex; import com.google.gerrit.server.index.change.IndexRewriter; import com.google.gerrit.server.query.Predicate; import com.google.gerrit.server.query.QueryParseException; import com.google.gerrit.server.query.change.ChangeData; import com.google.gerrit.server.query.change.ChangeDataSource; import com.google.gwtorm.protobuf.ProtobufCodec; import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.ResultSet; import com.google.inject.Provider; import com.google.inject.assistedinject.Assisted; import com.google.inject.assistedinject.AssistedInject; import org.apache.lucene.document.Document; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexableField; import org.apache.lucene.index.Term; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.SearcherFactory; import org.apache.lucene.search.SearcherManager; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.TopFieldDocs; import org.apache.lucene.store.RAMDirectory; import org.apache.lucene.util.BytesRef; import org.eclipse.jgit.lib.Config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutionException; /** * Secondary index implementation using Apache Lucene. * <p> * Writes are managed using a single {@link IndexWriter} per process, committed * aggressively. Reads use {@link SearcherManager} and periodically refresh, * though there may be some lag between a committed write and it showing up to * other threads' searchers. */ public class LuceneChangeIndex implements ChangeIndex { private static final Logger log = LoggerFactory.getLogger(LuceneChangeIndex.class); public static final String CHANGES_OPEN = "open"; public static final String CHANGES_CLOSED = "closed"; static final String UPDATED_SORT_FIELD = sortFieldName(ChangeField.UPDATED); static final String ID_SORT_FIELD = sortFieldName(ChangeField.LEGACY_ID); private static final String ADDED_FIELD = ChangeField.ADDED.getName(); private static final String APPROVAL_FIELD = ChangeField.APPROVAL.getName(); private static final String CHANGE_FIELD = ChangeField.CHANGE.getName(); private static final String DELETED_FIELD = ChangeField.DELETED.getName(); private static final String MERGEABLE_FIELD = ChangeField.MERGEABLE.getName(); private static final String PATCH_SET_FIELD = ChangeField.PATCH_SET.getName(); private static final String REVIEWEDBY_FIELD = ChangeField.REVIEWEDBY.getName(); private static final String HASHTAG_FIELD = ChangeField.HASHTAG_CASE_AWARE.getName(); private static final String STAR_FIELD = ChangeField.STAR.getName(); @Deprecated private static final String STARREDBY_FIELD = ChangeField.STARREDBY.getName(); static Term idTerm(ChangeData cd) { return QueryBuilder.intTerm(LEGACY_ID.getName(), cd.getId().get()); } static Term idTerm(Change.Id id) { return QueryBuilder.intTerm(LEGACY_ID.getName(), id.get()); } private final FillArgs fillArgs; private final ListeningExecutorService executor; private final Provider<ReviewDb> db; private final ChangeData.Factory changeDataFactory; private final Schema<ChangeData> schema; private final QueryBuilder<ChangeData> queryBuilder; private final ChangeSubIndex openIndex; private final ChangeSubIndex closedIndex; @AssistedInject LuceneChangeIndex( @GerritServerConfig Config cfg, SitePaths sitePaths, @IndexExecutor(INTERACTIVE) ListeningExecutorService executor, Provider<ReviewDb> db, ChangeData.Factory changeDataFactory, FillArgs fillArgs, @Assisted Schema<ChangeData> schema) throws IOException { this.fillArgs = fillArgs; this.executor = executor; this.db = db; this.changeDataFactory = changeDataFactory; this.schema = schema; GerritIndexWriterConfig openConfig = new GerritIndexWriterConfig(cfg, "changes_open"); GerritIndexWriterConfig closedConfig = new GerritIndexWriterConfig(cfg, "changes_closed"); queryBuilder = new QueryBuilder<>(schema, openConfig.getAnalyzer()); SearcherFactory searcherFactory = new SearcherFactory(); if (LuceneIndexModule.isInMemoryTest(cfg)) { openIndex = new ChangeSubIndex(schema, sitePaths, new RAMDirectory(), "ramOpen", openConfig, searcherFactory); closedIndex = new ChangeSubIndex(schema, sitePaths, new RAMDirectory(), "ramClosed", closedConfig, searcherFactory); } else { Path dir = LuceneVersionManager.getDir(sitePaths, CHANGES_PREFIX, schema); openIndex = new ChangeSubIndex(schema, sitePaths, dir.resolve(CHANGES_OPEN), openConfig, searcherFactory); closedIndex = new ChangeSubIndex(schema, sitePaths, dir.resolve(CHANGES_CLOSED), closedConfig, searcherFactory); } } @Override public void close() { List<ListenableFuture<?>> closeFutures = Lists.newArrayListWithCapacity(2); closeFutures.add(executor.submit(new Runnable() { @Override public void run() { openIndex.close(); } })); closeFutures.add(executor.submit(new Runnable() { @Override public void run() { closedIndex.close(); } })); Futures.getUnchecked(Futures.allAsList(closeFutures)); } @Override public Schema<ChangeData> getSchema() { return schema; } @Override public void replace(ChangeData cd) throws IOException { Term id = LuceneChangeIndex.idTerm(cd); // toDocument is essentially static and doesn't depend on the specific // sub-index, so just pick one. Document doc = openIndex.toDocument(cd, fillArgs); try { if (cd.change().getStatus().isOpen()) { Futures.allAsList( closedIndex.delete(id), openIndex.replace(id, doc)).get(); } else { Futures.allAsList( openIndex.delete(id), closedIndex.replace(id, doc)).get(); } } catch (OrmException | ExecutionException | InterruptedException e) { throw new IOException(e); } } @Override public void delete(Change.Id id) throws IOException { Term idTerm = LuceneChangeIndex.idTerm(id); try { Futures.allAsList( openIndex.delete(idTerm), closedIndex.delete(idTerm)).get(); } catch (ExecutionException | InterruptedException e) { throw new IOException(e); } } @Override public void deleteAll() throws IOException { openIndex.deleteAll(); closedIndex.deleteAll(); } @Override public ChangeDataSource getSource(Predicate<ChangeData> p, QueryOptions opts) throws QueryParseException { Set<Change.Status> statuses = IndexRewriter.getPossibleStatus(p); List<ChangeSubIndex> indexes = Lists.newArrayListWithCapacity(2); if (!Sets.intersection(statuses, OPEN_STATUSES).isEmpty()) { indexes.add(openIndex); } if (!Sets.intersection(statuses, CLOSED_STATUSES).isEmpty()) { indexes.add(closedIndex); } return new QuerySource(indexes, queryBuilder.toQuery(p), opts, getSort()); } @Override public void markReady(boolean ready) throws IOException { // Arbitrary done on open index, as ready bit is set // per index and not sub index openIndex.markReady(ready); } private Sort getSort() { return new Sort( new SortField(UPDATED_SORT_FIELD, SortField.Type.LONG, true), new SortField(ID_SORT_FIELD, SortField.Type.LONG, true)); } public ChangeSubIndex getClosedChangesIndex() { return closedIndex; } private class QuerySource implements ChangeDataSource { private final List<ChangeSubIndex> indexes; private final Query query; private final QueryOptions opts; private final Sort sort; private QuerySource(List<ChangeSubIndex> indexes, Query query, QueryOptions opts, Sort sort) { this.indexes = indexes; this.query = checkNotNull(query, "null query from Lucene"); this.opts = opts; this.sort = sort; } @Override public int getCardinality() { return 10; // TODO(dborowitz): estimate from Lucene? } @Override public boolean hasChange() { return false; } @Override public String toString() { return query.toString(); } @Override public ResultSet<ChangeData> read() throws OrmException { IndexSearcher[] searchers = new IndexSearcher[indexes.size()]; try { int realLimit = opts.start() + opts.limit(); TopFieldDocs[] hits = new TopFieldDocs[indexes.size()]; for (int i = 0; i < indexes.size(); i++) { searchers[i] = indexes.get(i).acquire(); hits[i] = searchers[i].search(query, realLimit, sort); } TopDocs docs = TopDocs.merge(sort, realLimit, hits); List<ChangeData> result = Lists.newArrayListWithCapacity(docs.scoreDocs.length); Set<String> fields = fields(opts); String idFieldName = LEGACY_ID.getName(); for (int i = opts.start(); i < docs.scoreDocs.length; i++) { ScoreDoc sd = docs.scoreDocs[i]; Document doc = searchers[sd.shardIndex].doc(sd.doc, fields); result.add(toChangeData(doc, fields, idFieldName)); } final List<ChangeData> r = Collections.unmodifiableList(result); return new ResultSet<ChangeData>() { @Override public Iterator<ChangeData> iterator() { return r.iterator(); } @Override public List<ChangeData> toList() { return r; } @Override public void close() { // Do nothing. } }; } catch (IOException e) { throw new OrmException(e); } finally { for (int i = 0; i < indexes.size(); i++) { if (searchers[i] != null) { try { indexes.get(i).release(searchers[i]); } catch (IOException e) { log.warn("cannot release Lucene searcher", e); } } } } } } private Set<String> fields(QueryOptions opts) { // Ensure we request enough fields to construct a ChangeData. Set<String> fs = opts.fields(); if (fs.contains(CHANGE.getName())) { // A Change is always sufficient. return fs; } if (!schema.hasField(PROJECT)) { // Schema is not new enough to have project field. Ensure we have ID // field, and call createOnlyWhenNoteDbDisabled from toChangeData below. if (fs.contains(LEGACY_ID.getName())) { return fs; } else { return Sets.union(fs, ImmutableSet.of(LEGACY_ID.getName())); } } // New enough schema to have project field, so ensure that is requested. if (fs.contains(PROJECT.getName()) && fs.contains(LEGACY_ID.getName())) { return fs; } else { return Sets.union(fs, ImmutableSet.of(LEGACY_ID.getName(), PROJECT.getName())); } } private ChangeData toChangeData(Document doc, Set<String> fields, String idFieldName) { ChangeData cd; // Either change or the ID field was guaranteed to be included in the call // to fields() above. BytesRef cb = doc.getBinaryValue(CHANGE_FIELD); if (cb != null) { cd = changeDataFactory.create(db.get(), ChangeProtoField.CODEC.decode(cb.bytes, cb.offset, cb.length)); } else { Change.Id id = new Change.Id(doc.getField(idFieldName).numericValue().intValue()); IndexableField project = doc.getField(PROJECT.getName()); if (project == null) { // Old schema without project field: we can safely assume NoteDb is // disabled. cd = changeDataFactory.createOnlyWhenNoteDbDisabled(db.get(), id); } else { cd = changeDataFactory.create( db.get(), new Project.NameKey(project.stringValue()), id); } } if (fields.contains(PATCH_SET_FIELD)) { decodePatchSets(doc, cd); } if (fields.contains(APPROVAL_FIELD)) { decodeApprovals(doc, cd); } if (fields.contains(ADDED_FIELD) && fields.contains(DELETED_FIELD)) { decodeChangedLines(doc, cd); } if (fields.contains(MERGEABLE_FIELD)) { decodeMergeable(doc, cd); } if (fields.contains(REVIEWEDBY_FIELD)) { decodeReviewedBy(doc, cd); } if (fields.contains(HASHTAG_FIELD)) { decodeHashtags(doc, cd); } if (fields.contains(STARREDBY_FIELD)) { decodeStarredBy(doc, cd); } if (fields.contains(STAR_FIELD)) { decodeStar(doc, cd); } return cd; } private void decodePatchSets(Document doc, ChangeData cd) { List<PatchSet> patchSets = decodeProtos(doc, PATCH_SET_FIELD, PatchSetProtoField.CODEC); if (!patchSets.isEmpty()) { // Will be an empty list for schemas prior to when this field was stored; // this cannot be valid since a change needs at least one patch set. cd.setPatchSets(patchSets); } } private void decodeApprovals(Document doc, ChangeData cd) { cd.setCurrentApprovals( decodeProtos(doc, APPROVAL_FIELD, PatchSetApprovalProtoField.CODEC)); } private void decodeChangedLines(Document doc, ChangeData cd) { IndexableField added = doc.getField(ADDED_FIELD); IndexableField deleted = doc.getField(DELETED_FIELD); if (added != null && deleted != null) { cd.setChangedLines( added.numericValue().intValue(), deleted.numericValue().intValue()); } } private void decodeMergeable(Document doc, ChangeData cd) { String mergeable = doc.get(MERGEABLE_FIELD); if ("1".equals(mergeable)) { cd.setMergeable(true); } else if ("0".equals(mergeable)) { cd.setMergeable(false); } } private void decodeReviewedBy(Document doc, ChangeData cd) { IndexableField[] reviewedBy = doc.getFields(REVIEWEDBY_FIELD); if (reviewedBy.length > 0) { Set<Account.Id> accounts = Sets.newHashSetWithExpectedSize(reviewedBy.length); for (IndexableField r : reviewedBy) { int id = r.numericValue().intValue(); if (reviewedBy.length == 1 && id == ChangeField.NOT_REVIEWED) { break; } accounts.add(new Account.Id(id)); } cd.setReviewedBy(accounts); } } private void decodeHashtags(Document doc, ChangeData cd) { IndexableField[] hashtag = doc.getFields(HASHTAG_FIELD); Set<String> hashtags = Sets.newHashSetWithExpectedSize(hashtag.length); for (IndexableField r : hashtag) { hashtags.add(r.binaryValue().utf8ToString()); } cd.setHashtags(hashtags); } @Deprecated private void decodeStarredBy(Document doc, ChangeData cd) { IndexableField[] starredBy = doc.getFields(STARREDBY_FIELD); Set<Account.Id> accounts = Sets.newHashSetWithExpectedSize(starredBy.length); for (IndexableField r : starredBy) { accounts.add(new Account.Id(r.numericValue().intValue())); } cd.setStarredBy(accounts); } private void decodeStar(Document doc, ChangeData cd) { IndexableField[] star = doc.getFields(STAR_FIELD); Multimap<Account.Id, String> stars = ArrayListMultimap.create(); for (IndexableField r : star) { StarredChangesUtil.StarField starField = StarredChangesUtil.StarField.parse(r.stringValue()); if (starField != null) { stars.put(starField.accountId(), starField.label()); } } cd.setStars(stars); } private static <T> List<T> decodeProtos(Document doc, String fieldName, ProtobufCodec<T> codec) { BytesRef[] bytesRefs = doc.getBinaryValues(fieldName); if (bytesRefs.length == 0) { return Collections.emptyList(); } List<T> result = new ArrayList<>(bytesRefs.length); for (BytesRef r : bytesRefs) { result.add(codec.decode(r.bytes, r.offset, r.length)); } return result; } }
Drain executor of index change requests before closing index IndexCollection.stop() closes the index to flush pending index writes at shutdown. Unfortunately some pending index writes can be enqueued in the index executor without the index even being aware of them yet, causing lost writes on exit. Drain the work queue to avoid this. This has always been possible in a gerrit instance with >1 index threads (e.g., with '[index] threads = 2' in gerrit.config). 176cd58bb0bb (Always use a thread pool for interactive indexing, 2016-05-09) made Gerrit use a thread pool with multiple threads for indexing by default, making the problem easier to trigger. Noticed by using ctrl+c to exit gerrit daemon in a development environment. Making the close calls parallel as in a44d8396e72d (Lucene: close sub-indexes in parallel, 2013-06-21) can wait for a followup change. Change-Id: I7bda1305858fe4aa5ea12a4bc68d35f0cdedf225
gerrit-lucene/src/main/java/com/google/gerrit/lucene/LuceneChangeIndex.java
Drain executor of index change requests before closing index
Java
apache-2.0
d482fdb7029d8d5d999cf996ce34668fd3e36c7a
0
abdallahynajar/foursquared,sonyraj/foursquared.eclair,Archenemy-xiatian/foursquared,summerzhao/foursquared,fuzhou0099/foursquared.eclair,aasaandinesh/foursquared,vsvankhede/foursquared.eclair,rihtak/foursquared.eclair,starspace/foursquared.eclair,idmouh/foursquared,xuyunhong/foursquared.eclair,kvnh/foursquared,nluetkemeyer/foursquared,jotish/foursquared,malathicode/foursquared.eclair,ksrpraneeth/foursquared,thtak/foursquared,tyzhaoqi/foursquared,hardikamal/foursquared,kitencx/foursquared,daya-shankar/foursquared,davideuler/foursquared.eclair,thtak/foursquared.eclair,zhmkof/foursquared.eclair,lenkyun/foursquared,bubao/foursquared,haithemhamzaoui/foursquared.eclair,xuyunhong/foursquared,nehalok/foursquared,ckarademir/foursquared,ewugreensignal/foursquared,daya-shankar/foursquared.eclair,shivasrinath/foursquared,abedmaatalla/foursquared.eclair,osiloke/foursquared,Mutai/foursquared,prashantkumar0509/foursquared,hardikamal/foursquared.eclair,azizjonm/foursquared,xzamirx/foursquared.eclair,suman4674/foursquared,Bishwajet/foursquared,solubrew/foursquared,malathicode/foursquared,smakeit/foursquared.eclair,zhmkof/foursquared.eclair,savelees/foursquared.eclair,aasaandinesh/foursquared,artificiallight92/foursquared,jamesmartins/foursquared,ACCTFORGH/foursquared.eclair,smakeit/foursquared,Bishwajet/foursquared.eclair,tyzhaoqi/foursquared,navesdad/foursquared.eclair,nluetkemeyer/foursquared.eclair,fatihcelik/foursquared.eclair,suripaleru/foursquared,karthikkumar12/foursquared,MarginC/foursquared,tamzi/foursquared,martadewi/foursquared,rahul18cool/foursquared,kiruthikak/foursquared.eclair,foobarprime/foursquared,thenewnewbie/foursquared,murat8505/foursquared.eclair,azai91/foursquared,suman4674/foursquared,yusuf-shalahuddin/foursquared.eclair,summerzhao/foursquared.eclair,weizp/foursquared.eclair,ayndev/foursquared,dreamapps786/foursquared,nehalok/foursquared.eclair,manisoni28/foursquared.eclair,cairenjie1985/foursquared,hunanlike/foursquared,vsvankhede/foursquared,fatihcelik/foursquared,Mutai/foursquared,kolawoletech/foursquared.eclair,kiruthikak/foursquared,ckarademir/foursquared.eclair,summerzhao/foursquared.eclair,nextzy/foursquared,rahul18cool/foursquared,malathicode/foursquared.eclair,ragesh91/foursquared,rguindon/raymondeguindon-foursquared,tianyong2/foursquared,sathiamour/foursquared.eclair,manisoni28/foursquared.eclair,RahulRavindren/foursquared.eclair,martinx/martinxus-foursquared,aasaandinesh/foursquared.eclair,kitencx/foursquared,xzamirx/foursquared.eclair,sathiamour/foursquared.eclair,itzmesayooj/foursquared.eclair,santoshmehta82/foursquared,hunanlike/foursquared,azizjonm/foursquared,isaiasmercadom/foursquared,smakeit/foursquared,sandeip-yadav/foursquared.eclair,sibendu/foursquared.eclair,suman4674/foursquared.eclair,sbagadi/foursquared,kiruthikak/foursquared,martinx/martinxus-foursquared,karthikkumar12/foursquared.eclair,xytrams/foursquared,sathiamour/foursquared,sbagadi/foursquared.eclair,abdallahynajar/foursquared,savelees/foursquared.eclair,hejie/foursquared.eclair,Mutai/foursquared.eclair,since2014/foursquared,rahulnagar8/foursquared.eclair,psvijayk/foursquared,mikehowson/foursquared,632840804/foursquared.eclair,yusuf-shalahuddin/foursquared,ewugreensignal/foursquared,PriteshJain/foursquared,harajuko/foursquared,edwinsnao/foursquared,jotish/foursquared.eclair,Zebronaft/foursquared.eclair,nluetkemeyer/foursquared.eclair,sbolisetty/foursquared.eclair,karanVkgp/foursquared.eclair,smallperson/foursquared,Archenemy-xiatian/foursquared.eclair,gtostock/foursquared,suripaleru/foursquared,sakethkaparthi/foursquared,codingz/foursquared.eclair,itzmesayooj/foursquared,appoll/foursquared,savelees/foursquared,martadewi/foursquared,srikanthguduru/foursquared.eclair,abou78180/foursquared,AnthonyCAS/foursquared.eclair,mayankz/foursquared,abdallahynajar/foursquared,murat8505/foursquared.eclair,donka-s27/foursquared,harajuko/foursquared,nextzy/foursquared.eclair,daya-shankar/foursquared,shrikantzarekar/foursquared.eclair,harajuko/foursquared.eclair,manisoni28/foursquared,donka-s27/foursquared.eclair,andrewjsauer/foursquared,zhoujianhanyu/foursquared,votinhaooo/foursquared,rahulnagar8/foursquared,waasilzamri/foursquared,coersum01/foursquared.eclair,ming0627/foursquared,gokultaka/foursquared,nasvil/foursquared.eclair,jamesmartins/foursquared.eclair,wenkeyang/foursquared.eclair,murat8505/foursquared,foobarprime/foursquared,mikehowson/foursquared,bancool/foursquared.eclair,gtostock/foursquared.eclair,smallperson/foursquared.eclair,aasaandinesh/foursquared.eclair,BinodAryal/foursquared.eclair,AnthonyCAS/foursquared.eclair,tianyong2/foursquared.eclair,azai91/foursquared.eclair,navesdad/foursquared,lenkyun/foursquared,tahainfocreator/foursquared.eclair,nara-l/foursquared.eclair,nara-l/foursquared,rahul18cool/foursquared.eclair,coersum01/foursquared,navesdad/foursquared,hardikamal/foursquared,cairenjie1985/foursquared,jotish/foursquared.eclair,pratikjk/foursquared,karthikkumar12/foursquared,artificiallight92/foursquared,lepinay/foursquared.eclair,since2014/foursquared,abdallahynajar/foursquared.eclair,solubrew/foursquared.eclair,zhoujianhanyu/foursquared,RameshBhupathi/foursquared,sovaa/foursquared,ksrpraneeth/foursquared,sonyraj/foursquared.eclair,srikanthguduru/foursquared,suman4674/foursquared,daya-shankar/foursquared,NarikSmouke228/foursquared.eclair,coersum01/foursquared,rihtak/foursquared.eclair,martadewi/foursquared.eclair,abou78180/foursquared,Bishwajet/foursquared.eclair,sandeip-yadav/foursquared,rahul18cool/foursquared,gabtni/foursquared.eclair,sbolisetty/foursquared.eclair,abou78180/foursquared,akhilesh9205/foursquared.eclair,tahainfocreator/foursquared,PriteshJain/foursquared,idmouh/foursquared.eclair,akhilesh9205/foursquared,hardikamal/foursquared,foobarprime/foursquared,nara-l/foursquared,stonyyi/foursquared.eclair,Archenemy-xiatian/foursquared,bancool/foursquared,artificiallight92/foursquared,shivasrinath/foursquared,NarikSmouke228/foursquared,gokultaka/foursquared.eclair,rahulnagar8/foursquared,NarikSmouke228/foursquared,isaiasmercadom/foursquared,stonyyi/foursquared,tyzhaoqi/foursquared,harajuko/foursquared,aasaandinesh/foursquared,lepinay/foursquared,lenkyun/foursquared,tamzi/foursquared,nasvil/foursquared,varunprathap/foursquared.eclair,osiloke/foursquared.eclair,andrewjsauer/foursquared,stonyyi/foursquared,pratikjk/foursquared.eclair,sbolisetty/foursquared,ramaraokotu/foursquared,sibendu/foursquared,sbagadi/foursquared.eclair,summerzhao/foursquared,itzmesayooj/foursquared,dreamapps786/foursquared,sibendu/foursquared.eclair,cairenjie1985/foursquared.eclair,nasvil/foursquared,martadewi/foursquared,azai91/foursquared,smakeit/foursquared.eclair,BinodAryal/foursquared.eclair,karanVkgp/foursquared,xytrams/foursquared.eclair,shivasrinath/foursquared.eclair,davideuler/foursquared,osiloke/foursquared,omondiy/foursquared,cairenjie1985/foursquared.eclair,BinodAryal/foursquared,prashantkumar0509/foursquared.eclair,edwinsnao/foursquared.eclair,psvijayk/foursquared.eclair,codingz/foursquared,dhysf/foursquared.eclair,itzmesayooj/foursquared,smallperson/foursquared.eclair,appoll/foursquared,ksrpraneeth/foursquared.eclair,mypapit/foursquared,EphraimKigamba/foursquared.eclair,rihtak/foursquared,gtostock/foursquared,ramaraokotu/foursquared.eclair,Zebronaft/foursquared.eclair,abedmaatalla/foursquared.eclair,wenkeyang/foursquared,gtostock/foursquared.eclair,kiruthikak/foursquared.eclair,edwinsnao/foursquared,votinhaooo/foursquared,kolawoletech/foursquared,suripaleru/foursquared,bancool/foursquared.eclair,dhysf/foursquared.eclair,since2014/foursquared,ksrpraneeth/foursquared,NarikSmouke228/foursquared.eclair,haithemhamzaoui/foursquared,ayndev/foursquared,solubrew/foursquared,karanVkgp/foursquared,tamzi/foursquared.eclair,lxz2014/foursquared,paulodiogo/foursquared.eclair,sonyraj/foursquared,vsvankhede/foursquared,Bishwajet/foursquared,kolawoletech/foursquared.eclair,EphraimKigamba/foursquared.eclair,cairenjie1985/foursquared,bubao/foursquared,Archenemy-xiatian/foursquared.eclair,thenewnewbie/foursquared.eclair,tahainfocreator/foursquared,savelees/foursquared,murat8505/foursquared,srikanthguduru/foursquared,abou78180/foursquared.eclair,nasvil/foursquared,sovaa/foursquared.eclair,rguindon/raymondeguindon-foursquared,akhilesh9205/foursquared,Archenemy-xiatian/foursquared,izBasit/foursquared,hunanlike/foursquared.eclair,since2014/foursquared.eclair,sovaa/foursquared,abedmaatalla/foursquared,4DvAnCeBoY/foursquared.eclair,davideuler/foursquared.eclair,tahainfocreator/foursquared.eclair,ekospinach/foursquared.eclair,idmouh/foursquared.eclair,ragesh91/foursquared.eclair,dreamapps786/foursquared.eclair,xytrams/foursquared.eclair,RameshBhupathi/foursquared,kiruthikak/foursquared,shrikantzarekar/foursquared.eclair,santoshmehta82/foursquared,manisoni28/foursquared,yusuf-shalahuddin/foursquared,sevenOneHero/foursquared.eclair,weizp/foursquared,abedmaatalla/foursquared,lepinay/foursquared,starspace/foursquared,prashantkumar0509/foursquared,omondiy/foursquared,nextzy/foursquared.eclair,psvijayk/foursquared.eclair,daya-shankar/foursquared.eclair,Bishwajet/foursquared,tyzhaoqi/foursquared.eclair,karthikkumar12/foursquared.eclair,sathiamour/foursquared,santoshmehta82/foursquared.eclair,hejie/foursquared.eclair,sbagadi/foursquared,prashantkumar0509/foursquared.eclair,4DvAnCeBoY/foursquared.eclair,lxz2014/foursquared.eclair,osiloke/foursquared,4DvAnCeBoY/foursquared,waasilzamri/foursquared,ksrpraneeth/foursquared.eclair,ACCTFORGH/foursquared,srikanthguduru/foursquared,kolawoletech/foursquared,ckarademir/foursquared.eclair,idmouh/foursquared,dreamapps786/foursquared.eclair,nehalok/foursquared.eclair,andrewjsauer/foursquared,donka-s27/foursquared,BinodAryal/foursquared,azai91/foursquared.eclair,solubrew/foursquared.eclair,itrobertson/foursquared,coersum01/foursquared.eclair,tyzhaoqi/foursquared.eclair,lxz2014/foursquared,starspace/foursquared,MarginC/foursquared,sbagadi/foursquared,hunanlike/foursquared.eclair,RameshBhupathi/foursquared.eclair,navesdad/foursquared.eclair,weizp/foursquared,jamesmartins/foursquared.eclair,suripaleru/foursquared.eclair,sakethkaparthi/foursquared,edwinsnao/foursquared,rihtak/foursquared,votinhaooo/foursquared.eclair,izBasit/foursquared.eclair,jamesmartins/foursquared,sakethkaparthi/foursquared,bubao/foursquared.eclair,rguindon/raymondeguindon-foursquared,ayndev/foursquared,hunanlike/foursquared,Zebronaft/foursquared,nextzy/foursquared,ewugreensignal/foursquared.eclair,tianyong2/foursquared,donka-s27/foursquared,mypapit/foursquared,dhysf/foursquared,NarikSmouke228/foursquared,navesdad/foursquared,varunprathap/foursquared,vsvankhede/foursquared.eclair,RahulRavindren/foursquared,mansourifatimaezzahraa/foursquared,kvnh/foursquared,ekospinach/foursquared.eclair,haithemhamzaoui/foursquared.eclair,forevervhuo/foursquared.eclair,abou78180/foursquared.eclair,martadewi/foursquared.eclair,thenewnewbie/foursquared,murat8505/foursquared,hejie/foursquared,rahulnagar8/foursquared,mikehowson/foursquared.eclair,karanVkgp/foursquared,CoderJackyHuang/foursquared.eclair,ckarademir/foursquared,smallperson/foursquared,RahulRavindren/foursquared,gokultaka/foursquared,karthikkumar12/foursquared,ramaraokotu/foursquared.eclair,mansourifatimaezzahraa/foursquared.eclair,ragesh91/foursquared,suman4674/foursquared.eclair,thenewnewbie/foursquared,mansourifatimaezzahraa/foursquared,ekospinach/foursquared,lxz2014/foursquared.eclair,RahulRavindren/foursquared.eclair,abedmaatalla/foursquared,xuyunhong/foursquared,fatihcelik/foursquared.eclair,ramaraokotu/foursquared,sonyraj/foursquared,ramaraokotu/foursquared,itrobertson/foursquared,xuyunhong/foursquared,weizp/foursquared,kvnh/foursquared.eclair,bancool/foursquared,mayankz/foursquared,nara-l/foursquared.eclair,gabtni/foursquared,thtak/foursquared,RameshBhupathi/foursquared.eclair,osiloke/foursquared.eclair,donka-s27/foursquared.eclair,izBasit/foursquared.eclair,manisoni28/foursquared,votinhaooo/foursquared,harajuko/foursquared.eclair,azai91/foursquared,EphraimKigamba/foursquared,solubrew/foursquared,martinx/martinxus-foursquared,PriteshJain/foursquared.eclair,sathiamour/foursquared,abdallahynajar/foursquared.eclair,wenkeyang/foursquared.eclair,summerzhao/foursquared,weizp/foursquared.eclair,nluetkemeyer/foursquared,mikehowson/foursquared,haithemhamzaoui/foursquared,hejie/foursquared,gabtni/foursquared,kitencx/foursquared,pratikjk/foursquared.eclair,akhilesh9205/foursquared,varunprathap/foursquared,davideuler/foursquared,isaiasmercadom/foursquared.eclair,sbolisetty/foursquared,jamesmartins/foursquared,fatihcelik/foursquared,since2014/foursquared.eclair,santoshmehta82/foursquared.eclair,idmouh/foursquared,xytrams/foursquared,wenkeyang/foursquared,paulodiogo/foursquared.eclair,shrikantzarekar/foursquared,codingz/foursquared.eclair,omondiy/foursquared.eclair,xytrams/foursquared,waasilzamri/foursquared.eclair,jiveshwar/foursquared.eclair,akhilesh9205/foursquared.eclair,stonyyi/foursquared.eclair,kvnh/foursquared.eclair,mansourifatimaezzahraa/foursquared,tamzi/foursquared,sandeip-yadav/foursquared.eclair,appoll/foursquared,sandeip-yadav/foursquared,kolawoletech/foursquared,EphraimKigamba/foursquared,rihtak/foursquared,forevervhuo/foursquared.eclair,zhoujianhanyu/foursquared.eclair,nasvil/foursquared.eclair,savelees/foursquared,malathicode/foursquared,gokultaka/foursquared.eclair,jotish/foursquared,srikanthguduru/foursquared.eclair,yusuf-shalahuddin/foursquared,isaiasmercadom/foursquared.eclair,mansourifatimaezzahraa/foursquared.eclair,kvnh/foursquared,lepinay/foursquared.eclair,nehalok/foursquared,ming0627/foursquared,shivasrinath/foursquared.eclair,waasilzamri/foursquared,gabtni/foursquared,suripaleru/foursquared.eclair,varunprathap/foursquared,jotish/foursquared,yusuf-shalahuddin/foursquared.eclair,fuzhou0099/foursquared.eclair,hejie/foursquared,pratikjk/foursquared,PriteshJain/foursquared,ewugreensignal/foursquared.eclair,haithemhamzaoui/foursquared,jiveshwar/foursquared.eclair,RameshBhupathi/foursquared,lepinay/foursquared,Zebronaft/foursquared,nehalok/foursquared,Mutai/foursquared,nara-l/foursquared,nluetkemeyer/foursquared,izBasit/foursquared,sovaa/foursquared,rahul18cool/foursquared.eclair,ACCTFORGH/foursquared.eclair,sandeip-yadav/foursquared,tahainfocreator/foursquared,bancool/foursquared,632840804/foursquared.eclair,tianyong2/foursquared,ckarademir/foursquared,smallperson/foursquared,bubao/foursquared,omondiy/foursquared,sevenOneHero/foursquared.eclair,itzmesayooj/foursquared.eclair,codingz/foursquared,starspace/foursquared,Zebronaft/foursquared,prashantkumar0509/foursquared,edwinsnao/foursquared.eclair,mayankz/foursquared,sbolisetty/foursquared,dreamapps786/foursquared,mikehowson/foursquared.eclair,ming0627/foursquared.eclair,ming0627/foursquared,zhoujianhanyu/foursquared,CoderJackyHuang/foursquared.eclair,santoshmehta82/foursquared,lxz2014/foursquared,foobarprime/foursquared.eclair,hardikamal/foursquared.eclair,artificiallight92/foursquared.eclair,4DvAnCeBoY/foursquared,BinodAryal/foursquared,foobarprime/foursquared.eclair,PriteshJain/foursquared.eclair,codingz/foursquared,rahulnagar8/foursquared.eclair,davideuler/foursquared,gtostock/foursquared,varunprathap/foursquared.eclair,ayndev/foursquared.eclair,ekospinach/foursquared,mypapit/foursquared,thtak/foursquared,thenewnewbie/foursquared.eclair,shivasrinath/foursquared,artificiallight92/foursquared.eclair,itrobertson/foursquared,votinhaooo/foursquared.eclair,tamzi/foursquared.eclair,sibendu/foursquared,sevenOneHero/foursquared.eclair,shrikantzarekar/foursquared,psvijayk/foursquared,dhysf/foursquared,sovaa/foursquared.eclair,psvijayk/foursquared,vsvankhede/foursquared,ragesh91/foursquared,starspace/foursquared.eclair,ayndev/foursquared.eclair,malathicode/foursquared,bubao/foursquared.eclair,coersum01/foursquared,sonyraj/foursquared,tianyong2/foursquared.eclair,ACCTFORGH/foursquared,xuyunhong/foursquared.eclair,pratikjk/foursquared,RahulRavindren/foursquared,waasilzamri/foursquared.eclair,shrikantzarekar/foursquared,smakeit/foursquared,zhoujianhanyu/foursquared.eclair,thtak/foursquared.eclair,ewugreensignal/foursquared,ACCTFORGH/foursquared,omondiy/foursquared.eclair,nextzy/foursquared,sibendu/foursquared,Mutai/foursquared.eclair,azizjonm/foursquared,wenkeyang/foursquared,fatihcelik/foursquared,ming0627/foursquared.eclair,gokultaka/foursquared,ragesh91/foursquared.eclair,izBasit/foursquared,stonyyi/foursquared,isaiasmercadom/foursquared,ekospinach/foursquared,4DvAnCeBoY/foursquared,gabtni/foursquared.eclair,karanVkgp/foursquared.eclair,EphraimKigamba/foursquared,dhysf/foursquared,MarginC/foursquared
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.types.City; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.Foursquared.LocationListener; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.Window; import android.widget.EditText; import android.widget.Toast; import java.io.IOException; /** * @author Joe LaPenna ([email protected]) */ public class AddVenueActivity extends Activity { private static final String TAG = "AddVenueActivity"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private static final int MENU_SUBMIT = 1; private LocationListener mLocationListener; private LocationManager mLocationManager; FieldsHolder mFieldsHolder = new FieldsHolder(); private EditText mNameEditText; private EditText mCityEditText; private EditText mAddressEditText; private EditText mCrossstreetEditText; private EditText mStateEditText; private EditText mZipEditText; private EditText mPhoneEditText; private MenuItem mMenuSubmit; private BroadcastReceiver mLoggedInReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override public void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); super.onCreate(savedInstanceState); setContentView(R.layout.add_venue_activity); registerReceiver(mLoggedInReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); mLocationListener = ((Foursquared)getApplication()).getLocationListener(); mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); mNameEditText = (EditText)findViewById(R.id.nameEditText); mCityEditText = (EditText)findViewById(R.id.cityEditText); mAddressEditText = (EditText)findViewById(R.id.addressEditText); mCrossstreetEditText = (EditText)findViewById(R.id.crossstreetEditText); mStateEditText = (EditText)findViewById(R.id.stateEditText); mZipEditText = (EditText)findViewById(R.id.zipEditText); mPhoneEditText = (EditText)findViewById(R.id.phoneEditText); if (getLastNonConfigurationInstance() != null) { setFields((FieldsHolder)getLastNonConfigurationInstance()); } else { new AddressLookupTask().execute(); } } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedInReceiver); } @Override public void onStart() { super.onStart(); // We should probably dynamically connect to any location provider we can find and not just // the gps/network providers. mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LocationListener.LOCATION_UPDATE_MIN_TIME, LocationListener.LOCATION_UPDATE_MIN_DISTANCE, mLocationListener); mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LocationListener.LOCATION_UPDATE_MIN_TIME, LocationListener.LOCATION_UPDATE_MIN_DISTANCE, mLocationListener); } @Override public void onStop() { super.onStop(); mLocationManager.removeUpdates(mLocationListener); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); mMenuSubmit = menu.add(Menu.NONE, MENU_SUBMIT, Menu.NONE, R.string.add_venue_label) // .setIcon(android.R.drawable.ic_menu_add).setEnabled(false); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_SUBMIT: new AddVenueTask().execute(); return true; } return false; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); mMenuSubmit.setEnabled(mFieldsHolder.foursquareCity != null); return true; } @Override public Object onRetainNonConfigurationInstance() { return mFieldsHolder; } private void setFields(FieldsHolder fields) { mFieldsHolder = fields; mCityEditText.setText(fields.foursquareCity.getName()); if (fields.geocodedAddress != null) { String address = fields.geocodedAddress.getAddressLine(0); if (address != null) { mAddressEditText.setText(address); } String zip = fields.geocodedAddress.getPostalCode(); if (zip != null) { mZipEditText.setText(zip); } String state = fields.geocodedAddress.getAdminArea(); if (state != null) { mStateEditText.setText(state); } String phone = fields.geocodedAddress.getPhone(); if (phone != null) { mPhoneEditText.setText(phone); } } } class AddVenueTask extends AsyncTask<Void, Void, Venue> { @Override protected void onPreExecute() { setProgressBarIndeterminateVisibility(true); } @Override protected Venue doInBackground(Void... params) { // name, address, crossstreet, city, state, zip, cityid, phone try { return Foursquared.getFoursquare().addVenue( // mNameEditText.getText().toString(), // mAddressEditText.getText().toString(), // mCrossstreetEditText.getText().toString(), // mCityEditText.getText().toString(), // mStateEditText.getText().toString(), // mZipEditText.getText().toString(), // mFieldsHolder.foursquareCity.getId(), // mPhoneEditText.getText().toString()); } catch (FoursquareException e) { // TODO Auto-generated catch block if (DEBUG) Log.d(TAG, "FoursquareException", e); } catch (IOException e) { // TODO Auto-generated catch block if (DEBUG) Log.d(TAG, "IOException", e); } return null; } @Override protected void onPostExecute(Venue venue) { setProgressBarIndeterminateVisibility(false); if (venue == null) { Toast.makeText(AddVenueActivity.this, "Unable to add venue!", Toast.LENGTH_LONG) .show(); } else { Intent intent = new Intent(AddVenueActivity.this, VenueActivity.class); intent.putExtra(VenueActivity.EXTRA_VENUE, venue.getId()); startActivity(intent); finish(); } } @Override protected void onCancelled() { setProgressBarIndeterminateVisibility(false); } } class AddressLookupTask extends AsyncTask<Void, Void, FieldsHolder> { @Override protected void onPreExecute() { setProgressBarIndeterminateVisibility(true); } @Override protected FieldsHolder doInBackground(Void... params) { FieldsHolder fieldsHolder = new FieldsHolder(); Location location = mLocationListener.getLastKnownLocation(); try { if (DEBUG) Log.d(TAG, location.toString()); fieldsHolder.foursquareCity = Foursquared.getFoursquare().checkCity( String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude())); Geocoder geocoder = new Geocoder(AddVenueActivity.this); fieldsHolder.geocodedAddress = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1).get(0); } catch (FoursquareException e) { // TODO Auto-generated catch block if (DEBUG) Log.d(TAG, "FoursquareException", e); } catch (IOException e) { // TODO Auto-generated catch block if (DEBUG) Log.d(TAG, "IOException", e); } return fieldsHolder; } @Override protected void onPostExecute(FieldsHolder fields) { setProgressBarIndeterminateVisibility(false); try { if (fields == null) { Toast.makeText(AddVenueActivity.this, "Unable to lookup venue city. Try again later.", Toast.LENGTH_LONG) .show(); finish(); } else { setFields(fields); } } finally { setProgressBarIndeterminateVisibility(false); } } @Override protected void onCancelled() { setProgressBarIndeterminateVisibility(false); } } private static class FieldsHolder { City foursquareCity = null; Address geocodedAddress = null; } }
main/src/com/joelapenna/foursquared/AddVenueActivity.java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.types.City; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.Foursquared.LocationListener; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.Window; import android.widget.EditText; import android.widget.Toast; import java.io.IOException; /** * @author Joe LaPenna ([email protected]) */ public class AddVenueActivity extends Activity { private static final String TAG = "AddVenueActivity"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private static final int MENU_SUBMIT = 1; private LocationListener mLocationListener; private LocationManager mLocationManager; FieldsHolder mFieldsHolder = new FieldsHolder(); private EditText mNameEditText; private EditText mCityEditText; private EditText mAddressEditText; private EditText mCrossstreetEditText; private EditText mStateEditText; private EditText mZipEditText; private EditText mPhoneEditText; private MenuItem mMenuSubmit; private BroadcastReceiver mLoggedInReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override public void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); super.onCreate(savedInstanceState); setContentView(R.layout.add_venue_activity); mLocationListener = ((Foursquared)getApplication()).getLocationListener(); mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); mNameEditText = (EditText)findViewById(R.id.nameEditText); mCityEditText = (EditText)findViewById(R.id.cityEditText); mAddressEditText = (EditText)findViewById(R.id.addressEditText); mCrossstreetEditText = (EditText)findViewById(R.id.crossstreetEditText); mStateEditText = (EditText)findViewById(R.id.stateEditText); mZipEditText = (EditText)findViewById(R.id.zipEditText); mPhoneEditText = (EditText)findViewById(R.id.phoneEditText); if (getLastNonConfigurationInstance() != null) { setFields((FieldsHolder)getLastNonConfigurationInstance()); } else { new AddressLookupTask().execute(); } } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedInReceiver); } @Override public void onStart() { super.onStart(); // We should probably dynamically connect to any location provider we can find and not just // the gps/network providers. mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LocationListener.LOCATION_UPDATE_MIN_TIME, LocationListener.LOCATION_UPDATE_MIN_DISTANCE, mLocationListener); mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LocationListener.LOCATION_UPDATE_MIN_TIME, LocationListener.LOCATION_UPDATE_MIN_DISTANCE, mLocationListener); } @Override public void onStop() { super.onStop(); mLocationManager.removeUpdates(mLocationListener); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); mMenuSubmit = menu.add(Menu.NONE, MENU_SUBMIT, Menu.NONE, R.string.add_venue_label) // .setIcon(android.R.drawable.ic_menu_add).setEnabled(false); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_SUBMIT: new AddVenueTask().execute(); return true; } return false; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); mMenuSubmit.setEnabled(mFieldsHolder.foursquareCity != null); return true; } @Override public Object onRetainNonConfigurationInstance() { return mFieldsHolder; } private void setFields(FieldsHolder fields) { mFieldsHolder = fields; mCityEditText.setText(fields.foursquareCity.getName()); if (fields.geocodedAddress != null) { String address = fields.geocodedAddress.getAddressLine(0); if (address != null) { mAddressEditText.setText(address); } String zip = fields.geocodedAddress.getPostalCode(); if (zip != null) { mZipEditText.setText(zip); } String state = fields.geocodedAddress.getAdminArea(); if (state != null) { mStateEditText.setText(state); } String phone = fields.geocodedAddress.getPhone(); if (phone != null) { mPhoneEditText.setText(phone); } } } class AddVenueTask extends AsyncTask<Void, Void, Venue> { @Override protected void onPreExecute() { setProgressBarIndeterminateVisibility(true); } @Override protected Venue doInBackground(Void... params) { // name, address, crossstreet, city, state, zip, cityid, phone try { return Foursquared.getFoursquare().addVenue( // mNameEditText.getText().toString(), // mAddressEditText.getText().toString(), // mCrossstreetEditText.getText().toString(), // mCityEditText.getText().toString(), // mStateEditText.getText().toString(), // mZipEditText.getText().toString(), // mFieldsHolder.foursquareCity.getId(), // mPhoneEditText.getText().toString()); } catch (FoursquareException e) { // TODO Auto-generated catch block if (DEBUG) Log.d(TAG, "FoursquareException", e); } catch (IOException e) { // TODO Auto-generated catch block if (DEBUG) Log.d(TAG, "IOException", e); } return null; } @Override protected void onPostExecute(Venue venue) { setProgressBarIndeterminateVisibility(false); if (venue == null) { Toast.makeText(AddVenueActivity.this, "Unable to add venue!", Toast.LENGTH_LONG) .show(); } else { Intent intent = new Intent(AddVenueActivity.this, VenueActivity.class); intent.putExtra(VenueActivity.EXTRA_VENUE, venue.getId()); startActivity(intent); finish(); } } @Override protected void onCancelled() { setProgressBarIndeterminateVisibility(false); } } class AddressLookupTask extends AsyncTask<Void, Void, FieldsHolder> { @Override protected void onPreExecute() { setProgressBarIndeterminateVisibility(true); } @Override protected FieldsHolder doInBackground(Void... params) { FieldsHolder fieldsHolder = new FieldsHolder(); Location location = mLocationListener.getLastKnownLocation(); try { if (DEBUG) Log.d(TAG, location.toString()); fieldsHolder.foursquareCity = Foursquared.getFoursquare().checkCity( String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude())); Geocoder geocoder = new Geocoder(AddVenueActivity.this); fieldsHolder.geocodedAddress = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1).get(0); } catch (FoursquareException e) { // TODO Auto-generated catch block if (DEBUG) Log.d(TAG, "FoursquareException", e); } catch (IOException e) { // TODO Auto-generated catch block if (DEBUG) Log.d(TAG, "IOException", e); } return fieldsHolder; } @Override protected void onPostExecute(FieldsHolder fields) { setProgressBarIndeterminateVisibility(false); try { if (fields == null) { Toast.makeText(AddVenueActivity.this, "Unable to lookup venue city. Try again later.", Toast.LENGTH_LONG) .show(); finish(); } else { setFields(fields); } } finally { setProgressBarIndeterminateVisibility(false); } } @Override protected void onCancelled() { setProgressBarIndeterminateVisibility(false); } } private static class FieldsHolder { City foursquareCity = null; Address geocodedAddress = null; } }
Register the log out receiver on AddVenueActivity.
main/src/com/joelapenna/foursquared/AddVenueActivity.java
Register the log out receiver on AddVenueActivity.
Java
apache-2.0
86d2e2c64a541b18183a26d17131168ee0500c92
0
filestack/filestack-java,filestack/filestack-java
package com.filestack; import com.filestack.errors.InternalException; import com.filestack.errors.InvalidParameterException; import com.filestack.errors.PolicySignatureException; import com.filestack.errors.ResourceNotFoundException; import com.filestack.errors.ValidationException; import com.filestack.transforms.ImageTransform; import com.filestack.util.FsService; import com.filestack.util.Util; import io.reactivex.Completable; import io.reactivex.Single; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import java.io.File; import java.io.IOException; import java.net.URLConnection; import java.util.concurrent.Callable; import okhttp3.MediaType; import okhttp3.RequestBody; import okhttp3.ResponseBody; import okio.BufferedSink; import okio.BufferedSource; import okio.Okio; import retrofit2.Response; /** References and performs operations on an individual file. */ public class FileLink { private String apiKey; private String handle; private Security security; private FsService fsService; /** * Constructs an instance without security. * * @see #FileLink(String, String, Security) */ public FileLink(String apiKey, String handle) { this(apiKey, handle, null); } /** * Constructs an instance with security. * * @param apiKey account key from the dev portal * @param handle id for a file, first path segment in dev portal urls * @param security needs required permissions for your intended actions */ public FileLink(String apiKey, String handle, Security security) { this.apiKey = apiKey; this.handle = handle; this.security = security; this.fsService = new FsService(); } FileLink() {} /** * Builds new {@link FilestackClient}. */ public static class Builder { private FileLink building = new FileLink(); public Builder apiKey(String apiKey) { building.apiKey = apiKey; return this; } public Builder handle(String handle) { building.handle = handle; return this; } public Builder security(Security security) { building.security = security; return this; } public Builder service(FsService service) { building.fsService = service; return this; } public FileLink build() { return building; } } /** * Returns the content of a file. * * @return byte[] of file content * @throws IOException if request fails because of network or other IO issue * @throws PolicySignatureException if policy and/or signature are invalid or inadequate * @throws ResourceNotFoundException if handle isn't found * @throws InvalidParameterException if handle is malformed * @throws InternalException if unexpected error occurs */ public byte[] getContent() throws IOException, PolicySignatureException, ResourceNotFoundException, InvalidParameterException, InternalException { String policy = security != null ? security.getPolicy() : null; String signature = security != null ? security.getSignature() : null; Response<ResponseBody> response = fsService.get(this.handle, policy, signature).execute(); Util.checkResponseAndThrow(response); ResponseBody body = response.body(); if (body == null) { throw new IOException(); } return body.bytes(); } /** * Saves the file using the name it was uploaded with. * * @see #download(String, String) */ public File download(String directory) throws ValidationException, IOException, PolicySignatureException, ResourceNotFoundException, InvalidParameterException, InternalException { return download(directory, null); } /** * Saves the file overriding the name it was uploaded with. * * @param directory location to save the file in * @param filename local name for the file * @throws ValidationException if the path (directory/filename) isn't writable * @throws IOException if request fails because of network or other IO issue * @throws PolicySignatureException if policy and/or signature are invalid or inadequate * @throws ResourceNotFoundException if handle isn't found * @throws InvalidParameterException if handle is malformed * @throws InternalException if unexpected error occurs */ public File download(String directory, String filename) throws ValidationException, IOException, PolicySignatureException, ResourceNotFoundException, InvalidParameterException, InternalException { String policy = security != null ? security.getPolicy() : null; String signature = security != null ? security.getSignature() : null; Response<ResponseBody> response = fsService.get(this.handle, policy, signature).execute(); Util.checkResponseAndThrow(response); if (filename == null) { filename = response.headers().get("x-file-name"); } File file = Util.createWriteFile(directory + "/" + filename); ResponseBody body = response.body(); if (body == null) { throw new IOException(); } BufferedSource source = body.source(); BufferedSink sink = Okio.buffer(Okio.sink(file)); sink.writeAll(source); sink.close(); return file; } /** * Replace the content of an existing file handle. Requires security to be set. * Does not update the filename or MIME type. * * @param pathname path to the file, can be local or absolute * @throws ValidationException if security isn't set or the pathname is invalid * @throws IOException if request fails because of network or other IO issue * @throws PolicySignatureException if policy and/or signature are invalid or inadequate * @throws ResourceNotFoundException if handle isn't found * @throws InvalidParameterException if handle is malformed * @throws InternalException if unexpected error occurs */ public void overwrite(String pathname) throws ValidationException, IOException, PolicySignatureException, ResourceNotFoundException, InvalidParameterException, InternalException { if (security == null) { throw new ValidationException("Security must be set in order to overwrite"); } File file = Util.createReadFile(pathname); String mimeType = URLConnection.guessContentTypeFromName(file.getName()); RequestBody body = RequestBody.create(MediaType.parse(mimeType), file); String policy = security.getPolicy(); String signature = security.getSignature(); Response response = fsService.overwrite(handle, policy, signature, body).execute(); Util.checkResponseAndThrow(response); } /** * Deletes a file handle. Requires security to be set. * * @throws ValidationException if security isn't set * @throws IOException if request fails because of network or other IO issue * @throws PolicySignatureException if policy and/or signature are invalid or inadequate * @throws ResourceNotFoundException if handle isn't found * @throws InvalidParameterException if handle is malformed * @throws InternalException if unexpected error occurs */ public void delete() throws ValidationException, IOException, PolicySignatureException, ResourceNotFoundException, InvalidParameterException, InternalException { if (security == null) { throw new ValidationException("Security must be set in order to delete"); } String policy = security.getPolicy(); String signature = security.getSignature(); Response response = fsService.delete(handle, apiKey, policy, signature).execute(); Util.checkResponseAndThrow(response); } // Async method wrappers /** * Asynchronously returns the content of a file. * * @see #getContent() */ public Single<byte[]> getContentAsync() { return Single.fromCallable(new Callable<byte[]>() { @Override public byte[] call() throws Exception { return getContent(); } }) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.single()); } /** * Asynchronously saves the file using the name it was uploaded with. * * @see #download(String, String) */ public Single<File> downloadAsync(final String directory) { return downloadAsync(directory, null); } /** * Asynchronously saves the file overriding the name it was uploaded with. * * @see #download(String, String) */ public Single<File> downloadAsync(final String directory, final String filename) { return Single.fromCallable(new Callable<File>() { @Override public File call() throws Exception { return download(directory, filename); } }) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.single()); } /** * Asynchronously replace the content of an existing file handle. Requires security to be set. * Does not update the filename or MIME type. * * @see #overwrite(String) */ public Completable overwriteAsync(final String pathname) { return Completable.fromAction(new Action() { @Override public void run() throws Exception { overwrite(pathname); } }) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.single()); } /** * Asynchronously deletes a file handle. Requires security to be set. * * @see #delete() */ public Completable deleteAsync() { return Completable.fromAction(new Action() { @Override public void run() throws Exception { delete(); } }) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.single()); } /** * Creates an {@link ImageTransform} object for this file. * A transformation call isn't made directly by this method. * * @return {@link ImageTransform ImageTransform} instance configured for this file */ public ImageTransform imageTransform() { return new ImageTransform(this); } public String getHandle() { return handle; } public Security getSecurity() { return security; } public FsService getFsService() { return fsService; } }
src/main/java/com/filestack/FileLink.java
package com.filestack; import com.filestack.errors.InternalException; import com.filestack.errors.InvalidParameterException; import com.filestack.errors.PolicySignatureException; import com.filestack.errors.ResourceNotFoundException; import com.filestack.errors.ValidationException; import com.filestack.transforms.ImageTransform; import com.filestack.util.FsApiService; import com.filestack.util.FsCdnService; import com.filestack.util.Networking; import com.filestack.util.Util; import io.reactivex.Completable; import io.reactivex.Single; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import java.io.File; import java.io.IOException; import java.net.URLConnection; import java.util.concurrent.Callable; import okhttp3.MediaType; import okhttp3.RequestBody; import okhttp3.ResponseBody; import okio.BufferedSink; import okio.BufferedSource; import okio.Okio; import retrofit2.Response; /** References and performs operations on an individual file. */ public class FileLink { private String apiKey; private String handle; private Security security; private FsApiService fsApiService; private FsCdnService fsCdnService; /** * Constructs an instance without security. * * @see #FileLink(String, String, Security) */ public FileLink(String apiKey, String handle) { this(apiKey, handle, null); } /** * Constructs an instance with security. * * @param apiKey account key from the dev portal * @param handle id for a file, first path segment in dev portal urls * @param security needs required permissions for your intended actions */ public FileLink(String apiKey, String handle, Security security) { this.apiKey = apiKey; this.handle = handle; this.security = security; this.fsApiService = Networking.getFsApiService(); this.fsCdnService = Networking.getFsCdnService(); } /** * Returns the content of a file. * * @return byte[] of file content * @throws IOException if request fails because of network or other IO issue * @throws PolicySignatureException if policy and/or signature are invalid or inadequate * @throws ResourceNotFoundException if handle isn't found * @throws InvalidParameterException if handle is malformed * @throws InternalException if unexpected error occurs */ public byte[] getContent() throws IOException, PolicySignatureException, ResourceNotFoundException, InvalidParameterException, InternalException { String policy = security != null ? security.getPolicy() : null; String signature = security != null ? security.getSignature() : null; Response<ResponseBody> response = fsCdnService.get(this.handle, policy, signature).execute(); Util.checkResponseAndThrow(response); ResponseBody body = response.body(); if (body == null) { throw new IOException(); } return body.bytes(); } /** * Saves the file using the name it was uploaded with. * * @see #download(String, String) */ public File download(String directory) throws ValidationException, IOException, PolicySignatureException, ResourceNotFoundException, InvalidParameterException, InternalException { return download(directory, null); } /** * Saves the file overriding the name it was uploaded with. * * @param directory location to save the file in * @param filename local name for the file * @throws ValidationException if the path (directory/filename) isn't writable * @throws IOException if request fails because of network or other IO issue * @throws PolicySignatureException if policy and/or signature are invalid or inadequate * @throws ResourceNotFoundException if handle isn't found * @throws InvalidParameterException if handle is malformed * @throws InternalException if unexpected error occurs */ public File download(String directory, String filename) throws ValidationException, IOException, PolicySignatureException, ResourceNotFoundException, InvalidParameterException, InternalException { String policy = security != null ? security.getPolicy() : null; String signature = security != null ? security.getSignature() : null; Response<ResponseBody> response = fsCdnService.get(this.handle, policy, signature).execute(); Util.checkResponseAndThrow(response); if (filename == null) { filename = response.headers().get("x-file-name"); } File file = Util.createWriteFile(directory + "/" + filename); ResponseBody body = response.body(); if (body == null) { throw new IOException(); } BufferedSource source = body.source(); BufferedSink sink = Okio.buffer(Okio.sink(file)); sink.writeAll(source); sink.close(); return file; } /** * Replace the content of an existing file handle. Requires security to be set. * Does not update the filename or MIME type. * * @param pathname path to the file, can be local or absolute * @throws ValidationException if security isn't set or the pathname is invalid * @throws IOException if request fails because of network or other IO issue * @throws PolicySignatureException if policy and/or signature are invalid or inadequate * @throws ResourceNotFoundException if handle isn't found * @throws InvalidParameterException if handle is malformed * @throws InternalException if unexpected error occurs */ public void overwrite(String pathname) throws ValidationException, IOException, PolicySignatureException, ResourceNotFoundException, InvalidParameterException, InternalException { if (security == null) { throw new ValidationException("Security must be set in order to overwrite"); } File file = Util.createReadFile(pathname); String mimeType = URLConnection.guessContentTypeFromName(file.getName()); RequestBody body = RequestBody.create(MediaType.parse(mimeType), file); String policy = security.getPolicy(); String signature = security.getSignature(); Response response = fsApiService.overwrite(handle, policy, signature, body).execute(); Util.checkResponseAndThrow(response); } /** * Deletes a file handle. Requires security to be set. * * @throws ValidationException if security isn't set * @throws IOException if request fails because of network or other IO issue * @throws PolicySignatureException if policy and/or signature are invalid or inadequate * @throws ResourceNotFoundException if handle isn't found * @throws InvalidParameterException if handle is malformed * @throws InternalException if unexpected error occurs */ public void delete() throws ValidationException, IOException, PolicySignatureException, ResourceNotFoundException, InvalidParameterException, InternalException { if (security == null) { throw new ValidationException("Security must be set in order to delete"); } String policy = security.getPolicy(); String signature = security.getSignature(); Response response = fsApiService.delete(handle, apiKey, policy, signature).execute(); Util.checkResponseAndThrow(response); } // Async method wrappers /** * Asynchronously returns the content of a file. * * @see #getContent() */ public Single<byte[]> getContentAsync() { return Single.fromCallable(new Callable<byte[]>() { @Override public byte[] call() throws Exception { return getContent(); } }) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.single()); } /** * Asynchronously saves the file using the name it was uploaded with. * * @see #download(String, String) */ public Single<File> downloadAsync(final String directory) { return downloadAsync(directory, null); } /** * Asynchronously saves the file overriding the name it was uploaded with. * * @see #download(String, String) */ public Single<File> downloadAsync(final String directory, final String filename) { return Single.fromCallable(new Callable<File>() { @Override public File call() throws Exception { return download(directory, filename); } }) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.single()); } /** * Asynchronously replace the content of an existing file handle. Requires security to be set. * Does not update the filename or MIME type. * * @see #overwrite(String) */ public Completable overwriteAsync(final String pathname) { return Completable.fromAction(new Action() { @Override public void run() throws Exception { overwrite(pathname); } }) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.single()); } /** * Asynchronously deletes a file handle. Requires security to be set. * * @see #delete() */ public Completable deleteAsync() { return Completable.fromAction(new Action() { @Override public void run() throws Exception { delete(); } }) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.single()); } /** * Creates an {@link ImageTransform} object for this file. * A transformation call isn't made directly by this method. * * @return {@link ImageTransform ImageTransform} instance configured for this file */ public ImageTransform imageTransform() { return new ImageTransform(this); } public String getHandle() { return handle; } public Security getSecurity() { return security; } }
Update FileLink to use FsService
src/main/java/com/filestack/FileLink.java
Update FileLink to use FsService
Java
bsd-2-clause
512839713cee5e3880d105ccb0efc1e8df0ccb98
0
clementval/claw-compiler,clementval/claw-compiler
/* * This file is released under terms of BSD license * See LICENSE file for more information */ package cx2x.xcodeml.helper; import cx2x.translator.language.ClawDimension; import cx2x.translator.language.OverPosition; import cx2x.translator.xnode.ClawAttr; import cx2x.xcodeml.exception.*; import cx2x.xcodeml.xnode.*; import exc.xcodeml.XcodeMLtools_Fmod; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.TransformerFactory; import javax.xml.transform.Transformer; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.*; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; /** * The class XnodeUtil contains only static method to help manipulating the * raw Elements in the XcodeML representation by using the abstracted Xnode. * * @author clementval */ public class XnodeUtil { public static final String XMOD_FILE_EXTENSION = ".xmod"; /** * Find a function definition according to a function call. * @param xcodeml The XcodeML program to search in. * @param fctCall The function call used to find the function definition. * @return A function definition element if found. Null otherwise. */ public static XfunctionDefinition findFunctionDefinition(XcodeProgram xcodeml, Xnode fctCall) { if(xcodeml.getElement() == null){ return null; } String name = fctCall.findNode(Xcode.NAME).getValue(); NodeList nList = xcodeml.getElement(). getElementsByTagName(Xname.F_FUNCTION_DEFINITION); for (int i = 0; i < nList.getLength(); i++) { Node fctDefNode = nList.item(i); if (fctDefNode.getNodeType() == Node.ELEMENT_NODE) { Xnode dummyFctDef = new Xnode((Element)fctDefNode); Xnode fctDefName = dummyFctDef.find(Xcode.NAME); if(name != null && fctDefName.getValue().toLowerCase().equals(name.toLowerCase())) { return new XfunctionDefinition(dummyFctDef.getElement()); } } } return null; } /** * Find a function definition in a module definition. * @param module Module definition in which we search for the function * definition. * @param name Name of the function to be found. * @return A function definition element if found. Null otherwise. */ public static XfunctionDefinition findFunctionDefinitionInModule( XmoduleDefinition module, String name) { if(module.getElement() == null){ return null; } NodeList nList = module.getElement(). getElementsByTagName(Xname.F_FUNCTION_DEFINITION); for (int i = 0; i < nList.getLength(); i++) { Node n = nList.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { XfunctionDefinition fctDef = new XfunctionDefinition((Element)n); if(fctDef.getName().getValue().equals(name)){ return fctDef; } } } return null; } /** * Find all array references elements in a given body and give var name. * @param parent The body element to search for the array references. * @param arrayName Name of the array for the array reference to be found. * @return A list of all array references found. */ public static List<Xnode> getAllArrayReferences(Xnode parent, String arrayName) { List<Xnode> references = new ArrayList<>(); NodeList nList = parent.getElement(). getElementsByTagName(Xname.F_ARRAY_REF); for (int i = 0; i < nList.getLength(); i++) { Node n = nList.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { Xnode ref = new Xnode((Element) n); Xnode var = ref.find(Xcode.VARREF, Xcode.VAR); if(var != null && var.getValue().toLowerCase(). equals(arrayName.toLowerCase())) { references.add(ref); } } } return references; } /** * Find all function definitions in an XcodeML unit. * @param xcodeml Current XcodeML unit. * @return A list of all function definitions in the program. */ public static List<XfunctionDefinition> getAllFctDef(XcodeProgram xcodeml) { List<XfunctionDefinition> definitions = new ArrayList<>(); NodeList nList = xcodeml.getElement(). getElementsByTagName(Xname.F_FUNCTION_DEFINITION); for (int i = 0; i < nList.getLength(); i++) { Node n = nList.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { definitions.add(new XfunctionDefinition((Element) n)); } } return definitions; } /** * Find all var references elements in a given body and give var name. * @param parent The body element to search for the array references. * @param varName Name of the var for the reference to be found. * @return A list of all references found. */ public static List<Xnode> getAllVarReferences(Xnode parent, String varName){ List<Xnode> references = new ArrayList<>(); NodeList nList = parent.getElement(). getElementsByTagName(Xname.VAR); for (int i = 0; i < nList.getLength(); i++) { Node n = nList.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { Xnode var = new Xnode((Element) n); if(var.getValue().toLowerCase().equals(varName.toLowerCase())) { references.add(var); } } } return references; } /** * Demote an array reference to a var reference. * @param ref The array reference to be modified. */ public static void demoteToScalar(Xnode ref){ Xnode var = ref.find(Xcode.VARREF, Xcode.VAR).cloneObject(); insertAfter(ref, var); ref.delete(); } /** * Demote an array reference to a reference with fewer dimensions. * @param ref The array reference to be modified. * @param keptDimensions List of dimensions to be kept. Dimension index starts * at 1. */ public static void demote(Xnode ref, List<Integer> keptDimensions){ for(int i = 1; i < ref.getChildren().size(); ++i){ if(!keptDimensions.contains(i)){ ref.getChild(i).delete(); } } } /** * Retrieve the index ranges of an array notation. * @param arrayRef The array reference statements to extract the ranges from. * @return A list if indexRanges elements. */ public static List<Xnode> getIdxRangesFromArrayRef(Xnode arrayRef){ List<Xnode> ranges = new ArrayList<>(); if(arrayRef.opcode() != Xcode.FARRAYREF){ return ranges; } for(Xnode el : arrayRef.getChildren()){ if(el.opcode() == Xcode.INDEXRANGE){ ranges.add(el); } } return ranges; } /** * Compare two list of indexRange. * @param list1 First list of indexRange. * @param list2 Second list of indexRange. * @return True if the indexRange at the same position in the two list are all * identical. False otherwise. */ public static boolean compareIndexRanges(List<Xnode> list1, List<Xnode> list2) { if(list1.size() != list2.size()){ return false; } for(int i = 0; i < list1.size(); ++i){ if(!isIndexRangeIdentical(list1.get(i), list2.get(i), true)){ return false; } } return true; } /** * <pre> * Intersect two sets of elements in XPath 1.0 * * This method use Xpath to select the correct nodes. Xpath 1.0 does not have * the intersect operator but only union. By using the Kaysian Method, we can * it is possible to express the intersection of two node sets. * * $set1[count(.|$set2)=count($set2)] * * </pre> * @param s1 First set of element. * @param s2 Second set of element. * @return Xpath query that performs the intersect operator between s1 and s2. */ private static String xPathIntersect(String s1, String s2){ return String.format("%s[count(.|%s)=count(%s)]", s1, s2, s2); } /** * <pre> * Find all assignment statement from a node until the end pragma. * * We intersect all assign statements which are next siblings of * the "from" element with all the assign statements which are previous * siblings of the ending pragma. * </pre> * * @param from The element from which the search is initiated. * @param endPragma Value of the end pragma. Search will be performed until * there. * @return A list of all assign statements found. List is empty if no * statements are found. */ public static List<Xnode> getArrayAssignInBlock(Xnode from, String endPragma){ /* Define all the assign element with array refs which are next siblings of * the "from" element */ String s1 = String.format( "following-sibling::%s[%s]", Xname.F_ASSIGN_STMT, Xname.F_ARRAY_REF ); /* Define all the assign element with array refs which are previous siblings * of the end pragma element */ String s2 = String.format( "following-sibling::%s[text()=\"%s\"]/preceding-sibling::%s[%s]", Xname.PRAGMA_STMT, endPragma, Xname.F_ASSIGN_STMT, Xname.F_ARRAY_REF ); // Use the Kaysian method to express the intersect operator String intersect = XnodeUtil.xPathIntersect(s1, s2); return getFromXpath(from, intersect); } /** * Get all array references in the siblings of the given element. * @param from Element to start from. * @param identifier Array name value. * @return List of all array references found. List is empty if nothing is * found. */ public static List<Xnode> getAllArrayReferencesInSiblings(Xnode from, String identifier) { String s1 = String.format("following-sibling::*//%s[%s[%s[text()=\"%s\"]]]", Xname.F_ARRAY_REF, Xname.VAR_REF, Xname.VAR, identifier ); return getFromXpath(from, s1); } /** * Get the first assignment statement for an array reference. * @param from Statement to look from. * @param arrayName Identifier of the array. * @return The assignment statement if found. Null otherwise. */ public static Xnode getFirstArrayAssign(Xnode from, String arrayName){ String s1 = String.format( "following::%s[%s[%s[%s[text()=\"%s\"]] and position()=1]]", Xname.F_ASSIGN_STMT, Xname.F_ARRAY_REF, Xname.VAR_REF, Xname.VAR, arrayName ); try { NodeList output = evaluateXpath(from.getElement(), s1); if(output.getLength() == 0){ return null; } Element assign = (Element) output.item(0); return new Xnode(assign); } catch (XPathExpressionException ignored) { return null; } } /** * Find all the nested do statement groups following the inductions iterations * define in inductionVars and being located between the "from" element and * the end pragma. * @param from Element from which the search is started. * @param endPragma End pragma that terminates the search block. * @param inductionVars Induction variables that define the nested group to * locates. * @return List of do statements elements (outer most loops for each nested * group) found between the "from" element and the end pragma. */ public static List<Xnode> findDoStatement(Xnode from, Xnode endPragma, List<String> inductionVars) { /* s1 is selecting all the nested do statement groups that meet the criteria * from the "from" element down to the end of the block. */ String s1 = "following::"; String dynamic_part_s1 = ""; for(int i = inductionVars.size() - 1; i >= 0; --i){ /* * Here is example of there xpath query format for 1,2 and 3 nested loops * * FdoStatement[Var[text()="induction_var"]] * * FdoStatement[Var[text()="induction_var"] and * body[FdoStatement[Var[text()="induction_var"]]] * * FdoStatement[Var[text()="induction_var"] and * body[FdoStatement[Var[text()="induction_var"] and * body[FdoStatement[Var[text()="induction_var"]]]] */ String tempQuery; if(i == inductionVars.size() - 1) { // first iteration tempQuery = String.format("%s[%s[text()=\"%s\"]]", Xname.F_DO_STATEMENT, Xname.VAR, inductionVars.get(i)); } else { tempQuery = String.format("%s[%s[text()=\"%s\"] and %s[%s]]", Xname.F_DO_STATEMENT, Xname.VAR, inductionVars.get(i), Xname.BODY, dynamic_part_s1); // Including previously formed xpath query } dynamic_part_s1 = tempQuery; } s1 = s1 + dynamic_part_s1; List<Xnode> doStatements = new ArrayList<>(); try { NodeList output = evaluateXpath(from.getElement(), s1); for (int i = 0; i < output.getLength(); i++) { Element el = (Element) output.item(i); Xnode doStmt = new Xnode(el); if(doStmt.getLineNo() != 0 && doStmt.getLineNo() < endPragma.getLineNo()) { doStatements.add(doStmt); } } } catch (XPathExpressionException ignored) { } return doStatements; } /** * Evaluates an Xpath expression and return its result as a NodeList. * @param from Element to start the evaluation. * @param xpath Xpath expression. * @return Result of evaluation as a NodeList. * @throws XPathExpressionException if evaluation fails. */ private static NodeList evaluateXpath(Element from, String xpath) throws XPathExpressionException { XPathExpression ex = XPathFactory.newInstance().newXPath().compile(xpath); return (NodeList)ex.evaluate(from, XPathConstants.NODESET); } /** * Find all array references in the next children that match the given * criteria. * * This methods use powerful Xpath expression to locate the correct nodes in * the AST * * Here is an example of such a query that return all node that are array * references for the array "array6" with an offset of 0 -1 * * //FarrayRef[varRef[Var[text()="array6"]] and arrayIndex and * arrayIndex[minusExpr[Var and FintConstant[text()="1"]]]] * * @param from The element from which the search is initiated. * @param identifier Identifier of the array. * @param offsets List of offsets to be search for. * @return A list of all array references found. */ public static List<Xnode> getAllArrayReferencesByOffsets(Xnode from, String identifier, List<Integer> offsets) { String offsetXpath = ""; for (int i = 0; i < offsets.size(); ++i){ if(offsets.get(i) == 0){ offsetXpath += String.format("%s[position()=%s and %s]", Xname.ARRAY_INDEX, i+1, Xname.VAR ); } else if(offsets.get(i) > 0) { offsetXpath += String.format("%s[position()=%s and %s[%s and %s[text()=\"%s\"]]]", Xname.ARRAY_INDEX, i+1, Xname.MINUS_EXPR, Xname.VAR, Xname.F_INT_CONST, offsets.get(i)); } else { offsetXpath += String.format("%s[position()=%s and %s[%s and %s[text()=\"%s\"]]]", Xname.ARRAY_INDEX, i+1, Xname.MINUS_EXPR, Xname.VAR, Xname.F_INT_CONST, Math.abs(offsets.get(i))); } if(i != offsets.size()-1){ offsetXpath += " and "; } } // Start of the Xpath query String xpathQuery = String.format(".//%s[%s[%s[text()=\"%s\"]] and %s]", Xname.F_ARRAY_REF, Xname.VAR_REF, Xname.VAR, identifier, offsetXpath ); return getFromXpath(from, xpathQuery); } /** * Find a pragma element in the previous nodes containing a given keyword. * @param from Element to start from. * @param keyword Keyword to be found in the pragma. * @return The pragma if found. Null otherwise. */ public static Xnode findPreviousPragma(Xnode from, String keyword) { if (from == null || from.getElement() == null) { return null; } Node prev = from.getElement().getPreviousSibling(); Node parent = from.getElement(); do { while (prev != null) { if (prev.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) prev; if (element.getTagName().equals(Xcode.FPRAGMASTATEMENT.code()) && element.getTextContent().toLowerCase(). contains(keyword.toLowerCase())) { return new Xnode(element); } } prev = prev.getPreviousSibling(); } parent = parent.getParentNode(); prev = parent; } while (parent != null); return null; } /** * Find all the index elements (arrayIndex and indexRange) in an element. * @param parent Root element to search from. * @return A list of all index ranges found. */ public static List<Xnode> findIndexes(Xnode parent){ List<Xnode> indexRanges = new ArrayList<>(); if(parent == null || parent.getElement() == null){ return indexRanges; } Node node = parent.getElement().getFirstChild(); while (node != null){ if(node.getNodeType() == Node.ELEMENT_NODE){ Element element = (Element)node; switch (element.getTagName()){ case Xname.ARRAY_INDEX: case Xname.INDEX_RANGE: indexRanges.add(new Xnode(element)); break; } } node = node.getNextSibling(); } return indexRanges; } /** * Find all the name elements in an element. * @param parent Root element to search from. * @return A list of all name elements found. */ public static List<Xnode> findAllNames(Xnode parent){ return findAll(Xcode.NAME, parent); } /** * Find all the var elements that are real references to a variable. Var * element nested in an arrayIndex element are excluded. * @param parent Root element to search from. * @return A list of all var elements found. */ public static List<Xnode> findAllReferences(Xnode parent){ List<Xnode> vars = findAll(Xcode.VAR, parent); List<Xnode> realReferences = new ArrayList<>(); for(Xnode var : vars){ if(!((Element)var.getElement().getParentNode()).getTagName(). equals(Xcode.ARRAYINDEX.code())) { realReferences.add(var); } } return realReferences; } /** * Find all the var elements that are real references to a variable. Var * element nested in an arrayIndex element are excluded. * @param parent Root element to search from. * @param id Identifier of the var to be found. * @return A list of all var elements found. */ public static List<Xnode> findAllReferences(Xnode parent, String id){ List<Xnode> vars = findAll(Xcode.VAR, parent); List<Xnode> realReferences = new ArrayList<>(); for(Xnode var : vars){ if(!((Element)var.getElement().getParentNode()).getTagName(). equals(Xcode.ARRAYINDEX.code()) && var.getValue().toLowerCase().equals(id.toLowerCase())) { realReferences.add(var); } } return realReferences; } /** * Find all the pragma element in an XcodeML tree. * @param xcodeml The XcodeML program to search in. * @return A list of all pragmas found in the XcodeML program. */ public static List<Xnode> findAllPragmas(XcodeProgram xcodeml){ NodeList pragmaList = xcodeml.getDocument() .getElementsByTagName(Xcode.FPRAGMASTATEMENT.code()); List<Xnode> pragmas = new ArrayList<>(); for (int i = 0; i < pragmaList.getLength(); i++) { Node pragmaNode = pragmaList.item(i); if (pragmaNode.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) pragmaNode; pragmas.add(new Xnode(element)); } } return pragmas; } /** * Extract the body of a do statement and place it directly after it. * @param loop The do statement containing the body to be extracted. */ public static void extractBody(Xnode loop){ extractBody(loop, loop); } /** * Extract the body of a do statement and place it after the reference node. * @param loop The do statement containing the body to be extracted. * @param ref Element after which statement are shifted. */ public static void extractBody(Xnode loop, Xnode ref){ Element loopElement = loop.getElement(); Element body = XnodeUtil.findFirstElement(loopElement, Xname.BODY); if(body == null){ return; } Node refNode = ref.getElement(); for(Node childNode = body.getFirstChild(); childNode!=null;){ Node nextChild = childNode.getNextSibling(); // Do something with childNode, including move or delete... if(childNode.getNodeType() == Node.ELEMENT_NODE){ insertAfter(refNode, childNode); refNode = childNode; } childNode = nextChild; } } /** * Delete an element for the tree. * @param element Element to be deleted. */ public static void delete(Node element){ if(element == null || element.getParentNode() == null){ return; } element.getParentNode().removeChild(element); } /** * Write the XcodeML to file or std out * @param xcodeml The XcodeML to write in the output * @param outputFile Path of the output file or null to output on std out * @param indent Number of spaces used for the indentation * @throws IllegalTransformationException if XML file cannot be written. */ public static void writeXcodeML(XcodeML xcodeml, String outputFile, int indent) throws IllegalTransformationException { try { XnodeUtil.cleanEmptyTextNodes(xcodeml.getDocument()); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", Integer.toString(indent)); DOMSource source = new DOMSource(xcodeml.getDocument()); if(outputFile == null){ // Output to console StreamResult console = new StreamResult(System.out); transformer.transform(source, console); } else { // Output to file StreamResult console = new StreamResult(new File(outputFile)); transformer.transform(source, console); } } catch (Exception ignored){ throw new IllegalTransformationException("Cannot output file: " + outputFile, 0); } } /** * Removes text nodes that only contains whitespace. The conditions for * removing text nodes, besides only containing whitespace, are: If the * parent node has at least one child of any of the following types, all * whitespace-only text-node children will be removed: - ELEMENT child - * CDATA child - COMMENT child. * @param parentNode Root node to start the cleaning. */ private static void cleanEmptyTextNodes(Node parentNode) { boolean removeEmptyTextNodes = false; Node childNode = parentNode.getFirstChild(); while (childNode != null) { removeEmptyTextNodes |= checkNodeTypes(childNode); childNode = childNode.getNextSibling(); } if (removeEmptyTextNodes) { removeEmptyTextNodes(parentNode); } } /* * PRIVATE SECTION */ /** * Remove all empty text nodes in the subtree. * @param parentNode Root node to start the search. */ private static void removeEmptyTextNodes(Node parentNode) { Node childNode = parentNode.getFirstChild(); while (childNode != null) { // grab the "nextSibling" before the child node is removed Node nextChild = childNode.getNextSibling(); short nodeType = childNode.getNodeType(); if (nodeType == Node.TEXT_NODE) { boolean containsOnlyWhitespace = childNode.getNodeValue() .trim().isEmpty(); if (containsOnlyWhitespace) { parentNode.removeChild(childNode); } } childNode = nextChild; } } /** * Check the type of the given node. * @param childNode Node to be checked. * @return True if the node contains data. False otherwise. */ private static boolean checkNodeTypes(Node childNode) { short nodeType = childNode.getNodeType(); if (nodeType == Node.ELEMENT_NODE) { cleanEmptyTextNodes(childNode); // recurse into subtree } return nodeType == Node.ELEMENT_NODE || nodeType == Node.CDATA_SECTION_NODE || nodeType == Node.COMMENT_NODE; } /** * Insert a node directly after a reference node. * @param refNode The reference node. New node will be inserted after this * one. * @param newNode The new node to be inserted. */ private static void insertAfter(Node refNode, Node newNode){ refNode.getParentNode().insertBefore(newNode, refNode.getNextSibling()); } /** * Find the first element with tag corresponding to elementName nested under * the parent element. * @param parent The root element to search from. * @param elementName The tag of the element to search for. * @return The first element found under parent with the corresponding tag. * Null if no element is found. */ private static Element findFirstElement(Element parent, String elementName){ NodeList elements = parent.getElementsByTagName(elementName); if(elements.getLength() == 0){ return null; } return (Element) elements.item(0); } /** * Find the first element with tag corresponding to elementName in the direct * children of the parent element. * @param parent The root element to search from. * @param elementName The tag of the element to search for. * @return The first element found in the direct children of the element * parent with the corresponding tag. Null if no element is found. */ private static Element findFirstChildElement(Element parent, String elementName){ NodeList nodeList = parent.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node nextNode = nodeList.item(i); if(nextNode.getNodeType() == Node.ELEMENT_NODE){ Element element = (Element) nextNode; if(element.getTagName().equals(elementName)){ return element; } } } return null; } /** * Get the depth of an element in the AST. * @param element XML element for which the depth is computed. * @return A depth value greater or equal to 0. */ private static int getDepth(Element element){ Node parent = element.getParentNode(); int depth = 0; while(parent != null && parent.getNodeType() == Node.ELEMENT_NODE) { ++depth; parent = parent.getParentNode(); } return depth; } /** * Shift all statements from the first siblings of the "from" element until * the "until" element (not included). * @param from Start element for the swifting. * @param until End element for the swifting. * @param targetBody Body element in which statements are inserted. */ public static void shiftStatementsInBody(Xnode from, Xnode until, Xnode targetBody) { Node currentSibling = from.getElement().getNextSibling(); Node firstStatementInBody = targetBody.getElement().getFirstChild(); while(currentSibling != null && currentSibling != until.getElement()){ Node nextSibling = currentSibling.getNextSibling(); targetBody.getElement().insertBefore(currentSibling, firstStatementInBody); currentSibling = nextSibling; } } /** * Copy the whole body element into the destination one. Destination is * overwritten. * @param from The body to be copied. * @param to The destination of the copied body. */ public static void copyBody(Xnode from, Xnode to){ Node copiedBody = from.cloneNode(); if(to.getBody() != null){ to.getBody().delete(); } to.getElement().appendChild(copiedBody); } /** * Check whether the given type is a built-in type or is a type defined in the * type table. * @param type Type to check. * @return True if the type is built-in. False otherwise. */ public static boolean isBuiltInType(String type){ switch (type){ case Xname.TYPE_F_CHAR: case Xname.TYPE_F_COMPLEX: case Xname.TYPE_F_INT: case Xname.TYPE_F_LOGICAL: case Xname.TYPE_F_REAL: case Xname.TYPE_F_VOID: return true; default: return false; } } /* XNODE SECTION */ /** * Find module definition element in which the child is included if any. * @param from The child element to search from. * @return A XmoduleDefinition object if found. Null otherwise. */ public static XmoduleDefinition findParentModule(Xnode from) { Xnode moduleDef = findParent(Xcode.FMODULEDEFINITION, from); if(moduleDef == null){ return null; } return new XmoduleDefinition(moduleDef.getElement()); } /** * Find function definition in the ancestor of the give element. * @param from Element to start search from. * @return The function definition found. Null if nothing found. */ public static XfunctionDefinition findParentFunction(Xnode from){ Xnode fctDef = findParent(Xcode.FFUNCTIONDEFINITION, from); if(fctDef == null){ return null; } return new XfunctionDefinition(fctDef.getElement()); } /** * Find element of the the given type that is directly after the given from * element. * @param opcode Code of the element to be found. * @param from Element to start the search from. * @return The element found. Null if no element is found. */ public static Xnode findDirectNext(Xcode opcode, Xnode from) { if(from == null){ return null; } Node nextNode = from.getElement().getNextSibling(); while (nextNode != null){ if(nextNode.getNodeType() == Node.ELEMENT_NODE){ Element element = (Element) nextNode; if(element.getTagName().equals(opcode.code())){ return new Xnode(element); } return null; } nextNode = nextNode.getNextSibling(); } return null; } /** * Delete all the elements between the two given elements. * @param start The start element. Deletion start from next element. * @param end The end element. Deletion end just before this element. */ public static void deleteBetween(Xnode start, Xnode end){ List<Element> toDelete = new ArrayList<>(); Node node = start.getElement().getNextSibling(); while (node != null && node != end.getElement()){ if(node.getNodeType() == Node.ELEMENT_NODE){ Element element = (Element)node; toDelete.add(element); } node = node.getNextSibling(); } for(Element e : toDelete){ delete(e); } } /** * Insert an element just after a reference element. * @param refElement The reference element. * @param element The element to be inserted. */ public static void insertAfter(Xnode refElement, Xnode element){ XnodeUtil.insertAfter(refElement.getElement(), element.getElement()); } /** * Find the first element with tag corresponding to elementName. * @param opcode The XcodeML code of the element to search for. * @param parent The root element to search from. * @param any If true, find in any nested element under parent. If false, * only direct children are search for. * @return first element found. Null if no element is found. */ public static Xnode find(Xcode opcode, Xnode parent, boolean any){ Element el; if(any){ el = findFirstElement(parent.getElement(), opcode.code()); } else { el = findFirstChildElement(parent.getElement(), opcode.code()); } return (el == null) ? null : new Xnode(el); } /** * Find element of the the given type that is directly after the given from * element. * @param opcode Code of the element to be found. * @param from Element to start the search from. * @return The element found. Null if no element is found. */ public static Xnode findNext(Xcode opcode, Xnode from) { return findInDirection(opcode, from, true); } /** * Find an element in the ancestor of the given element. * @param opcode Code of the element to be found. * @param from Element to start the search from. * @return The element found. Null if nothing found. */ public static Xnode findParent(Xcode opcode, Xnode from){ return findInDirection(opcode, from, false); } /** * Find an element either in the next siblings or in the ancestors. * @param opcode Code of the element to be found. * @param from Element to start the search from. * @param down If True, search in the siblings. If false, search in the * ancestors. * @return The element found. Null if nothing found. */ private static Xnode findInDirection(Xcode opcode, Xnode from, boolean down){ if(from == null){ return null; } Node nextNode = down ? from.getElement().getNextSibling() : from.getElement().getParentNode(); while(nextNode != null){ if (nextNode.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) nextNode; if(element.getTagName().equals(opcode.code())){ return new Xnode(element); } } nextNode = down ? nextNode.getNextSibling() : nextNode.getParentNode(); } return null; } /** * Insert all the statements from a given body at the end of another body * @param originalBody The body in which the extra body will be appended * @param extraBody The body that will be appended to the original body * @throws IllegalTransformationException if one of the body or their base * element is null. */ public static void appendBody(Xnode originalBody, Xnode extraBody) throws IllegalTransformationException { if(originalBody == null || originalBody.getElement() == null || extraBody == null || extraBody.getElement() == null || originalBody.opcode() != Xcode.BODY || extraBody.opcode() != Xcode.BODY) { throw new IllegalTransformationException("One of the body is null."); } // Append content of loop-body (loop) to this loop-body Node childNode = extraBody.getElement().getFirstChild(); while(childNode != null){ Node nextChild = childNode.getNextSibling(); // Do something with childNode, including move or delete... if(childNode.getNodeType() == Node.ELEMENT_NODE){ originalBody.getElement().appendChild(childNode); } childNode = nextChild; } } /** * Check if the two element are direct children of the same parent element. * @param e1 First element. * @param e2 Second element. * @return True if the two element are direct children of the same parent. * False otherwise. */ public static boolean hasSameParentBlock(Xnode e1, Xnode e2) { return !(e1 == null || e2 == null || e1.getElement() == null || e2.getElement() == null) && e1.getElement().getParentNode() == e2.getElement().getParentNode(); } /** Compare the iteration range of two do statements. * @param e1 First do statement. * @param e2 Second do statement. * @param withLowerBound Compare lower bound or not. * @return True if the iteration range are identical. */ private static boolean compareIndexRanges(Xnode e1, Xnode e2, boolean withLowerBound) { // The two nodes must be do statement if (e1.opcode() != Xcode.FDOSTATEMENT || e2.opcode() != Xcode.FDOSTATEMENT) { return false; } Xnode inductionVar1 = XnodeUtil.find(Xcode.VAR, e1, false); Xnode inductionVar2 = XnodeUtil.find(Xcode.VAR, e2, false); Xnode indexRange1 = XnodeUtil.find(Xcode.INDEXRANGE, e1, false); Xnode indexRange2 = XnodeUtil.find(Xcode.INDEXRANGE, e2, false); return compareValues(inductionVar1, inductionVar2) && isIndexRangeIdentical(indexRange1, indexRange2, withLowerBound); } /** * Compare the iteration range of two do statements. * @param e1 First do statement. * @param e2 Second do statement. * @return True if the iteration range are identical. */ public static boolean hasSameIndexRange(Xnode e1, Xnode e2) { return compareIndexRanges(e1, e2, true); } /** * Compare the iteration range of two do statements. * @param e1 First do statement. * @param e2 Second do statement. * @return True if the iteration range are identical besides the lower bound. */ public static boolean hasSameIndexRangeBesidesLower(Xnode e1, Xnode e2) { return compareIndexRanges(e1, e2, false); } /** * Compare the inner values of two nodes. * @param n1 First node. * @param n2 Second node. * @return True if the values are identical. False otherwise. */ private static boolean compareValues(Xnode n1, Xnode n2) { return !(n1 == null || n2 == null) && n1.getValue().toLowerCase().equals(n2.getValue().toLowerCase()); } /** * Compare the inner value of the first child of two nodes. * @param n1 First node. * @param n2 Second node. * @return True if the value are identical. False otherwise. */ private static boolean compareFirstChildValues(Xnode n1, Xnode n2) { if(n1 == null || n2 == null){ return false; } Xnode c1 = n1.getChild(0); Xnode c2 = n2.getChild(0); return compareValues(c1, c2); } /** * Compare the inner values of two optional nodes. * @param n1 First node. * @param n2 Second node. * @return True if the values are identical or elements are null. False * otherwise. */ private static boolean compareOptionalValues(Xnode n1, Xnode n2){ return n1 == null && n2 == null || (n1 != null && n2 != null && n1.getValue().toLowerCase().equals(n2.getValue().toLowerCase())); } /** * Compare the iteration range of two do statements * @param idx1 First do statement. * @param idx2 Second do statement. * @param withLowerBound If true, compare lower bound. If false, lower bound * is not compared. * @return True if the index range are identical. */ private static boolean isIndexRangeIdentical(Xnode idx1, Xnode idx2, boolean withLowerBound) { if (idx1.opcode() != Xcode.INDEXRANGE || idx2.opcode() != Xcode.INDEXRANGE) { return false; } if (idx1.getBooleanAttribute(Xattr.IS_ASSUMED_SHAPE) && idx2.getBooleanAttribute(Xattr.IS_ASSUMED_SHAPE)) { return true; } Xnode low1 = idx1.find(Xcode.LOWERBOUND); Xnode up1 = idx1.find(Xcode.UPPERBOUND); Xnode low2 = idx2.find(Xcode.LOWERBOUND); Xnode up2 = idx2.find(Xcode.UPPERBOUND); Xnode s1 = idx1.find(Xcode.STEP); Xnode s2 = idx2.find(Xcode.STEP); if (s1 != null) { s1 = s1.getChild(0); } if (s2 != null) { s2 = s2.getChild(0); } if(withLowerBound){ return compareFirstChildValues(low1, low2) && compareFirstChildValues(up1, up2) && compareOptionalValues(s1, s2); } else { return compareFirstChildValues(up1, up2) && compareOptionalValues(s1, s2); } } /** * Swap the iteration range information of two do statement. * @param e1 First do statement. * @param e2 Second do statement. * @throws IllegalTransformationException if necessary elements are missing * to apply the transformation. */ public static void swapIterationRange(Xnode e1, Xnode e2) throws IllegalTransformationException { // The two nodes must be do statement if(e1.opcode() != Xcode.FDOSTATEMENT || e2.opcode() != Xcode.FDOSTATEMENT){ return; } Xnode inductionVar1 = XnodeUtil.find(Xcode.VAR, e1, false); Xnode inductionVar2 = XnodeUtil.find(Xcode.VAR, e2, false); Xnode indexRange1 = XnodeUtil.find(Xcode.INDEXRANGE, e1, false); Xnode indexRange2 = XnodeUtil.find(Xcode.INDEXRANGE, e2, false); if(inductionVar1 == null || inductionVar2 == null || indexRange1 == null || indexRange2 == null) { throw new IllegalTransformationException("Induction variable or index " + "range missing."); } Xnode low1 = indexRange1.find(Xcode.LOWERBOUND).getChild(0); Xnode up1 = indexRange1.find(Xcode.UPPERBOUND).getChild(0); Xnode s1 = indexRange1.find(Xcode.STEP).getChild(0); Xnode low2 = indexRange2.find(Xcode.LOWERBOUND).getChild(0); Xnode up2 = indexRange2.find(Xcode.UPPERBOUND).getChild(0); Xnode s2 = indexRange2.find(Xcode.STEP).getChild(0); // Set the range of loop2 to loop1 XnodeUtil.insertAfter(inductionVar2, inductionVar1.cloneObject()); XnodeUtil.insertAfter(low2, low1.cloneObject()); XnodeUtil.insertAfter(up2, up1.cloneObject()); XnodeUtil.insertAfter(s2, s1.cloneObject()); XnodeUtil.insertAfter(inductionVar1, inductionVar2.cloneObject()); XnodeUtil.insertAfter(low1, low2.cloneObject()); XnodeUtil.insertAfter(up1, up2.cloneObject()); XnodeUtil.insertAfter(s1, s2.cloneObject()); inductionVar1.delete(); inductionVar2.delete(); low1.delete(); up1.delete(); s1.delete(); low2.delete(); up2.delete(); s2.delete(); } /** * Get the depth of an element in the AST. * @param element The element for which the depth is computed. * @return A depth value greater or equal to 0. */ public static int getDepth(Xnode element) { if(element == null || element.getElement() == null){ return -1; } return getDepth(element.getElement()); } /** * Copy the enhanced information from an element to a target element. * Enhanced information include line number and original file name. * @param base Base element to copy information from. * @param target Target element to copy information to. */ public static void copyEnhancedInfo(Xnode base, Xnode target) { target.setLine(base.getLineNo()); target.setFile(base.getFile()); } /** * Insert an element just before a reference element. * @param ref The reference element. * @param insert The element to be inserted. */ public static void insertBefore(Xnode ref, Xnode insert){ ref.getElement().getParentNode().insertBefore(insert.getElement(), ref.getElement()); } /** * Get a list of T elements from an xpath query executed from the * given element. * @param from Element to start from. * @param query XPath query to be executed. * @return List of all array references found. List is empty if nothing is * found. */ private static List<Xnode> getFromXpath(Xnode from, String query) { List<Xnode> elements = new ArrayList<>(); try { XPathExpression ex = XPathFactory.newInstance().newXPath().compile(query); NodeList output = (NodeList) ex.evaluate(from.getElement(), XPathConstants.NODESET); for (int i = 0; i < output.getLength(); i++) { Element element = (Element) output.item(i); elements.add(new Xnode(element)); } } catch (XPathExpressionException ignored) { } return elements; } /** * Find specific argument in a function call. * @param value Value of the argument to be found. * @param fctCall Function call to search from. * @return The argument if found. Null otherwise. */ public static Xnode findArg(String value, Xnode fctCall){ if(fctCall.opcode() != Xcode.FUNCTIONCALL) { return null; } Xnode args = fctCall.find(Xcode.ARGUMENTS); if(args == null){ return null; } for(Xnode arg : args.getChildren()){ if(value.toLowerCase().equals(arg.getValue().toLowerCase())){ return arg; } } return null; } /** * Find all elements of a given type in the subtree. * @param opcode Type of the element to be found. * @param parent Root of the subtree. * @return List of all elements found in the subtree. */ public static List<Xnode> findAll(Xcode opcode, Xnode parent) { List<Xnode> elements = new ArrayList<>(); if(parent == null) { return elements; } NodeList nodes = parent.getElement().getElementsByTagName(opcode.code()); for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { elements.add(new Xnode((Element)n)); } } return elements; } /** * Create a new FunctionCall element with elements name and arguments as * children. * @param xcodeml The current XcodeML unit in which the elements are * created. * @param returnType Value of the type attribute for the functionCall element. * @param name Value of the name element. * @param nameType Value of the type attribute for the name element. * @return The newly created element. */ public static Xnode createFctCall(XcodeML xcodeml, String returnType, String name, String nameType){ Xnode fctCall = new Xnode(Xcode.FUNCTIONCALL, xcodeml); fctCall.setAttribute(Xattr.TYPE, returnType); Xnode fctName = new Xnode(Xcode.NAME, xcodeml); fctName.setValue(name); fctName.setAttribute(Xattr.TYPE, nameType); Xnode args = new Xnode(Xcode.ARGUMENTS, xcodeml); fctCall.appendToChildren(fctName, false); fctCall.appendToChildren(args, false); return fctCall; } /** * Create a new FarrayRef element with varRef element as a child with the * given Var element. * @param xcodeml The current XcodeML unit in which the elements are created. * @param type Value of the type attribute for the FarrayRef element. * @param var Var element nested in the varRef element. * @return The newly created element. */ public static Xnode createArrayRef(XcodeML xcodeml, XbasicType type, Xnode var) { Xnode ref = new Xnode(Xcode.FARRAYREF, xcodeml); ref.setAttribute(Xattr.TYPE, type.getRef()); Xnode varRef = new Xnode(Xcode.VARREF, xcodeml); varRef.setAttribute(Xattr.TYPE, type.getType()); varRef.appendToChildren(var, false); ref.appendToChildren(varRef, false); return ref; } /** * Create a new Id element with all the underlying needed elements. * @param xcodeml The current XcodeML program unit in which the elements * are created. * @param type Value for the attribute type. * @param sclass Value for the attribute sclass. * @param nameValue Value of the name inner element. * @return The newly created element. */ public static Xid createId(XcodeML xcodeml, String type, String sclass, String nameValue) { Xnode id = new Xnode(Xcode.ID, xcodeml); Xnode internalName = new Xnode(Xcode.NAME, xcodeml); internalName.setValue(nameValue); id.appendToChildren(internalName, false); id.setAttribute(Xattr.TYPE, type); id.setAttribute(Xattr.SCLASS, sclass); return new Xid(id.getElement()); } /** * Constructs a new basicType element with the given information. * @param xcodeml The current XcodeML file unit in which the elements * are created. * @param type Type hash. * @param ref Reference type. * @param intent Optional intent information. * @return The newly created element. */ public static XbasicType createBasicType(XcodeML xcodeml, String type, String ref, Xintent intent) { Xnode bt = new Xnode(Xcode.FBASICTYPE, xcodeml); bt.setAttribute(Xattr.TYPE, type); if(ref != null) { bt.setAttribute(Xattr.REF, ref); } if(intent != null) { bt.setAttribute(Xattr.INTENT, intent.toString()); } return new XbasicType(bt.getElement()); } /** * Create a new Xdecl object with all the underlying elements for a varDecl. * @param xcodeml The current XcodeML file unit in which the elements * are created. * @param nameType Value for the attribute type of the name element. * @param nameValue Value of the name inner element. * @return The newly created element. */ public static Xdecl createVarDecl(XcodeML xcodeml, String nameType, String nameValue) { Xnode varD = new Xnode(Xcode.VARDECL, xcodeml); Xnode internalName = new Xnode(Xcode.NAME, xcodeml); internalName.setValue(nameValue); internalName.setAttribute(Xattr.TYPE, nameType); varD.appendToChildren(internalName, false); return new Xdecl(varD.getElement()); } /** * Constructs a new name element with name value and optional type. * @param xcodeml Current XcodeML file unit in which the element is * created. * @param name Name value. * @param type Optional type value. * @return The newly created element. */ private static Xnode createName(XcodeML xcodeml, String name, String type) { Xnode n = new Xnode(Xcode.NAME, xcodeml); n.setValue(name); if(type != null){ n.setAttribute(Xattr.TYPE, type); } return n; } /** * Create an empty assumed shape indexRange element. * @param xcodeml Current XcodeML file unit in which the element is * created. * @return The newly created element. */ public static Xnode createEmptyAssumedShaped(XcodeML xcodeml) { Xnode range = new Xnode(Xcode.INDEXRANGE, xcodeml); range.setAttribute(Xattr.IS_ASSUMED_SHAPE, Xname.TRUE); return range; } /** * Create an indexRange element to loop over an assumed shape array. * @param xcodeml Current XcodeML file unit in which the element is * created. * @param arrayVar Var element representing the array variable. * @param startIndex Lower bound index value. * @param dimension Dimension index for the upper bound value. * @return The newly created element. */ public static Xnode createAssumedShapeRange(XcodeML xcodeml, Xnode arrayVar, int startIndex, int dimension) { // Base structure Xnode indexRange = new Xnode(Xcode.INDEXRANGE, xcodeml); Xnode lower = new Xnode(Xcode.LOWERBOUND, xcodeml); Xnode upper = new Xnode(Xcode.UPPERBOUND, xcodeml); indexRange.appendToChildren(lower, false); indexRange.appendToChildren(upper, false); // Lower bound Xnode lowerBound = new Xnode(Xcode.FINTCONSTANT, xcodeml); lowerBound.setValue(String.valueOf(startIndex)); lower.appendToChildren(lowerBound, false); // Upper bound Xnode fctCall = new Xnode(Xcode.FUNCTIONCALL, xcodeml); upper.appendToChildren(fctCall, false); fctCall.setAttribute(Xattr.IS_INTRINSIC, Xname.TRUE); fctCall.setAttribute(Xattr.TYPE, Xname.TYPE_F_INT); Xnode name = new Xnode(Xcode.NAME, xcodeml); name.setValue(Xname.INTRINSIC_SIZE); fctCall.appendToChildren(name, false); Xnode args = new Xnode(Xcode.ARGUMENTS, xcodeml); fctCall.appendToChildren(args, false); args.appendToChildren(arrayVar, true); Xnode dim = new Xnode(Xcode.FINTCONSTANT, xcodeml); dim.setValue(String.valueOf(dimension)); args.appendToChildren(dim, false); return indexRange; } /** * Create a new FifStatement element with an empty then body. * @param xcodeml Current XcodeML file unit in which the element is * created. * @return The newly created element. */ public static Xnode createIfThen(XcodeML xcodeml){ Xnode root = new Xnode(Xcode.FIFSTATEMENT, xcodeml); Xnode cond = new Xnode(Xcode.CONDITION, xcodeml); Xnode thenBlock = new Xnode(Xcode.THEN, xcodeml); Xnode thenBody = new Xnode(Xcode.BODY, xcodeml); thenBlock.appendToChildren(thenBody, false); root.appendToChildren(cond, false); root.appendToChildren(thenBlock, false); return root; } /** * Create a new FdoStatement element with an empty body. * @param xcodeml Current XcodeML file unit in which the element is * created. * @param inductionVar Var element for the induction variable. * @param indexRange indexRange element for the iteration range. * @return The newly created element. */ public static Xnode createDoStmt(XcodeML xcodeml, Xnode inductionVar, Xnode indexRange) { Xnode root = new Xnode(Xcode.FDOSTATEMENT, xcodeml); root.appendToChildren(inductionVar, false); root.appendToChildren(indexRange, false); Xnode body = new Xnode(Xcode.BODY, xcodeml); root.appendToChildren(body, false); return root; } /** * Create a new var element. * @param type Value of the type attribute. * @param value Value of the var. * @param scope Value of the scope attribute. * @param xcodeml Current XcodeML file unit in which the element is created. * @return The newly created element. */ public static Xnode createVar(String type, String value, Xscope scope, XcodeML xcodeml) { Xnode var = new Xnode(Xcode.VAR, xcodeml); var.setAttribute(Xattr.TYPE, type); var.setAttribute(Xattr.SCOPE, scope.toString()); var.setValue(value); return var; } /** * Create a new namedValue element with its attribute. * @param value Value of the name attribute. * @param xcodeml Current XcodeML file unit in which the element is created. * @return The newly created element. */ public static Xnode createNamedValue(String value, XcodeML xcodeml){ Xnode namedValue = new Xnode(Xcode.NAMEDVALUE, xcodeml); namedValue.setAttribute(Xattr.NAME, value); return namedValue; } /** * Find module containing the function and read its .xmod file. * @param fctDef Function definition nested in the module. * @return Xmod object if the module has been found and read. Null otherwise. */ public static Xmod findContainingModule(XfunctionDefinition fctDef){ XmoduleDefinition mod = findParentModule(fctDef); if(mod == null){ return null; } String modName = mod.getAttribute(Xattr.NAME); return findModule(modName); } /** * Find module by name. * @param moduleName Name of the module. * @return Module object if found. Null otherwise. */ public static Xmod findModule(String moduleName){ for(String dir : XcodeMLtools_Fmod.getSearchPath()){ String path = dir + "/" + moduleName + XMOD_FILE_EXTENSION; File f = new File(path); if(f.exists()){ Document doc = readXmlFile(path); return doc != null ? new Xmod(doc, moduleName, dir) : null; } } return null; } /** * Read XML file. * @param input Xml file path. * @return Document if the XML file could be read. Null otherwise. */ public static Document readXmlFile(String input){ try { File fXmlFile = new File(input); if(!fXmlFile.exists()){ return null; } DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); return doc; } catch(Exception ignored){} return null; } /** * Create the id and varDecl elements and add them to the symbol/declaration * table. * @param name Name of the variable. * @param type Type of the variable. * @param sclass Scope class of the variable (from Xname). * @param fctDef Function definition in which id and decl are created. * @param xcodeml Current XcodeML unit in which the elements will be created. */ public static void createIdAndDecl(String name, String type, String sclass, XfunctionDefinition fctDef, XcodeML xcodeml) { Xid id = XnodeUtil.createId(xcodeml, type, sclass, name); fctDef.getSymbolTable().add(id); Xdecl decl = XnodeUtil.createVarDecl(xcodeml, type, name); fctDef.getDeclarationTable().add(decl); } /** * Create a name element and adds it as a parameter of the given function * type. If the function has optional parameters, the newly created parameter * is added before the optional ones. * @param xcodeml Current XcodeML file unit. * @param nameValue Value of the name element to create. * @param type Type of the name element to create. * @param fctType Function type in which the element will be added as a * parameter. */ public static Xnode createAndAddParam(XcodeML xcodeml, String nameValue, String type, XfunctionType fctType) { Xnode newParam = XnodeUtil.createName(xcodeml, nameValue, type); Xnode hook = null; // Newly created parameter must be added before any optional parameter for(Xnode param : fctType.getParams().getAll()){ XbasicType paramType = (XbasicType) xcodeml. getTypeTable().get(param.getAttribute(Xattr.TYPE)); if(paramType.getBooleanAttribute(Xattr.IS_OPTIONAL)){ hook = param; break; } } if(hook == null){ fctType.getParams().add(newParam); } else { fctType.getParams().addBefore(hook, newParam); } // TODO move method to TransformationHelper newParam.setAttribute(ClawAttr.IS_CLAW.toString(), Xname.TRUE); return newParam; } /** * Create a name element and adds it as a parameter of the given function * type if this parameter is does not exist yet. * @param xcodeml Current XcodeML file unit. * @param nameValue Value of the name element to create. * @param type Type of the name element to create. * @param fctType Function type in which the element will be added as a * parameter. */ public static void createAndAddParamIfNotExists(XcodeML xcodeml, String nameValue, String type, XfunctionType fctType) { for(Xnode p : fctType.getParams().getAll()){ if(p.getValue().toLowerCase().equals(nameValue.toLowerCase())) { return; } } createAndAddParam(xcodeml, nameValue, type, fctType); } /** * Import a type description from one XcodeML unit to another one. If the type * id is not present in the source XcodeML unit, nothing is done. * @param src Source XcodeML unit. * @param dst Destination XcodeML unit. * @param typeId Type id to be imported. */ public static void importType(XcodeML src, XcodeML dst, String typeId){ if(typeId == null || dst.getTypeTable().hasType(typeId)) { return; } Xtype type = src.getTypeTable().get(typeId); if(type == null){ return; } Node rawNode = dst.getDocument().importNode(type.getElement(), true); Xtype importedType = new Xtype((Element)rawNode); dst.getTypeTable().add(importedType); if(importedType.hasAttribute(Xattr.REF) && !XnodeUtil.isBuiltInType(importedType.getAttribute(Xattr.REF))) { XnodeUtil.importType(src, dst, importedType.getAttribute(Xattr.REF)); } // Handle possible type ref in indexRange element List<Xnode> vars = XnodeUtil.findAll(Xcode.VAR, importedType); for(Xnode var : vars){ importType(src, dst, var.getAttribute(Xattr.TYPE)); } } /** * Duplicates the type to update and add extra dimensions to match the base * type. * @param base Base type. * @param toUpdate Type to update. * @param xcodemlDst Destination XcodeML unit. Duplicate will be created here. * @param xcodemlSrc Source XcodeML unit. Contains base dimension. * @return The new type hash generated. */ public static String duplicateWithDimension(XbasicType base, XbasicType toUpdate, XcodeML xcodemlDst, XcodeML xcodemlSrc, OverPosition overPos, List<ClawDimension> dimensions) throws IllegalTransformationException { XbasicType newType = toUpdate.cloneObject(); String type = xcodemlDst.getTypeTable().generateArrayTypeHash(); newType.setAttribute(Xattr.TYPE, type); if(base.isAllAssumedShape() && toUpdate.isAllAssumedShape()){ int additionalDimensions = base.getDimensions() - toUpdate.getDimensions(); for(int i = 0; i < additionalDimensions; ++i){ Xnode index = XnodeUtil.createEmptyAssumedShaped(xcodemlDst); newType.addDimension(index, 0); } } else if(base.isAllAssumedShape() && !toUpdate.isAllAssumedShape()) { switch (overPos){ case BEFORE: // TODO control and validate the before/after for(ClawDimension dim : dimensions){ newType.addDimension(dim.generateIndexRange(xcodemlDst, false), XbasicType.APPEND); } break; case AFTER: for(ClawDimension dim : dimensions){ newType.addDimension(dim.generateIndexRange(xcodemlDst, false), 0); } break; case MIDDLE: throw new IllegalTransformationException("Not supported yet. " + "Insertion in middle for duplicated array type.", 0); } } else { newType.resetDimension(); for(int i = 0; i < base.getDimensions(); ++i){ Xnode newDim = new Xnode(Xcode.INDEXRANGE, xcodemlDst); newType.appendToChildren(newDim, false); Xnode baseDim = base.getDimensions(i); Xnode lowerBound = baseDim.find(Xcode.LOWERBOUND); Xnode upperBound = baseDim.find(Xcode.UPPERBOUND); if(lowerBound != null) { Xnode newLowerBound = duplicateBound(lowerBound, xcodemlDst, xcodemlSrc); newDim.appendToChildren(newLowerBound, false); } if(upperBound != null){ Xnode newUpperBound = duplicateBound(upperBound, xcodemlDst, xcodemlSrc); newDim.appendToChildren(newUpperBound, false); } newType.addDimension(newDim, XbasicType.APPEND); } } xcodemlDst.getTypeTable().add(newType); return type; } /** * Duplicate a lower or an upper bound between two different XcodeML units. * @param baseBound Base bound to be duplicated. * @param xcodemlDst Destination XcodeML unit. Duplicate will be created here. * @param xcodemlSrc Source XcodeML unit. Contains base bound. * @return The newly duplicated bound element. * @throws IllegalTransformationException If bound cannot be duplicated. */ private static Xnode duplicateBound(Xnode baseBound, XcodeML xcodemlDst, XcodeML xcodemlSrc) throws IllegalTransformationException { if(baseBound.opcode() != Xcode.LOWERBOUND && baseBound.opcode() != Xcode.UPPERBOUND) { throw new IllegalTransformationException("Cannot duplicate bound"); } if(xcodemlSrc == xcodemlDst){ return baseBound.cloneObject(); } Xnode boundChild = baseBound.getChild(0); if(boundChild == null){ throw new IllegalTransformationException("Cannot duplicate bound as it " + "has no children element"); } Xnode bound = new Xnode(baseBound.opcode(), xcodemlDst); if(boundChild.opcode() == Xcode.FINTCONSTANT || boundChild.opcode() == Xcode.VAR) { bound.appendToChildren( importConstOrVar(boundChild, xcodemlSrc, xcodemlDst), false); } else if(boundChild.opcode() == Xcode.PLUSEXPR) { Xnode lhs = boundChild.getChild(0); Xnode rhs = boundChild.getChild(1); Xnode plusExpr = new Xnode(Xcode.PLUSEXPR, xcodemlDst); bound.appendToChildren(plusExpr, false); plusExpr.appendToChildren( importConstOrVar(lhs, xcodemlSrc, xcodemlDst), false); plusExpr.appendToChildren( importConstOrVar(rhs, xcodemlSrc, xcodemlDst), false); } else { throw new IllegalTransformationException( String.format("Lower/upper bound type currently not supported (%s)", boundChild.opcode().toString()) ); } return bound; } /** * Create a copy of a variable element or an integer constant from a XcodeML * unit to another one. * @param base Base element to be copied. * @param xcodemlSrc Source XcodeML unit. * @param xcodemlDst Destination XcodeML unit. * @return The newly created element in the destination XcodeML unit. * @throws IllegalTransformationException If the variable element doesn't meet * the criteria. */ private static Xnode importConstOrVar(Xnode base, XcodeML xcodemlSrc, XcodeML xcodemlDst) throws IllegalTransformationException { if(base.opcode() != Xcode.FINTCONSTANT && base.opcode() != Xcode.VAR){ throw new IllegalTransformationException( String.format("Lower/upper bound type currently not supported (%s)", base.opcode().toString()) ); } if(base.opcode() == Xcode.VAR){ return importVar(base, xcodemlSrc, xcodemlDst); } else { Xnode intConst = new Xnode(Xcode.FINTCONSTANT, xcodemlDst); intConst.setValue(base.getValue()); return intConst; } } /** * Create a copy with a new hash type of an integer variable element from one * XcodeML unit to another one. * @param base Base variable element to be copied. * @param xcodemlSrc Source XcodeML unit. * @param xcodemlDst Destination XcodeML unit. * @return The newly created element in the destination XcodeML unit. * @throws IllegalTransformationException If the variable element doesn't meet * the criteria. */ private static Xnode importVar(Xnode base, XcodeML xcodemlSrc, XcodeML xcodemlDst) throws IllegalTransformationException { String typeValue = base.getAttribute(Xattr.TYPE); if(!typeValue.startsWith(Xtype.PREFIX_INTEGER)) { throw new IllegalTransformationException("Only integer variable are " + "supported as lower/upper bound value for promotted arrays."); } XbasicType type = (XbasicType) xcodemlSrc.getTypeTable().get(typeValue); Xnode bType = new Xnode(Xcode.FBASICTYPE, xcodemlDst); bType.setAttribute(Xattr.REF, Xname.TYPE_F_INT); bType.setAttribute(Xattr.TYPE, xcodemlDst.getTypeTable().generateIntegerTypeHash()); if(type != null && type.getIntent() != Xintent.NONE){ bType.setAttribute(Xattr.INTENT, type.getIntent().toString()); } Xnode var = new Xnode(Xcode.VAR, xcodemlDst); var.setAttribute(Xattr.SCOPE, base.getAttribute(Xattr.SCOPE)); var.setValue(base.getValue()); var.setAttribute(Xattr.TYPE, bType.getAttribute(Xattr.TYPE)); return var; } /** * Try to locate a function definition in the current declaration table or * recursively in the modules' delcaration tables. * @param dt Declaration table to search in. * @param fctName Function's name to be found. * @return The function definition if found. Null otherwise. */ public static XfunctionDefinition findFunctionDefinition(XglobalDeclTable dt, String fctName) { Iterator<Map.Entry<String, Xnode>> it = dt.getIterator(); while(it.hasNext()){ Map.Entry<String, Xnode> entry = it.next(); if(entry.getValue() instanceof XmoduleDefinition){ XfunctionDefinition fctDef = findFunctionDefinitionInModule( (XmoduleDefinition)entry.getValue(), fctName); if(fctDef != null){ return fctDef; } } else if (entry.getValue() instanceof XfunctionDefinition){ XfunctionDefinition fctDef = (XfunctionDefinition)entry.getValue(); if(fctDef.getName().getValue().equals(fctName)){ return fctDef; } } } return null; } /** * Get next sibling node. * @param crt Current node. * @return Next sibling node. */ public static Xnode getNextSibling(Xnode crt){ Node n = crt.getElement().getNextSibling(); while (n != null){ if(n.getNodeType() == Node.ELEMENT_NODE){ return new Xnode((Element)n); } n = n.getNextSibling(); } return null; } /** * Get all the USE statement declaration in a module definition. * @param mod Module definition. * @return A list of all declaration. Empty list if no USE declaration. */ public static List<Xdecl> getAllUse(XmoduleDefinition mod){ return mod == null ? getAllUseFromDeclTable(null) : getAllUseFromDeclTable(mod.getDeclarationTable()); } /** * Get all the USE statement declaration in a function definition. * @param fctDef Function definition. * @return A list of all declaration. Empty list if no USE declaration. */ public static List<Xdecl> getAllUse(XfunctionDefinition fctDef){ return fctDef == null ? getAllUseFromDeclTable(null) : getAllUseFromDeclTable(fctDef.getDeclarationTable()); } /** * Get all the USE statement declaration in a declaration table. * @param dt Declaration table. * @return A list of all declaration. Empty list if no USE declaration. */ private static List<Xdecl> getAllUseFromDeclTable(XdeclTable dt){ if(dt == null){ return new ArrayList<Xdecl>(); } List<Xdecl> uses = dt.getAll(Xcode.FUSEDECL); uses.addAll(dt.getAll(Xcode.FUSEONLYDECL)); return uses; } /** * Delete all sibling elements from the start element included. * @param start Element to start from. */ public static void deleteFrom(Xnode start){ List<Node> toDelete = new ArrayList<>(); toDelete.add(start.getElement()); Node sibling = start.getElement().getNextSibling(); while (sibling != null){ toDelete.add(sibling); sibling = sibling.getNextSibling(); } for (Node n : toDelete) { XnodeUtil.delete(n); } } }
omni-cx2x/src/cx2x/xcodeml/helper/XnodeUtil.java
/* * This file is released under terms of BSD license * See LICENSE file for more information */ package cx2x.xcodeml.helper; import cx2x.translator.xnode.ClawAttr; import cx2x.xcodeml.exception.*; import cx2x.xcodeml.xnode.*; import exc.xcodeml.XcodeMLtools_Fmod; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.TransformerFactory; import javax.xml.transform.Transformer; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.*; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; /** * The class XnodeUtil contains only static method to help manipulating the * raw Elements in the XcodeML representation by using the abstracted Xnode. * * @author clementval */ public class XnodeUtil { public static final String XMOD_FILE_EXTENSION = ".xmod"; /** * Find a function definition according to a function call. * @param xcodeml The XcodeML program to search in. * @param fctCall The function call used to find the function definition. * @return A function definition element if found. Null otherwise. */ public static XfunctionDefinition findFunctionDefinition(XcodeProgram xcodeml, Xnode fctCall) { if(xcodeml.getElement() == null){ return null; } String name = fctCall.findNode(Xcode.NAME).getValue(); NodeList nList = xcodeml.getElement(). getElementsByTagName(Xname.F_FUNCTION_DEFINITION); for (int i = 0; i < nList.getLength(); i++) { Node fctDefNode = nList.item(i); if (fctDefNode.getNodeType() == Node.ELEMENT_NODE) { Xnode dummyFctDef = new Xnode((Element)fctDefNode); Xnode fctDefName = dummyFctDef.find(Xcode.NAME); if(name != null && fctDefName.getValue().toLowerCase().equals(name.toLowerCase())) { return new XfunctionDefinition(dummyFctDef.getElement()); } } } return null; } /** * Find a function definition in a module definition. * @param module Module definition in which we search for the function * definition. * @param name Name of the function to be found. * @return A function definition element if found. Null otherwise. */ public static XfunctionDefinition findFunctionDefinitionInModule( XmoduleDefinition module, String name) { if(module.getElement() == null){ return null; } NodeList nList = module.getElement(). getElementsByTagName(Xname.F_FUNCTION_DEFINITION); for (int i = 0; i < nList.getLength(); i++) { Node n = nList.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { XfunctionDefinition fctDef = new XfunctionDefinition((Element)n); if(fctDef.getName().getValue().equals(name)){ return fctDef; } } } return null; } /** * Find all array references elements in a given body and give var name. * @param parent The body element to search for the array references. * @param arrayName Name of the array for the array reference to be found. * @return A list of all array references found. */ public static List<Xnode> getAllArrayReferences(Xnode parent, String arrayName) { List<Xnode> references = new ArrayList<>(); NodeList nList = parent.getElement(). getElementsByTagName(Xname.F_ARRAY_REF); for (int i = 0; i < nList.getLength(); i++) { Node n = nList.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { Xnode ref = new Xnode((Element) n); Xnode var = ref.find(Xcode.VARREF, Xcode.VAR); if(var != null && var.getValue().toLowerCase(). equals(arrayName.toLowerCase())) { references.add(ref); } } } return references; } /** * Find all function definitions in an XcodeML unit. * @param xcodeml Current XcodeML unit. * @return A list of all function definitions in the program. */ public static List<XfunctionDefinition> getAllFctDef(XcodeProgram xcodeml) { List<XfunctionDefinition> definitions = new ArrayList<>(); NodeList nList = xcodeml.getElement(). getElementsByTagName(Xname.F_FUNCTION_DEFINITION); for (int i = 0; i < nList.getLength(); i++) { Node n = nList.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { definitions.add(new XfunctionDefinition((Element) n)); } } return definitions; } /** * Find all var references elements in a given body and give var name. * @param parent The body element to search for the array references. * @param varName Name of the var for the reference to be found. * @return A list of all references found. */ public static List<Xnode> getAllVarReferences(Xnode parent, String varName){ List<Xnode> references = new ArrayList<>(); NodeList nList = parent.getElement(). getElementsByTagName(Xname.VAR); for (int i = 0; i < nList.getLength(); i++) { Node n = nList.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { Xnode var = new Xnode((Element) n); if(var.getValue().toLowerCase().equals(varName.toLowerCase())) { references.add(var); } } } return references; } /** * Demote an array reference to a var reference. * @param ref The array reference to be modified. */ public static void demoteToScalar(Xnode ref){ Xnode var = ref.find(Xcode.VARREF, Xcode.VAR).cloneObject(); insertAfter(ref, var); ref.delete(); } /** * Demote an array reference to a reference with fewer dimensions. * @param ref The array reference to be modified. * @param keptDimensions List of dimensions to be kept. Dimension index starts * at 1. */ public static void demote(Xnode ref, List<Integer> keptDimensions){ for(int i = 1; i < ref.getChildren().size(); ++i){ if(!keptDimensions.contains(i)){ ref.getChild(i).delete(); } } } /** * Retrieve the index ranges of an array notation. * @param arrayRef The array reference statements to extract the ranges from. * @return A list if indexRanges elements. */ public static List<Xnode> getIdxRangesFromArrayRef(Xnode arrayRef){ List<Xnode> ranges = new ArrayList<>(); if(arrayRef.opcode() != Xcode.FARRAYREF){ return ranges; } for(Xnode el : arrayRef.getChildren()){ if(el.opcode() == Xcode.INDEXRANGE){ ranges.add(el); } } return ranges; } /** * Compare two list of indexRange. * @param list1 First list of indexRange. * @param list2 Second list of indexRange. * @return True if the indexRange at the same position in the two list are all * identical. False otherwise. */ public static boolean compareIndexRanges(List<Xnode> list1, List<Xnode> list2) { if(list1.size() != list2.size()){ return false; } for(int i = 0; i < list1.size(); ++i){ if(!isIndexRangeIdentical(list1.get(i), list2.get(i), true)){ return false; } } return true; } /** * <pre> * Intersect two sets of elements in XPath 1.0 * * This method use Xpath to select the correct nodes. Xpath 1.0 does not have * the intersect operator but only union. By using the Kaysian Method, we can * it is possible to express the intersection of two node sets. * * $set1[count(.|$set2)=count($set2)] * * </pre> * @param s1 First set of element. * @param s2 Second set of element. * @return Xpath query that performs the intersect operator between s1 and s2. */ private static String xPathIntersect(String s1, String s2){ return String.format("%s[count(.|%s)=count(%s)]", s1, s2, s2); } /** * <pre> * Find all assignment statement from a node until the end pragma. * * We intersect all assign statements which are next siblings of * the "from" element with all the assign statements which are previous * siblings of the ending pragma. * </pre> * * @param from The element from which the search is initiated. * @param endPragma Value of the end pragma. Search will be performed until * there. * @return A list of all assign statements found. List is empty if no * statements are found. */ public static List<Xnode> getArrayAssignInBlock(Xnode from, String endPragma){ /* Define all the assign element with array refs which are next siblings of * the "from" element */ String s1 = String.format( "following-sibling::%s[%s]", Xname.F_ASSIGN_STMT, Xname.F_ARRAY_REF ); /* Define all the assign element with array refs which are previous siblings * of the end pragma element */ String s2 = String.format( "following-sibling::%s[text()=\"%s\"]/preceding-sibling::%s[%s]", Xname.PRAGMA_STMT, endPragma, Xname.F_ASSIGN_STMT, Xname.F_ARRAY_REF ); // Use the Kaysian method to express the intersect operator String intersect = XnodeUtil.xPathIntersect(s1, s2); return getFromXpath(from, intersect); } /** * Get all array references in the siblings of the given element. * @param from Element to start from. * @param identifier Array name value. * @return List of all array references found. List is empty if nothing is * found. */ public static List<Xnode> getAllArrayReferencesInSiblings(Xnode from, String identifier) { String s1 = String.format("following-sibling::*//%s[%s[%s[text()=\"%s\"]]]", Xname.F_ARRAY_REF, Xname.VAR_REF, Xname.VAR, identifier ); return getFromXpath(from, s1); } /** * Get the first assignment statement for an array reference. * @param from Statement to look from. * @param arrayName Identifier of the array. * @return The assignment statement if found. Null otherwise. */ public static Xnode getFirstArrayAssign(Xnode from, String arrayName){ String s1 = String.format( "following::%s[%s[%s[%s[text()=\"%s\"]] and position()=1]]", Xname.F_ASSIGN_STMT, Xname.F_ARRAY_REF, Xname.VAR_REF, Xname.VAR, arrayName ); try { NodeList output = evaluateXpath(from.getElement(), s1); if(output.getLength() == 0){ return null; } Element assign = (Element) output.item(0); return new Xnode(assign); } catch (XPathExpressionException ignored) { return null; } } /** * Find all the nested do statement groups following the inductions iterations * define in inductionVars and being located between the "from" element and * the end pragma. * @param from Element from which the search is started. * @param endPragma End pragma that terminates the search block. * @param inductionVars Induction variables that define the nested group to * locates. * @return List of do statements elements (outer most loops for each nested * group) found between the "from" element and the end pragma. */ public static List<Xnode> findDoStatement(Xnode from, Xnode endPragma, List<String> inductionVars) { /* s1 is selecting all the nested do statement groups that meet the criteria * from the "from" element down to the end of the block. */ String s1 = "following::"; String dynamic_part_s1 = ""; for(int i = inductionVars.size() - 1; i >= 0; --i){ /* * Here is example of there xpath query format for 1,2 and 3 nested loops * * FdoStatement[Var[text()="induction_var"]] * * FdoStatement[Var[text()="induction_var"] and * body[FdoStatement[Var[text()="induction_var"]]] * * FdoStatement[Var[text()="induction_var"] and * body[FdoStatement[Var[text()="induction_var"] and * body[FdoStatement[Var[text()="induction_var"]]]] */ String tempQuery; if(i == inductionVars.size() - 1) { // first iteration tempQuery = String.format("%s[%s[text()=\"%s\"]]", Xname.F_DO_STATEMENT, Xname.VAR, inductionVars.get(i)); } else { tempQuery = String.format("%s[%s[text()=\"%s\"] and %s[%s]]", Xname.F_DO_STATEMENT, Xname.VAR, inductionVars.get(i), Xname.BODY, dynamic_part_s1); // Including previously formed xpath query } dynamic_part_s1 = tempQuery; } s1 = s1 + dynamic_part_s1; List<Xnode> doStatements = new ArrayList<>(); try { NodeList output = evaluateXpath(from.getElement(), s1); for (int i = 0; i < output.getLength(); i++) { Element el = (Element) output.item(i); Xnode doStmt = new Xnode(el); if(doStmt.getLineNo() != 0 && doStmt.getLineNo() < endPragma.getLineNo()) { doStatements.add(doStmt); } } } catch (XPathExpressionException ignored) { } return doStatements; } /** * Evaluates an Xpath expression and return its result as a NodeList. * @param from Element to start the evaluation. * @param xpath Xpath expression. * @return Result of evaluation as a NodeList. * @throws XPathExpressionException if evaluation fails. */ private static NodeList evaluateXpath(Element from, String xpath) throws XPathExpressionException { XPathExpression ex = XPathFactory.newInstance().newXPath().compile(xpath); return (NodeList)ex.evaluate(from, XPathConstants.NODESET); } /** * Find all array references in the next children that match the given * criteria. * * This methods use powerful Xpath expression to locate the correct nodes in * the AST * * Here is an example of such a query that return all node that are array * references for the array "array6" with an offset of 0 -1 * * //FarrayRef[varRef[Var[text()="array6"]] and arrayIndex and * arrayIndex[minusExpr[Var and FintConstant[text()="1"]]]] * * @param from The element from which the search is initiated. * @param identifier Identifier of the array. * @param offsets List of offsets to be search for. * @return A list of all array references found. */ public static List<Xnode> getAllArrayReferencesByOffsets(Xnode from, String identifier, List<Integer> offsets) { String offsetXpath = ""; for (int i = 0; i < offsets.size(); ++i){ if(offsets.get(i) == 0){ offsetXpath += String.format("%s[position()=%s and %s]", Xname.ARRAY_INDEX, i+1, Xname.VAR ); } else if(offsets.get(i) > 0) { offsetXpath += String.format("%s[position()=%s and %s[%s and %s[text()=\"%s\"]]]", Xname.ARRAY_INDEX, i+1, Xname.MINUS_EXPR, Xname.VAR, Xname.F_INT_CONST, offsets.get(i)); } else { offsetXpath += String.format("%s[position()=%s and %s[%s and %s[text()=\"%s\"]]]", Xname.ARRAY_INDEX, i+1, Xname.MINUS_EXPR, Xname.VAR, Xname.F_INT_CONST, Math.abs(offsets.get(i))); } if(i != offsets.size()-1){ offsetXpath += " and "; } } // Start of the Xpath query String xpathQuery = String.format(".//%s[%s[%s[text()=\"%s\"]] and %s]", Xname.F_ARRAY_REF, Xname.VAR_REF, Xname.VAR, identifier, offsetXpath ); return getFromXpath(from, xpathQuery); } /** * Find a pragma element in the previous nodes containing a given keyword. * @param from Element to start from. * @param keyword Keyword to be found in the pragma. * @return The pragma if found. Null otherwise. */ public static Xnode findPreviousPragma(Xnode from, String keyword) { if (from == null || from.getElement() == null) { return null; } Node prev = from.getElement().getPreviousSibling(); Node parent = from.getElement(); do { while (prev != null) { if (prev.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) prev; if (element.getTagName().equals(Xcode.FPRAGMASTATEMENT.code()) && element.getTextContent().toLowerCase(). contains(keyword.toLowerCase())) { return new Xnode(element); } } prev = prev.getPreviousSibling(); } parent = parent.getParentNode(); prev = parent; } while (parent != null); return null; } /** * Find all the index elements (arrayIndex and indexRange) in an element. * @param parent Root element to search from. * @return A list of all index ranges found. */ public static List<Xnode> findIndexes(Xnode parent){ List<Xnode> indexRanges = new ArrayList<>(); if(parent == null || parent.getElement() == null){ return indexRanges; } Node node = parent.getElement().getFirstChild(); while (node != null){ if(node.getNodeType() == Node.ELEMENT_NODE){ Element element = (Element)node; switch (element.getTagName()){ case Xname.ARRAY_INDEX: case Xname.INDEX_RANGE: indexRanges.add(new Xnode(element)); break; } } node = node.getNextSibling(); } return indexRanges; } /** * Find all the name elements in an element. * @param parent Root element to search from. * @return A list of all name elements found. */ public static List<Xnode> findAllNames(Xnode parent){ return findAll(Xcode.NAME, parent); } /** * Find all the var elements that are real references to a variable. Var * element nested in an arrayIndex element are excluded. * @param parent Root element to search from. * @return A list of all var elements found. */ public static List<Xnode> findAllReferences(Xnode parent){ List<Xnode> vars = findAll(Xcode.VAR, parent); List<Xnode> realReferences = new ArrayList<>(); for(Xnode var : vars){ if(!((Element)var.getElement().getParentNode()).getTagName(). equals(Xcode.ARRAYINDEX.code())) { realReferences.add(var); } } return realReferences; } /** * Find all the var elements that are real references to a variable. Var * element nested in an arrayIndex element are excluded. * @param parent Root element to search from. * @param id Identifier of the var to be found. * @return A list of all var elements found. */ public static List<Xnode> findAllReferences(Xnode parent, String id){ List<Xnode> vars = findAll(Xcode.VAR, parent); List<Xnode> realReferences = new ArrayList<>(); for(Xnode var : vars){ if(!((Element)var.getElement().getParentNode()).getTagName(). equals(Xcode.ARRAYINDEX.code()) && var.getValue().toLowerCase().equals(id.toLowerCase())) { realReferences.add(var); } } return realReferences; } /** * Find all the pragma element in an XcodeML tree. * @param xcodeml The XcodeML program to search in. * @return A list of all pragmas found in the XcodeML program. */ public static List<Xnode> findAllPragmas(XcodeProgram xcodeml){ NodeList pragmaList = xcodeml.getDocument() .getElementsByTagName(Xcode.FPRAGMASTATEMENT.code()); List<Xnode> pragmas = new ArrayList<>(); for (int i = 0; i < pragmaList.getLength(); i++) { Node pragmaNode = pragmaList.item(i); if (pragmaNode.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) pragmaNode; pragmas.add(new Xnode(element)); } } return pragmas; } /** * Extract the body of a do statement and place it directly after it. * @param loop The do statement containing the body to be extracted. */ public static void extractBody(Xnode loop){ extractBody(loop, loop); } /** * Extract the body of a do statement and place it after the reference node. * @param loop The do statement containing the body to be extracted. * @param ref Element after which statement are shifted. */ public static void extractBody(Xnode loop, Xnode ref){ Element loopElement = loop.getElement(); Element body = XnodeUtil.findFirstElement(loopElement, Xname.BODY); if(body == null){ return; } Node refNode = ref.getElement(); for(Node childNode = body.getFirstChild(); childNode!=null;){ Node nextChild = childNode.getNextSibling(); // Do something with childNode, including move or delete... if(childNode.getNodeType() == Node.ELEMENT_NODE){ insertAfter(refNode, childNode); refNode = childNode; } childNode = nextChild; } } /** * Delete an element for the tree. * @param element Element to be deleted. */ public static void delete(Node element){ if(element == null || element.getParentNode() == null){ return; } element.getParentNode().removeChild(element); } /** * Write the XcodeML to file or std out * @param xcodeml The XcodeML to write in the output * @param outputFile Path of the output file or null to output on std out * @param indent Number of spaces used for the indentation * @throws IllegalTransformationException if XML file cannot be written. */ public static void writeXcodeML(XcodeML xcodeml, String outputFile, int indent) throws IllegalTransformationException { try { XnodeUtil.cleanEmptyTextNodes(xcodeml.getDocument()); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", Integer.toString(indent)); DOMSource source = new DOMSource(xcodeml.getDocument()); if(outputFile == null){ // Output to console StreamResult console = new StreamResult(System.out); transformer.transform(source, console); } else { // Output to file StreamResult console = new StreamResult(new File(outputFile)); transformer.transform(source, console); } } catch (Exception ignored){ throw new IllegalTransformationException("Cannot output file: " + outputFile, 0); } } /** * Removes text nodes that only contains whitespace. The conditions for * removing text nodes, besides only containing whitespace, are: If the * parent node has at least one child of any of the following types, all * whitespace-only text-node children will be removed: - ELEMENT child - * CDATA child - COMMENT child. * @param parentNode Root node to start the cleaning. */ private static void cleanEmptyTextNodes(Node parentNode) { boolean removeEmptyTextNodes = false; Node childNode = parentNode.getFirstChild(); while (childNode != null) { removeEmptyTextNodes |= checkNodeTypes(childNode); childNode = childNode.getNextSibling(); } if (removeEmptyTextNodes) { removeEmptyTextNodes(parentNode); } } /* * PRIVATE SECTION */ /** * Remove all empty text nodes in the subtree. * @param parentNode Root node to start the search. */ private static void removeEmptyTextNodes(Node parentNode) { Node childNode = parentNode.getFirstChild(); while (childNode != null) { // grab the "nextSibling" before the child node is removed Node nextChild = childNode.getNextSibling(); short nodeType = childNode.getNodeType(); if (nodeType == Node.TEXT_NODE) { boolean containsOnlyWhitespace = childNode.getNodeValue() .trim().isEmpty(); if (containsOnlyWhitespace) { parentNode.removeChild(childNode); } } childNode = nextChild; } } /** * Check the type of the given node. * @param childNode Node to be checked. * @return True if the node contains data. False otherwise. */ private static boolean checkNodeTypes(Node childNode) { short nodeType = childNode.getNodeType(); if (nodeType == Node.ELEMENT_NODE) { cleanEmptyTextNodes(childNode); // recurse into subtree } return nodeType == Node.ELEMENT_NODE || nodeType == Node.CDATA_SECTION_NODE || nodeType == Node.COMMENT_NODE; } /** * Insert a node directly after a reference node. * @param refNode The reference node. New node will be inserted after this * one. * @param newNode The new node to be inserted. */ private static void insertAfter(Node refNode, Node newNode){ refNode.getParentNode().insertBefore(newNode, refNode.getNextSibling()); } /** * Find the first element with tag corresponding to elementName nested under * the parent element. * @param parent The root element to search from. * @param elementName The tag of the element to search for. * @return The first element found under parent with the corresponding tag. * Null if no element is found. */ private static Element findFirstElement(Element parent, String elementName){ NodeList elements = parent.getElementsByTagName(elementName); if(elements.getLength() == 0){ return null; } return (Element) elements.item(0); } /** * Find the first element with tag corresponding to elementName in the direct * children of the parent element. * @param parent The root element to search from. * @param elementName The tag of the element to search for. * @return The first element found in the direct children of the element * parent with the corresponding tag. Null if no element is found. */ private static Element findFirstChildElement(Element parent, String elementName){ NodeList nodeList = parent.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node nextNode = nodeList.item(i); if(nextNode.getNodeType() == Node.ELEMENT_NODE){ Element element = (Element) nextNode; if(element.getTagName().equals(elementName)){ return element; } } } return null; } /** * Get the depth of an element in the AST. * @param element XML element for which the depth is computed. * @return A depth value greater or equal to 0. */ private static int getDepth(Element element){ Node parent = element.getParentNode(); int depth = 0; while(parent != null && parent.getNodeType() == Node.ELEMENT_NODE) { ++depth; parent = parent.getParentNode(); } return depth; } /** * Shift all statements from the first siblings of the "from" element until * the "until" element (not included). * @param from Start element for the swifting. * @param until End element for the swifting. * @param targetBody Body element in which statements are inserted. */ public static void shiftStatementsInBody(Xnode from, Xnode until, Xnode targetBody) { Node currentSibling = from.getElement().getNextSibling(); Node firstStatementInBody = targetBody.getElement().getFirstChild(); while(currentSibling != null && currentSibling != until.getElement()){ Node nextSibling = currentSibling.getNextSibling(); targetBody.getElement().insertBefore(currentSibling, firstStatementInBody); currentSibling = nextSibling; } } /** * Copy the whole body element into the destination one. Destination is * overwritten. * @param from The body to be copied. * @param to The destination of the copied body. */ public static void copyBody(Xnode from, Xnode to){ Node copiedBody = from.cloneNode(); if(to.getBody() != null){ to.getBody().delete(); } to.getElement().appendChild(copiedBody); } /** * Check whether the given type is a built-in type or is a type defined in the * type table. * @param type Type to check. * @return True if the type is built-in. False otherwise. */ public static boolean isBuiltInType(String type){ switch (type){ case Xname.TYPE_F_CHAR: case Xname.TYPE_F_COMPLEX: case Xname.TYPE_F_INT: case Xname.TYPE_F_LOGICAL: case Xname.TYPE_F_REAL: case Xname.TYPE_F_VOID: return true; default: return false; } } /* XNODE SECTION */ /** * Find module definition element in which the child is included if any. * @param from The child element to search from. * @return A XmoduleDefinition object if found. Null otherwise. */ public static XmoduleDefinition findParentModule(Xnode from) { Xnode moduleDef = findParent(Xcode.FMODULEDEFINITION, from); if(moduleDef == null){ return null; } return new XmoduleDefinition(moduleDef.getElement()); } /** * Find function definition in the ancestor of the give element. * @param from Element to start search from. * @return The function definition found. Null if nothing found. */ public static XfunctionDefinition findParentFunction(Xnode from){ Xnode fctDef = findParent(Xcode.FFUNCTIONDEFINITION, from); if(fctDef == null){ return null; } return new XfunctionDefinition(fctDef.getElement()); } /** * Find element of the the given type that is directly after the given from * element. * @param opcode Code of the element to be found. * @param from Element to start the search from. * @return The element found. Null if no element is found. */ public static Xnode findDirectNext(Xcode opcode, Xnode from) { if(from == null){ return null; } Node nextNode = from.getElement().getNextSibling(); while (nextNode != null){ if(nextNode.getNodeType() == Node.ELEMENT_NODE){ Element element = (Element) nextNode; if(element.getTagName().equals(opcode.code())){ return new Xnode(element); } return null; } nextNode = nextNode.getNextSibling(); } return null; } /** * Delete all the elements between the two given elements. * @param start The start element. Deletion start from next element. * @param end The end element. Deletion end just before this element. */ public static void deleteBetween(Xnode start, Xnode end){ List<Element> toDelete = new ArrayList<>(); Node node = start.getElement().getNextSibling(); while (node != null && node != end.getElement()){ if(node.getNodeType() == Node.ELEMENT_NODE){ Element element = (Element)node; toDelete.add(element); } node = node.getNextSibling(); } for(Element e : toDelete){ delete(e); } } /** * Insert an element just after a reference element. * @param refElement The reference element. * @param element The element to be inserted. */ public static void insertAfter(Xnode refElement, Xnode element){ XnodeUtil.insertAfter(refElement.getElement(), element.getElement()); } /** * Find the first element with tag corresponding to elementName. * @param opcode The XcodeML code of the element to search for. * @param parent The root element to search from. * @param any If true, find in any nested element under parent. If false, * only direct children are search for. * @return first element found. Null if no element is found. */ public static Xnode find(Xcode opcode, Xnode parent, boolean any){ Element el; if(any){ el = findFirstElement(parent.getElement(), opcode.code()); } else { el = findFirstChildElement(parent.getElement(), opcode.code()); } return (el == null) ? null : new Xnode(el); } /** * Find element of the the given type that is directly after the given from * element. * @param opcode Code of the element to be found. * @param from Element to start the search from. * @return The element found. Null if no element is found. */ public static Xnode findNext(Xcode opcode, Xnode from) { return findInDirection(opcode, from, true); } /** * Find an element in the ancestor of the given element. * @param opcode Code of the element to be found. * @param from Element to start the search from. * @return The element found. Null if nothing found. */ public static Xnode findParent(Xcode opcode, Xnode from){ return findInDirection(opcode, from, false); } /** * Find an element either in the next siblings or in the ancestors. * @param opcode Code of the element to be found. * @param from Element to start the search from. * @param down If True, search in the siblings. If false, search in the * ancestors. * @return The element found. Null if nothing found. */ private static Xnode findInDirection(Xcode opcode, Xnode from, boolean down){ if(from == null){ return null; } Node nextNode = down ? from.getElement().getNextSibling() : from.getElement().getParentNode(); while(nextNode != null){ if (nextNode.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) nextNode; if(element.getTagName().equals(opcode.code())){ return new Xnode(element); } } nextNode = down ? nextNode.getNextSibling() : nextNode.getParentNode(); } return null; } /** * Insert all the statements from a given body at the end of another body * @param originalBody The body in which the extra body will be appended * @param extraBody The body that will be appended to the original body * @throws IllegalTransformationException if one of the body or their base * element is null. */ public static void appendBody(Xnode originalBody, Xnode extraBody) throws IllegalTransformationException { if(originalBody == null || originalBody.getElement() == null || extraBody == null || extraBody.getElement() == null || originalBody.opcode() != Xcode.BODY || extraBody.opcode() != Xcode.BODY) { throw new IllegalTransformationException("One of the body is null."); } // Append content of loop-body (loop) to this loop-body Node childNode = extraBody.getElement().getFirstChild(); while(childNode != null){ Node nextChild = childNode.getNextSibling(); // Do something with childNode, including move or delete... if(childNode.getNodeType() == Node.ELEMENT_NODE){ originalBody.getElement().appendChild(childNode); } childNode = nextChild; } } /** * Check if the two element are direct children of the same parent element. * @param e1 First element. * @param e2 Second element. * @return True if the two element are direct children of the same parent. * False otherwise. */ public static boolean hasSameParentBlock(Xnode e1, Xnode e2) { return !(e1 == null || e2 == null || e1.getElement() == null || e2.getElement() == null) && e1.getElement().getParentNode() == e2.getElement().getParentNode(); } /** Compare the iteration range of two do statements. * @param e1 First do statement. * @param e2 Second do statement. * @param withLowerBound Compare lower bound or not. * @return True if the iteration range are identical. */ private static boolean compareIndexRanges(Xnode e1, Xnode e2, boolean withLowerBound) { // The two nodes must be do statement if (e1.opcode() != Xcode.FDOSTATEMENT || e2.opcode() != Xcode.FDOSTATEMENT) { return false; } Xnode inductionVar1 = XnodeUtil.find(Xcode.VAR, e1, false); Xnode inductionVar2 = XnodeUtil.find(Xcode.VAR, e2, false); Xnode indexRange1 = XnodeUtil.find(Xcode.INDEXRANGE, e1, false); Xnode indexRange2 = XnodeUtil.find(Xcode.INDEXRANGE, e2, false); return compareValues(inductionVar1, inductionVar2) && isIndexRangeIdentical(indexRange1, indexRange2, withLowerBound); } /** * Compare the iteration range of two do statements. * @param e1 First do statement. * @param e2 Second do statement. * @return True if the iteration range are identical. */ public static boolean hasSameIndexRange(Xnode e1, Xnode e2) { return compareIndexRanges(e1, e2, true); } /** * Compare the iteration range of two do statements. * @param e1 First do statement. * @param e2 Second do statement. * @return True if the iteration range are identical besides the lower bound. */ public static boolean hasSameIndexRangeBesidesLower(Xnode e1, Xnode e2) { return compareIndexRanges(e1, e2, false); } /** * Compare the inner values of two nodes. * @param n1 First node. * @param n2 Second node. * @return True if the values are identical. False otherwise. */ private static boolean compareValues(Xnode n1, Xnode n2) { return !(n1 == null || n2 == null) && n1.getValue().toLowerCase().equals(n2.getValue().toLowerCase()); } /** * Compare the inner value of the first child of two nodes. * @param n1 First node. * @param n2 Second node. * @return True if the value are identical. False otherwise. */ private static boolean compareFirstChildValues(Xnode n1, Xnode n2) { if(n1 == null || n2 == null){ return false; } Xnode c1 = n1.getChild(0); Xnode c2 = n2.getChild(0); return compareValues(c1, c2); } /** * Compare the inner values of two optional nodes. * @param n1 First node. * @param n2 Second node. * @return True if the values are identical or elements are null. False * otherwise. */ private static boolean compareOptionalValues(Xnode n1, Xnode n2){ return n1 == null && n2 == null || (n1 != null && n2 != null && n1.getValue().toLowerCase().equals(n2.getValue().toLowerCase())); } /** * Compare the iteration range of two do statements * @param idx1 First do statement. * @param idx2 Second do statement. * @param withLowerBound If true, compare lower bound. If false, lower bound * is not compared. * @return True if the index range are identical. */ private static boolean isIndexRangeIdentical(Xnode idx1, Xnode idx2, boolean withLowerBound) { if (idx1.opcode() != Xcode.INDEXRANGE || idx2.opcode() != Xcode.INDEXRANGE) { return false; } if (idx1.getBooleanAttribute(Xattr.IS_ASSUMED_SHAPE) && idx2.getBooleanAttribute(Xattr.IS_ASSUMED_SHAPE)) { return true; } Xnode low1 = idx1.find(Xcode.LOWERBOUND); Xnode up1 = idx1.find(Xcode.UPPERBOUND); Xnode low2 = idx2.find(Xcode.LOWERBOUND); Xnode up2 = idx2.find(Xcode.UPPERBOUND); Xnode s1 = idx1.find(Xcode.STEP); Xnode s2 = idx2.find(Xcode.STEP); if (s1 != null) { s1 = s1.getChild(0); } if (s2 != null) { s2 = s2.getChild(0); } if(withLowerBound){ return compareFirstChildValues(low1, low2) && compareFirstChildValues(up1, up2) && compareOptionalValues(s1, s2); } else { return compareFirstChildValues(up1, up2) && compareOptionalValues(s1, s2); } } /** * Swap the iteration range information of two do statement. * @param e1 First do statement. * @param e2 Second do statement. * @throws IllegalTransformationException if necessary elements are missing * to apply the transformation. */ public static void swapIterationRange(Xnode e1, Xnode e2) throws IllegalTransformationException { // The two nodes must be do statement if(e1.opcode() != Xcode.FDOSTATEMENT || e2.opcode() != Xcode.FDOSTATEMENT){ return; } Xnode inductionVar1 = XnodeUtil.find(Xcode.VAR, e1, false); Xnode inductionVar2 = XnodeUtil.find(Xcode.VAR, e2, false); Xnode indexRange1 = XnodeUtil.find(Xcode.INDEXRANGE, e1, false); Xnode indexRange2 = XnodeUtil.find(Xcode.INDEXRANGE, e2, false); if(inductionVar1 == null || inductionVar2 == null || indexRange1 == null || indexRange2 == null) { throw new IllegalTransformationException("Induction variable or index " + "range missing."); } Xnode low1 = indexRange1.find(Xcode.LOWERBOUND).getChild(0); Xnode up1 = indexRange1.find(Xcode.UPPERBOUND).getChild(0); Xnode s1 = indexRange1.find(Xcode.STEP).getChild(0); Xnode low2 = indexRange2.find(Xcode.LOWERBOUND).getChild(0); Xnode up2 = indexRange2.find(Xcode.UPPERBOUND).getChild(0); Xnode s2 = indexRange2.find(Xcode.STEP).getChild(0); // Set the range of loop2 to loop1 XnodeUtil.insertAfter(inductionVar2, inductionVar1.cloneObject()); XnodeUtil.insertAfter(low2, low1.cloneObject()); XnodeUtil.insertAfter(up2, up1.cloneObject()); XnodeUtil.insertAfter(s2, s1.cloneObject()); XnodeUtil.insertAfter(inductionVar1, inductionVar2.cloneObject()); XnodeUtil.insertAfter(low1, low2.cloneObject()); XnodeUtil.insertAfter(up1, up2.cloneObject()); XnodeUtil.insertAfter(s1, s2.cloneObject()); inductionVar1.delete(); inductionVar2.delete(); low1.delete(); up1.delete(); s1.delete(); low2.delete(); up2.delete(); s2.delete(); } /** * Get the depth of an element in the AST. * @param element The element for which the depth is computed. * @return A depth value greater or equal to 0. */ public static int getDepth(Xnode element) { if(element == null || element.getElement() == null){ return -1; } return getDepth(element.getElement()); } /** * Copy the enhanced information from an element to a target element. * Enhanced information include line number and original file name. * @param base Base element to copy information from. * @param target Target element to copy information to. */ public static void copyEnhancedInfo(Xnode base, Xnode target) { target.setLine(base.getLineNo()); target.setFile(base.getFile()); } /** * Insert an element just before a reference element. * @param ref The reference element. * @param insert The element to be inserted. */ public static void insertBefore(Xnode ref, Xnode insert){ ref.getElement().getParentNode().insertBefore(insert.getElement(), ref.getElement()); } /** * Get a list of T elements from an xpath query executed from the * given element. * @param from Element to start from. * @param query XPath query to be executed. * @return List of all array references found. List is empty if nothing is * found. */ private static List<Xnode> getFromXpath(Xnode from, String query) { List<Xnode> elements = new ArrayList<>(); try { XPathExpression ex = XPathFactory.newInstance().newXPath().compile(query); NodeList output = (NodeList) ex.evaluate(from.getElement(), XPathConstants.NODESET); for (int i = 0; i < output.getLength(); i++) { Element element = (Element) output.item(i); elements.add(new Xnode(element)); } } catch (XPathExpressionException ignored) { } return elements; } /** * Find specific argument in a function call. * @param value Value of the argument to be found. * @param fctCall Function call to search from. * @return The argument if found. Null otherwise. */ public static Xnode findArg(String value, Xnode fctCall){ if(fctCall.opcode() != Xcode.FUNCTIONCALL) { return null; } Xnode args = fctCall.find(Xcode.ARGUMENTS); if(args == null){ return null; } for(Xnode arg : args.getChildren()){ if(value.toLowerCase().equals(arg.getValue().toLowerCase())){ return arg; } } return null; } /** * Find all elements of a given type in the subtree. * @param opcode Type of the element to be found. * @param parent Root of the subtree. * @return List of all elements found in the subtree. */ public static List<Xnode> findAll(Xcode opcode, Xnode parent) { List<Xnode> elements = new ArrayList<>(); if(parent == null) { return elements; } NodeList nodes = parent.getElement().getElementsByTagName(opcode.code()); for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { elements.add(new Xnode((Element)n)); } } return elements; } /** * Create a new FunctionCall element with elements name and arguments as * children. * @param xcodeml The current XcodeML unit in which the elements are * created. * @param returnType Value of the type attribute for the functionCall element. * @param name Value of the name element. * @param nameType Value of the type attribute for the name element. * @return The newly created element. */ public static Xnode createFctCall(XcodeML xcodeml, String returnType, String name, String nameType){ Xnode fctCall = new Xnode(Xcode.FUNCTIONCALL, xcodeml); fctCall.setAttribute(Xattr.TYPE, returnType); Xnode fctName = new Xnode(Xcode.NAME, xcodeml); fctName.setValue(name); fctName.setAttribute(Xattr.TYPE, nameType); Xnode args = new Xnode(Xcode.ARGUMENTS, xcodeml); fctCall.appendToChildren(fctName, false); fctCall.appendToChildren(args, false); return fctCall; } /** * Create a new FarrayRef element with varRef element as a child with the * given Var element. * @param xcodeml The current XcodeML unit in which the elements are created. * @param type Value of the type attribute for the FarrayRef element. * @param var Var element nested in the varRef element. * @return The newly created element. */ public static Xnode createArrayRef(XcodeML xcodeml, XbasicType type, Xnode var) { Xnode ref = new Xnode(Xcode.FARRAYREF, xcodeml); ref.setAttribute(Xattr.TYPE, type.getRef()); Xnode varRef = new Xnode(Xcode.VARREF, xcodeml); varRef.setAttribute(Xattr.TYPE, type.getType()); varRef.appendToChildren(var, false); ref.appendToChildren(varRef, false); return ref; } /** * Create a new Id element with all the underlying needed elements. * @param xcodeml The current XcodeML program unit in which the elements * are created. * @param type Value for the attribute type. * @param sclass Value for the attribute sclass. * @param nameValue Value of the name inner element. * @return The newly created element. */ public static Xid createId(XcodeML xcodeml, String type, String sclass, String nameValue) { Xnode id = new Xnode(Xcode.ID, xcodeml); Xnode internalName = new Xnode(Xcode.NAME, xcodeml); internalName.setValue(nameValue); id.appendToChildren(internalName, false); id.setAttribute(Xattr.TYPE, type); id.setAttribute(Xattr.SCLASS, sclass); return new Xid(id.getElement()); } /** * Constructs a new basicType element with the given information. * @param xcodeml The current XcodeML file unit in which the elements * are created. * @param type Type hash. * @param ref Reference type. * @param intent Optional intent information. * @return The newly created element. */ public static XbasicType createBasicType(XcodeML xcodeml, String type, String ref, Xintent intent) { Xnode bt = new Xnode(Xcode.FBASICTYPE, xcodeml); bt.setAttribute(Xattr.TYPE, type); if(ref != null) { bt.setAttribute(Xattr.REF, ref); } if(intent != null) { bt.setAttribute(Xattr.INTENT, intent.toString()); } return new XbasicType(bt.getElement()); } /** * Create a new Xdecl object with all the underlying elements for a varDecl. * @param xcodeml The current XcodeML file unit in which the elements * are created. * @param nameType Value for the attribute type of the name element. * @param nameValue Value of the name inner element. * @return The newly created element. */ public static Xdecl createVarDecl(XcodeML xcodeml, String nameType, String nameValue) { Xnode varD = new Xnode(Xcode.VARDECL, xcodeml); Xnode internalName = new Xnode(Xcode.NAME, xcodeml); internalName.setValue(nameValue); internalName.setAttribute(Xattr.TYPE, nameType); varD.appendToChildren(internalName, false); return new Xdecl(varD.getElement()); } /** * Constructs a new name element with name value and optional type. * @param xcodeml Current XcodeML file unit in which the element is * created. * @param name Name value. * @param type Optional type value. * @return The newly created element. */ private static Xnode createName(XcodeML xcodeml, String name, String type) { Xnode n = new Xnode(Xcode.NAME, xcodeml); n.setValue(name); if(type != null){ n.setAttribute(Xattr.TYPE, type); } return n; } /** * Create an empty assumed shape indexRange element. * @param xcodeml Current XcodeML file unit in which the element is * created. * @return The newly created element. */ public static Xnode createEmptyAssumedShaped(XcodeML xcodeml) { Xnode range = new Xnode(Xcode.INDEXRANGE, xcodeml); range.setAttribute(Xattr.IS_ASSUMED_SHAPE, Xname.TRUE); return range; } /** * Create an indexRange element to loop over an assumed shape array. * @param xcodeml Current XcodeML file unit in which the element is * created. * @param arrayVar Var element representing the array variable. * @param startIndex Lower bound index value. * @param dimension Dimension index for the upper bound value. * @return The newly created element. */ public static Xnode createAssumedShapeRange(XcodeML xcodeml, Xnode arrayVar, int startIndex, int dimension) { // Base structure Xnode indexRange = new Xnode(Xcode.INDEXRANGE, xcodeml); Xnode lower = new Xnode(Xcode.LOWERBOUND, xcodeml); Xnode upper = new Xnode(Xcode.UPPERBOUND, xcodeml); indexRange.appendToChildren(lower, false); indexRange.appendToChildren(upper, false); // Lower bound Xnode lowerBound = new Xnode(Xcode.FINTCONSTANT, xcodeml); lowerBound.setValue(String.valueOf(startIndex)); lower.appendToChildren(lowerBound, false); // Upper bound Xnode fctCall = new Xnode(Xcode.FUNCTIONCALL, xcodeml); upper.appendToChildren(fctCall, false); fctCall.setAttribute(Xattr.IS_INTRINSIC, Xname.TRUE); fctCall.setAttribute(Xattr.TYPE, Xname.TYPE_F_INT); Xnode name = new Xnode(Xcode.NAME, xcodeml); name.setValue(Xname.INTRINSIC_SIZE); fctCall.appendToChildren(name, false); Xnode args = new Xnode(Xcode.ARGUMENTS, xcodeml); fctCall.appendToChildren(args, false); args.appendToChildren(arrayVar, true); Xnode dim = new Xnode(Xcode.FINTCONSTANT, xcodeml); dim.setValue(String.valueOf(dimension)); args.appendToChildren(dim, false); return indexRange; } /** * Create a new FifStatement element with an empty then body. * @param xcodeml Current XcodeML file unit in which the element is * created. * @return The newly created element. */ public static Xnode createIfThen(XcodeML xcodeml){ Xnode root = new Xnode(Xcode.FIFSTATEMENT, xcodeml); Xnode cond = new Xnode(Xcode.CONDITION, xcodeml); Xnode thenBlock = new Xnode(Xcode.THEN, xcodeml); Xnode thenBody = new Xnode(Xcode.BODY, xcodeml); thenBlock.appendToChildren(thenBody, false); root.appendToChildren(cond, false); root.appendToChildren(thenBlock, false); return root; } /** * Create a new FdoStatement element with an empty body. * @param xcodeml Current XcodeML file unit in which the element is * created. * @param inductionVar Var element for the induction variable. * @param indexRange indexRange element for the iteration range. * @return The newly created element. */ public static Xnode createDoStmt(XcodeML xcodeml, Xnode inductionVar, Xnode indexRange) { Xnode root = new Xnode(Xcode.FDOSTATEMENT, xcodeml); root.appendToChildren(inductionVar, false); root.appendToChildren(indexRange, false); Xnode body = new Xnode(Xcode.BODY, xcodeml); root.appendToChildren(body, false); return root; } /** * Create a new var element. * @param type Value of the type attribute. * @param value Value of the var. * @param scope Value of the scope attribute. * @param xcodeml Current XcodeML file unit in which the element is created. * @return The newly created element. */ public static Xnode createVar(String type, String value, Xscope scope, XcodeML xcodeml) { Xnode var = new Xnode(Xcode.VAR, xcodeml); var.setAttribute(Xattr.TYPE, type); var.setAttribute(Xattr.SCOPE, scope.toString()); var.setValue(value); return var; } /** * Create a new namedValue element with its attribute. * @param value Value of the name attribute. * @param xcodeml Current XcodeML file unit in which the element is created. * @return The newly created element. */ public static Xnode createNamedValue(String value, XcodeML xcodeml){ Xnode namedValue = new Xnode(Xcode.NAMEDVALUE, xcodeml); namedValue.setAttribute(Xattr.NAME, value); return namedValue; } /** * Find module containing the function and read its .xmod file. * @param fctDef Function definition nested in the module. * @return Xmod object if the module has been found and read. Null otherwise. */ public static Xmod findContainingModule(XfunctionDefinition fctDef){ XmoduleDefinition mod = findParentModule(fctDef); if(mod == null){ return null; } String modName = mod.getAttribute(Xattr.NAME); return findModule(modName); } /** * Find module by name. * @param moduleName Name of the module. * @return Module object if found. Null otherwise. */ public static Xmod findModule(String moduleName){ for(String dir : XcodeMLtools_Fmod.getSearchPath()){ String path = dir + "/" + moduleName + XMOD_FILE_EXTENSION; File f = new File(path); if(f.exists()){ Document doc = readXmlFile(path); return doc != null ? new Xmod(doc, moduleName, dir) : null; } } return null; } /** * Read XML file. * @param input Xml file path. * @return Document if the XML file could be read. Null otherwise. */ public static Document readXmlFile(String input){ try { File fXmlFile = new File(input); if(!fXmlFile.exists()){ return null; } DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); return doc; } catch(Exception ignored){} return null; } /** * Create the id and varDecl elements and add them to the symbol/declaration * table. * @param name Name of the variable. * @param type Type of the variable. * @param sclass Scope class of the variable (from Xname). * @param fctDef Function definition in which id and decl are created. * @param xcodeml Current XcodeML unit in which the elements will be created. */ public static void createIdAndDecl(String name, String type, String sclass, XfunctionDefinition fctDef, XcodeML xcodeml) { Xid id = XnodeUtil.createId(xcodeml, type, sclass, name); fctDef.getSymbolTable().add(id); Xdecl decl = XnodeUtil.createVarDecl(xcodeml, type, name); fctDef.getDeclarationTable().add(decl); } /** * Create a name element and adds it as a parameter of the given function * type. If the function has optional parameters, the newly created parameter * is added before the optional ones. * @param xcodeml Current XcodeML file unit. * @param nameValue Value of the name element to create. * @param type Type of the name element to create. * @param fctType Function type in which the element will be added as a * parameter. */ public static Xnode createAndAddParam(XcodeML xcodeml, String nameValue, String type, XfunctionType fctType) { Xnode newParam = XnodeUtil.createName(xcodeml, nameValue, type); Xnode hook = null; // Newly created parameter must be added before any optional parameter for(Xnode param : fctType.getParams().getAll()){ XbasicType paramType = (XbasicType) xcodeml. getTypeTable().get(param.getAttribute(Xattr.TYPE)); if(paramType.getBooleanAttribute(Xattr.IS_OPTIONAL)){ hook = param; break; } } if(hook == null){ fctType.getParams().add(newParam); } else { fctType.getParams().addBefore(hook, newParam); } // TODO move method to TransformationHelper newParam.setAttribute(ClawAttr.IS_CLAW.toString(), Xname.TRUE); return newParam; } /** * Create a name element and adds it as a parameter of the given function * type if this parameter is does not exist yet. * @param xcodeml Current XcodeML file unit. * @param nameValue Value of the name element to create. * @param type Type of the name element to create. * @param fctType Function type in which the element will be added as a * parameter. */ public static void createAndAddParamIfNotExists(XcodeML xcodeml, String nameValue, String type, XfunctionType fctType) { for(Xnode p : fctType.getParams().getAll()){ if(p.getValue().toLowerCase().equals(nameValue.toLowerCase())) { return; } } createAndAddParam(xcodeml, nameValue, type, fctType); } /** * Import a type description from one XcodeML unit to another one. If the type * id is not present in the source XcodeML unit, nothing is done. * @param src Source XcodeML unit. * @param dst Destination XcodeML unit. * @param typeId Type id to be imported. */ public static void importType(XcodeML src, XcodeML dst, String typeId){ if(typeId == null || dst.getTypeTable().hasType(typeId)) { return; } Xtype type = src.getTypeTable().get(typeId); if(type == null){ return; } Node rawNode = dst.getDocument().importNode(type.getElement(), true); Xtype importedType = new Xtype((Element)rawNode); dst.getTypeTable().add(importedType); if(importedType.hasAttribute(Xattr.REF) && !XnodeUtil.isBuiltInType(importedType.getAttribute(Xattr.REF))) { XnodeUtil.importType(src, dst, importedType.getAttribute(Xattr.REF)); } // Handle possible type ref in indexRange element List<Xnode> vars = XnodeUtil.findAll(Xcode.VAR, importedType); for(Xnode var : vars){ importType(src, dst, var.getAttribute(Xattr.TYPE)); } } /** * Duplicates the type to update and add extra dimensions to match the base * type. * @param base Base type. * @param toUpdate Type to update. * @param xcodemlDst Destination XcodeML unit. Duplicate will be created here. * @param xcodemlSrc Source XcodeML unit. Contains base dimension. * @return The new type hash generated. */ public static String duplicateWithDimension(XbasicType base, XbasicType toUpdate, XcodeML xcodemlDst, XcodeML xcodemlSrc) throws IllegalTransformationException { XbasicType newType = toUpdate.cloneObject(); String type = xcodemlDst.getTypeTable().generateArrayTypeHash(); newType.setAttribute(Xattr.TYPE, type); if(base.isAllAssumedShape()){ int additionalDimensions = base.getDimensions() - toUpdate.getDimensions(); for(int i = 0; i < additionalDimensions; ++i){ Xnode index = XnodeUtil.createEmptyAssumedShaped(xcodemlDst); newType.addDimension(index, 0); } } else { newType.resetDimension(); for(int i = 0; i < base.getDimensions(); ++i){ Xnode newDim = new Xnode(Xcode.INDEXRANGE, xcodemlDst); newType.appendToChildren(newDim, false); Xnode baseDim = base.getDimensions(i); Xnode lowerBound = baseDim.find(Xcode.LOWERBOUND); Xnode upperBound = baseDim.find(Xcode.UPPERBOUND); // Create lower bound Xnode newLowerBound = duplicateBound(lowerBound, xcodemlDst, xcodemlSrc); Xnode newUpperBound = duplicateBound(upperBound, xcodemlDst, xcodemlSrc); newDim.appendToChildren(newLowerBound, false); newDim.appendToChildren(newUpperBound, false); newType.addDimension(newDim, XbasicType.APPEND); } } xcodemlDst.getTypeTable().add(newType); return type; } /** * Duplicate a lower or an upper bound between two different XcodeML units. * @param baseBound Base bound to be duplicated. * @param xcodemlDst Destination XcodeML unit. Duplicate will be created here. * @param xcodemlSrc Source XcodeML unit. Contains base bound. * @return The newly duplicated bound element. * @throws IllegalTransformationException If bound cannot be duplicated. */ private static Xnode duplicateBound(Xnode baseBound, XcodeML xcodemlDst, XcodeML xcodemlSrc) throws IllegalTransformationException { if(baseBound.opcode() != Xcode.LOWERBOUND && baseBound.opcode() != Xcode.UPPERBOUND) { throw new IllegalTransformationException("Cannot duplicate bound"); } if(xcodemlSrc == xcodemlDst){ return baseBound.cloneObject(); } Xnode boundChild = baseBound.getChild(0); if(boundChild == null){ throw new IllegalTransformationException("Cannot duplicate bound as it " + "has no children element"); } Xnode bound = new Xnode(baseBound.opcode(), xcodemlDst); if(boundChild.opcode() == Xcode.FINTCONSTANT || boundChild.opcode() == Xcode.VAR) { bound.appendToChildren( importConstOrVar(boundChild, xcodemlSrc, xcodemlDst), false); } else if(boundChild.opcode() == Xcode.PLUSEXPR) { Xnode lhs = boundChild.getChild(0); Xnode rhs = boundChild.getChild(1); Xnode plusExpr = new Xnode(Xcode.PLUSEXPR, xcodemlDst); bound.appendToChildren(plusExpr, false); plusExpr.appendToChildren( importConstOrVar(lhs, xcodemlSrc, xcodemlDst), false); plusExpr.appendToChildren( importConstOrVar(rhs, xcodemlSrc, xcodemlDst), false); } else { throw new IllegalTransformationException( String.format("Lower/upper bound type currently not supported (%s)", boundChild.opcode().toString()) ); } return bound; } /** * Create a copy of a variable element or an integer constant from a XcodeML * unit to another one. * @param base Base element to be copied. * @param xcodemlSrc Source XcodeML unit. * @param xcodemlDst Destination XcodeML unit. * @return The newly created element in the destination XcodeML unit. * @throws IllegalTransformationException If the variable element doesn't meet * the criteria. */ private static Xnode importConstOrVar(Xnode base, XcodeML xcodemlSrc, XcodeML xcodemlDst) throws IllegalTransformationException { if(base.opcode() != Xcode.FINTCONSTANT && base.opcode() != Xcode.VAR){ throw new IllegalTransformationException( String.format("Lower/upper bound type currently not supported (%s)", base.opcode().toString()) ); } if(base.opcode() == Xcode.VAR){ return importVar(base, xcodemlSrc, xcodemlDst); } else { Xnode intConst = new Xnode(Xcode.FINTCONSTANT, xcodemlDst); intConst.setValue(base.getValue()); return intConst; } } /** * Create a copy with a new hash type of an integer variable element from one * XcodeML unit to another one. * @param base Base variable element to be copied. * @param xcodemlSrc Source XcodeML unit. * @param xcodemlDst Destination XcodeML unit. * @return The newly created element in the destination XcodeML unit. * @throws IllegalTransformationException If the variable element doesn't meet * the criteria. */ private static Xnode importVar(Xnode base, XcodeML xcodemlSrc, XcodeML xcodemlDst) throws IllegalTransformationException { String typeValue = base.getAttribute(Xattr.TYPE); if(!typeValue.startsWith(Xtype.PREFIX_INTEGER)) { throw new IllegalTransformationException("Only integer variable are " + "supported as lower/upper bound value for promotted arrays."); } XbasicType type = (XbasicType) xcodemlSrc.getTypeTable().get(typeValue); Xnode bType = new Xnode(Xcode.FBASICTYPE, xcodemlDst); bType.setAttribute(Xattr.REF, Xname.TYPE_F_INT); bType.setAttribute(Xattr.TYPE, xcodemlDst.getTypeTable().generateIntegerTypeHash()); if(type != null && type.getIntent() != Xintent.NONE){ bType.setAttribute(Xattr.INTENT, type.getIntent().toString()); } Xnode var = new Xnode(Xcode.VAR, xcodemlDst); var.setAttribute(Xattr.SCOPE, base.getAttribute(Xattr.SCOPE)); var.setValue(base.getValue()); var.setAttribute(Xattr.TYPE, bType.getAttribute(Xattr.TYPE)); return var; } /** * Try to locate a function definition in the current declaration table or * recursively in the modules' delcaration tables. * @param dt Declaration table to search in. * @param fctName Function's name to be found. * @return The function definition if found. Null otherwise. */ public static XfunctionDefinition findFunctionDefinition(XglobalDeclTable dt, String fctName) { Iterator<Map.Entry<String, Xnode>> it = dt.getIterator(); while(it.hasNext()){ Map.Entry<String, Xnode> entry = it.next(); if(entry.getValue() instanceof XmoduleDefinition){ XfunctionDefinition fctDef = findFunctionDefinitionInModule( (XmoduleDefinition)entry.getValue(), fctName); if(fctDef != null){ return fctDef; } } else if (entry.getValue() instanceof XfunctionDefinition){ XfunctionDefinition fctDef = (XfunctionDefinition)entry.getValue(); if(fctDef.getName().getValue().equals(fctName)){ return fctDef; } } } return null; } /** * Get next sibling node. * @param crt Current node. * @return Next sibling node. */ public static Xnode getNextSibling(Xnode crt){ Node n = crt.getElement().getNextSibling(); while (n != null){ if(n.getNodeType() == Node.ELEMENT_NODE){ return new Xnode((Element)n); } n = n.getNextSibling(); } return null; } /** * Get all the USE statement declaration in a module definition. * @param mod Module definition. * @return A list of all declaration. Empty list if no USE declaration. */ public static List<Xdecl> getAllUse(XmoduleDefinition mod){ return mod == null ? getAllUseFromDeclTable(null) : getAllUseFromDeclTable(mod.getDeclarationTable()); } /** * Get all the USE statement declaration in a function definition. * @param fctDef Function definition. * @return A list of all declaration. Empty list if no USE declaration. */ public static List<Xdecl> getAllUse(XfunctionDefinition fctDef){ return fctDef == null ? getAllUseFromDeclTable(null) : getAllUseFromDeclTable(fctDef.getDeclarationTable()); } /** * Get all the USE statement declaration in a declaration table. * @param dt Declaration table. * @return A list of all declaration. Empty list if no USE declaration. */ private static List<Xdecl> getAllUseFromDeclTable(XdeclTable dt){ if(dt == null){ return new ArrayList<Xdecl>(); } List<Xdecl> uses = dt.getAll(Xcode.FUSEDECL); uses.addAll(dt.getAll(Xcode.FUSEONLYDECL)); return uses; } /** * Delete all sibling elements from the start element included. * @param start Element to start from. */ public static void deleteFrom(Xnode start){ List<Node> toDelete = new ArrayList<>(); toDelete.add(start.getElement()); Node sibling = start.getElement().getNextSibling(); while (sibling != null){ toDelete.add(sibling); sibling = sibling.getNextSibling(); } for (Node n : toDelete) { XnodeUtil.delete(n); } } }
Create dimensions
omni-cx2x/src/cx2x/xcodeml/helper/XnodeUtil.java
Create dimensions
Java
bsd-2-clause
e36e4ff9cace1807fa16917f2de2f46acc47cc37
0
biovoxxel/imagej,biovoxxel/imagej,biovoxxel/imagej,TehSAUCE/imagej,TehSAUCE/imagej,TehSAUCE/imagej
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2013 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.display; /** * TODO * * @author Barry DeZonia */ public interface Displayable { /** TODO */ void draw(); }
core/core/src/main/java/imagej/display/Displayable.java
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2013 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.display; /** * @author Barry DeZonia */ public interface Displayable { void draw(); }
Displayable: add missing TODO reminders
core/core/src/main/java/imagej/display/Displayable.java
Displayable: add missing TODO reminders
Java
bsd-3-clause
f3f17434e09b306d6a01c0c53573a8f65d145939
0
stain/alibaba,stain/alibaba,stain/alibaba
/* * Copyright (c) 2009, James Leigh All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the openrdf.org 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 org.openrdf.http.object.model; import info.aduna.net.ParsedURI; import java.net.URISyntaxException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.List; import javax.servlet.http.HttpServletRequest; /** * Utility class for {@link HttpServletRequest}. * * @author James Leigh * */ public class RequestHeader { private HttpServletRequest request; private boolean unspecifiedVary; private String uri; private List<String> vary = new ArrayList<String>(); public RequestHeader(HttpServletRequest request) { this.request = request; String host = getAuthority(); try { String scheme = request.getScheme().toLowerCase(); String path = getPath(); uri = new java.net.URI(scheme, host, path, null).toASCIIString(); } catch (URISyntaxException e) { // bad Host header StringBuffer url1 = request.getRequestURL(); int idx = url1.indexOf("?"); if (idx > 0) { uri = url1.substring(0, idx); } else { uri = url1.toString(); } } } public String getContentType() { return request.getContentType(); } public long getDateHeader(String name) { return request.getDateHeader(name); } public String resolve(String url) { if (url == null) return null; return parseURI(url).toString(); } public String getResolvedHeader(String name) { String value = request.getHeader(name); if (value == null) return null; return resolve(value); } public String getHeader(String name) { return request.getHeader(name); } public X509Certificate getX509Certificate() { return (X509Certificate) request .getAttribute("javax.servlet.request.X509Certificate"); } public Enumeration getHeaderNames() { unspecifiedVary = true; return request.getHeaderNames(); } public Enumeration getVaryHeaders(String name) { if (!vary.contains(name)) { vary.add(name); } return request.getHeaders(name); } public Enumeration getHeaders(String name) { return request.getHeaders(name); } public int getMaxAge() { return getCacheControl("max-age", Integer.MAX_VALUE); } public int getMinFresh() { return getCacheControl("min-fresh", 0); } public int getMaxStale() { return getCacheControl("max-stale", 0); } public boolean isStorable() { boolean safe = isSafe(); return safe && !isMessageBody() && getCacheControl("no-store", 0) == 0; } public boolean isSafe() { String method = getMethod(); return method.equals("HEAD") || method.equals("GET") || method.equals("OPTIONS") || method.equals("PROFIND"); } public boolean invalidatesCache() { String method = getMethod(); return !isSafe() && !method.equals("TRACE") && !method.equals("COPY") && !method.equals("LOCK") && !method.equals("UNLOCK"); } public boolean isNoCache() { return isStorable() && getCacheControl("no-cache", 0) > 0; } public boolean isOnlyIfCache() { return isStorable() && getCacheControl("only-if-cached", 0) > 0; } public String getRemoteAddr() { return request.getRemoteAddr(); } public String getMethod() { return request.getMethod(); } public String getRequestURI() { return request.getRequestURI(); } public String getRequestURL() { String qs = request.getQueryString(); if (qs == null) return uri; return uri + "?" + qs; } public String getURI() { return uri; } public ParsedURI parseURI(String uriSpec) { ParsedURI base = new ParsedURI(uri); base.normalize(); ParsedURI uri = new ParsedURI(uriSpec); return base.resolve(uri); } public List<String> getVary() { if (unspecifiedVary) return Collections.singletonList("*"); return vary; } public boolean isMessageBody() { return getHeader("Content-Length") != null || getHeader("Transfer-Encoding") != null; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getMethod()).append(" ").append(getRequestURL()); return sb.toString(); } public String getAuthority() { String host = request.getHeader("Host"); if (host == null) { int port = request.getServerPort(); if (port == 80 && "http".equals(request.getScheme())) return request.getServerName().toLowerCase(); if (port == 443 && "https".equals(request.getScheme())) return request.getServerName(); return request.getServerName().toLowerCase() + ":" + port; } return host.toLowerCase(); } public String getPath() { String path = request.getRequestURI(); int idx = path.indexOf('?'); if (idx > 0) { path = path.substring(0, idx); } return path; } private int getCacheControl(String directive, int def) { Enumeration headers = getHeaders("Cache-Control"); while (headers.hasMoreElements()) { String value = (String) headers.nextElement(); for (String v : value.split("\\s*,\\s*")) { int idx = v.indexOf('='); if (idx >= 0 && directive.equals(v.substring(0, idx))) { try { return Integer.parseInt(v.substring(idx + 1)); } catch (NumberFormatException e) { // invalid number } } else if (directive.equals(v)) { return Integer.MAX_VALUE; } } } return def; } }
object-server/src/main/java/org/openrdf/http/object/model/RequestHeader.java
/* * Copyright (c) 2009, James Leigh All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the openrdf.org 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 org.openrdf.http.object.model; import info.aduna.net.ParsedURI; import java.net.URISyntaxException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.List; import javax.servlet.http.HttpServletRequest; /** * Utility class for {@link HttpServletRequest}. * * @author James Leigh * */ public class RequestHeader { private HttpServletRequest request; private boolean unspecifiedVary; private String uri; private List<String> vary = new ArrayList<String>(); public RequestHeader(HttpServletRequest request) { this.request = request; String host = getAuthority(); try { String scheme = request.getScheme(); String path = getPath(); uri = new java.net.URI(scheme, host, path, null).toASCIIString(); } catch (URISyntaxException e) { // bad Host header StringBuffer url1 = request.getRequestURL(); int idx = url1.indexOf("?"); if (idx > 0) { uri = url1.substring(0, idx); } else { uri = url1.toString(); } } } public String getContentType() { return request.getContentType(); } public long getDateHeader(String name) { return request.getDateHeader(name); } public String resolve(String url) { if (url == null) return null; return parseURI(url).toString(); } public String getResolvedHeader(String name) { String value = request.getHeader(name); if (value == null) return null; return resolve(value); } public String getHeader(String name) { return request.getHeader(name); } public X509Certificate getX509Certificate() { return (X509Certificate) request .getAttribute("javax.servlet.request.X509Certificate"); } public Enumeration getHeaderNames() { unspecifiedVary = true; return request.getHeaderNames(); } public Enumeration getVaryHeaders(String name) { if (!vary.contains(name)) { vary.add(name); } return request.getHeaders(name); } public Enumeration getHeaders(String name) { return request.getHeaders(name); } public int getMaxAge() { return getCacheControl("max-age", Integer.MAX_VALUE); } public int getMinFresh() { return getCacheControl("min-fresh", 0); } public int getMaxStale() { return getCacheControl("max-stale", 0); } public boolean isStorable() { boolean safe = isSafe(); return safe && !isMessageBody() && getCacheControl("no-store", 0) == 0; } public boolean isSafe() { String method = getMethod(); return method.equals("HEAD") || method.equals("GET") || method.equals("OPTIONS") || method.equals("PROFIND"); } public boolean invalidatesCache() { String method = getMethod(); return !isSafe() && !method.equals("TRACE") && !method.equals("COPY") && !method.equals("LOCK") && !method.equals("UNLOCK"); } public boolean isNoCache() { return isStorable() && getCacheControl("no-cache", 0) > 0; } public boolean isOnlyIfCache() { return isStorable() && getCacheControl("only-if-cached", 0) > 0; } public String getRemoteAddr() { return request.getRemoteAddr(); } public String getMethod() { return request.getMethod(); } public String getRequestURI() { return request.getRequestURI(); } public String getRequestURL() { String qs = request.getQueryString(); if (qs == null) return uri; return uri + "?" + qs; } public String getURI() { return uri; } public ParsedURI parseURI(String uriSpec) { ParsedURI base = new ParsedURI(uri); base.normalize(); ParsedURI uri = new ParsedURI(uriSpec); return base.resolve(uri); } public List<String> getVary() { if (unspecifiedVary) return Collections.singletonList("*"); return vary; } public boolean isMessageBody() { return getHeader("Content-Length") != null || getHeader("Transfer-Encoding") != null; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getMethod()).append(" ").append(getRequestURL()); return sb.toString(); } public String getAuthority() { String host = request.getHeader("Host"); if (host == null) { int port = request.getServerPort(); if (port == 80 && "http".equals(request.getScheme())) return request.getServerName(); if (port == 443 && "https".equals(request.getScheme())) return request.getServerName(); return request.getServerName() + ":" + port; } return host; } public String getPath() { String path = request.getRequestURI(); int idx = path.indexOf('?'); if (idx > 0) { path = path.substring(0, idx); } return path; } private int getCacheControl(String directive, int def) { Enumeration headers = getHeaders("Cache-Control"); while (headers.hasMoreElements()) { String value = (String) headers.nextElement(); for (String v : value.split("\\s*,\\s*")) { int idx = v.indexOf('='); if (idx >= 0 && directive.equals(v.substring(0, idx))) { try { return Integer.parseInt(v.substring(idx + 1)); } catch (NumberFormatException e) { // invalid number } } else if (directive.equals(v)) { return Integer.MAX_VALUE; } } } return def; } }
Use the lower case version of the Host header to construct the URI git-svn-id: cd7eace78e14be71dd0d8bb0613a77a632a34638@9981 3fbd4d3e-0f96-47c4-bab7-89622e02a19e
object-server/src/main/java/org/openrdf/http/object/model/RequestHeader.java
Use the lower case version of the Host header to construct the URI
Java
mit
46472330aa6d7aa26ffb2001caa2e7df195babbd
0
sdcote/dataframe,sdcote/dataframe
src/main/java/coyote/dataframe/CLI.java
/* * Copyright (c) 2006 Stephan D. Cote' - All rights reserved. * * This program and the accompanying materials are made available under the * terms of the MIT License which accompanies this distribution, and is * available at http://creativecommons.org/licenses/MIT/ * * Contributors: * Stephan D. Cote * - Initial API and implementation */ package coyote.dataframe; /** * This class models a command line interface to perform a variety of marshaling tasks. * * XML to dataframe to XML * JSON to dataframe to JSON * and any other useful command line functions. */ public class CLI { /** * @param args */ public static void main( String[] args ) { System.out.println( "Done." ); System.exit( 0 ); } }
Removed unused class
src/main/java/coyote/dataframe/CLI.java
Removed unused class
Java
mit
894503d56b387c65b82acb268b2cdc5fe87179ed
0
MylesIsCool/ViaVersion
package us.myles.ViaVersion.protocols.protocol1_14to1_13_2.data; import com.google.common.base.Optional; import java.util.HashMap; import java.util.Map; public class EntityTypeRewriter { private static Map<Integer, Integer> entityTypes = new HashMap<>(); static { regEnt(6, 7); // cave_spider regEnt(7, 8); // chicken regEnt(8, 9); // cod regEnt(9, 10); // cow regEnt(10, 11); // creeper regEnt(11, 12); // donkey regEnt(12, 13); // dolphin regEnt(13, 14); // dragon_fireball regEnt(14, 15); // drowned regEnt(15, 16); // elder_guardian regEnt(16, 17); // end_crystal regEnt(17, 18); // ender_dragon regEnt(18, 19); // enderman regEnt(19, 20); // endermite regEnt(20, 21); // evoker_fangs regEnt(21, 22); // evoker regEnt(22, 23); // experience_orb regEnt(23, 24); // eye_of_ender regEnt(24, 25); // falling_block regEnt(25, 26); // firework_rocket regEnt(26, 28); // ghast regEnt(27, 29); // giant regEnt(28, 30); // guardian regEnt(29, 31); // horse regEnt(30, 32); // husk regEnt(31, 33); // illusioner regEnt(32, 34); // item regEnt(33, 35); // item_frame regEnt(34, 36); // fireball regEnt(35, 37); // leash_knot regEnt(36, 38); // llama regEnt(37, 39); // llama_spit regEnt(38, 40); // magma_cube regEnt(39, 41); // minecart regEnt(40, 42); // chest_minecart regEnt(41, 43); // command_block_minecart regEnt(42, 44); // furnace_minecart regEnt(43, 45); // hopper_minecart regEnt(44, 46); // spawner_minecart regEnt(45, 47); // tnt_minecart regEnt(46, 48); // mule regEnt(47, 49); // mooshroom regEnt(48, 6); // ocelot -> cat TODO Remap untamed ocelot to ocelot? regEnt(49, 51); // painting regEnt(50, 53); // parrot regEnt(51, 54); // pig regEnt(52, 55); // pufferfish regEnt(53, 56); // zombie_pigman regEnt(54, 57); // polar_bear regEnt(55, 58); // tnt regEnt(56, 59); // rabbit regEnt(57, 60); // salmon regEnt(58, 61); // sheep regEnt(59, 62); // shulker regEnt(60, 63); // shulker_bullet regEnt(61, 64); // silverfish regEnt(62, 65); // skeleton regEnt(63, 66); // skeleton_horse regEnt(64, 67); // slime regEnt(65, 68); // small_fireball regEnt(66, 69); // snowgolem regEnt(67, 70); // snowball regEnt(68, 71); // spectral_arrow regEnt(69, 72); // spider regEnt(70, 73); // squid regEnt(71, 74); // stray regEnt(72, 76); // tropical_fish regEnt(73, 77); // turtle regEnt(74, 78); // egg regEnt(75, 79); // ender_pearl regEnt(76, 80); // experience_bottle regEnt(77, 81); // potion regEnt(78, 83); // vex regEnt(79, 84); // villager regEnt(80, 85); // iron_golem regEnt(81, 86); // vindicator regEnt(82, 89); // witch regEnt(83, 90); // wither regEnt(84, 91); // wither_skeleton regEnt(85, 92); // wither_skull regEnt(86, 93); // wolf regEnt(87, 94); // zombie regEnt(88, 95); // zombie_horse regEnt(89, 96); // zombie_villager regEnt(90, 97); // phantom regEnt(91, 99); // lightning_bolt regEnt(92, 100); // player regEnt(93, 101); // fishing_bobber regEnt(94, 82); // trident } private static void regEnt(int type1_13, int type1_14) { entityTypes.put(type1_13, type1_14); } public static Optional<Integer> getNewId(int type1_13) { return Optional.fromNullable(entityTypes.get(type1_13)); } }
common/src/main/java/us/myles/ViaVersion/protocols/protocol1_14to1_13_2/data/EntityTypeRewriter.java
package us.myles.ViaVersion.protocols.protocol1_14to1_13_2.data; import com.google.common.base.Optional; import java.util.HashMap; import java.util.Map; public class EntityTypeRewriter { private static Map<Integer, Integer> entityTypes = new HashMap<>(); static { regEnt(6, 7); // cave_spider regEnt(7, 8); // chicken regEnt(8, 9); // cod regEnt(9, 10); // cow regEnt(10, 11); // creeper regEnt(11, 12); // donkey regEnt(12, 13); // dolphin regEnt(13, 14); // dragon_fireball regEnt(14, 15); // drowned regEnt(15, 16); // elder_guardian regEnt(16, 17); // end_crystal regEnt(17, 18); // ender_dragon regEnt(18, 19); // enderman regEnt(19, 20); // endermite regEnt(20, 21); // evoker_fangs regEnt(21, 22); // evoker regEnt(22, 23); // experience_orb regEnt(23, 24); // eye_of_ender regEnt(24, 25); // falling_block regEnt(25, 26); // firework_rocket regEnt(26, 28); // ghast regEnt(27, 29); // giant regEnt(28, 30); // guardian regEnt(29, 31); // horse regEnt(30, 32); // husk regEnt(31, 33); // illusioner regEnt(32, 34); // item regEnt(33, 35); // item_frame regEnt(34, 36); // fireball regEnt(35, 37); // leash_knot regEnt(36, 38); // llama regEnt(37, 39); // llama_spit regEnt(38, 40); // magma_cube regEnt(39, 41); // minecart regEnt(40, 42); // chest_minecart regEnt(41, 43); // command_block_minecart regEnt(42, 44); // furnace_minecart regEnt(43, 45); // hopper_minecart regEnt(45, 47); // tnt_minecart regEnt(46, 48); // mule regEnt(47, 49); // mooshroom regEnt(48, 6); // ocelot -> cat TODO Remap untamed ocelot to ocelot? regEnt(49, 51); // painting regEnt(50, 53); // parrot regEnt(51, 54); // pig regEnt(52, 55); // pufferfish regEnt(53, 56); // zombie_pigman regEnt(54, 57); // polar_bear regEnt(55, 58); // tnt regEnt(56, 59); // rabbit regEnt(57, 60); // salmon regEnt(58, 61); // sheep regEnt(59, 62); // shulker regEnt(60, 63); // shulker_bullet regEnt(61, 64); // silverfish regEnt(62, 65); // skeleton regEnt(63, 66); // skeleton_horse regEnt(64, 67); // slime regEnt(65, 68); // small_fireball regEnt(66, 69); // snowgolem regEnt(67, 70); // snowball regEnt(68, 71); // spectral_arrow regEnt(69, 72); // spider regEnt(70, 73); // squid regEnt(71, 74); // stray regEnt(72, 76); // tropical_fish regEnt(73, 77); // turtle regEnt(74, 78); // egg regEnt(75, 79); // ender_pearl regEnt(76, 80); // experience_bottle regEnt(77, 81); // potion regEnt(78, 83); // vex regEnt(79, 84); // villager regEnt(80, 85); // iron_golem regEnt(81, 86); // vindicator regEnt(82, 89); // witch regEnt(83, 90); // wither regEnt(84, 91); // wither_skeleton regEnt(85, 92); // wither_skull regEnt(86, 93); // wolf regEnt(87, 94); // zombie regEnt(88, 95); // zombie_horse regEnt(89, 96); // zombie_villager regEnt(90, 97); // phantom regEnt(91, 99); // lightning_bolt regEnt(92, 100); // player regEnt(93, 101); // fishing_bobber regEnt(94, 82); // trident } private static void regEnt(int type1_13, int type1_14) { entityTypes.put(type1_13, type1_14); } public static Optional<Integer> getNewId(int type1_13) { return Optional.fromNullable(entityTypes.get(type1_13)); } }
Fix minecart mapping
common/src/main/java/us/myles/ViaVersion/protocols/protocol1_14to1_13_2/data/EntityTypeRewriter.java
Fix minecart mapping
Java
mit
e4c6448ce40a70d3d013015c9908bc64aeefcef8
0
PrinceOfAmber/Cyclic,PrinceOfAmber/CyclicMagic
package com.lothrazar.cyclicmagic.compat.fastbench; import com.lothrazar.cyclicmagic.block.workbench.InventoryWorkbench; import com.lothrazar.cyclicmagic.block.workbench.TileEntityWorkbench; import com.lothrazar.cyclicmagic.util.Const; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.ContainerPlayer; import net.minecraft.inventory.Slot; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.minecraftforge.fml.common.registry.ForgeRegistries; import shadows.fastbench.gui.ContainerFastBench; import shadows.fastbench.gui.SlotCraftingSucks; public class ContainerFastWorkbench extends ContainerFastBench { static Block workbench = ForgeRegistries.BLOCKS.getValue(new ResourceLocation(Const.MODID, "block_workbench")); final TileEntityWorkbench te; public ContainerFastWorkbench(EntityPlayer player, World world, TileEntityWorkbench te) { super(player, world, te.getPos()); this.te = te; this.craftMatrix = new InventoryWorkbench(this, te); int x = 0; replaceSlot(x++, new SlotCraftingSucks(this, player, this.craftMatrix, this.craftResult, 0, 124, 35)); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { replaceSlot(x++, new Slot(this.craftMatrix, j + i * 3, 30 + j * 18, 17 + i * 18)); } } onCraftMatrixChanged(te); } void replaceSlot(int num, Slot slotIn) { slotIn.slotNumber = num; this.inventorySlots.set(num, slotIn); } @Override public boolean canInteractWith(EntityPlayer playerIn) { if (te.getWorld().getBlockState(te.getPos()).getBlock() != workbench) { return false; } else { return playerIn.getDistanceSq(te.getPos().getX() + 0.5D, te.getPos().getY() + 0.5D, te.getPos().getZ() + 0.5D) <= 64.0D; } } @Override public void onContainerClosed(EntityPlayer player) { ((ContainerPlayer) player.inventoryContainer).craftResult.clear(); //For whatever reason the workbench causes a desync that makes the last available recipe show in the 2x2 grid. super.onContainerClosed(player); } }
src/main/java/com/lothrazar/cyclicmagic/compat/fastbench/ContainerFastWorkbench.java
package com.lothrazar.cyclicmagic.compat.fastbench; import com.lothrazar.cyclicmagic.block.workbench.InventoryWorkbench; import com.lothrazar.cyclicmagic.block.workbench.TileEntityWorkbench; import com.lothrazar.cyclicmagic.util.Const; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Slot; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.minecraftforge.fml.common.registry.ForgeRegistries; import shadows.fastbench.gui.ContainerFastBench; import shadows.fastbench.gui.SlotCraftingSucks; public class ContainerFastWorkbench extends ContainerFastBench { static Block workbench = ForgeRegistries.BLOCKS.getValue(new ResourceLocation(Const.MODID, "block_workbench")); final TileEntityWorkbench te; public ContainerFastWorkbench(EntityPlayer player, World world, TileEntityWorkbench te) { super(player, world, te.getPos()); this.te = te; this.craftMatrix = new InventoryWorkbench(this, te); int x = 0; replaceSlot(x++, new SlotCraftingSucks(this, player, this.craftMatrix, this.craftResult, 0, 124, 35)); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { replaceSlot(x++, new Slot(this.craftMatrix, j + i * 3, 30 + j * 18, 17 + i * 18)); } } onCraftMatrixChanged(te); } void replaceSlot(int num, Slot slotIn) { slotIn.slotNumber = num; this.inventorySlots.set(num, slotIn); } @Override public boolean canInteractWith(EntityPlayer playerIn) { if (te.getWorld().getBlockState(te.getPos()).getBlock() != workbench) { return false; } else { return playerIn.getDistanceSq(te.getPos().getX() + 0.5D, te.getPos().getY() + 0.5D, te.getPos().getZ() + 0.5D) <= 64.0D; } } }
Fix some strange desync issue
src/main/java/com/lothrazar/cyclicmagic/compat/fastbench/ContainerFastWorkbench.java
Fix some strange desync issue
Java
mit
e339d97f90b35b989ade007cc22ca6b58cbb2a89
0
jenkinsci/aws-beanstalk-publisher-plugin,jenkinsci/aws-beanstalk-publisher-plugin,DavidTanner/aws-beanstalk-publisher,DavidTanner/aws-beanstalk-publisher
package org.jenkinsci.plugins.awsbeanstalkpublisher.extensions; import hudson.Extension; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.BuildListener; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import java.util.ArrayList; import java.util.List; import org.jenkinsci.plugins.awsbeanstalkpublisher.AWSEBCredentials; import org.jenkinsci.plugins.awsbeanstalkpublisher.AWSEBEnvironmentUpdater; import org.jenkinsci.plugins.awsbeanstalkpublisher.AWSEBUtils; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import com.amazonaws.regions.Regions; import com.google.common.base.Joiner; public class AWSEBElasticBeanstalkSetup extends AWSEBSetup { @Extension public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl(); private final AWSEBCredentials credentials; private final Regions awsRegion; private final String applicationName; private final String versionLabelFormat; private final Boolean failOnError; private final List<String> environments; private final String awsRegionText; private List<AWSEBSetup> extensions; @DataBoundConstructor public AWSEBElasticBeanstalkSetup( Regions awsRegion, String awsRegionText, String credentials, String applicationName, String environmentList, String versionLabelFormat, Boolean failOnError, List<AWSEBSetup> extensions) { this.awsRegion = awsRegion; this.awsRegionText = awsRegionText; this.credentials = AWSEBCredentials.getCredentialsByString(credentials); this.applicationName = applicationName; this.environments = new ArrayList<String>(); for (String next : environmentList.split("\n")) { this.environments.add(next); } this.versionLabelFormat = versionLabelFormat; this.failOnError = failOnError; this.extensions = extensions; } public List<AWSEBSetup> getExtensions() { return extensions == null ? new ArrayList<AWSEBSetup>(0) : extensions; } public String getEnvironmentList() { return Joiner.on("\n").join(environments); } public List<String> getEnvironments() { return environments; } public Regions getAwsRegion(AbstractBuild<?, ?> build) { String regionName = AWSEBUtils.getValue(build, awsRegionText); try { return Regions.fromName(regionName); } catch (Exception e) { return awsRegion == null ? Regions.US_WEST_1 : awsRegion; } } public String getApplicationName() { return applicationName == null ? "" : applicationName; } public String getVersionLabelFormat() { return versionLabelFormat == null ? "" : versionLabelFormat; } public Boolean getFailOnError() { return failOnError == null ? false : failOnError; } public AWSEBCredentials getCredentials() { return credentials; } @Override public void perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws Exception { AWSEBEnvironmentUpdater updater = new AWSEBEnvironmentUpdater(build, launcher, listener, this); updater.perform(); } // Overridden for better type safety. // If your plugin doesn't really define any property on Descriptor, // you don't have to do this. @Override public DescriptorImpl getDescriptor() { return DESCRIPTOR; } public static DescriptorImpl getDesc() { return DESCRIPTOR; } @Extension public static class DescriptorImpl extends AWSEBSetupDescriptor { @Override public String getDisplayName() { return "Elastic Beanstalk Application"; } public ListBoxModel doFillCredentialsItems(@QueryParameter String credentials) { ListBoxModel items = new ListBoxModel(); for (AWSEBCredentials creds : AWSEBCredentials.getCredentials()) { items.add(creds, creds.toString()); if (creds.toString().equals(credentials)) { items.get(items.size()-1).selected = true; } } return items; } public FormValidation doCheckEnvironmentList(@QueryParameter String environmentList) { List<String> badEnv = AWSEBUtils.getBadEnvironmentNames(environmentList); if (badEnv.size() > 0) { return FormValidation.error("Bad environment names: %s", badEnv.toString()); } else { return FormValidation.ok(); } } public FormValidation doLoadApplications(@QueryParameter("credentials") String credentialsString, @QueryParameter("awsRegion") String regionString) { AWSEBCredentials credentials = AWSEBCredentials.getCredentialsByString(credentialsString); if (credentials == null) { return FormValidation.error("Missing valid credentials"); } Regions region = Enum.valueOf(Regions.class, regionString); if (region == null) { return FormValidation.error("Missing valid Region"); } return FormValidation.ok(AWSEBUtils.getApplicationListAsString(credentials, region)); } public FormValidation doLoadEnvironments(@QueryParameter("credentials") String credentialsString, @QueryParameter("awsRegion") String regionString, @QueryParameter("applicationName") String appName) { AWSEBCredentials credentials = AWSEBCredentials.getCredentialsByString(credentialsString); if (credentials == null) { return FormValidation.error("Missing valid credentials"); } Regions region = Enum.valueOf(Regions.class, regionString); if (region == null) { return FormValidation.error("Missing valid Region"); } if (appName == null) { return FormValidation.error("Missing an application name"); } return FormValidation.ok(AWSEBUtils.getEnvironmentsListAsString(credentials, region, appName)); } public List<AWSEBSetupDescriptor> getExtensionDescriptors() { List<AWSEBSetupDescriptor> extensions = new ArrayList<AWSEBSetupDescriptor>(1); extensions.add(AWSEBS3Setup.getDesc()); return extensions; } } }
src/main/java/org/jenkinsci/plugins/awsbeanstalkpublisher/extensions/AWSEBElasticBeanstalkSetup.java
package org.jenkinsci.plugins.awsbeanstalkpublisher.extensions; import hudson.Extension; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.BuildListener; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import java.util.ArrayList; import java.util.List; import org.jenkinsci.plugins.awsbeanstalkpublisher.AWSEBCredentials; import org.jenkinsci.plugins.awsbeanstalkpublisher.AWSEBEnvironmentUpdater; import org.jenkinsci.plugins.awsbeanstalkpublisher.AWSEBUtils; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import com.amazonaws.regions.Regions; import com.google.common.base.Joiner; public class AWSEBElasticBeanstalkSetup extends AWSEBSetup { @Extension public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl(); private final AWSEBCredentials credentials; private final Regions awsRegion; private final String applicationName; private final String versionLabelFormat; private final Boolean failOnError; private final List<String> environments; private final String awsRegionText; private List<AWSEBSetup> extensions; @DataBoundConstructor public AWSEBElasticBeanstalkSetup( Regions awsRegion, String awsRegionText, String credentials, String applicationName, String environmentList, String versionLabelFormat, Boolean failOnError, List<AWSEBSetup> extensions) { this.awsRegion = awsRegion; this.awsRegionText = awsRegionText; this.credentials = AWSEBCredentials.getCredentialsByString(credentials); this.applicationName = applicationName; this.environments = new ArrayList<String>(); for (String next : environmentList.split("\n")) { this.environments.add(next); } this.versionLabelFormat = versionLabelFormat; this.failOnError = failOnError; this.extensions = extensions; } public List<AWSEBSetup> getExtensions() { return extensions == null ? new ArrayList<AWSEBSetup>(0) : extensions; } public String getEnvironmentList() { return Joiner.on("\n").join(environments); } public List<String> getEnvironments() { return environments; } public Regions getAwsRegion(AbstractBuild<?, ?> build) { String regionName = AWSEBUtils.getValue(build, awsRegionText); try { return Regions.fromName(regionName); } catch (IllegalArgumentException e) { return awsRegion == null ? Regions.US_WEST_1 : awsRegion; } } public String getApplicationName() { return applicationName == null ? "" : applicationName; } public String getVersionLabelFormat() { return versionLabelFormat == null ? "" : versionLabelFormat; } public Boolean getFailOnError() { return failOnError == null ? false : failOnError; } public AWSEBCredentials getCredentials() { return credentials; } @Override public void perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws Exception { AWSEBEnvironmentUpdater updater = new AWSEBEnvironmentUpdater(build, launcher, listener, this); updater.perform(); } // Overridden for better type safety. // If your plugin doesn't really define any property on Descriptor, // you don't have to do this. @Override public DescriptorImpl getDescriptor() { return DESCRIPTOR; } public static DescriptorImpl getDesc() { return DESCRIPTOR; } @Extension public static class DescriptorImpl extends AWSEBSetupDescriptor { @Override public String getDisplayName() { return "Elastic Beanstalk Application"; } public ListBoxModel doFillCredentialsItems(@QueryParameter String credentials) { ListBoxModel items = new ListBoxModel(); for (AWSEBCredentials creds : AWSEBCredentials.getCredentials()) { items.add(creds, creds.toString()); if (creds.toString().equals(credentials)) { items.get(items.size()-1).selected = true; } } return items; } public FormValidation doCheckEnvironmentList(@QueryParameter String environmentList) { List<String> badEnv = AWSEBUtils.getBadEnvironmentNames(environmentList); if (badEnv.size() > 0) { return FormValidation.error("Bad environment names: %s", badEnv.toString()); } else { return FormValidation.ok(); } } public FormValidation doLoadApplications(@QueryParameter("credentials") String credentialsString, @QueryParameter("awsRegion") String regionString) { AWSEBCredentials credentials = AWSEBCredentials.getCredentialsByString(credentialsString); if (credentials == null) { return FormValidation.error("Missing valid credentials"); } Regions region = Enum.valueOf(Regions.class, regionString); if (region == null) { return FormValidation.error("Missing valid Region"); } return FormValidation.ok(AWSEBUtils.getApplicationListAsString(credentials, region)); } public FormValidation doLoadEnvironments(@QueryParameter("credentials") String credentialsString, @QueryParameter("awsRegion") String regionString, @QueryParameter("applicationName") String appName) { AWSEBCredentials credentials = AWSEBCredentials.getCredentialsByString(credentialsString); if (credentials == null) { return FormValidation.error("Missing valid credentials"); } Regions region = Enum.valueOf(Regions.class, regionString); if (region == null) { return FormValidation.error("Missing valid Region"); } if (appName == null) { return FormValidation.error("Missing an application name"); } return FormValidation.ok(AWSEBUtils.getEnvironmentsListAsString(credentials, region, appName)); } public List<AWSEBSetupDescriptor> getExtensionDescriptors() { List<AWSEBSetupDescriptor> extensions = new ArrayList<AWSEBSetupDescriptor>(1); extensions.add(AWSEBS3Setup.getDesc()); return extensions; } } }
Change to handle any exception from Regions.fromName()
src/main/java/org/jenkinsci/plugins/awsbeanstalkpublisher/extensions/AWSEBElasticBeanstalkSetup.java
Change to handle any exception from Regions.fromName()
Java
mit
cc3c5d18e7ac37ce67998c755557a43b98efc01b
0
Grinch/SpongeCommon,DDoS/SpongeCommon,SpongePowered/Sponge,kenzierocks/SpongeCommon,sanman00/SpongeCommon,DDoS/SpongeCommon,modwizcode/SpongeCommon,SpongePowered/Sponge,ryantheleach/SpongeCommon,RTLSponge/SpongeCommon,hsyyid/SpongeCommon,clienthax/SpongeCommon,ryantheleach/SpongeCommon,JBYoshi/SpongeCommon,SpongePowered/SpongeCommon,clienthax/SpongeCommon,RTLSponge/SpongeCommon,JBYoshi/SpongeCommon,SpongePowered/Sponge,hsyyid/SpongeCommon,kenzierocks/SpongeCommon,SpongePowered/SpongeCommon,modwizcode/SpongeCommon,sanman00/SpongeCommon,Grinch/SpongeCommon
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.data.processor.value.entity; import net.minecraft.entity.player.EntityPlayer; import org.spongepowered.api.data.DataTransactionResult; import org.spongepowered.api.data.key.Keys; import org.spongepowered.api.data.value.ValueContainer; import org.spongepowered.api.data.value.immutable.ImmutableValue; import org.spongepowered.api.data.value.mutable.MutableBoundedValue; import org.spongepowered.common.data.processor.common.AbstractSpongeValueProcessor; import org.spongepowered.common.data.processor.common.ExperienceHolderUtils; import org.spongepowered.common.data.value.SpongeValueFactory; import java.util.Optional; public class TotalExperienceValueProcessor extends AbstractSpongeValueProcessor<EntityPlayer, Integer, MutableBoundedValue<Integer>> { public TotalExperienceValueProcessor() { super(EntityPlayer.class, Keys.TOTAL_EXPERIENCE); } @Override public DataTransactionResult removeFrom(ValueContainer<?> container) { return DataTransactionResult.failNoData(); } @Override public MutableBoundedValue<Integer> constructValue(Integer defaultValue) { return SpongeValueFactory.boundedBuilder(Keys.TOTAL_EXPERIENCE) .defaultValue(0) .minimum(0) .maximum(Integer.MAX_VALUE) .actualValue(defaultValue) .build(); } @Override protected boolean set(EntityPlayer container, Integer value) { int level = -1; int experienceForCurrentLevel; int experienceAtNextLevel = -1; // We work iteratively to get the level. Remember, the level variable contains the CURRENT level and the method // calculates what we need to get to the NEXT level, so we work our way up, summing up all these intervals, until // we get an experience value that is larger than the value. This gives us our level. // // If the cumulative experience required for level+1 is still below that (or in the edge case, equal to) our // value, we need to go up a level. So, if the boundary is at 7 exp, and we have 7 exp, we need one more loop // to increment the level as we are at 100% and therefore should be at level+1. do { // We need this later. experienceForCurrentLevel = experienceAtNextLevel; // Increment level, as we know we are at least that level (in the first instance -1 -> 0) // and add the next amount of experience to the variable. experienceAtNextLevel += ExperienceHolderUtils.getExpBetweenLevels(++level); } while (experienceAtNextLevel <= value); // Once we're here, we have the correct level. The experience is the decimal fraction that we are through the // current level. This is why we require the experienceForCurrentLevel variable, we need the difference between // the current value and the beginning of the level. container.experience = (float)(value - experienceForCurrentLevel) / ExperienceHolderUtils.getExpBetweenLevels(level); container.experienceLevel = level; container.experienceTotal = value; return true; } @Override protected Optional<Integer> getVal(EntityPlayer container) { return Optional.of(container.experienceTotal); } @Override protected ImmutableValue<Integer> constructImmutableValue(Integer value) { return constructValue(value).asImmutable(); } }
src/main/java/org/spongepowered/common/data/processor/value/entity/TotalExperienceValueProcessor.java
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.data.processor.value.entity; import net.minecraft.entity.player.EntityPlayer; import org.spongepowered.api.data.DataTransactionResult; import org.spongepowered.api.data.key.Keys; import org.spongepowered.api.data.value.ValueContainer; import org.spongepowered.api.data.value.immutable.ImmutableValue; import org.spongepowered.api.data.value.mutable.MutableBoundedValue; import org.spongepowered.common.data.processor.common.AbstractSpongeValueProcessor; import org.spongepowered.common.data.processor.common.ExperienceHolderUtils; import org.spongepowered.common.data.value.SpongeValueFactory; import java.util.Optional; public class TotalExperienceValueProcessor extends AbstractSpongeValueProcessor<EntityPlayer, Integer, MutableBoundedValue<Integer>> { public TotalExperienceValueProcessor() { super(EntityPlayer.class, Keys.TOTAL_EXPERIENCE); } @Override public DataTransactionResult removeFrom(ValueContainer<?> container) { return DataTransactionResult.failNoData(); } @Override public MutableBoundedValue<Integer> constructValue(Integer defaultValue) { return SpongeValueFactory.boundedBuilder(Keys.TOTAL_EXPERIENCE) .defaultValue(0) .minimum(0) .maximum(Integer.MAX_VALUE) .actualValue(defaultValue) .build(); } @Override protected boolean set(EntityPlayer container, Integer value) { int level = 0; for (int i = value; true; i -= ExperienceHolderUtils.getExpBetweenLevels(level)) { if (i - ExperienceHolderUtils.getExpBetweenLevels(level) <= 0) { container.experience = (float) i / ExperienceHolderUtils.getExpBetweenLevels(level); container.experienceLevel = level; break; } level++; } container.experienceTotal = value; return false; } @Override protected Optional<Integer> getVal(EntityPlayer container) { return Optional.of(container.experienceTotal); } @Override protected ImmutableValue<Integer> constructImmutableValue(Integer value) { return constructValue(value).asImmutable(); } }
Update the Total Experience value processor. * The processor now returns true when data is set. * Fixed setting the total experience returning wrong level.
src/main/java/org/spongepowered/common/data/processor/value/entity/TotalExperienceValueProcessor.java
Update the Total Experience value processor.
Java
mit
2a33045bb0d66d25d84bdead6a5e39cd1a79c9da
0
luizgrp/SectionedRecyclerViewAdapter
package io.github.luizgrp.sectionedrecyclerviewadapter; import org.junit.Before; import org.junit.Test; import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.FootedSectionStub; import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.FootedStatelessSectionStub; import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.HeadedFootedSectionStub; import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.HeadedFootedStatelessSectionStub; import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.HeadedSectionStub; import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.HeadedStatelessSectionStub; import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.SectionStub; import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.StatelessSectionStub; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; /** * Unit tests for {@link SectionedRecyclerViewAdapter} */ public class SectionedRecyclerViewAdapterTest { private final int ITEMS_QTY = 10; private final String SECTION_TAG = "tag"; private SectionedRecyclerViewAdapter sectionAdapter; @Before public void setup() { sectionAdapter = new SectionedRecyclerViewAdapter(); } @Test(expected = IndexOutOfBoundsException.class) public void getPositionInSection_withEmptyAdapter_throwsException() { // When sectionAdapter.getPositionInSection(0); } @Test public void getPositionInSection_withAdapterWithInvisibleSection_returnsCorrectPosition() { // Given addHeadedFootedStatelessSectionStubToAdapter(); addInvisibleStatelessSectionStubToAdapter(); addHeadedFootedStatelessSectionStubToAdapter(); // When int result = sectionAdapter.getPositionInSection(13); int result2 = sectionAdapter.getPositionInSection(22); // Then assertThat(result, is(0)); assertThat(result2, is(9)); } @Test(expected = IllegalArgumentException.class) public void getSectionPositionUsingTag_withEmptyAdapter_throwsException() { // When sectionAdapter.getSectionPosition(SECTION_TAG); } @Test(expected = IllegalArgumentException.class) public void getSectionPositionUsingTag_withInvalidTag_throwsException() { // Given addStatelessSectionStubToAdapter(); addStatelessSectionStubToAdapter(); // When sectionAdapter.getSectionPosition(SECTION_TAG); } @Test public void getSectionPositionUsingTag_withAdapterWithInvisibleSection_returnsCorrectPosition() { // Given addStatelessSectionStubToAdapter(); addInvisibleStatelessSectionStubToAdapter(); sectionAdapter.addSection(SECTION_TAG, new StatelessSectionStub(ITEMS_QTY)); // When int result = sectionAdapter.getSectionPosition(SECTION_TAG); // Then assertThat(result, is(10)); } @Test(expected = IllegalArgumentException.class) public void getSectionPositionUsingSection_withEmptyAdapter_throwsException() { // When sectionAdapter.getSectionPosition(new StatelessSectionStub(ITEMS_QTY)); } @Test(expected = IllegalArgumentException.class) public void getSectionPositionUsingSection_withInvalidSection_throwsException() { // Given addStatelessSectionStubToAdapter(); addStatelessSectionStubToAdapter(); // When sectionAdapter.getSectionPosition(new StatelessSectionStub(ITEMS_QTY)); } @Test public void getSectionPositionUsingSection_withAdapterWithInvisibleSection_returnsCorrectPosition() { // Given addStatelessSectionStubToAdapter(); addInvisibleStatelessSectionStubToAdapter(); StatelessSectionStub statelessSectionStub = new StatelessSectionStub(ITEMS_QTY); sectionAdapter.addSection(statelessSectionStub); // When int result = sectionAdapter.getSectionPosition(statelessSectionStub); // Then assertThat(result, is(10)); } @Test(expected = IndexOutOfBoundsException.class) public void onBindViewHolder_withEmptyAdapter_throwsException() { // When sectionAdapter.onBindViewHolder(null, 0); } @Test public void addSection_withEmptyAdapter_succeeds() { // Given Section section = new StatelessSectionStub(ITEMS_QTY); // When sectionAdapter.addSection(SECTION_TAG, section); // Then assertSame(sectionAdapter.getSection(SECTION_TAG), section); assertSame(sectionAdapter.getSectionsMap().get(SECTION_TAG), section); } @Test public void addSectionWithTag_withEmptyAdapter_succeeds() { // Given Section section = new StatelessSectionStub(ITEMS_QTY); // When sectionAdapter.addSection(SECTION_TAG, section); // Then assertSame(sectionAdapter.getSection(SECTION_TAG), section); assertSame(sectionAdapter.getSectionsMap().get(SECTION_TAG), section); } @Test public void getSectionWithTag_withRemovedSection_returnsNull() { // Given sectionAdapter.addSection(SECTION_TAG, new StatelessSectionStub(ITEMS_QTY)); // When sectionAdapter.removeSection(SECTION_TAG); // Then assertNull(sectionAdapter.getSection(SECTION_TAG)); } @Test public void getSectionWithTag_withEmptyAdapter_returnsNull() { // When Section result = sectionAdapter.getSection(SECTION_TAG); // Then assertNull(result); } @Test public void getItemCount_withEmptyAdapter_isZero() { // When int result = sectionAdapter.getItemCount(); // Then assertThat(result, is(0)); } @Test public void getItemCount_withAdapterWithInvisibleSection_returnsCorrectQuantity() { // Given addStatelessSectionStubToAdapter(); addInvisibleStatelessSectionStubToAdapter(); // When int result = sectionAdapter.getItemCount(); // Then assertThat(result, is(ITEMS_QTY)); } @Test public void getSectionsMap_withEmptyAdapter_isEmpty() { // When boolean result = sectionAdapter.getSectionsMap().isEmpty(); // Then assertTrue(result); } @Test public void getSectionsMap_withAdapterWithInvisibleSection_hasCorrectSize() { // Given addStatelessSectionStubToAdapter(); addInvisibleStatelessSectionStubToAdapter(); // When int result = sectionAdapter.getSectionsMap().size(); // Then assertThat(result, is(2)); } @Test public void getSection_withEmptyAdapter_isNull() { // When Section result = sectionAdapter.getSection(SECTION_TAG); // Then assertNull(result); } @Test public void getSection_withAdapterWithManySections_returnsCorrectSection() { // Given addStatelessSectionStubToAdapter(); Section section = new StatelessSectionStub(ITEMS_QTY); sectionAdapter.addSection(SECTION_TAG, section); addStatelessSectionStubToAdapter(); // When Section result = sectionAdapter.getSection(SECTION_TAG); // Then assertSame(result, section); } @Test(expected = IndexOutOfBoundsException.class) public void getSectionForPosition_withEmptyAdapter_throwsException() { // When sectionAdapter.getSectionForPosition(0); } @Test public void getSectionForPosition_withAdapterWithManySections_returnsCorrectSection() { // Given Section sectionStub1 = addStatelessSectionStubToAdapter(); Section sectionStub2 = addStatelessSectionStubToAdapter(); Section sectionStub3 = addStatelessSectionStubToAdapter(); // When Section result = sectionAdapter.getSectionForPosition(0); Section result2 = sectionAdapter.getSectionForPosition(9); Section result3 = sectionAdapter.getSectionForPosition(10); Section result4 = sectionAdapter.getSectionForPosition(19); Section result5 = sectionAdapter.getSectionForPosition(20); Section result6 = sectionAdapter.getSectionForPosition(29); // Then assertSame(result, sectionStub1); assertSame(result2, sectionStub1); assertSame(result3, sectionStub2); assertSame(result4, sectionStub2); assertSame(result5, sectionStub3); assertSame(result6, sectionStub3); } @Test(expected = IndexOutOfBoundsException.class) public void getSectionItemViewType_withEmptyAdapter_throwsException() { // When sectionAdapter.getSectionItemViewType(0); } @Test public void getSectionItemViewType_withAdapterWithManySections_returnsCorrectValuesForHeadedFootedStatelessSection() { // Given addFourStatelessSectionsAndFourSectionsToAdapter(); // When int viewTypeHeader = sectionAdapter.getSectionItemViewType(32); int viewTypeItemStart = sectionAdapter.getSectionItemViewType(33); int viewTypeItemEnd = sectionAdapter.getSectionItemViewType(42); int viewTypeFooter = sectionAdapter.getSectionItemViewType(43); // Then assertThat(viewTypeHeader, is(SectionedRecyclerViewAdapter.VIEW_TYPE_HEADER)); assertThat(viewTypeItemStart, is(SectionedRecyclerViewAdapter.VIEW_TYPE_ITEM_LOADED)); assertThat(viewTypeItemEnd, is(SectionedRecyclerViewAdapter.VIEW_TYPE_ITEM_LOADED)); assertThat(viewTypeFooter, is(SectionedRecyclerViewAdapter.VIEW_TYPE_FOOTER)); } @Test(expected = IndexOutOfBoundsException.class) public void getItemViewType_withEmptyAdapter_throwsException() { // When sectionAdapter.getItemViewType(0); } @Test public void getItemViewType_withAdapterWithManySections_returnsCorrectValuesForHeadedFootedStatelessSection() { // Given addFourStatelessSectionsAndFourSectionsToAdapter(); // When int viewTypeHeader = sectionAdapter.getItemViewType(32); int viewTypeItemStart = sectionAdapter.getItemViewType(33); int viewTypeItemEnd = sectionAdapter.getItemViewType(42); int viewTypeFooter = sectionAdapter.getItemViewType(43); // Then assertThat(viewTypeHeader, is(18)); assertThat(viewTypeItemStart, is(20)); assertThat(viewTypeItemEnd, is(20)); assertThat(viewTypeFooter, is(19)); } @Test public void getItemViewType_withAdapterWithManySections_returnsCorrectValuesForSectionWithLoadingState() { // Given addStatelessSectionStubToAdapter(); addHeadedStatelessSectionStubToAdapter(); addFootedStatelessSectionStubToAdapter(); addHeadedFootedStatelessSectionStubToAdapter(); Section section = addSectionStubToAdapter(); section.setState(Section.State.LOADING); addHeadedSectionStubToAdapter(); addFootedSectionStubToAdapter(); addHeadedFootedSectionStubToAdapter(); // When int viewTypeLoading = sectionAdapter.getItemViewType(44); // Then assertThat(viewTypeLoading, is(27)); } @Test public void getItemViewType_withAdapterWithManySections_returnsCorrectValuesForSectionWithFailedState() { // Given addStatelessSectionStubToAdapter(); addHeadedStatelessSectionStubToAdapter(); addFootedStatelessSectionStubToAdapter(); addHeadedFootedStatelessSectionStubToAdapter(); Section section = addSectionStubToAdapter(); section.setState(Section.State.FAILED); addHeadedSectionStubToAdapter(); addFootedSectionStubToAdapter(); addHeadedFootedSectionStubToAdapter(); // When int viewTypeFailed = sectionAdapter.getItemViewType(44); // Then assertThat(viewTypeFailed, is(28)); } @Test public void getItemViewType_withAdapterWithManySections_returnsCorrectValuesForSectionWithEmptyState() { // Given addStatelessSectionStubToAdapter(); addHeadedStatelessSectionStubToAdapter(); addFootedStatelessSectionStubToAdapter(); addHeadedFootedStatelessSectionStubToAdapter(); Section section = addSectionStubToAdapter(); section.setState(Section.State.EMPTY); addHeadedSectionStubToAdapter(); addFootedSectionStubToAdapter(); addHeadedFootedSectionStubToAdapter(); // When int viewTypeEmpty = sectionAdapter.getItemViewType(44); // Then assertThat(viewTypeEmpty, is(29)); } @Test public void onCreateViewHolder_withEmptyAdapter_returnsNull() { // When Object result = sectionAdapter.onCreateViewHolder(null, 0); // Then assertNull(result); } @Test(expected = NullPointerException.class) public void onCreateViewHolder_withStatelessSection_throwsExceptionForHeader() { // Given addStatelessSectionStubToAdapter(); sectionAdapter.onCreateViewHolder(null, SectionedRecyclerViewAdapter.VIEW_TYPE_HEADER); } @Test(expected = NullPointerException.class) public void onCreateViewHolder_withStatelessSection_throwsExceptionForFooter() { // Given addStatelessSectionStubToAdapter(); // When sectionAdapter.onCreateViewHolder(null, SectionedRecyclerViewAdapter.VIEW_TYPE_FOOTER); } @Test(expected = NullPointerException.class) public void onCreateViewHolder_withStatelessSection_throwsExceptionForLoading() { // Given addStatelessSectionStubToAdapter(); // When sectionAdapter.onCreateViewHolder(null, SectionedRecyclerViewAdapter.VIEW_TYPE_LOADING); } @Test(expected = NullPointerException.class) public void onCreateViewHolder_withStatelessSection_throwsExceptionForFailed() { // Given addStatelessSectionStubToAdapter(); // When sectionAdapter.onCreateViewHolder(null, SectionedRecyclerViewAdapter.VIEW_TYPE_FAILED); } @Test public void removeAllSections_withAdapterWithManySections_succeeds() { // Given addFourStatelessSectionsAndFourSectionsToAdapter(); // When sectionAdapter.removeAllSections(); // Then assertThat(sectionAdapter.getItemCount(), is(0)); assertTrue(sectionAdapter.getSectionsMap().isEmpty()); } @Test public void getPositionInAdapterUsingTag_withAdapterWithManySections_returnsCorrectAdapterPosition() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY)); // When int result = spySectionedRecyclerViewAdapter.getPositionInAdapter(SECTION_TAG, 0); // Then assertThat(result, is(11)); } @Test public void getPositionInAdapterUsingSection_withAdapterWithManySections_returnsCorrectAdapterPosition() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY); spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub); // When int result = spySectionedRecyclerViewAdapter.getPositionInAdapter(headedFootedStatelessSectionStub, 0); // Then assertThat(result, is(11)); } @Test public void getHeaderPositionInAdapterUsingTag_withAdapterWithManySections_returnsCorrectAdapterHeaderPosition() { // Given sectionAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); sectionAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY)); // When int result = sectionAdapter.getHeaderPositionInAdapter(SECTION_TAG); // Then assertThat(result, is(10)); } @Test(expected = IllegalStateException.class) public void getHeaderPositionInAdapterUsingTag_withAdapterWithManySections_throwsIllegalStateException() { sectionAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); sectionAdapter.addSection(SECTION_TAG, new StatelessSectionStub(ITEMS_QTY)); // When sectionAdapter.getHeaderPositionInAdapter(SECTION_TAG); } @Test public void getFooterPositionInAdapterUsingTag_withAdapterWithManySections_returnsCorrectAdapterFooterPosition() { // Given sectionAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); sectionAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY)); // When int result = sectionAdapter.getFooterPositionInAdapter(SECTION_TAG); // Then assertThat(result, is(21)); } @Test(expected = IllegalStateException.class) public void getFooterPositionInAdapterUsingTag_withAdapterWithManySections_throwsIllegalStateException() { sectionAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); sectionAdapter.addSection(SECTION_TAG, new StatelessSectionStub(ITEMS_QTY)); // When sectionAdapter.getFooterPositionInAdapter(SECTION_TAG); } @Test public void notifyItemInsertedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemInserted() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY)); // When spySectionedRecyclerViewAdapter.notifyItemInsertedInSection(SECTION_TAG, 0); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(11); } @Test public void notifyItemInsertedInSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemInserted() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY); spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub); // When spySectionedRecyclerViewAdapter.notifyItemInsertedInSection(headedFootedStatelessSectionStub, 0); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(11); } @Test public void notifyItemRangeInsertedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemRangeInserted() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeInserted(anyInt(), anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY)); // When spySectionedRecyclerViewAdapter.notifyItemRangeInsertedInSection(SECTION_TAG, 0, 4); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeInserted(11, 4); } @Test public void notifyItemRangeInsertedInSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemRangeInserted() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeInserted(anyInt(), anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY); spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub); // When spySectionedRecyclerViewAdapter.notifyItemRangeInsertedInSection(headedFootedStatelessSectionStub, 0, 4); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeInserted(11, 4); } @Test public void notifyItemRemovedFromSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemRemoved() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRemoved(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY)); // When spySectionedRecyclerViewAdapter.notifyItemRemovedFromSection(SECTION_TAG, 0); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRemoved(11); } @Test public void notifyItemRemovedFromSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemRemoved() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRemoved(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY); spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub); // When spySectionedRecyclerViewAdapter.notifyItemRemovedFromSection(headedFootedStatelessSectionStub, 0); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRemoved(11); } @Test public void notifyItemRangeRemovedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemRangeRemoved() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeRemoved(anyInt(), anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY)); // When spySectionedRecyclerViewAdapter.notifyItemRangeRemovedFromSection(SECTION_TAG, 0, 4); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeRemoved(11, 4); } @Test public void notifyItemRangeRemovedInSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemRangeRemoved() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeRemoved(anyInt(), anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY); spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub); // When spySectionedRecyclerViewAdapter.notifyItemRangeRemovedFromSection(headedFootedStatelessSectionStub, 0, 4); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeRemoved(11, 4); } @Test public void notifyItemChangedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemChangedInSection() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY)); // When spySectionedRecyclerViewAdapter.notifyItemChangedInSection(SECTION_TAG, 0); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(11); } @Test public void notifyItemChangedInSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemChangedInSection() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY); spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub); // When spySectionedRecyclerViewAdapter.notifyItemChangedInSection(headedFootedStatelessSectionStub, 0); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(11); } @Test public void notifyHeaderChangedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemChangedInSection() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY)); // When spySectionedRecyclerViewAdapter.notifyHeaderChangedInSection(SECTION_TAG); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(10); } @Test(expected = IllegalStateException.class) public void notifyHeaderChangedInSectionUsingTag_withAdapterWithManySections_throwsIllegalStateException() { // Given sectionAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); sectionAdapter.addSection(SECTION_TAG, new StatelessSectionStub(ITEMS_QTY)); // When sectionAdapter.notifyHeaderChangedInSection(SECTION_TAG); } @Test public void notifyFooterChangedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemChangedInSection() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY)); // When spySectionedRecyclerViewAdapter.notifyFooterChangedInSection(SECTION_TAG); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(21); } @Test(expected = IllegalStateException.class) public void notifyFooterChangedInSectionUsingTag_withAdapterWithManySections_throwsIllegalStateException() { // Given sectionAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); sectionAdapter.addSection(SECTION_TAG, new StatelessSectionStub(ITEMS_QTY)); // When sectionAdapter.notifyFooterChangedInSection(SECTION_TAG); } @Test public void notifyItemRangeChangedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemRangeChanged() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(anyInt(), anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY)); // When spySectionedRecyclerViewAdapter.notifyItemRangeChangedInSection(SECTION_TAG, 0, 4); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(11, 4); } @Test public void notifyItemRangeChangedInSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemRangeChanged() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(anyInt(), anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY); spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub); // When spySectionedRecyclerViewAdapter.notifyItemRangeChangedInSection(headedFootedStatelessSectionStub, 0, 4); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(11, 4); } @Test public void notifyItemRangeChangedInSectionWithPayloadUsingTag_withAdapterWithManySections_callsSuperNotifyItemRangeChanged() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(anyInt(), anyInt(), any()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY)); // When spySectionedRecyclerViewAdapter.notifyItemRangeChangedInSection(SECTION_TAG, 0, 4, null); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(11, 4, null); } @Test public void notifyItemRangeChangedInSectionWithPayloadUsingSection_withAdapterWithManySections_callsSuperNotifyItemRangeChanged() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(anyInt(), anyInt(), any()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY); spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub); // When spySectionedRecyclerViewAdapter.notifyItemRangeChangedInSection(headedFootedStatelessSectionStub, 0, 4, null); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(11, 4, null); } @Test public void notifyItemMovedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemMoved() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemMoved(anyInt(), anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY)); // When spySectionedRecyclerViewAdapter.notifyItemMovedInSection(SECTION_TAG, 0, 4); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemMoved(11, 15); } @Test public void notifyItemMovedInSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemMoved() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemMoved(anyInt(), anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY); spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub); // When spySectionedRecyclerViewAdapter.notifyItemMovedInSection(headedFootedStatelessSectionStub, 0, 4); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemMoved(11, 15); } @Test public void notifyHeaderInsertedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemInserted() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedSectionStub headedFootedSectionStub = new HeadedFootedSectionStub(ITEMS_QTY); headedFootedSectionStub.setHasHeader(false); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, headedFootedSectionStub); // When headedFootedSectionStub.setHasHeader(true); spySectionedRecyclerViewAdapter.notifyHeaderInsertedInSection(SECTION_TAG); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(10); } @Test public void notifyFooterInsertedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemInserted() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedSectionStub headedFootedSectionStub = new HeadedFootedSectionStub(ITEMS_QTY); headedFootedSectionStub.setHasFooter(false); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, headedFootedSectionStub); // When headedFootedSectionStub.setHasFooter(true); spySectionedRecyclerViewAdapter.notifyFooterInsertedInSection(SECTION_TAG); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(21); } @Test public void notifyHeaderRemovedFromSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemRemoved() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRemoved(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedSectionStub headedFootedSectionStub = new HeadedFootedSectionStub(ITEMS_QTY); headedFootedSectionStub.setHasHeader(true); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, headedFootedSectionStub); // When headedFootedSectionStub.setHasHeader(false); spySectionedRecyclerViewAdapter.notifyHeaderRemovedFromSection(SECTION_TAG); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRemoved(10); } @Test public void notifyFooterRemovedFromSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemRemoved() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRemoved(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedSectionStub headedFootedSectionStub = new HeadedFootedSectionStub(ITEMS_QTY); headedFootedSectionStub.setHasFooter(true); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, headedFootedSectionStub); // When headedFootedSectionStub.setHasFooter(false); spySectionedRecyclerViewAdapter.notifyFooterRemovedFromSection(SECTION_TAG); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRemoved(21); } @Test(expected = IllegalStateException.class) public void notifySectionChangedToVisibleUsingTag_withInvisibleSection_throwsException() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeInserted(anyInt(), anyInt()); HeadedFootedSectionStub headedFootedSectionStub = new HeadedFootedSectionStub(ITEMS_QTY); headedFootedSectionStub.setVisible(false); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, headedFootedSectionStub); // When spySectionedRecyclerViewAdapter.notifySectionChangedToVisible(SECTION_TAG); } @Test(expected = IllegalStateException.class) public void notifySectionChangedToInvisibleUsingTag_withVisibleSection_throwsException() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeRemoved(anyInt(), anyInt()); HeadedFootedSectionStub headedFootedSectionStub = new HeadedFootedSectionStub(ITEMS_QTY); headedFootedSectionStub.setVisible(true); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, headedFootedSectionStub); // When int previousSectionPosition = spySectionedRecyclerViewAdapter.getSectionPosition(headedFootedSectionStub); spySectionedRecyclerViewAdapter.notifySectionChangedToInvisible(SECTION_TAG, previousSectionPosition); } @Test public void notifySectionChangedToVisibleUsingTag_withAdapterWithManySections_callsSuperNotifyItemRangeInserted() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeInserted(anyInt(), anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedSectionStub headedFootedSectionStub = new HeadedFootedSectionStub(ITEMS_QTY); headedFootedSectionStub.setVisible(false); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, headedFootedSectionStub); // When headedFootedSectionStub.setVisible(true); spySectionedRecyclerViewAdapter.notifySectionChangedToVisible(SECTION_TAG); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeInserted(10, 12); } @Test public void notifySectionChangedToInvisibleUsingTag_withAdapterWithManySections_callsSuperNotifyItemRangeInserted() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeRemoved(anyInt(), anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedSectionStub headedFootedSectionStub = new HeadedFootedSectionStub(ITEMS_QTY); headedFootedSectionStub.setVisible(true); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, headedFootedSectionStub); // When int previousSectionPosition = spySectionedRecyclerViewAdapter.getSectionPosition(headedFootedSectionStub); headedFootedSectionStub.setVisible(false); spySectionedRecyclerViewAdapter.notifySectionChangedToInvisible(SECTION_TAG, previousSectionPosition); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeRemoved(10, 12); } private void addFourStatelessSectionsAndFourSectionsToAdapter() { addStatelessSectionStubToAdapter(); addHeadedStatelessSectionStubToAdapter(); addFootedStatelessSectionStubToAdapter(); addHeadedFootedStatelessSectionStubToAdapter(); addSectionStubToAdapter(); addHeadedSectionStubToAdapter(); addFootedSectionStubToAdapter(); addHeadedFootedSectionStubToAdapter(); } private StatelessSectionStub addStatelessSectionStubToAdapter() { StatelessSectionStub sectionStub = new StatelessSectionStub(ITEMS_QTY); sectionAdapter.addSection(sectionStub); return sectionStub; } private void addInvisibleStatelessSectionStubToAdapter() { Section sectionStub = addStatelessSectionStubToAdapter(); sectionStub.setVisible(false); } private SectionStub addSectionStubToAdapter() { SectionStub sectionStub = new SectionStub(ITEMS_QTY); sectionAdapter.addSection(sectionStub); return sectionStub; } private HeadedStatelessSectionStub addHeadedStatelessSectionStubToAdapter() { HeadedStatelessSectionStub headedSectionSub = new HeadedStatelessSectionStub(ITEMS_QTY); sectionAdapter.addSection(headedSectionSub); return headedSectionSub; } private HeadedSectionStub addHeadedSectionStubToAdapter() { HeadedSectionStub headedSectionSub = new HeadedSectionStub(ITEMS_QTY); sectionAdapter.addSection(headedSectionSub); return headedSectionSub; } private FootedStatelessSectionStub addFootedStatelessSectionStubToAdapter() { FootedStatelessSectionStub footedSectionSub = new FootedStatelessSectionStub(ITEMS_QTY); sectionAdapter.addSection(footedSectionSub); return footedSectionSub; } private FootedSectionStub addFootedSectionStubToAdapter() { FootedSectionStub footedSectionSub = new FootedSectionStub(ITEMS_QTY); sectionAdapter.addSection(footedSectionSub); return footedSectionSub; } private HeadedFootedStatelessSectionStub addHeadedFootedStatelessSectionStubToAdapter() { HeadedFootedStatelessSectionStub headedFootedSectionSub = new HeadedFootedStatelessSectionStub(ITEMS_QTY); sectionAdapter.addSection(headedFootedSectionSub); return headedFootedSectionSub; } private HeadedFootedSectionStub addHeadedFootedSectionStubToAdapter() { HeadedFootedSectionStub headedFootedSectionSub = new HeadedFootedSectionStub(ITEMS_QTY); sectionAdapter.addSection(headedFootedSectionSub); return headedFootedSectionSub; } }
library/src/test/java/io/github/luizgrp/sectionedrecyclerviewadapter/SectionedRecyclerViewAdapterTest.java
package io.github.luizgrp.sectionedrecyclerviewadapter; import org.junit.Before; import org.junit.Test; import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.FootedSectionStub; import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.FootedStatelessSectionStub; import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.HeadedFootedSectionStub; import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.HeadedFootedStatelessSectionStub; import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.HeadedSectionStub; import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.HeadedStatelessSectionStub; import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.SectionStub; import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.StatelessSectionStub; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; /** * Unit tests for {@link SectionedRecyclerViewAdapter} */ public class SectionedRecyclerViewAdapterTest { private final int ITEMS_QTY = 10; private final String SECTION_TAG = "tag"; private SectionedRecyclerViewAdapter sectionAdapter; @Before public void setup() { sectionAdapter = new SectionedRecyclerViewAdapter(); } @Test(expected = IndexOutOfBoundsException.class) public void getPositionInSection_withEmptyAdapter_throwsException() { // When sectionAdapter.getPositionInSection(0); } @Test public void getPositionInSection_withAdapterWithInvisibleSection_returnsCorrectPosition() { // Given addHeadedFootedStatelessSectionStubToAdapter(); addInvisibleStatelessSectionStubToAdapter(); addHeadedFootedStatelessSectionStubToAdapter(); // When int result = sectionAdapter.getPositionInSection(13); int result2 = sectionAdapter.getPositionInSection(22); // Then assertThat(result, is(0)); assertThat(result2, is(9)); } @Test(expected = IllegalArgumentException.class) public void getSectionPositionUsingTag_withEmptyAdapter_throwsException() { // When sectionAdapter.getSectionPosition(SECTION_TAG); } @Test(expected = IllegalArgumentException.class) public void getSectionPositionUsingTag_withInvalidTag_throwsException() { // Given addStatelessSectionStubToAdapter(); addStatelessSectionStubToAdapter(); // When sectionAdapter.getSectionPosition(SECTION_TAG); } @Test public void getSectionPositionUsingTag_withAdapterWithInvisibleSection_returnsCorrectPosition() { // Given addStatelessSectionStubToAdapter(); addInvisibleStatelessSectionStubToAdapter(); sectionAdapter.addSection(SECTION_TAG, new StatelessSectionStub(ITEMS_QTY)); // When int result = sectionAdapter.getSectionPosition(SECTION_TAG); // Then assertThat(result, is(10)); } @Test(expected = IllegalArgumentException.class) public void getSectionPositionUsingSection_withEmptyAdapter_throwsException() { // When sectionAdapter.getSectionPosition(new StatelessSectionStub(ITEMS_QTY)); } @Test(expected = IllegalArgumentException.class) public void getSectionPositionUsingSection_withInvalidSection_throwsException() { // Given addStatelessSectionStubToAdapter(); addStatelessSectionStubToAdapter(); // When sectionAdapter.getSectionPosition(new StatelessSectionStub(ITEMS_QTY)); } @Test public void getSectionPositionUsingSection_withAdapterWithInvisibleSection_returnsCorrectPosition() { // Given addStatelessSectionStubToAdapter(); addInvisibleStatelessSectionStubToAdapter(); StatelessSectionStub statelessSectionStub = new StatelessSectionStub(ITEMS_QTY); sectionAdapter.addSection(statelessSectionStub); // When int result = sectionAdapter.getSectionPosition(statelessSectionStub); // Then assertThat(result, is(10)); } @Test(expected = IndexOutOfBoundsException.class) public void onBindViewHolder_withEmptyAdapter_throwsException() { // When sectionAdapter.onBindViewHolder(null, 0); } @Test public void addSection_withEmptyAdapter_succeeds() { // Given Section section = new StatelessSectionStub(ITEMS_QTY); // When sectionAdapter.addSection(SECTION_TAG, section); // Then assertSame(sectionAdapter.getSection(SECTION_TAG), section); assertSame(sectionAdapter.getSectionsMap().get(SECTION_TAG), section); } @Test public void addSectionWithTag_withEmptyAdapter_succeeds() { // Given Section section = new StatelessSectionStub(ITEMS_QTY); // When sectionAdapter.addSection(SECTION_TAG, section); // Then assertSame(sectionAdapter.getSection(SECTION_TAG), section); assertSame(sectionAdapter.getSectionsMap().get(SECTION_TAG), section); } @Test public void getSectionWithTag_withRemovedSection_returnsNull() { // Given sectionAdapter.addSection(SECTION_TAG, new StatelessSectionStub(ITEMS_QTY)); // When sectionAdapter.removeSection(SECTION_TAG); // Then assertNull(sectionAdapter.getSection(SECTION_TAG)); } @Test public void getSectionWithTag_withEmptyAdapter_returnsNull() { // When Section result = sectionAdapter.getSection(SECTION_TAG); // Then assertNull(result); } @Test public void getItemCount_withEmptyAdapter_isZero() { // When int result = sectionAdapter.getItemCount(); // Then assertThat(result, is(0)); } @Test public void getItemCount_withAdapterWithInvisibleSection_returnsCorrectQuantity() { // Given addStatelessSectionStubToAdapter(); addInvisibleStatelessSectionStubToAdapter(); // When int result = sectionAdapter.getItemCount(); // Then assertThat(result, is(ITEMS_QTY)); } @Test public void getSectionsMap_withEmptyAdapter_isEmpty() { // When boolean result = sectionAdapter.getSectionsMap().isEmpty(); // Then assertTrue(result); } @Test public void getSectionsMap_withAdapterWithInvisibleSection_hasCorrectSize() { // Given addStatelessSectionStubToAdapter(); addInvisibleStatelessSectionStubToAdapter(); // When int result = sectionAdapter.getSectionsMap().size(); // Then assertThat(result, is(2)); } @Test public void getSection_withEmptyAdapter_isNull() { // When Section result = sectionAdapter.getSection(SECTION_TAG); // Then assertNull(result); } @Test public void getSection_withAdapterWithManySections_returnsCorrectSection() { // Given addStatelessSectionStubToAdapter(); Section section = new StatelessSectionStub(ITEMS_QTY); sectionAdapter.addSection(SECTION_TAG, section); addStatelessSectionStubToAdapter(); // When Section result = sectionAdapter.getSection(SECTION_TAG); // Then assertSame(result, section); } @Test(expected = IndexOutOfBoundsException.class) public void getSectionForPosition_withEmptyAdapter_throwsException() { // When sectionAdapter.getSectionForPosition(0); } @Test public void getSectionForPosition_withAdapterWithManySections_returnsCorrectSection() { // Given Section sectionStub1 = addStatelessSectionStubToAdapter(); Section sectionStub2 = addStatelessSectionStubToAdapter(); Section sectionStub3 = addStatelessSectionStubToAdapter(); // When Section result = sectionAdapter.getSectionForPosition(0); Section result2 = sectionAdapter.getSectionForPosition(9); Section result3 = sectionAdapter.getSectionForPosition(10); Section result4 = sectionAdapter.getSectionForPosition(19); Section result5 = sectionAdapter.getSectionForPosition(20); Section result6 = sectionAdapter.getSectionForPosition(29); // Then assertSame(result, sectionStub1); assertSame(result2, sectionStub1); assertSame(result3, sectionStub2); assertSame(result4, sectionStub2); assertSame(result5, sectionStub3); assertSame(result6, sectionStub3); } @Test(expected = IndexOutOfBoundsException.class) public void getSectionItemViewType_withEmptyAdapter_throwsException() { // When sectionAdapter.getSectionItemViewType(0); } @Test public void getSectionItemViewType_withAdapterWithManySections_returnsCorrectValuesForHeadedFootedStatelessSection() { // Given addFourStatelessSectionsAndFourSectionsToAdapter(); // When int viewTypeHeader = sectionAdapter.getSectionItemViewType(32); int viewTypeItemStart = sectionAdapter.getSectionItemViewType(33); int viewTypeItemEnd = sectionAdapter.getSectionItemViewType(42); int viewTypeFooter = sectionAdapter.getSectionItemViewType(43); // Then assertThat(viewTypeHeader, is(SectionedRecyclerViewAdapter.VIEW_TYPE_HEADER)); assertThat(viewTypeItemStart, is(SectionedRecyclerViewAdapter.VIEW_TYPE_ITEM_LOADED)); assertThat(viewTypeItemEnd, is(SectionedRecyclerViewAdapter.VIEW_TYPE_ITEM_LOADED)); assertThat(viewTypeFooter, is(SectionedRecyclerViewAdapter.VIEW_TYPE_FOOTER)); } @Test(expected = IndexOutOfBoundsException.class) public void getItemViewType_withEmptyAdapter_throwsException() { // When sectionAdapter.getItemViewType(0); } @Test public void getItemViewType_withAdapterWithManySections_returnsCorrectValuesForHeadedFootedStatelessSection() { // Given addFourStatelessSectionsAndFourSectionsToAdapter(); // When int viewTypeHeader = sectionAdapter.getItemViewType(32); int viewTypeItemStart = sectionAdapter.getItemViewType(33); int viewTypeItemEnd = sectionAdapter.getItemViewType(42); int viewTypeFooter = sectionAdapter.getItemViewType(43); // Then assertThat(viewTypeHeader, is(18)); assertThat(viewTypeItemStart, is(20)); assertThat(viewTypeItemEnd, is(20)); assertThat(viewTypeFooter, is(19)); } @Test public void getItemViewType_withAdapterWithManySections_returnsCorrectValuesForSectionWithLoadingState() { // Given addStatelessSectionStubToAdapter(); addHeadedStatelessSectionStubToAdapter(); addFootedStatelessSectionStubToAdapter(); addHeadedFootedStatelessSectionStubToAdapter(); Section section = addSectionStubToAdapter(); section.setState(Section.State.LOADING); addHeadedSectionStubToAdapter(); addFootedSectionStubToAdapter(); addHeadedFootedSectionStubToAdapter(); // When int viewTypeLoading = sectionAdapter.getItemViewType(44); // Then assertThat(viewTypeLoading, is(27)); } @Test public void getItemViewType_withAdapterWithManySections_returnsCorrectValuesForSectionWithFailedState() { // Given addStatelessSectionStubToAdapter(); addHeadedStatelessSectionStubToAdapter(); addFootedStatelessSectionStubToAdapter(); addHeadedFootedStatelessSectionStubToAdapter(); Section section = addSectionStubToAdapter(); section.setState(Section.State.FAILED); addHeadedSectionStubToAdapter(); addFootedSectionStubToAdapter(); addHeadedFootedSectionStubToAdapter(); // When int viewTypeFailed = sectionAdapter.getItemViewType(44); // Then assertThat(viewTypeFailed, is(28)); } @Test public void getItemViewType_withAdapterWithManySections_returnsCorrectValuesForSectionWithEmptyState() { // Given addStatelessSectionStubToAdapter(); addHeadedStatelessSectionStubToAdapter(); addFootedStatelessSectionStubToAdapter(); addHeadedFootedStatelessSectionStubToAdapter(); Section section = addSectionStubToAdapter(); section.setState(Section.State.EMPTY); addHeadedSectionStubToAdapter(); addFootedSectionStubToAdapter(); addHeadedFootedSectionStubToAdapter(); // When int viewTypeEmpty = sectionAdapter.getItemViewType(44); // Then assertThat(viewTypeEmpty, is(29)); } @Test public void onCreateViewHolder_withEmptyAdapter_returnsNull() { // When Object result = sectionAdapter.onCreateViewHolder(null, 0); // Then assertNull(result); } @Test(expected = NullPointerException.class) public void onCreateViewHolder_withStatelessSection_throwsExceptionForHeader() { // Given addStatelessSectionStubToAdapter(); sectionAdapter.onCreateViewHolder(null, SectionedRecyclerViewAdapter.VIEW_TYPE_HEADER); } @Test(expected = NullPointerException.class) public void onCreateViewHolder_withStatelessSection_throwsExceptionForFooter() { // Given addStatelessSectionStubToAdapter(); // When sectionAdapter.onCreateViewHolder(null, SectionedRecyclerViewAdapter.VIEW_TYPE_FOOTER); } @Test(expected = NullPointerException.class) public void onCreateViewHolder_withStatelessSection_throwsExceptionForLoading() { // Given addStatelessSectionStubToAdapter(); // When sectionAdapter.onCreateViewHolder(null, SectionedRecyclerViewAdapter.VIEW_TYPE_LOADING); } @Test(expected = NullPointerException.class) public void onCreateViewHolder_withStatelessSection_throwsExceptionForFailed() { // Given addStatelessSectionStubToAdapter(); // When sectionAdapter.onCreateViewHolder(null, SectionedRecyclerViewAdapter.VIEW_TYPE_FAILED); } @Test public void removeAllSections_withAdapterWithManySections_succeeds() { // Given addFourStatelessSectionsAndFourSectionsToAdapter(); // When sectionAdapter.removeAllSections(); // Then assertThat(sectionAdapter.getItemCount(), is(0)); assertTrue(sectionAdapter.getSectionsMap().isEmpty()); } @Test public void getPositionInAdapterUsingTag_withAdapterWithManySections_returnsCorrectAdapterPosition() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY)); // When int result = spySectionedRecyclerViewAdapter.getPositionInAdapter(SECTION_TAG, 0); // Then assertThat(result, is(11)); } @Test public void getPositionInAdapterUsingSection_withAdapterWithManySections_returnsCorrectAdapterPosition() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY); spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub); // When int result = spySectionedRecyclerViewAdapter.getPositionInAdapter(headedFootedStatelessSectionStub, 0); // Then assertThat(result, is(11)); } @Test public void getHeaderPositionInAdapterUsingTag_withAdapterWithManySections_returnsCorrectAdapterHeaderPosition() { // Given sectionAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); sectionAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY)); // When int result = sectionAdapter.getHeaderPositionInAdapter(SECTION_TAG); // Then assertThat(result, is(10)); } @Test(expected = IllegalStateException.class) public void getHeaderPositionInAdapterUsingTag_withAdapterWithManySections_throwsIllegalStateException() { sectionAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); sectionAdapter.addSection(SECTION_TAG, new StatelessSectionStub(ITEMS_QTY)); // When sectionAdapter.getHeaderPositionInAdapter(SECTION_TAG); } @Test public void getFooterPositionInAdapterUsingTag_withAdapterWithManySections_returnsCorrectAdapterFooterPosition() { // Given sectionAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); sectionAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY)); // When int result = sectionAdapter.getFooterPositionInAdapter(SECTION_TAG); // Then assertThat(result, is(21)); } @Test(expected = IllegalStateException.class) public void getFooterPositionInAdapterUsingTag_withAdapterWithManySections_throwsIllegalStateException() { sectionAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); sectionAdapter.addSection(SECTION_TAG, new StatelessSectionStub(ITEMS_QTY)); // When sectionAdapter.getFooterPositionInAdapter(SECTION_TAG); } @Test public void notifyItemInsertedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemInserted() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY)); // When spySectionedRecyclerViewAdapter.notifyItemInsertedInSection(SECTION_TAG, 0); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(11); } @Test public void notifyItemInsertedInSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemInserted() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY); spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub); // When spySectionedRecyclerViewAdapter.notifyItemInsertedInSection(headedFootedStatelessSectionStub, 0); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(11); } @Test public void notifyItemRangeInsertedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemRangeInserted() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeInserted(anyInt(), anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY)); // When spySectionedRecyclerViewAdapter.notifyItemRangeInsertedInSection(SECTION_TAG, 0, 4); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeInserted(11, 4); } @Test public void notifyItemRangeInsertedInSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemRangeInserted() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeInserted(anyInt(), anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY); spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub); // When spySectionedRecyclerViewAdapter.notifyItemRangeInsertedInSection(headedFootedStatelessSectionStub, 0, 4); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeInserted(11, 4); } @Test public void notifyItemRemovedFromSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemRemoved() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRemoved(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY)); // When spySectionedRecyclerViewAdapter.notifyItemRemovedFromSection(SECTION_TAG, 0); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRemoved(11); } @Test public void notifyItemRemovedFromSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemRemoved() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRemoved(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY); spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub); // When spySectionedRecyclerViewAdapter.notifyItemRemovedFromSection(headedFootedStatelessSectionStub, 0); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRemoved(11); } @Test public void notifyItemRangeRemovedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemRangeRemoved() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeRemoved(anyInt(), anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY)); // When spySectionedRecyclerViewAdapter.notifyItemRangeRemovedFromSection(SECTION_TAG, 0, 4); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeRemoved(11, 4); } @Test public void notifyItemRangeRemovedInSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemRangeRemoved() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeRemoved(anyInt(), anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY); spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub); // When spySectionedRecyclerViewAdapter.notifyItemRangeRemovedFromSection(headedFootedStatelessSectionStub, 0, 4); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeRemoved(11, 4); } @Test public void notifyItemChangedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemChangedInSection() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY)); // When spySectionedRecyclerViewAdapter.notifyItemChangedInSection(SECTION_TAG, 0); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(11); } @Test public void notifyItemChangedInSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemChangedInSection() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY); spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub); // When spySectionedRecyclerViewAdapter.notifyItemChangedInSection(headedFootedStatelessSectionStub, 0); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(11); } @Test public void notifyHeaderChangedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemChangedInSection() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY)); // When spySectionedRecyclerViewAdapter.notifyHeaderChangedInSection(SECTION_TAG); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(10); } @Test(expected = IllegalStateException.class) public void notifyHeaderChangedInSectionUsingTag_withAdapterWithManySections_throwsIllegalStateException() { // Given sectionAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); sectionAdapter.addSection(SECTION_TAG, new StatelessSectionStub(ITEMS_QTY)); // When sectionAdapter.notifyHeaderChangedInSection(SECTION_TAG); } @Test public void notifyFooterChangedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemChangedInSection() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY)); // When spySectionedRecyclerViewAdapter.notifyFooterChangedInSection(SECTION_TAG); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(21); } @Test(expected = IllegalStateException.class) public void notifyFooterChangedInSectionUsingTag_withAdapterWithManySections_throwsIllegalStateException() { // Given sectionAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); sectionAdapter.addSection(SECTION_TAG, new StatelessSectionStub(ITEMS_QTY)); // When sectionAdapter.notifyFooterChangedInSection(SECTION_TAG); } @Test public void notifyItemRangeChangedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemRangeChanged() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(anyInt(), anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY)); // When spySectionedRecyclerViewAdapter.notifyItemRangeChangedInSection(SECTION_TAG, 0, 4); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(11, 4); } @Test public void notifyItemRangeChangedInSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemRangeChanged() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(anyInt(), anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY); spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub); // When spySectionedRecyclerViewAdapter.notifyItemRangeChangedInSection(headedFootedStatelessSectionStub, 0, 4); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(11, 4); } @Test public void notifyItemRangeChangedInSectionWithPayloadUsingTag_withAdapterWithManySections_callsSuperNotifyItemRangeChanged() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(anyInt(), anyInt(), any()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY)); // When spySectionedRecyclerViewAdapter.notifyItemRangeChangedInSection(SECTION_TAG, 0, 4, null); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(11, 4, null); } @Test public void notifyItemRangeChangedInSectionWithPayloadUsingSection_withAdapterWithManySections_callsSuperNotifyItemRangeChanged() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(anyInt(), anyInt(), any()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY); spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub); // When spySectionedRecyclerViewAdapter.notifyItemRangeChangedInSection(headedFootedStatelessSectionStub, 0, 4, null); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(11, 4, null); } @Test public void notifyItemMovedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemMoved() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemMoved(anyInt(), anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY)); // When spySectionedRecyclerViewAdapter.notifyItemMovedInSection(SECTION_TAG, 0, 4); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemMoved(11, 15); } @Test public void notifyItemMovedInSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemMoved() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemMoved(anyInt(), anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY); spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub); // When spySectionedRecyclerViewAdapter.notifyItemMovedInSection(headedFootedStatelessSectionStub, 0, 4); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemMoved(11, 15); } @Test public void notifyHeaderInsertedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemInserted() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedSectionStub headedFootedSectionStub = new HeadedFootedSectionStub(ITEMS_QTY); headedFootedSectionStub.setHasHeader(false); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, headedFootedSectionStub); // When headedFootedSectionStub.setHasHeader(true); spySectionedRecyclerViewAdapter.notifyHeaderInsertedInSection(SECTION_TAG); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(10); } @Test public void notifyFooterInsertedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemInserted() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedSectionStub headedFootedSectionStub = new HeadedFootedSectionStub(ITEMS_QTY); headedFootedSectionStub.setHasFooter(false); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, headedFootedSectionStub); // When headedFootedSectionStub.setHasFooter(true); spySectionedRecyclerViewAdapter.notifyFooterInsertedInSection(SECTION_TAG); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(21); } @Test public void notifyHeaderRemovedFromSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemRemoved() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRemoved(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedSectionStub headedFootedSectionStub = new HeadedFootedSectionStub(ITEMS_QTY); headedFootedSectionStub.setHasHeader(true); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, headedFootedSectionStub); // When headedFootedSectionStub.setHasHeader(false); spySectionedRecyclerViewAdapter.notifyHeaderRemovedFromSection(SECTION_TAG); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRemoved(10); } @Test public void notifyFooterRemovedFromSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemRemoved() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRemoved(anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedSectionStub headedFootedSectionStub = new HeadedFootedSectionStub(ITEMS_QTY); headedFootedSectionStub.setHasFooter(true); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, headedFootedSectionStub); // When headedFootedSectionStub.setHasFooter(false); spySectionedRecyclerViewAdapter.notifyFooterRemovedFromSection(SECTION_TAG); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRemoved(21); } @Test(expected = IllegalStateException.class) public void notifySectionChangedToVisibleUsingTag_withAdapterWithManySections_throwsException() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeInserted(anyInt(), anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedSectionStub headedFootedSectionStub = new HeadedFootedSectionStub(ITEMS_QTY); headedFootedSectionStub.setVisible(false); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, headedFootedSectionStub); // When spySectionedRecyclerViewAdapter.notifySectionChangedToVisible(SECTION_TAG); } @Test(expected = IllegalStateException.class) public void notifySectionChangedToInvisibleUsingTag_withAdapterWithManySections_throwsException() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeRemoved(anyInt(), anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedSectionStub headedFootedSectionStub = new HeadedFootedSectionStub(ITEMS_QTY); headedFootedSectionStub.setVisible(true); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, headedFootedSectionStub); // When int previousSectionPosition = spySectionedRecyclerViewAdapter.getSectionPosition(headedFootedSectionStub); spySectionedRecyclerViewAdapter.notifySectionChangedToInvisible(SECTION_TAG, previousSectionPosition); } @Test public void notifySectionChangedToVisibleUsingTag_withAdapterWithManySections_callsSuperNotifyItemRangeInserted() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeInserted(anyInt(), anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedSectionStub headedFootedSectionStub = new HeadedFootedSectionStub(ITEMS_QTY); headedFootedSectionStub.setVisible(false); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, headedFootedSectionStub); // When headedFootedSectionStub.setVisible(true); spySectionedRecyclerViewAdapter.notifySectionChangedToVisible(SECTION_TAG); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeInserted(10, 12); } @Test public void notifySectionChangedToInvisibleUsingTag_withAdapterWithManySections_callsSuperNotifyItemRangeInserted() { // Given SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class); doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeRemoved(anyInt(), anyInt()); spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY)); HeadedFootedSectionStub headedFootedSectionStub = new HeadedFootedSectionStub(ITEMS_QTY); headedFootedSectionStub.setVisible(true); spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, headedFootedSectionStub); // When int previousSectionPosition = spySectionedRecyclerViewAdapter.getSectionPosition(headedFootedSectionStub); headedFootedSectionStub.setVisible(false); spySectionedRecyclerViewAdapter.notifySectionChangedToInvisible(SECTION_TAG, previousSectionPosition); // Then verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeRemoved(10, 12); } private void addFourStatelessSectionsAndFourSectionsToAdapter() { addStatelessSectionStubToAdapter(); addHeadedStatelessSectionStubToAdapter(); addFootedStatelessSectionStubToAdapter(); addHeadedFootedStatelessSectionStubToAdapter(); addSectionStubToAdapter(); addHeadedSectionStubToAdapter(); addFootedSectionStubToAdapter(); addHeadedFootedSectionStubToAdapter(); } private StatelessSectionStub addStatelessSectionStubToAdapter() { StatelessSectionStub sectionStub = new StatelessSectionStub(ITEMS_QTY); sectionAdapter.addSection(sectionStub); return sectionStub; } private void addInvisibleStatelessSectionStubToAdapter() { Section sectionStub = addStatelessSectionStubToAdapter(); sectionStub.setVisible(false); } private SectionStub addSectionStubToAdapter() { SectionStub sectionStub = new SectionStub(ITEMS_QTY); sectionAdapter.addSection(sectionStub); return sectionStub; } private HeadedStatelessSectionStub addHeadedStatelessSectionStubToAdapter() { HeadedStatelessSectionStub headedSectionSub = new HeadedStatelessSectionStub(ITEMS_QTY); sectionAdapter.addSection(headedSectionSub); return headedSectionSub; } private HeadedSectionStub addHeadedSectionStubToAdapter() { HeadedSectionStub headedSectionSub = new HeadedSectionStub(ITEMS_QTY); sectionAdapter.addSection(headedSectionSub); return headedSectionSub; } private FootedStatelessSectionStub addFootedStatelessSectionStubToAdapter() { FootedStatelessSectionStub footedSectionSub = new FootedStatelessSectionStub(ITEMS_QTY); sectionAdapter.addSection(footedSectionSub); return footedSectionSub; } private FootedSectionStub addFootedSectionStubToAdapter() { FootedSectionStub footedSectionSub = new FootedSectionStub(ITEMS_QTY); sectionAdapter.addSection(footedSectionSub); return footedSectionSub; } private HeadedFootedStatelessSectionStub addHeadedFootedStatelessSectionStubToAdapter() { HeadedFootedStatelessSectionStub headedFootedSectionSub = new HeadedFootedStatelessSectionStub(ITEMS_QTY); sectionAdapter.addSection(headedFootedSectionSub); return headedFootedSectionSub; } private HeadedFootedSectionStub addHeadedFootedSectionStubToAdapter() { HeadedFootedSectionStub headedFootedSectionSub = new HeadedFootedSectionStub(ITEMS_QTY); sectionAdapter.addSection(headedFootedSectionSub); return headedFootedSectionSub; } }
Reviewed.
library/src/test/java/io/github/luizgrp/sectionedrecyclerviewadapter/SectionedRecyclerViewAdapterTest.java
Reviewed.