answer
stringlengths
17
10.2M
package hudson.model.queue; import hudson.model.AbstractProject; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.Label; import hudson.model.Node; import hudson.model.Queue; import hudson.model.ResourceList; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestExtension; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.concurrent.TimeUnit; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; public class BuildKeepsRunningWhenFaultySubTasksTest { @Rule public JenkinsRule j = new JenkinsRule(); public static final String ERROR_MESSAGE = "My unexpected exception"; // When using SubTaskContributor (FailingSubTaskContributor) the build never ends @Test @Issue("JENKINS-59793") public void buildFinishesWhenSubTaskFails() throws Exception { FreeStyleProject p = j.createProject(FreeStyleProject.class); QueueTaskFuture<FreeStyleBuild> future = p.scheduleBuild2(0); assertThat("Build should be actually scheduled by Jenkins", future, notNullValue()); // We don't get stalled waiting the finalization of the job future.get(5, TimeUnit.SECONDS); } // A SubTask failing with an exception @TestExtension public static class FailingSubTaskContributor extends SubTaskContributor { @Override public Collection<? extends SubTask> forProject(final AbstractProject<?, ?> p) { return Collections.singleton(new SubTask() { private final SubTask outer = this; public Queue.Executable createExecutable() throws IOException { return new Queue.Executable() { public SubTask getParent() { return outer; } public void run() { throw new ArrayIndexOutOfBoundsException(ERROR_MESSAGE); } public long getEstimatedDuration() { return 0; } }; } @Override public Label getAssignedLabel() { return null; } @Override public Node getLastBuiltOn() { return null; } @Override public long getEstimatedDuration() { return 0; } @Override public Queue.Task getOwnerTask() { return p; } @Override public Object getSameNodeConstraint() { return null; } @Override public ResourceList getResourceList() { return ResourceList.EMPTY; } @Override public String getDisplayName() { return "Subtask of " + p.getDisplayName(); } }); } } }
package com.hazelcast.simulator.tests.external; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.ICountDownLatch; import com.hazelcast.core.IList; import com.hazelcast.logging.ILogger; import com.hazelcast.logging.Logger; import com.hazelcast.simulator.probes.probes.IntervalProbe; import com.hazelcast.simulator.probes.probes.SimpleProbe; import com.hazelcast.simulator.test.TestContext; import com.hazelcast.simulator.test.annotations.Run; import com.hazelcast.simulator.test.annotations.Setup; import com.hazelcast.util.EmptyStatement; import java.util.concurrent.TimeUnit; import static java.lang.String.format; public class ExternalClientTest { private static final ILogger LOGGER = Logger.getLogger(ExternalClientTest.class); // properties public String basename = "externalClientsRunning"; public int waitForClientsCount = 1; public int waitIntervalSeconds = 60; IntervalProbe externalClientLatency; SimpleProbe externalClientThroughput; private TestContext testContext; private HazelcastInstance hazelcastInstance; private ICountDownLatch clientsRunning; private boolean isExternalResultsCollectorInstance; @Setup public void setUp(TestContext testContext) throws Exception { this.testContext = testContext; hazelcastInstance = testContext.getTargetInstance(); clientsRunning = hazelcastInstance.getCountDownLatch(basename); clientsRunning.trySetCount(waitForClientsCount); // determine one instance per cluster if (hazelcastInstance.getMap(basename).putIfAbsent(basename, true) == null) { isExternalResultsCollectorInstance = true; LOGGER.info("This instance will collect all probe results from external clients"); } else { LOGGER.info("This instance will not collect probe results"); } } @Run public void run() { // wait for external clients to finish while (true) { try { clientsRunning.await(waitIntervalSeconds, TimeUnit.SECONDS); } catch (InterruptedException ignored) { EmptyStatement.ignore(ignored); } long clientsRunningCount = clientsRunning.getCount(); if (clientsRunningCount > 0) { LOGGER.info("Waiting for " + clientsRunningCount + " clients..."); } else { LOGGER.info("Got response from " + waitForClientsCount + " clients, stopping now!"); break; } } // just a single instance will collect the results from all external clients if (!isExternalResultsCollectorInstance) { // disable probes externalClientLatency.disable(); externalClientThroughput.disable(); LOGGER.info("Stopping non result collecting ExternalClientTest"); testContext.stop(); return; } LOGGER.info("Collecting results from external clients..."); // fetch latency results IList<Long> latencyResults = hazelcastInstance.getList("externalClientsLatencyResults"); int latencyResultSize = latencyResults.size(); LOGGER.info(format("Collecting %d latency results...", latencyResultSize)); Long[] latencyArray = new Long[latencyResultSize]; latencyResults.<Long>toArray(latencyArray); LOGGER.info(format("Adding %d latency results to probe...", latencyResultSize)); int counter = 0; for (Long latency : latencyArray) { externalClientLatency.recordValue(latency); if (++counter % 100000 == 0) { LOGGER.info(format("Collected %d/%d latency results...", counter, latencyResultSize)); } } LOGGER.info("Done!"); // fetch throughput results IList<String> throughputResults = hazelcastInstance.getList("externalClientsThroughputResults"); LOGGER.info("Collecting " + throughputResults.size() + " throughput results..."); double totalDuration = 0; int totalInvocations = 0; for (String throughputString : throughputResults) { String[] throughput = throughputString.split("\\|"); long operationCount = Long.valueOf(throughput[0]); long duration = TimeUnit.NANOSECONDS.toMillis(Long.valueOf(throughput[1])); LOGGER.info(format("External client executed %d operations in %d ms", operationCount, duration)); totalDuration += duration; totalInvocations += operationCount; } LOGGER.info("Done!"); long durationAvg = Math.round(totalDuration / throughputResults.size()); LOGGER.info(format("All external clients executed %d operations in %d ms", totalInvocations, durationAvg)); externalClientThroughput.setValues(durationAvg, totalInvocations); LOGGER.info("Stopping result collecting ExternalClientTest"); testContext.stop(); } }
package to.etc.domui.hibernate.model; import java.util.*; import org.hibernate.*; import org.hibernate.criterion.*; import org.hibernate.impl.*; import org.hibernate.metadata.*; import org.hibernate.persister.collection.*; import org.hibernate.persister.entity.*; import org.hibernate.type.*; import to.etc.domui.component.meta.*; import to.etc.util.*; import to.etc.webapp.*; import to.etc.webapp.qsql.*; import to.etc.webapp.query.*; public class CriteriaCreatingVisitor extends QNodeVisitorBase { private Session m_session; /** The topmost Criteria: the one that will be returned to effect the translated query */ private final Criteria m_rootCriteria; /** * This either holds a Criteria or a DetachedCriteria; since these are not related (sigh) we must * use instanceof everywhere. Bad, bad, bad hibernate design. */ private Object m_currentCriteria; private Criterion m_last; private Object m_lastSubCriteria; private int m_aliasIndex; private Class< ? > m_rootClass; static private final class CritEntry { // /** The class type queried by this subcriterion */ // private Class< ? > m_actualClass; /** Either a Criteria or a DetachedCriteria object, sigh */ private Object m_abomination; public CritEntry(Class< ? > actualClass, Object abomination) { // m_actualClass = actualClass; m_abomination = abomination; } /** * Return either the Criteria or DetachedCriteria. * @return */ public Object getAbomination() { return m_abomination; } // /** // * Return the actual type queried by the criterion. // * @return // */ // public Class< ? > getActualClass() { // return m_actualClass; } /** * Maps all subcriteria created for path entries, indexed by their FULL path name * from the root object. This prevents us from creating multiple subcriteria for * fields that lay after the same path reaching a parent relation. */ private Map<String, CritEntry> m_subCriteriaMap = new HashMap<String, CritEntry>(); public CriteriaCreatingVisitor(Session ses, final Criteria crit) { m_session = ses; m_rootCriteria = crit; m_currentCriteria = crit; } /** * Does a check to see if the class is a persistent class- because Hibernate itself is too * bloody stupid to do it. Querying an unknown class in Hibernate will return an empty * result set, sigh. * @param clz * @return */ public void checkHibernateClass(Class< ? > clz) { ClassMetadata childmd = m_session.getSessionFactory().getClassMetadata(clz); if(childmd == null) throw new IllegalArgumentException("The class " + clz + " is not known by Hibernate as a persistent class"); } private String nextAlias() { return "a" + (++m_aliasIndex); } private void addCriterion(Criterion c) { if(m_currentCriteria instanceof Criteria) { ((Criteria) m_currentCriteria).add(c); // Crapfest } else if(m_currentCriteria instanceof DetachedCriteria) { ((DetachedCriteria) m_currentCriteria).add(c); } else throw new IllegalStateException("Unexpected current thing: " + m_currentCriteria); } private void addOrder(Order c) { if(m_currentCriteria instanceof Criteria) { ((Criteria) m_currentCriteria).addOrder(c); // Crapfest } else if(m_currentCriteria instanceof DetachedCriteria) { ((DetachedCriteria) m_currentCriteria).addOrder(c); } else throw new IllegalStateException("Unexpected current thing: " + m_currentCriteria); } private void addSubCriterion(Criterion c) { if(m_subCriteria instanceof Criteria) { ((Criteria) m_subCriteria).add(c); // Crapfest } else if(m_subCriteria instanceof DetachedCriteria) { ((DetachedCriteria) m_subCriteria).add(c); } else throw new IllegalStateException("Unexpected current thing: " + m_subCriteria); } /** * Create a join either on a Criteria or a DetachedCriteria. Needed because the joker that creates those * did not interface/baseclass them. * @param current * @param name * @param joinType * @return */ private Object createSubCriteria(Object current, String name, int joinType) { if(current instanceof Criteria) return ((Criteria) current).createCriteria(name, joinType); else if(current instanceof DetachedCriteria) return ((DetachedCriteria) current).createCriteria(name, joinType); else throw new IllegalStateException("? Unexpected criteria abomination: " + current); } private void addSubOrder(Order c) { if(m_subCriteria instanceof Criteria) { ((Criteria) m_subCriteria).addOrder(c); // Crapfest } else if(m_subCriteria instanceof DetachedCriteria) { ((DetachedCriteria) m_subCriteria).addOrder(c); } else throw new IllegalStateException("Unexpected current thing: " + m_subCriteria); } @Override public void visitRestrictionsBase(QCriteriaQueryBase< ? > n) throws Exception { QOperatorNode r = n.getRestrictions(); if(r == null) return; if(r.getOperation() == QOperation.AND) { QMultiNode mn = (QMultiNode) r; for(QOperatorNode qtn : mn.getChildren()) { qtn.visit(this); if(m_last != null) { addCriterion(m_last); m_last = null; } } } else { r.visit(this); if(null != m_last) addCriterion(m_last); m_last = null; } } @Override public void visitCriteria(final QCriteria< ? > qc) throws Exception { checkHibernateClass(qc.getBaseClass()); m_rootClass = qc.getBaseClass(); super.visitCriteria(qc); //-- 2. Handle limits and start: applicable to root criterion only if(qc.getLimit() > 0) m_rootCriteria.setMaxResults(qc.getLimit()); if(qc.getStart() > 0) { m_rootCriteria.setFirstResult(qc.getStart()); } } /* CODING: Property path resolution code. */ /** The current subcriteria. */ private Object m_subCriteria; /** Temp array used in parser to decode the properties reached; used to prevent multiple object allocations. */ private PropertyMetaModel[] m_pendingJoinProps = new PropertyMetaModel[20]; private String[] m_pendingJoinPaths = new String[20]; private int m_pendingJoinIx; private String m_inputPath; private StringBuilder m_sb = new StringBuilder(); /** The current subcriteria's base class. */ // private Class< ? > m_subCriteriaClass; /** * This parses all dotted paths, and translates them to the proper Hibernate paths and joins. A big * bundle of hair is growing on this code. Take heed changing it! * <p>A dotted path reaching some final property on some part of a persistent class tree must * be interpreted in multiple ways, depending on the parts of the tree that are reached. All cases only * resolve the part <i>before</i> the last name in the path. So a dotted path like <i>address.city</i> will * resolve the "address" into a subcritera (see below) and return the name "city" as a property name to resolve * on the Address persistent class. * * <p>The possibilities for different resolutions are: * <dl> * <dt>Parent relations<dt> * <dd>When a parent relation is encountered directly on some persistent class it implies that a * <i>join</i> is to be done with that persistent class. If the property is non-null(1) an inner * join will be generated; if a property is optional it will generate an outer join to it. In Hibernate * terms: this will create another Criteria on that property, and that criteria instance should be used * to append criterions on that other table. If such a relation property is used more than once (because * multiple restrictions are placed on the joined table) we <i>must</i> reuse the same sub-Criteria * instance initially created to prevent multiple joins to that same table.</dd> * <dt>Compound primary keys</dt> * <dd>These are the hardest. A compound PK usually consists of "simple" fields and "parent" relation types. * The "simple" fields are usually of basic types like numbers or strings, and are present in the root table * only, forming the unique part of that root type's primary key. The "parent" relation properties in the PK * represent the parent entities that are part of the identifying relation for the root table. * <p>The problem is that depending on what is reached we either need to specify a join, or we just reach "deeper" * inside the compound key structure, reaching a property that is ultimately still a field in the root table. * </p> * <p>When parsing a PK structure deeply we usually have properties that alternate between pk fields and relation * fields. Only when this path touches a non-PK field need we create a subcriteria to the reached tables. In all * other cases, if the final property reaches a primary key field of an identifying PK somewhere in the root * table the column representing that field is part of that root table, so no joins are wanted.</p> * </dd> * * </dl> * Notes: * <p>(1): the nullity of a property should be directly derived off the datamodel. If it is changed from the * datamodel's definition then the resulting join will not be technically correct: it follows the override, * not the actual definition from the data model.</p> */ private String parseSubcriteria(String input) { m_subCriteria = null; m_inputPath = input; /* * We are going to traverse all names and determine the reached type. When a relation type * is encountered it's put on the "pending relation stack". The next name will determine * what to do with that relation: * - if there is NO next field the relation itself is meant. No join should be added. * - if the next field is a non-PK field then the relation MUST be joined in using a * subcriterion, and the next field will take off from there * - if the next field is a PK field we delay the join by keeping the relation stacked * and we follow the PK field, maintaining the subpath. If the entire path is always * either a parent relation or a PK field then we are staying in the /same/ record, never * leaving it's PK. In that case this will return the entire dotted path to that PK field, * for use by Hibernate. * - if the next field is NOT a pk we know that we must join fully all relations stacked. */ Class< ? > currentClass = m_rootClass; // The current class reached by the property; start @ the root entity String path = null; // The full path currently reached String subpath = null; // The subpath reached from the last PK association change, if applicable int ix = 0; final int len = input.length(); m_pendingJoinIx = 0; boolean last = false; // boolean inpk = false; // Not following a PK path boolean previspk = false; while(!last) { //-- Get next name. int pos = input.indexOf('.', ix); // Move to the NEXT dot, String name; if(pos == -1) { //-- QUICK EXIT: if the entire name has no dots quit immediately with the input. if(ix == 0) return input; //-- Get the last name fragment. name = input.substring(ix); ix = len; last = true; } else { name = input.substring(ix, pos); ix = pos + 1; } //-- Create the path and the subpath by adding the current name. path = path == null ? name : path + "." + name; // Full dotted path to the currently reached name subpath = subpath == null ? name : subpath + "." + name; // Partial dotted path (from the last relation) to the currently reached name //-- Get the property metadata and the reached class. PropertyMetaModel pmm = MetaManager.getPropertyMeta(currentClass, name); if(pmm.isPrimaryKey()) { if(previspk) throw new IllegalStateException("Pk field immediately after PK field - don't know what this is!?"); // inpk = true; previspk = true; pushPendingJoin(path, pmm); if(last) { //-- We have ended in a PK. All subrelations leading up to this are *part* of the PK of the current subcriterion. We need not join but just have to specify a dotted path. return createPendingJoinPath(); } currentClass = pmm.getActualType(); } else if(pmm.getRelationType() == PropertyRelationType.DOWN) { /* * Downward (childset) relation. This implicitly queries /existence/ of a child record having these * characteristics. This can never be a last item. */ if(last) throw new QQuerySyntaxException("The path '" + path + " reaches a 'list-of-children' (DOWN) property (" + pmm + ")- it is meaningless here"); /* * Must be a List type, and we must be able to determine the type of the child. */ if(!List.class.isAssignableFrom(pmm.getActualType())) throw new ProgrammerErrorException("The property '" + path + "' should be a list (it is a " + pmm.getActualType() + ")"); java.lang.reflect.Type coltype = pmm.getGenericActualType(); if(coltype == null) throw new ProgrammerErrorException("The property '" + path + "' has an undeterminable child type"); Class< ? > childtype = MetaManager.findCollectionType(coltype); //-- We are not really joining here; we're just querying. Drop the pending joinset; m_pendingJoinIx = 0; // Discard all pending; /* * We need to create a joined "exists" query, or get the "existing" one. */ CritEntry ce = m_subCriteriaMap.get(path); if(ce != null) { //-- Use this. m_subCriteria = ce.getAbomination(); } else { //-- Create a joined subselect DetachedCriteria dc = createExistsSubquery(childtype, currentClass, subpath); m_subCriteriaMap.put(path, new CritEntry(childtype, dc)); m_subCriteria = dc; } currentClass = childtype; } else if(pmm.getRelationType() != PropertyRelationType.NONE) { /* * This is a relation. If we are NOT in a PK currently AND there are relations queued then * we are sure that the queued ones must be joined, so flush as a simple join. */ //-- This is a relation type. If another relation was queued flush it: we always need a join. if(m_pendingJoinIx > 0 && !previspk) { flushJoin(); // inpk = false; } //-- Now queue this one- we decide whether to join @ the next name. pushPendingJoin(path, pmm); if(last) { //-- Last entry is a relation: we do not need to join this last one, just refer to it using it's dotted path also. return createPendingJoinPath(); } currentClass = pmm.getActualType(); previspk = false; } else if(!last) throw new QQuerySyntaxException("Property " + subpath + " in path " + input + " must be a parent relation or a compound primary key (property=" + pmm + ")"); else { /* * This is the last part and it is not a PK or relation itself. We need to decide what to do with the * current join stack. If the previous item was a PK we do not join but return the compound path... */ if(previspk) { pushPendingJoin(path, pmm); return createPendingJoinPath(); // This is a non-relation property immediately on a PK. Return dotted path. } /* * This is a normal property. Make sure a join is present then return the path inside that join. */ flushJoin(); return name; } } //-- Failsafe exit: all specific paths should have exited when last was signalled. throw new IllegalStateException("Should be unreachable?"); } private DetachedCriteria createExistsSubquery(Class< ? > childtype, Class< ? > parentclass, String parentproperty) { DetachedCriteria dc = DetachedCriteria.forClass(childtype, nextAlias()); Criterion exists = Subqueries.exists(dc); dc.setProjection(Projections.id()); // Whatever: just some thingy. //-- Append the join condition; we need all children here that are in the parent's collection. We need the parent reference to use in the child. ClassMetadata childmd = m_session.getSessionFactory().getClassMetadata(childtype); //-- Entering the crufty hellhole that is Hibernate meta"data": never seen more horrible cruddy garbage ClassMetadata parentmd = m_session.getSessionFactory().getClassMetadata(parentclass); int index = findMoronicPropertyIndexBecauseHibernateIsTooStupidToHaveAPropertyMetaDamnit(parentmd, parentproperty); if(index == -1) throw new IllegalStateException("Hibernate does not know property"); Type type = parentmd.getPropertyTypes()[index]; BagType bt = (BagType) type; final OneToManyPersister persister = (OneToManyPersister) ((SessionFactoryImpl) m_session.getSessionFactory()).getCollectionPersister(bt.getRole()); String[] keyCols = persister.getKeyColumnNames(); //-- Try to locate those FK column names in the FK table so we can fucking locate the mapping property. int fkindex = findCruddyChildProperty(childmd, keyCols); if(fkindex < 0) throw new IllegalStateException("Cannot find child's parent property in crufty Hibernate metadata: " + keyCols); String childupprop = childmd.getPropertyNames()[fkindex]; //-- Well, that was it. What a sheitfest. Add the join condition to the parent String parentAlias = getParentAlias(); dc.add(Restrictions.eqProperty(childupprop + "." + childmd.getIdentifierPropertyName(), parentAlias + "." + parentmd.getIdentifierPropertyName())); addCriterion(exists); return dc; } private String createPendingJoinPath() { m_sb.setLength(0); for(int i = 0; i < m_pendingJoinIx; i++) { if(m_sb.length() > 0) m_sb.append('.'); m_sb.append(m_pendingJoinProps[i].getName()); } return m_sb.toString(); } /** * Flush everything on the join stack and create the pertinent joins. The stack * is guaranteed to end in a RELATION property, but it can have PK fragments in * between. Those fragments are all part of a single record (the one that has * that PK) and should not be "joined". Instead the entire subpath leading to * that first relation that "exits" that record will be used as a path for the * subcriterion. */ private void flushJoin() { if(m_pendingJoinIx <= 0) return; //-- Create the join path upto and including till the last relation (subpath from last criterion to it). m_sb.setLength(0); PropertyMetaModel pmm = null; for(int i = 0; i < m_pendingJoinIx; i++) { pmm = m_pendingJoinProps[i]; if(m_sb.length() != 0) m_sb.append('.'); m_sb.append(pmm.getName()); } String subpath = m_sb.toString(); // This leads to the relation; //-- Now create/retrieve the subcriterion to that relation String path = m_pendingJoinPaths[m_pendingJoinIx - 1]; // The full path to this relation, CritEntry ce = m_subCriteriaMap.get(path); // Is a criteria entry present already? if(ce != null) { m_subCriteria = ce.getAbomination(); // Obtain cached version } else { //-- We need to create this join. int joinType = pmm.isRequired() ? CriteriaSpecification.INNER_JOIN : CriteriaSpecification.LEFT_JOIN; if(m_subCriteria == null) { // Current is the ROOT criteria? m_subCriteria = createSubCriteria(m_currentCriteria, subpath, joinType); } else { //-- Create a new version on the current subcriterion (multi join) m_subCriteria = createSubCriteria(m_subCriteria, subpath, joinType); } //-- Cache this so later paths refer to the same subcriteria if(m_subCriteriaMap == Collections.EMPTY_MAP) m_subCriteriaMap = new HashMap<String, CritEntry>(); m_subCriteriaMap.put(path, new CritEntry(pmm.getActualType(), m_subCriteria)); } m_pendingJoinIx = 0; } // private void dumpStateError(String string) { /** * Push a pending join or PK fragment on the TODO stack. * @param path * @param pmm */ private void pushPendingJoin(String path, PropertyMetaModel pmm) { if(m_pendingJoinIx >= m_pendingJoinPaths.length) throw new QQuerySyntaxException("The property path " + m_inputPath + " is too complex"); m_pendingJoinPaths[m_pendingJoinIx] = path; m_pendingJoinProps[m_pendingJoinIx++] = pmm; } // /** // * Flush all entries on the pending relation stack. This stack should ALWAYS contain // * relation and PK entries ajacent, i.e. a relation item ALWAYS follows a PK item and // * a PK item always follows a relation item. // * // * If this stack holds a PK path it ALWAYS starts with a PK // * // */ // private void flushPendingRelationJoins() { // int joinType = pmm.isRequired() ? CriteriaSpecification.INNER_JOIN : CriteriaSpecification.LEFT_JOIN; // if(m_subCriteria == null) { // Current is the ROOT criteria? // m_subCriteria = createSubCriteria(m_currentCriteria, subpath, joinType); // } else { // //-- Create a new version on the current subcriterion (multi join) // m_subCriteria = createSubCriteria(m_subCriteria, subpath, joinType); // //-- Store this subcriteria so that other paths will use the same one // if(m_subCriteriaMap == Collections.EMPTY_MAP) // m_subCriteriaMap = new HashMap<String, CritEntry>(); // currentClass = pmm.getActualType(); // m_subCriteriaMap.put(path, new CritEntry(currentClass, m_subCriteria)); // subpath = null; // Restart subpath @ next property. @Override public void visitPropertyComparison(QPropertyComparison n) throws Exception { QOperatorNode rhs = n.getExpr(); String name = n.getProperty(); QLiteral lit = null; if(rhs.getOperation() == QOperation.LITERAL) { lit = (QLiteral) rhs; } else if(rhs.getOperation() == QOperation.SELECTION_SUBQUERY) { handlePropertySubcriteriaComparison(n); return; } else throw new IllegalStateException("Unknown operands to " + n.getOperation() + ": " + name + " and " + rhs.getOperation()); //-- If prop refers to some relation (dotted pair): name = parseSubcriteria(name); Criterion last = null; switch(n.getOperation()){ default: throw new IllegalStateException("Unexpected operation: " + n.getOperation()); case EQ: if(lit.getValue() == null) { last = Restrictions.isNull(name); break; } last = Restrictions.eq(name, lit.getValue()); break; case NE: if(lit.getValue() == null) { last = Restrictions.isNotNull(name); break; } last = Restrictions.ne(name, lit.getValue()); break; case GT: last = Restrictions.gt(name, lit.getValue()); break; case GE: last = Restrictions.ge(name, lit.getValue()); break; case LT: last = Restrictions.lt(name, lit.getValue()); break; case LE: last = Restrictions.le(name, lit.getValue()); break; case LIKE: last = Restrictions.like(name, lit.getValue()); break; case ILIKE: last = Restrictions.ilike(name, lit.getValue()); break; } if(m_subCriteria != null) addSubCriterion(last); else m_last = last; m_subCriteria = null; } private void handlePropertySubcriteriaComparison(QPropertyComparison n) throws Exception { QSelectionSubquery qsq = (QSelectionSubquery) n.getExpr(); qsq.visit(this); // Resolve subquery String name = parseSubcriteria(n.getProperty()); // Handle dotted pair in name Criterion last = null; switch(n.getOperation()){ default: throw new IllegalStateException("Unexpected operation: " + n.getOperation()); case EQ: last = Subqueries.propertyEq(name, (DetachedCriteria) m_lastSubCriteria); break; case NE: last = Subqueries.propertyNe(name, (DetachedCriteria) m_lastSubCriteria); break; // case GT: // last = Restrictions.gt(name, lit.getValue()); // break; // case GE: // last = Restrictions.ge(name, lit.getValue()); // break; // case LT: // last = Restrictions.lt(name, lit.getValue()); // break; // case LE: // last = Restrictions.le(name, lit.getValue()); // break; // case LIKE: // last = Restrictions.like(name, lit.getValue()); // break; // case ILIKE: // last = Restrictions.ilike(name, lit.getValue()); // break; } if(m_subCriteria != null) addSubCriterion(last); else m_last = last; m_subCriteria = null; } @Override public void visitBetween(final QBetweenNode n) throws Exception { if(n.getA().getOperation() != QOperation.LITERAL || n.getB().getOperation() != QOperation.LITERAL) throw new IllegalStateException("Expecting literals as 2nd and 3rd between parameter"); QLiteral a = (QLiteral) n.getA(); QLiteral b = (QLiteral) n.getB(); //-- If prop refers to some relation (dotted pair): String name = n.getProp(); name = parseSubcriteria(name); if(m_subCriteria != null) addSubCriterion(Restrictions.between(name, a.getValue(), b.getValue())); else m_last = Restrictions.between(n.getProp(), a.getValue(), b.getValue()); m_subCriteria = null; } /** * Compound. Ands and ors. * * @see to.etc.webapp.query.QNodeVisitorBase#visitMulti(to.etc.webapp.query.QMultiNode) */ @Override public void visitMulti(final QMultiNode inn) throws Exception { //-- Walk all members, create nodes from 'm. Criterion c1 = null; for(QOperatorNode n : inn.getChildren()) { n.visit(this); // Convert node to Criterion thingydoodle if(c1 == null) { c1 = m_last; // If 1st one use as lhs, m_last = null; } else { switch(inn.getOperation()){ default: throw new IllegalStateException("Unexpected operation: " + inn.getOperation()); case AND: if(m_last != null) { c1 = Restrictions.and(c1, m_last); m_last = null; } break; case OR: if(m_last != null) { c1 = Restrictions.or(c1, m_last); m_last = null; } break; } } } // jal 20100122 FIXME Remove to allow combinatories on subchildren; needs to be revisited when join/logic is formalized. // if(c1 == null) m_last = c1; } @Override public void visitOrder(final QOrder o) throws Exception { String name = o.getProperty(); name = parseSubcriteria(name); Order ho = o.getDirection() == QSortOrderDirection.ASC ? Order.asc(name) : Order.desc(name); if(m_subCriteria != null) { addSubOrder(ho); m_subCriteria = null; } else addOrder(ho); } @Override public void visitUnaryNode(final QUnaryNode n) throws Exception { switch(n.getOperation()){ default: throw new IllegalStateException("Unsupported UNARY operation: " + n.getOperation()); case SQL: if(n.getNode() instanceof QLiteral) { QLiteral l = (QLiteral) n.getNode(); String s = (String) l.getValue(); m_last = Restrictions.sqlRestriction(s); return; } break; } throw new IllegalStateException("Unsupported UNARY operation: " + n.getOperation()); } @Override public void visitUnaryProperty(final QUnaryProperty n) throws Exception { String name = n.getProperty(); name = parseSubcriteria(name); // If this is a dotted name prepare a subcriteria on it. Criterion c; switch(n.getOperation()){ default: throw new IllegalStateException("Unsupported UNARY operation: " + n.getOperation()); case ISNOTNULL: c = Restrictions.isNotNull(name); break; case ISNULL: c = Restrictions.isNull(name); break; } if(m_subCriteria != null) addSubCriterion(c); else m_last = c; } @Override public void visitLiteral(final QLiteral n) throws Exception { throw new IllegalStateException("? Unexpected literal: " + n); } /** * Child-related subquery: determine existence of children having certain characteristics. Because * the worthless Hibernate "meta model" API and the utterly disgusting way that mapping data is * "stored" in Hibernate we resort to getting the generic type of the child property's collection * to determine the type where the subquery is executed on. * @see to.etc.webapp.query.QNodeVisitorBase#visitExistsSubquery(to.etc.webapp.query.QExistsSubquery) */ @Override public void visitExistsSubquery(QExistsSubquery< ? > q) throws Exception { //-- Sigh. Find the property. PropertyInfo pi = ClassUtil.findPropertyInfo(q.getParentQuery().getBaseClass(), q.getParentProperty()); if(pi == null) throw new ProgrammerErrorException("The property '" + q.getParentProperty() + "' is not found in class " + q.getParentQuery().getBaseClass()); //-- Should be List type if(!List.class.isAssignableFrom(pi.getActualType())) throw new ProgrammerErrorException("The property '" + q.getParentQuery().getBaseClass() + "." + q.getParentProperty() + "' should be a list (it is a " + pi.getActualType() + ")"); //-- Make sure there is a where condition to restrict QOperatorNode where = q.getRestrictions(); if(where == null) throw new ProgrammerErrorException("exists subquery has no restrictions: " + this); //-- Get the list's generic compound type because we're unable to get it from Hibernate easily. Idiots. Class< ? > coltype = pi.getCollectionValueType(); if(coltype == null) throw new ProgrammerErrorException("The property '" + q.getParentQuery().getBaseClass() + "." + q.getParentProperty() + "' has an undeterminable child type"); //-- 2. Create an exists subquery; create a sub-statement DetachedCriteria dc = DetachedCriteria.forClass(coltype, nextAlias()); Criterion exists = Subqueries.exists(dc); dc.setProjection(Projections.id()); // Whatever: just some thingy. //-- Append the join condition; we need all children here that are in the parent's collection. We need the parent reference to use in the child. ClassMetadata childmd = m_session.getSessionFactory().getClassMetadata(coltype); //-- Entering the crofty hellhole that is Hibernate meta"data": never seen more horrible cruddy garbage ClassMetadata parentmd = m_session.getSessionFactory().getClassMetadata(q.getParentQuery().getBaseClass()); int index = findMoronicPropertyIndexBecauseHibernateIsTooStupidToHaveAPropertyMetaDamnit(parentmd, q.getParentProperty()); if(index == -1) throw new IllegalStateException("Hibernate does not know property"); Type type = parentmd.getPropertyTypes()[index]; BagType bt = (BagType) type; final OneToManyPersister persister = (OneToManyPersister) ((SessionFactoryImpl) m_session.getSessionFactory()).getCollectionPersister(bt.getRole()); String[] keyCols = persister.getKeyColumnNames(); //-- Try to locate those FK column names in the FK table so we can fucking locate the mapping property. int fkindex = findCruddyChildProperty(childmd, keyCols); if(fkindex < 0) throw new IllegalStateException("Cannot find child's parent property in crufty Hibernate metadata: " + keyCols); String childupprop = childmd.getPropertyNames()[fkindex]; //-- Well, that was it. What a sheitfest. Add the join condition to the parent String parentAlias = getParentAlias(); dc.add(Restrictions.eqProperty(childupprop + "." + childmd.getIdentifierPropertyName(), parentAlias + "." + parentmd.getIdentifierPropertyName())); //-- Sigh; Recursively apply all parts to the detached thingerydoo Object old = m_currentCriteria; Class< ? > oldroot = m_rootClass; m_rootClass = q.getBaseClass(); checkHibernateClass(m_rootClass); m_currentCriteria = dc; where.visit(this); if(m_last != null) { dc.add(m_last); m_last = null; } m_currentCriteria = old; m_rootClass = oldroot; m_last = exists; } private String getParentAlias() { if(m_currentCriteria instanceof Criteria) return ((Criteria) m_currentCriteria).getAlias(); else if(m_currentCriteria instanceof DetachedCriteria) return ((DetachedCriteria) m_currentCriteria).getAlias(); else throw new IllegalStateException("Unknown type"); } /** * Try to locate the property in the child that refers to the parent in a horrible way. * @param cm * @param keyCols * @return */ private int findCruddyChildProperty(ClassMetadata cm, String[] keyCols) { SingleTableEntityPersister fuckup = (SingleTableEntityPersister) cm; for(int i = fuckup.getPropertyNames().length; --i >= 0;) { String[] cols = fuckup.getPropertyColumnNames(i); if(Arrays.equals(keyCols, cols)) { return i; } } return -1; } /** * Damn. * @param md * @param name * @return */ static private int findMoronicPropertyIndexBecauseHibernateIsTooStupidToHaveAPropertyMetaDamnit(ClassMetadata md, String name) { for(int i = md.getPropertyNames().length; --i >= 0;) { if(md.getPropertyNames()[i].equals(name)) return i; } return -1; } /* CODING: Selection translation to Projection. */ private ProjectionList m_proli; private Projection m_lastProj; @Override public void visitMultiSelection(QMultiSelection n) throws Exception { throw new ProgrammerErrorException("multi-operation selections not supported by Hibernate"); } @Override public void visitSelection(QSelection< ? > s) throws Exception { if(m_proli != null) throw new IllegalStateException("? Projection list already initialized??"); checkHibernateClass(s.getBaseClass()); m_rootClass = s.getBaseClass(); m_proli = Projections.projectionList(); visitSelectionColumns(s); if(m_currentCriteria instanceof Criteria) ((Criteria) m_currentCriteria).setProjection(m_proli); else if(m_currentCriteria instanceof DetachedCriteria) ((DetachedCriteria) m_currentCriteria).setProjection(m_proli); else throw new IllegalStateException("Unsupported current: " + m_currentCriteria); visitRestrictionsBase(s); visitOrderList(s.getOrder()); } @Override public void visitSelectionColumn(QSelectionColumn n) throws Exception { super.visitSelectionColumn(n); if(m_lastProj != null) m_proli.add(m_lastProj); } @Override public void visitSelectionItem(QSelectionItem n) throws Exception { throw new ProgrammerErrorException("Unexpected selection item: " + n); } @Override public void visitPropertySelection(QPropertySelection n) throws Exception { switch(n.getFunction()){ default: throw new IllegalStateException("Unexpected selection item function: " + n.getFunction()); case AVG: m_lastProj = Projections.avg(n.getProperty()); break; case MAX: m_lastProj = Projections.max(n.getProperty()); break; case MIN: m_lastProj = Projections.min(n.getProperty()); break; case SUM: m_lastProj = Projections.sum(n.getProperty()); break; case COUNT: m_lastProj = Projections.count(n.getProperty()); break; case COUNT_DISTINCT: m_lastProj = Projections.countDistinct(n.getProperty()); break; case ID: m_lastProj = Projections.id(); break; case PROPERTY: m_lastProj = Projections.property(n.getProperty()); break; case ROWCOUNT: m_lastProj = Projections.rowCount(); break; } } @Override public void visitSelectionSubquery(QSelectionSubquery n) throws Exception { DetachedCriteria dc = DetachedCriteria.forClass(n.getSelectionQuery().getBaseClass(), nextAlias()); //-- Recursively apply all parts to the detached thingerydoo ProjectionList oldpro = m_proli; m_proli = null; Projection oldlastproj = m_lastProj; m_lastProj = null; Object old = m_currentCriteria; Class< ? > oldroot = m_rootClass; m_rootClass = n.getSelectionQuery().getBaseClass(); checkHibernateClass(m_rootClass); m_currentCriteria = dc; n.getSelectionQuery().visit(this); if(m_last != null) { dc.add(m_last); m_last = null; } m_currentCriteria = old; // Restore root query m_rootClass = oldroot; m_proli = oldpro; m_lastProj = oldlastproj; m_lastSubCriteria = dc; } }
package org.sakaiproject.evaluation.tool.producers; import java.util.List; import org.sakaiproject.evaluation.logic.EvalEvaluationsLogic; import org.sakaiproject.evaluation.logic.EvalExternalLogic; import org.sakaiproject.evaluation.logic.EvalItemsLogic; import org.sakaiproject.evaluation.logic.EvalTemplatesLogic; import org.sakaiproject.evaluation.model.EvalItem; import org.sakaiproject.evaluation.tool.EvaluationConstant; import org.sakaiproject.evaluation.tool.viewparams.ItemViewParameters; import org.sakaiproject.evaluation.tool.viewparams.TemplateViewParameters; import uk.org.ponder.rsf.components.UIBranchContainer; import uk.org.ponder.rsf.components.UIContainer; import uk.org.ponder.rsf.components.UIForm; import uk.org.ponder.rsf.components.UIInternalLink; import uk.org.ponder.rsf.components.UIMessage; import uk.org.ponder.rsf.components.UIOutput; import uk.org.ponder.rsf.components.UISelect; import uk.org.ponder.rsf.components.UIVerbatim; import uk.org.ponder.rsf.components.decorators.DecoratorList; import uk.org.ponder.rsf.components.decorators.UIStyleDecorator; import uk.org.ponder.rsf.view.ComponentChecker; import uk.org.ponder.rsf.view.ViewComponentProducer; import uk.org.ponder.rsf.viewstate.SimpleViewParameters; import uk.org.ponder.rsf.viewstate.ViewParameters; /** * This lists items for users so they can add, modify, remove them * * @author Aaron Zeckoski (aaronz@vt.edu) */ public class ControlItemsProducer implements ViewComponentProducer { public static String VIEW_ID = "control_items"; public String getViewID() { return VIEW_ID; } private EvalExternalLogic external; public void setExternal(EvalExternalLogic external) { this.external = external; } private EvalTemplatesLogic templatesLogic; public void setTemplatesLogic(EvalTemplatesLogic templatesLogic) { this.templatesLogic = templatesLogic; } private EvalEvaluationsLogic evaluationsLogic; public void setEvaluationsLogic(EvalEvaluationsLogic evaluationsLogic) { this.evaluationsLogic = evaluationsLogic; } private EvalItemsLogic itemsLogic; public void setItemsLogic(EvalItemsLogic itemsLogic) { this.itemsLogic = itemsLogic; } /* (non-Javadoc) * @see uk.org.ponder.rsf.view.ComponentProducer#fillComponents(uk.org.ponder.rsf.components.UIContainer, uk.org.ponder.rsf.viewstate.ViewParameters, uk.org.ponder.rsf.view.ComponentChecker) */ public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) { // local variables used in the render logic String currentUserId = external.getCurrentUserId(); boolean userAdmin = external.isUserAdmin(currentUserId); boolean createTemplate = templatesLogic.canCreateTemplate(currentUserId); boolean beginEvaluation = evaluationsLogic.canBeginEvaluation(currentUserId); // page title UIMessage.make(tofill, "page-title", "controlitems.page.title"); /* * top links here */ UIInternalLink.make(tofill, "summary-link", UIMessage.make("summary.page.title"), new SimpleViewParameters(SummaryProducer.VIEW_ID)); if (userAdmin) { UIInternalLink.make(tofill, "administrate-link", UIMessage.make("administrate.page.title"), new SimpleViewParameters(AdministrateProducer.VIEW_ID)); } if (createTemplate) { UIInternalLink.make(tofill, "control-templates-link", UIMessage.make("controltemplates.page.title"), new SimpleViewParameters(ControlTemplatesProducer.VIEW_ID)); } if (beginEvaluation) { UIInternalLink.make(tofill, "control-evaluations-link", UIMessage.make("controlevaluations.page.title"), new SimpleViewParameters(ControlEvaluationsProducer.VIEW_ID)); UIInternalLink.make(tofill, "begin-evaluation-link", UIMessage.make("starteval.page.title"), new TemplateViewParameters(EvaluationStartProducer.VIEW_ID, null)); } UIMessage.make(tofill, "items-header", "controlitems.items.header"); UIMessage.make(tofill, "items-description", "controlitems.items.description"); // use get form to submit the type of item to create UIMessage.make(tofill, "add-item-header", "controlitems.items.add"); UIForm addItemForm = UIForm.make(tofill, "add-item-form", new ItemViewParameters(ModifyItemProducer.VIEW_ID, null)); UISelect.make(addItemForm, "item-classification-list", EvaluationConstant.ITEM_CLASSIFICATION_VALUES, EvaluationConstant.ITEM_CLASSIFICATION_LABELS_PROPS, "#{itemClassification}").setMessageKeys(); UIMessage.make(addItemForm, "add-item-button", "controlitems.items.add.button"); // get items for the current user List userItems = itemsLogic.getItemsForUser(currentUserId, null, null, userAdmin); if (userItems.size() > 0) { UIBranchContainer itemListing = UIBranchContainer.make(tofill, "item-listing:"); for (int i = 0; i < userItems.size(); i++) { EvalItem item = (EvalItem) userItems.get(i); UIBranchContainer itemBranch = UIBranchContainer.make(itemListing, "item-row:", item.getId().toString()); if (i % 2 == 0) { itemBranch.decorators = new DecoratorList( new UIStyleDecorator("itemsListOddLine") ); // must match the existing CSS class } UIOutput.make(itemBranch, "item-classification", item.getClassification()); if (item.getScaleDisplaySetting() != null) { String scaleDisplaySettingLabel = " - " + item.getScaleDisplaySetting(); UIOutput.make(itemBranch, "item-scale", scaleDisplaySettingLabel); } UIInternalLink.make(itemBranch, "item-preview-link", UIMessage.make("controlitems.preview.link"), new ItemViewParameters(PreviewItemProducer.VIEW_ID, item.getId(), (Long)null) ); UIOutput.make(itemBranch, "item-owner", external.getUserDisplayName( item.getOwner()) ); if (item.getExpert().booleanValue() == true) { // label expert items UIMessage.make(itemBranch, "item-expert", "controlitems.expert.label"); } UIVerbatim.make(itemBranch, "item-text", item.getItemText()); // local locked check is more efficient so do that first if ( !item.getLocked().booleanValue() && itemsLogic.canModifyItem(currentUserId, item.getId()) ) { UIInternalLink.make(itemBranch, "item-modify-link", UIMessage.make("controlitems.modify.link"), new ItemViewParameters(ModifyItemProducer.VIEW_ID, item.getId(), null)); } else { UIMessage.make(itemBranch, "item-modify-dummy", "controlitems.modify.link"); } // local locked check is more efficient so do that first if ( !item.getLocked().booleanValue() && itemsLogic.canRemoveItem(currentUserId, item.getId()) ) { UIInternalLink.make(itemBranch, "item-remove-link", UIMessage.make("controlitems.remove.link"), new ItemViewParameters(RemoveItemProducer.VIEW_ID, item.getId(), null)); } else { UIMessage.make(itemBranch, "item-remove-dummy", "controlitems.remove.link"); } } } else { UIMessage.make(tofill, "no-items", "controlitems.items.none"); } } }
package txtfnnl.uima.analysis_component; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.uima.UimaContext; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.cas.CASException; import org.apache.uima.cas.FSIterator; import org.apache.uima.cas.FSMatchConstraint; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.tcas.Annotation; import org.apache.uima.resource.ExternalResourceDescription; import org.apache.uima.resource.ResourceInitializationException; import org.apache.uima.util.Level; import org.apache.uima.util.Logger; import org.uimafit.component.JCasAnnotator_ImplBase; import org.uimafit.descriptor.ConfigurationParameter; import org.uimafit.descriptor.ExternalResource; import txtfnnl.uima.AnalysisComponentBuilder; import txtfnnl.uima.UniqueTextAnnotation; import txtfnnl.uima.Views; import txtfnnl.uima.resource.GazetteerResource; import txtfnnl.uima.tcas.SemanticAnnotation; import txtfnnl.uima.tcas.TextAnnotation; import txtfnnl.uima.tcas.TokenAnnotation; import txtfnnl.utils.Offset; import txtfnnl.utils.stringsim.LeitnerLevenshtein; import txtfnnl.utils.stringsim.Similarity; public class GazetteerAnnotator extends JCasAnnotator_ImplBase { /** The URI of this Annotator (namespace and ID are defined dynamically). */ public static final String URI = GazetteerAnnotator.class.getName(); /** The <b>required</b> namespace for the {@link SemanticAnnotation entity annotations}. */ public static final String PARAM_ENTITY_NAMESPACE = "EntityNamespace"; @ConfigurationParameter(name = PARAM_ENTITY_NAMESPACE, mandatory = true) private String entityNamespace; /** * The (optional) namespace of {@link TextAnnotation annotations} containing the text to match * against the Gazetteer (default: match all text). */ public static final String PARAM_TEXT_NAMESPACE = "TextNamespace"; @ConfigurationParameter(name = PARAM_TEXT_NAMESPACE, mandatory = false) private String sourceNamespace; /** * The (optional) identifier of the {@link TextAnnotation annotations} containing the relevant * text. * <p> * This parameter is only effective if {@link #PARAM_TEXT_NAMESPACE} is set, too. */ public static final String PARAM_TEXT_IDENTIFIER = "TextIdentifier"; @ConfigurationParameter(name = PARAM_TEXT_IDENTIFIER, mandatory = false) private String sourceIdentifier = null; /** The GazetteerResource used for entity matching. */ public static final String MODEL_KEY_GAZETTEER = "Gazetteer"; @ExternalResource(key = MODEL_KEY_GAZETTEER) private GazetteerResource<Set<String>> gazetteer; private Similarity measure = LeitnerLevenshtein.INSTANCE; // TODO: make configurable? private Logger logger; private int count; public static class Builder extends AnalysisComponentBuilder { Builder(String entityNamespace, ExternalResourceDescription gazetteerResourceDescription) { super(GazetteerAnnotator.class); setRequiredParameter(PARAM_ENTITY_NAMESPACE, entityNamespace); setRequiredParameter(MODEL_KEY_GAZETTEER, gazetteerResourceDescription); } /** * Define a {@link TextAnnotation TextAnnotation} identifier pattern when limiting the * Gazetteer's text to scan (in addition to and only used if a * {@link Builder#setTextNamespace(String) namespace} is set). */ public Builder setTextIdentifier(String sourceIdentifier) { setOptionalParameter(PARAM_TEXT_IDENTIFIER, sourceIdentifier); return this; } /** * Define the {@link TextAnnotation annotation} namespace to get the covered text from for the * Gazetteer's matcher. */ public Builder setTextNamespace(String sourceNamespace) { setOptionalParameter(PARAM_TEXT_NAMESPACE, sourceNamespace); return this; } } /** * Create a new gazetteer configuration builder with a pre-configured gazetteer resource. * * @param entityNamespace to use for the {@link SemanticAnnotation SemanticAnnotations} of the * entity DB IDs * @param gazetteerResourceDescription a pre-configured {@link GazetteerResource} description. */ public static Builder configure(String entityNamespace, ExternalResourceDescription gazetteerResourceDescription) { return new Builder(entityNamespace, gazetteerResourceDescription); } @Override public void initialize(UimaContext ctx) throws ResourceInitializationException { super.initialize(ctx); logger = ctx.getLogger(); logger.log(Level.INFO, "{0} Gazetteer initialized with {1} entities", new Object[] { entityNamespace, gazetteer.size() }); count = 0; } @Override public void process(JCas jcas) throws AnalysisEngineProcessException { // TODO: use default view try { jcas = jcas.getView(Views.CONTENT_TEXT.toString()); } catch (final CASException e) { throw new AnalysisEngineProcessException(e); } Set<UniqueTextAnnotation> annotated = new HashSet<UniqueTextAnnotation>(); if (sourceNamespace == null) { Map<Offset, String> matches = gazetteer.match(jcas.getDocumentText()); for (Offset offset : matches.keySet()) for (SemanticAnnotation ann : annotateEntities(jcas, annotated, matches.get(offset), offset)) ann.addToIndexes(); } else { FSMatchConstraint cons = TextAnnotation.makeConstraint(jcas, null, sourceNamespace, sourceIdentifier); FSIterator<Annotation> it = TextAnnotation.getIterator(jcas); it = jcas.createFilteredIterator(it, cons); List<SemanticAnnotation> coll = new LinkedList<SemanticAnnotation>(); while (it.hasNext()) findEntities(jcas, annotated, it.next(), coll); for (SemanticAnnotation ann : coll) ann.addToIndexes(); } } @Override public void destroy() { logger.log(Level.INFO, "tagged {0} {1} entities", new String[] { Integer.toString(count), entityNamespace }); } /** * Iterate over the entity keys and offsets of all Gazetteer matches in the text of the * <code>annotation</code>. */ private void findEntities(JCas jcas, Set<UniqueTextAnnotation> annotated, Annotation annotation, List<SemanticAnnotation> coll) { int base = annotation.getBegin(); logger.log(Level.FINE, "scanning for {0} in ''{1}''", new String[] { entityNamespace, annotation.getCoveredText() }); FSIterator<Annotation> tokenIt = jcas.getAnnotationIndex(TokenAnnotation.type).subiterator( annotation); List<Annotation> tokens = new LinkedList<Annotation>(); while (tokenIt.hasNext()) tokens.add(tokenIt.next()); Map<Offset, String> matches = gazetteer.match(annotation.getCoveredText()); for (Offset offset : matches.keySet()) coll.addAll(annotateEntities(jcas, annotated, matches.get(offset), makeOffset(base, offset, tokens))); } private Offset makeOffset(int base, Offset offset, List<Annotation> tokens) { int begin = base + offset.start(); int end = base + offset.end(); for (Annotation t : tokens) { if (t.getBegin() <= begin && t.getEnd() >= begin) begin = t.getBegin(); if (t.getBegin() <= end && t.getEnd() >= end) end = t.getEnd(); } return new Offset(begin, end); } /** * Determine if the match is exact, or requires resolving the entity key, and calculate the * (normalized) {@link Similarity#similarity(String, String) string similarity} for the * annotation confidence. */ private List<SemanticAnnotation> annotateEntities(JCas jcas, Set<UniqueTextAnnotation> annotated, String matchName, Offset offset) { List<SemanticAnnotation> coll = new LinkedList<SemanticAnnotation>(); String txtName = (sourceNamespace == null) ? matchName : jcas.getDocumentText().substring( offset.start(), offset.end()); if (gazetteer.containsKey(matchName)) { double confidence = measure.similarity(txtName, matchName); for (String dbId : gazetteer.get(matchName)) { UniqueTextAnnotation cta = new UniqueTextAnnotation(offset.start(), offset.end(), entityNamespace, dbId, URI); if (annotated.contains(cta)) continue; coll.add(annotate(dbId, jcas, offset, confidence)); annotated.add(cta); } } else { Map<String, Double> dbIdToSim = new HashMap<String, Double>(); Set<String> targets = gazetteer.resolve(matchName); for (String targetName : targets) { double sim = measure.similarity(txtName, targetName); for (String dbId : gazetteer.get(targetName)) { if (!dbIdToSim.containsKey(dbId) || dbIdToSim.get(dbId) < sim) dbIdToSim.put(dbId, sim); } } for (String dbId : dbIdToSim.keySet()) { UniqueTextAnnotation cta = new UniqueTextAnnotation(offset.start(), offset.end(), entityNamespace, dbId, URI); if (annotated.contains(cta)) continue; coll.add(annotate(dbId, jcas, offset, dbIdToSim.get(dbId))); annotated.add(cta); } } return coll; } /** * Add a {@link SemanticAnnotation semantic annotation} for a DB ID with a given confidence * value. */ private SemanticAnnotation annotate(String id, JCas jcas, Offset offset, double confidence) { SemanticAnnotation entity = new SemanticAnnotation(jcas, offset); entity.setAnnotator(URI); entity.setConfidence(confidence); entity.setIdentifier(id); entity.setNamespace(entityNamespace); logger.log(Level.FINE, "detected {0}:{1} ({2})", new String[] { entityNamespace, id, Double.toString(confidence) }); count++; return entity; } }
package com.github.vlsidlyarevich.unity.web.config; import org.springframework.stereotype.Component; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Component public class CorsFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "x-auth-token, Content-Type"); response.setHeader("Access-Control-Expose-Headers", "x-auth-token, Content-Type"); HttpServletRequest request = (HttpServletRequest) req; if (request.getMethod().equals("OPTIONS")) { try { response.getWriter().print("OK"); response.getWriter().flush(); } catch (IOException e) { e.printStackTrace(); } } else { chain.doFilter(request, response); } } @Override public void destroy() { } }
package com.yahoo.vespa.hadoop.mapreduce; import ai.vespa.feed.client.DocumentId; import ai.vespa.feed.client.DryrunResult; import ai.vespa.feed.client.FeedClient; import ai.vespa.feed.client.FeedClientBuilder; import ai.vespa.feed.client.JsonFeeder; import ai.vespa.feed.client.JsonParseException; import ai.vespa.feed.client.OperationParameters; import ai.vespa.feed.client.OperationStats; import ai.vespa.feed.client.Result; import com.yahoo.vespa.hadoop.mapreduce.util.VespaConfiguration; import com.yahoo.vespa.hadoop.mapreduce.util.VespaCounters; import com.yahoo.vespa.http.client.config.FeedParams; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.TaskAttemptContext; import java.io.IOException; import java.net.URI; import java.time.Duration; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ThreadLocalRandom; import java.util.logging.Logger; import static java.util.stream.Collectors.toList; /** * {@link VespaRecordWriter} sends the output &lt;key, value&gt; to one or more Vespa endpoints using vespa-feed-client. * * @author bjorncs */ public class VespaRecordWriter extends RecordWriter<Object, Object> { private final static Logger log = Logger.getLogger(VespaRecordWriter.class.getCanonicalName()); private final VespaCounters counters; private final VespaConfiguration config; private boolean initialized = false; private JsonFeeder feeder; protected VespaRecordWriter(VespaConfiguration config, VespaCounters counters) { this.counters = counters; this.config = config; } @Override public void write(Object key, Object data) throws IOException { initializeOnFirstWrite(); String json = data.toString().trim(); feeder.feedSingle(json) .whenComplete((result, error) -> { if (error != null) { if (error instanceof JsonParseException) { counters.incrementDocumentsSkipped(1); } else { String msg = "Failed to feed single document: " + error; System.out.println(msg); System.err.println(msg); log.warning(msg); counters.incrementDocumentsFailed(1); } } else { counters.incrementDocumentsOk(1); } }); counters.incrementDocumentsSent(1); if (counters.getDocumentsSent() % config.progressInterval() == 0) { String progress = String.format("Feed progress: %d / %d / %d / %d (sent, ok, failed, skipped)", counters.getDocumentsSent(), counters.getDocumentsOk(), counters.getDocumentsFailed(), counters.getDocumentsSkipped()); log.info(progress); } } @Override public void close(TaskAttemptContext context) throws IOException { if (feeder != null) { feeder.close(); feeder = null; initialized = false; } } /** Override method to alter {@link FeedClient} configuration */ protected void onFeedClientInitialization(FeedClientBuilder builder) {} private void initializeOnFirstWrite() { if (initialized) return; validateConfig(); useRandomizedStartupDelayIfEnabled(); feeder = createJsonStreamFeeder(); initialized = true; } private void validateConfig() { if (!config.useSSL()) { throw new IllegalArgumentException("SSL is required for this feed client implementation"); } if (config.dataFormat() != FeedParams.DataFormat.JSON_UTF8) { throw new IllegalArgumentException("Only JSON is support by this feed client implementation"); } if (config.proxyHost() != null) { log.warning(String.format("Ignoring proxy config (host='%s', port=%d)", config.proxyHost(), config.proxyPort())); } } private void useRandomizedStartupDelayIfEnabled() { if (!config.dryrun() && config.randomStartupSleepMs() > 0) { int delay = ThreadLocalRandom.current().nextInt(config.randomStartupSleepMs()); log.info("Delaying startup by " + delay + " ms"); try { Thread.sleep(delay); } catch (Exception e) {} } } private JsonFeeder createJsonStreamFeeder() { FeedClient feedClient = createFeedClient(); JsonFeeder.Builder builder = JsonFeeder.builder(feedClient) .withTimeout(Duration.ofMinutes(10)); if (config.route() != null) { builder.withRoute(config.route()); } return builder.build(); } private FeedClient createFeedClient() { if (config.dryrun()) { return new DryrunClient(); } else { FeedClientBuilder feedClientBuilder = FeedClientBuilder.create(endpointUris(config)) .setConnectionsPerEndpoint(config.numConnections()) .setMaxStreamPerConnection(streamsPerConnection(config)) .setRetryStrategy(retryStrategy(config)); onFeedClientInitialization(feedClientBuilder); return feedClientBuilder.build(); } } private static FeedClient.RetryStrategy retryStrategy(VespaConfiguration config) { int maxRetries = config.numRetries(); return new FeedClient.RetryStrategy() { @Override public int retries() { return maxRetries; } }; } private static int streamsPerConnection(VespaConfiguration config) { return Math.min(256, config.maxInFlightRequests() / config.numConnections()); } private static List<URI> endpointUris(VespaConfiguration config) { return Arrays.stream(config.endpoint().split(",")) .map(hostname -> URI.create(String.format("https://%s:%d/", hostname, config.defaultPort()))) .collect(toList()); } private static class DryrunClient implements FeedClient { @Override public CompletableFuture<Result> put(DocumentId documentId, String documentJson, OperationParameters params) { return createSuccessResult(documentId); } @Override public CompletableFuture<Result> update(DocumentId documentId, String updateJson, OperationParameters params) { return createSuccessResult(documentId); } @Override public CompletableFuture<Result> remove(DocumentId documentId, OperationParameters params) { return createSuccessResult(documentId); } @Override public OperationStats stats() { return null; } @Override public void close(boolean graceful) {} private static CompletableFuture<Result> createSuccessResult(DocumentId documentId) { return CompletableFuture.completedFuture(DryrunResult.create(Result.Type.success, documentId, "ok", null)); } } }
package net.orfjackal.visualvm4idea.core; import com.sun.tools.visualvm.application.Application; import com.sun.tools.visualvm.application.jvm.Jvm; import com.sun.tools.visualvm.application.jvm.JvmFactory; import com.sun.tools.visualvm.core.datasource.DataSourceRepository; import com.sun.tools.visualvm.profiler.CPUSettingsSupport; import com.sun.tools.visualvm.profiler.MemorySettingsSupport; import com.sun.tools.visualvm.profiler.ProfilerSupport; import net.orfjackal.visualvm4idea.util.Reflect; import net.orfjackal.visualvm4idea.visualvm.ProfilerSupportWrapper; import org.netbeans.lib.profiler.client.ClientUtils; import org.netbeans.lib.profiler.common.AttachSettings; import org.netbeans.lib.profiler.common.ProfilingSettings; import org.netbeans.lib.profiler.common.ProfilingSettingsPresets; import org.netbeans.lib.profiler.common.filters.SimpleFilter; import org.netbeans.lib.profiler.global.CommonConstants; import org.netbeans.modules.profiler.NetBeansProfiler; import org.netbeans.modules.profiler.utils.IDEUtils; import java.util.Set; /** * @author Esko Luontola * @since 10.10.2008 */ public class DebugRunner implements Runnable { // TODO: remove debug code public void run() { while (true) { System.out.println(" try { beginProfilingDirectly(); // beginProfiling(); // printDebugInfo(); } catch (Throwable t) { t.printStackTrace(System.out); return; } sleep(10000); } } private static void beginProfilingDirectly() { // com.sun.tools.visualvm.profiler.ApplicationProfilerView.MasterViewSupport.MasterViewSupport() // com.sun.tools.visualvm.profiler.ApplicationProfilerView.MasterViewSupport.initSettings() final AttachSettings attachSettings = new AttachSettings(); attachSettings.setDirect(true); // attachSettings.setDynamic16(true); // attachSettings.setPid(app.getPid()); attachSettings.setHost("localhost"); attachSettings.setPort(5140); System.out.println("attachSettings = " + attachSettings); // com.sun.tools.visualvm.profiler.ApplicationProfilerView.MasterViewSupport.handleCPUProfiling() // com.sun.tools.visualvm.profiler.CPUSettingsSupport.saveSettings() // Storage storage = app.getStorage(); // storage.setCustomProperty(CPUSettingsSupport.SNAPSHOT_VERSION, CURRENT_SNAPSHOT_VERSION); // storage.setCustomProperty(CPUSettingsSupport.PROP_ROOT_CLASSES, rootsArea.getTextArea().getText()); // storage.setCustomProperty(CPUSettingsSupport.PROP_PROFILE_RUNNABLES, Boolean.toString(runnablesCheckBox.isSelected())); // storage.setCustomProperty(CPUSettingsSupport.PROP_FILTER_TYPE, Integer.toString(inclFilterRadioButton.isSelected() ? // SimpleFilter.SIMPLE_FILTER_INCLUSIVE : SimpleFilter.SIMPLE_FILTER_EXCLUSIVE)); // storage.setCustomProperty(CPUSettingsSupport.PROP_FILTER_VALUE, filtersArea.getTextArea().getText()); // com.sun.tools.visualvm.profiler.ApplicationProfilerView.MasterViewSupport.handleCPUProfiling() // com.sun.tools.visualvm.profiler.CPUSettingsSupport.getSettings() final ProfilingSettings profilingSettings = ProfilingSettingsPresets.createCPUPreset(); profilingSettings.setInstrScheme(CommonConstants.INSTRSCHEME_LAZY); String instrFilter = "java.*, javax.*, sun.*, sunw.*, com.sun.*"; profilingSettings.setSelectedInstrumentationFilter( new SimpleFilter(instrFilter, SimpleFilter.SIMPLE_FILTER_EXCLUSIVE, instrFilter) ); profilingSettings.setInstrumentationRootMethods(new ClientUtils.SourceCodeSelection[]{ new ClientUtils.SourceCodeSelection("net.orfjackal.**", "*", null) }); profilingSettings.setInstrumentSpawnedThreads(true); System.out.println("profilingSettings = " + profilingSettings); // com.sun.tools.visualvm.profiler.ApplicationProfilerView.MasterViewSupport.handleCPUProfiling() // TODO: delay the call to setProfiledApplication, otherwise appears to work // ProfilerSupportWrapper.setProfiledApplication(app); IDEUtils.runInProfilerRequestProcessor(new Runnable() { public void run() { NetBeansProfiler.getDefaultNB().attachToApp(profilingSettings, attachSettings); } }); System.out.println("profiling started"); throw new RuntimeException("ok"); } private static void beginProfiling() { Set<Application> apps = DataSourceRepository.sharedInstance().getDataSources(Application.class); for (Application app : apps) { System.out.println("app = " + app); System.out.println("app.getPid() = " + app.getPid()); Jvm jvm = JvmFactory.getJVMFor(app); if (jvm.getClass().getSimpleName().equals("DefaultJvm")) { System.out.println("jvm = " + jvm); // com.sun.tools.visualvm.profiler.ApplicationProfilerView.MasterViewSupport.MasterViewSupport() // com.sun.tools.visualvm.profiler.ApplicationProfilerView.MasterViewSupport.initSettings() final AttachSettings attachSettings = new AttachSettings(); attachSettings.setDirect(true); // attachSettings.setDynamic16(true); attachSettings.setPid(app.getPid()); // attachSettings.setHost("localhost"); // attachSettings.setPort(5140); System.out.println("attachSettings = " + attachSettings); // com.sun.tools.visualvm.profiler.ApplicationProfilerView.MasterViewSupport.handleCPUProfiling() // com.sun.tools.visualvm.profiler.CPUSettingsSupport.saveSettings() // Storage storage = app.getStorage(); // storage.setCustomProperty(CPUSettingsSupport.SNAPSHOT_VERSION, CURRENT_SNAPSHOT_VERSION); // storage.setCustomProperty(CPUSettingsSupport.PROP_ROOT_CLASSES, rootsArea.getTextArea().getText()); // storage.setCustomProperty(CPUSettingsSupport.PROP_PROFILE_RUNNABLES, Boolean.toString(runnablesCheckBox.isSelected())); // storage.setCustomProperty(CPUSettingsSupport.PROP_FILTER_TYPE, Integer.toString(inclFilterRadioButton.isSelected() ? // SimpleFilter.SIMPLE_FILTER_INCLUSIVE : SimpleFilter.SIMPLE_FILTER_EXCLUSIVE)); // storage.setCustomProperty(CPUSettingsSupport.PROP_FILTER_VALUE, filtersArea.getTextArea().getText()); // com.sun.tools.visualvm.profiler.ApplicationProfilerView.MasterViewSupport.handleCPUProfiling() // com.sun.tools.visualvm.profiler.CPUSettingsSupport.getSettings() final ProfilingSettings profilingSettings = ProfilingSettingsPresets.createCPUPreset(); profilingSettings.setInstrScheme(CommonConstants.INSTRSCHEME_LAZY); String instrFilter = "java.*, javax.*, sun.*, sunw.*, com.sun.*"; profilingSettings.setSelectedInstrumentationFilter( new SimpleFilter(instrFilter, SimpleFilter.SIMPLE_FILTER_EXCLUSIVE, instrFilter) ); profilingSettings.setInstrumentationRootMethods(new ClientUtils.SourceCodeSelection[]{ new ClientUtils.SourceCodeSelection("net.orfjackal.**", "*", null) }); profilingSettings.setInstrumentSpawnedThreads(true); System.out.println("profilingSettings = " + profilingSettings); // com.sun.tools.visualvm.profiler.ApplicationProfilerView.MasterViewSupport.handleCPUProfiling() ProfilerSupportWrapper.setProfiledApplication(app); IDEUtils.runInProfilerRequestProcessor(new Runnable() { public void run() { NetBeansProfiler.getDefaultNB().attachToApp(profilingSettings, attachSettings); } }); System.out.println("profiling started"); sleep(10000); System.out.println("jvm1 = " + JvmFactory.getJVMFor(app)); System.out.println("providers = " + Reflect.on(JvmFactory.getDefault()).field("providers").get().value()); System.out.println("modelCache = " + Reflect.on(JvmFactory.getDefault()).field("modelCache").get().value()); System.out.println("JvmFactory.clearCache()"); Reflect.on(JvmFactory.getDefault()).method("clearCache").call(); System.out.println("providers = " + Reflect.on(JvmFactory.getDefault()).field("providers").get().value()); System.out.println("modelCache = " + Reflect.on(JvmFactory.getDefault()).field("modelCache").get().value()); System.out.println("jvm2 = " + JvmFactory.getJVMFor(app)); throw new RuntimeException("ok"); } } } private void printDebugInfo() { System.out.println(" Set<Application> applications = DataSourceRepository.sharedInstance().getDataSources(Application.class); for (Application app : applications) { System.out.println("app = " + app); System.out.println("app.getHost() = " + app.getHost()); System.out.println("app.getId() = " + app.getId()); System.out.println("app.getMaster() = " + app.getMaster()); System.out.println("app.getOwner() = " + app.getOwner()); System.out.println("app.getPid() = " + app.getPid()); System.out.println("app.getRepository() = " + app.getRepository()); System.out.println("app.getState() = " + app.getState()); System.out.println("app.getStorage() = " + app.getStorage()); System.out.println("app.isLocalApplication() = " + app.isLocalApplication()); System.out.println("app.isRemoved() = " + app.isRemoved()); System.out.println("app.isVisible() = " + app.isVisible()); System.out.println("app.supportsUserRemove() = " + app.supportsUserRemove()); Jvm jvm = JvmFactory.getJVMFor(app); System.out.println("jvm.getCommandLine() = " + jvm.getCommandLine()); System.out.println("jvm.getJavaHome() = " + jvm.getJavaHome()); System.out.println("jvm.getJvmArgs() = " + jvm.getJvmArgs()); System.out.println("jvm.getJvmFlags() = " + jvm.getJvmFlags()); System.out.println("jvm.getMainArgs() = " + jvm.getMainArgs()); System.out.println("jvm.getMainClass() = " + jvm.getMainClass()); System.out.println("jvm.getVmInfo() = " + jvm.getVmInfo()); System.out.println("jvm.getVmName() = " + jvm.getVmName()); System.out.println("jvm.getVmVendor() = " + jvm.getVmVendor()); System.out.println("jvm.getVmVersion() = " + jvm.getVmVersion()); ProfilerSupportWrapper.selectProfilerView(app); sleep(1000); Object masterViewSupport = Reflect.on(ProfilerSupport.getInstance()) .field("profilerViewProvider").get() .method("view", Application.class).call(app) .field("masterViewSupport").get().value(); System.out.println("masterViewSupport = " + masterViewSupport); CPUSettingsSupport cpuSettingsSupport = (CPUSettingsSupport) Reflect.on(masterViewSupport).field("cpuSettingsSupport").get().value(); MemorySettingsSupport memorySettingsSupport = (MemorySettingsSupport) Reflect.on(masterViewSupport).field("memorySettingsSupport").get().value(); System.out.println("cpuSettingsSupport = " + cpuSettingsSupport); System.out.println("memorySettingsSupport = " + memorySettingsSupport); } } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { // ignore } } }
package edu.yu.einstein.wasp.grid.work; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URI; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.concurrent.TimeUnit; import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.common.SecurityUtils; import net.schmizz.sshj.connection.ConnectionException; import net.schmizz.sshj.connection.channel.direct.Session; import net.schmizz.sshj.connection.channel.direct.Session.Command; import net.schmizz.sshj.transport.TransportException; import net.schmizz.sshj.userauth.keyprovider.KeyProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import edu.yu.einstein.wasp.grid.GridAccessException; import edu.yu.einstein.wasp.grid.GridExecutionException; import edu.yu.einstein.wasp.grid.GridUnresolvableHostException; import edu.yu.einstein.wasp.grid.MisconfiguredWorkUnitException; /** * {@link GridTransportConnection} implementation for execution of jobs over a * SSH connection. * * @author calder * */ public class SshTransportConnection implements GridTransportConnection, InitializingBean, DisposableBean { private static final Logger logger = LoggerFactory.getLogger(SshTransportConnection.class); private SSHClient client = new SSHClient(); private Session session; // TODO: configure private int execTimeout = 600000; // 10m, VERY generous private int execRetries = 5; private String identityFileName; private File identityFile; private String name; private String hostname; private String username; private Map<String, String> settings = new HashMap<String, String>(); private SoftwareManager softwareManager; private boolean userDirIsRoot = true; private Properties localProperties; public Map<String, String> getSettings() { return settings; } public SshTransportConnection() { loadKnownHosts(); } private void resetClientAndStartNewSession() throws GridAccessException, ConnectionException, TransportException{ doDisconnect(); client = new SSHClient(); loadKnownHosts(); initClient(); session = client.startSession(); } private void loadKnownHosts() { try { client.loadKnownHosts(); } catch (IOException e) { logger.error("unable to load known hosts file"); e.printStackTrace(); throw new RuntimeException("sshj unable to load known hosts file"); } } private void initClient() throws GridAccessException { try { logger.trace("attempting to configure and connect SSH connection"); logger.trace("loading identity file " + getIdentityFile().getAbsolutePath()); logger.trace("BouncyCastle: " + SecurityUtils.isBouncyCastleRegistered()); logger.trace("connecting " + getHostName()); logger.trace("client: " + client.toString()); client.connect(getHostName()); logger.debug("connected"); KeyProvider key = client.loadKeys(getIdentityFile().getAbsolutePath()); client.authPublickey(getUserName(), key); } catch (IOException e) { e.printStackTrace(); logger.error("unable to connect to remote host " + getHostName()); throw new GridAccessException("unable to connect to remote", e.getCause()); } logger.debug("adding sshj connection: " + this.client.toString()); } private void disconnectClient() throws IOException { logger.debug("disconnecting client"); client.disconnect(); } private void openSession() throws ConnectionException, TransportException, GridAccessException { if (!client.isConnected()) { logger.warn("client for " + getHostName() + " was not connected, reestablishing"); initClient(); } if (session == null) { session = client.startSession(); return; } if (session.isOpen()) { logger.debug("session already open"); return; } logger.debug("opening session"); try { session = client.startSession(); } catch (ConnectionException e) { logger.warn("session apparently timed out, attempting to recover: " + e.toString()); try{ initClient(); session = client.startSession(); } catch (Exception e1){ logger.warn("Unable to recover session so going to reset client and start a new session: " + e1.toString()); resetClientAndStartNewSession(); } } } private void closeSession() throws TransportException, ConnectionException { logger.debug("closing session"); if (session != null) { session.close(); } else { logger.debug("no session to close"); } } public void doDisconnect() throws GridAccessException { logger.debug("Disconnectiong SshTransportConnection to " + getHostName() + " as " + getUserName()); try { closeSession(); } catch (IOException e) { logger.warn("unable to close session " + e.getLocalizedMessage()); } try { disconnectClient(); } catch (IOException e) { logger.error("unable to cleanly disconnect: " + e.getLocalizedMessage()); throw new GridAccessException(e.getLocalizedMessage()); } } /** * Ssh implementation of {@link GridTransportConnection}. This method sends the exec to the target host without wrapping * in the extra methods defined in the {@link GridWorkService} (used by GridWorkService to "execute" work unit). * * {@inheritDoc} * @throws MisconfiguredWorkUnitException */ @Override public GridResult sendExecToRemote(WorkUnit w) throws GridAccessException, GridExecutionException, GridUnresolvableHostException, MisconfiguredWorkUnitException { GridResultImpl result = new GridResultImpl(); try { logger.trace("Attempting to create SshTransportConnection to " + getHostName()); openSession(); // ensure set for direct remote execution w.remoteWorkingDirectory = prefixRemoteFile(w.getWorkingDirectory()); w.remoteResultsDirectory = prefixRemoteFile(w.getResultsDirectory()); String command = w.getCommand(); if (w.getWrapperCommand() != null) command = w.getWrapperCommand(); command = "cd " + w.remoteWorkingDirectory + " && " + command; command = "if [ -e /etc/profile ]; then source /etc/profile > /dev/null 2>&1; fi && " + command; logger.trace("sending exec: " + command + " at: " + getHostName()); for (int tries=0; tries < execRetries; tries++) { try { doExec(result, command); break; } catch (ConnectionException ce) { logger.warn("Caught ConnectionException on session (" + ce.getLocalizedMessage() + ") try " + tries + ". Session open: " + session.isOpen() + ". Will try again up to " + execRetries + " times."); if (!session.isOpen()) { openSession(); } continue; } } } catch (Exception e) { e.printStackTrace(); logger.error("problem sending command"); throw new GridAccessException("problem closing session", e); } logger.trace("returning result"); return (GridResult) result; } private void doExec(GridResultImpl result, String command) throws ConnectionException, TransportException, GridAccessException { try { final Command exec = session.exec(command); // execute command and timeout exec.join(this.execTimeout, TimeUnit.MILLISECONDS); result.setExitStatus(exec.getExitStatus()); result.setStdErrStream(exec.getErrorStream()); result.setStdOutStream(exec.getInputStream()); logger.trace("sent command"); if (exec.getExitStatus() != 0) { logger.error("exec terminated with non-zero exit status: " + command); throw new GridAccessException("exec terminated with non-zero exit status: " + exec.getExitStatus() + " : " + exec.getOutputStream().toString()); } } finally { session.close(); } } @Override public SoftwareManager getSoftwareManager() { return softwareManager; } public void setSoftwareManager(SoftwareManager softwareManager) { this.softwareManager = softwareManager; } @Override public String getConfiguredSetting(String key) { return settings.get(key); } @Override public boolean isUserDirIsRoot() { return this.userDirIsRoot; } public void setUserDirIsRoot(boolean isRoot) { this.userDirIsRoot = isRoot; } @Override public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Override public String getHostName() { return this.hostname; } public void setHostName(String hostname) { this.hostname = hostname; } @Override public String getUserName() { return this.username; } public void setUserName(String username) { this.username = username; } @Override public File getIdentityFile() { return this.identityFile; } public void setIdentityFileName(String identityFileName) { this.identityFileName = identityFileName; setIdentityFile(this.identityFileName); } public Properties getLocalProperties() { return localProperties; } public void setLocalProperties(Properties waspSiteProperties) { this.localProperties = waspSiteProperties; String prefix = this.name + ".settings."; for (String key : this.localProperties.stringPropertyNames()) { if (key.startsWith(prefix)) { String newKey = key.replaceFirst(prefix, ""); String value = this.localProperties.getProperty(key); settings.put(newKey, value); logger.debug("Configured setting for host \"" + this.name + "\": " + newKey + "=" + value); } } } public void setIdentityFile(String s) { String home = System.getProperty("user.home"); s = home + s.replaceAll("~(.*)", "$1"); identityFile = new File(s).getAbsoluteFile(); logger.debug("set identity file to: " + identityFile.getAbsolutePath()); } @Override public String prefixRemoteFile(String filespec) { String prefix = ""; if (isUserDirIsRoot() && !filespec.startsWith("$HOME") && !filespec.startsWith("~")) prefix = "$HOME/"; String retval = prefix + filespec; return retval.replaceAll(" } @Override public String prefixRemoteFile(URI uri) throws FileNotFoundException, GridUnresolvableHostException { if ( !uri.getHost().toLowerCase().equals(hostname)) throw new GridUnresolvableHostException("file " + uri.toString() + " not registered on " + hostname); // TODO: implement remote file management if ( !uri.getScheme().equals("file")) throw new FileNotFoundException("file not found " + uri.toString() + " unknown scheme " + uri.getScheme()); return prefixRemoteFile(uri.getPath()); } @Override public void afterPropertiesSet() throws Exception { logger.debug("created sshTransportConnection"); } @Override public void destroy() throws Exception { logger.debug("destroying sshTransportConnection"); doDisconnect(); } }
package com.bearsoft.gwt.ui.containers; import com.bearsoft.gwt.ui.HasImageResource; import com.bearsoft.gwt.ui.XElement; import com.bearsoft.gwt.ui.menu.MenuItemImageText; import com.bearsoft.gwt.ui.widgets.ImageLabel; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.logical.shared.HasSelectionHandlers; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.safehtml.client.SafeHtmlTemplates; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeUri; import com.google.gwt.safehtml.shared.UriUtils; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HasHTML; import com.google.gwt.user.client.ui.HasText; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.IndexedPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.LayoutPanel; import com.google.gwt.user.client.ui.MenuBar; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.ui.ProvidesResize; import com.google.gwt.user.client.ui.RequiresResize; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.TabLayoutPanel; import com.google.gwt.user.client.ui.Widget; /** * * @author mg */ public class TabsDecoratedPanel extends SimplePanel implements RequiresResize, ProvidesResize, IndexedPanel, HasSelectionHandlers<Widget> { public interface Template extends SafeHtmlTemplates { @SafeHtmlTemplates.Template("<div class=\"{0}\"></div>") SafeHtml classedDiv(String aClasses); } private static final Template template = GWT.create(Template.class); protected boolean tabsOnTop = true; protected FlowPanel chevron = new FlowPanel(); protected Button scrollLeft; protected Button scrollRight; protected Button tabsList; protected TabLayoutPanel tabs; protected double barHeight; protected Style.Unit barUnit; protected LayoutPanel tabBarContainer; protected Widget tabBar; protected Widget tabsContent; protected Widget selected; public TabsDecoratedPanel(double aBarHeight, Style.Unit aBarUnit) { super(); barHeight = aBarHeight; barUnit = aBarUnit; tabs = new TabLayoutPanel(barHeight, barUnit) { @Override protected void initWidget(Widget w) { super.initWidget(w); assert w instanceof LayoutPanel; tabBarContainer = (LayoutPanel) w; } @Override public void insert(Widget child, Widget tab, int beforeIndex) { child.getElement().getStyle().clearWidth(); child.getElement().getStyle().clearHeight(); // if (child instanceof FocusWidget) { child.getElement().getStyle().clearRight(); child.getElement().getStyle().setWidth(100, Style.Unit.PCT); com.bearsoft.gwt.ui.CommonResources.INSTANCE.commons().ensureInjected(); child.getElement().addClassName(com.bearsoft.gwt.ui.CommonResources.INSTANCE.commons().borderSized()); super.insert(child, tab, beforeIndex); tabsList.setEnabled(true); } @Override public boolean remove(int index) { boolean res = super.remove(index); if (tabs.getWidgetCount() == 0) tabsList.setEnabled(false); return res; } @Override public void selectTab(final int index, boolean fireEvents) { super.selectTab(index, fireEvents); } }; tabs.addSelectionHandler(new SelectionHandler<Integer>() { @Override public void onSelection(SelectionEvent<Integer> event) { selected = event.getSelectedItem() != -1 ? tabs.getWidget(event.getSelectedItem()) : null; Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { if (selected instanceof RequiresResize) { ((RequiresResize) selected).onResize(); } } }); SelectionEvent.fire(TabsDecoratedPanel.this, selected); } }); tabBar = tabBarContainer.getWidget(0); tabsContent = tabBarContainer.getWidget(1); // GWT Layout animations are deprecated because of CSS3 transitions tabs.setAnimationDuration(0); scrollLeft = new Button(template.classedDiv("tabs-chevron-left"), new ClickHandler() { @Override public void onClick(ClickEvent event) { int offsetLeft = tabBar.getElement().getOffsetLeft(); if (offsetLeft < 0) { tabBar.getElement().getStyle().setLeft(Math.min(offsetLeft + 100, 0), Style.Unit.PX); } updateScrolls(); } }); scrollRight = new Button(template.classedDiv("tabs-chevron-right"), new ClickHandler() { @Override public void onClick(ClickEvent event) { int newTabBarLeft = calcNewScrollRightPosition(); tabBar.getElement().getStyle().setLeft(newTabBarLeft, Style.Unit.PX); updateScrolls(); } }); tabsList = new Button(template.classedDiv("tabs-chevron-list"), new ClickHandler() { @Override public void onClick(ClickEvent event) { final PopupPanel pp = new PopupPanel(); pp.setAutoHideEnabled(true); pp.setAutoHideOnHistoryEventsEnabled(true); pp.setAnimationEnabled(true); MenuBar menu = new MenuBar(true); for (int i = 0; i < tabs.getWidgetCount(); i++) { final Widget content = tabs.getWidget(i); Widget w = tabs.getTabWidget(i); if (w instanceof SimplePanel) { SimplePanel sp = (SimplePanel) w; w = sp.getWidget(); } ScheduledCommand tabSelector = new ScheduledCommand() { @Override public void execute() { tabs.selectTab(content); pp.hide(); Widget targetTab = tabs.getTabWidget(content); int tabCenterX = targetTab.getParent().getElement().getOffsetLeft() + targetTab.getParent().getElement().getOffsetWidth() / 2; int tabBarParentWidth = tabBar.getElement().getParentElement().getOffsetWidth() - chevron.getElement().getOffsetWidth(); int newOffsetLeft = tabBarParentWidth / 2 - tabCenterX; Widget lastTab = tabs.getTabWidget(tabs.getWidgetCount() - 1); int rightMostX = lastTab.getParent().getElement().getOffsetLeft() + lastTab.getParent().getElement().getOffsetWidth(); int width = rightMostX + newOffsetLeft; if (width > tabBarParentWidth) { tabBar.getElement().getStyle().setLeft(Math.min(newOffsetLeft, 0), Style.Unit.PX); } else { tabBar.getElement().getStyle().setLeft(Math.min(tabBarParentWidth - rightMostX, 0), Style.Unit.PX); } } }; SafeUri imageUri = null; if (w instanceof Image) { Image image = (Image) w; imageUri = UriUtils.fromTrustedString(image.getUrl()); } else if (w instanceof HasImageResource) { HasImageResource imageHost = (HasImageResource) w; if (imageHost.getImageResource() != null) { imageUri = imageHost.getImageResource().getSafeUri(); } } if (w instanceof HasHTML) { HasHTML h = (HasHTML) w; String textAsHtml = h.getHTML(); menu.addItem(new MenuItemImageText(textAsHtml != null ? textAsHtml : h.getText(), true, imageUri, tabSelector)); } else if (w instanceof HasText) { HasText l = (HasText) w; menu.addItem(new MenuItemImageText(l.getText(), false, imageUri, tabSelector)); } } pp.setWidget(menu); Widget lastWidget = chevron.getWidget(chevron.getWidgetCount() - 1); pp.setPopupPosition(lastWidget.getAbsoluteLeft(), lastWidget.getAbsoluteTop() + lastWidget.getElement().getOffsetHeight()); pp.showRelativeTo(lastWidget); } }); tabsList.setEnabled(false); getElement().getStyle().setPosition(Style.Position.RELATIVE); tabs.getElement().getStyle().setPosition(Style.Position.ABSOLUTE); tabs.getElement().getStyle().setWidth(100, Style.Unit.PCT); tabs.getElement().getStyle().setHeight(100, Style.Unit.PCT); setWidget(tabs); scrollLeft.getElement().getStyle().setPadding(0, Style.Unit.PX); scrollLeft.getElement().getStyle().setMargin(0, Style.Unit.PX); scrollRight.getElement().getStyle().setPadding(0, Style.Unit.PX); scrollRight.getElement().getStyle().setMargin(0, Style.Unit.PX); tabsList.getElement().getStyle().setPadding(0, Style.Unit.PX); tabsList.getElement().getStyle().setMargin(0, Style.Unit.PX); chevron.add(scrollLeft); chevron.add(scrollRight); chevron.add(tabsList); chevron.getElement().addClassName("tabs-chevron"); chevron.getElement().getStyle().setPosition(Style.Position.ABSOLUTE); assert tabBarContainer != null; tabBarContainer.getWidgetContainerElement(tabBar).appendChild(chevron.getElement()); getElement().<XElement> cast().addResizingTransitionEnd(this); } public boolean isTabsOnTop() { return tabsOnTop; } public void setTabsOnTop(boolean aValue) { if (tabsOnTop != aValue) { tabsOnTop = aValue; applyTabsOnTop(); } } protected void applyTabsOnTop() { if (tabBar != null && tabBarContainer != null && tabsContent != null) { final String tabBarLeft = tabBar.getElement().getStyle().getLeft(); Element tabBarContainerElement = tabBarContainer.getWidgetContainerElement(tabBar); tabBarContainerElement.getStyle().clearTop(); tabBarContainerElement.getStyle().clearHeight(); tabBarContainerElement.getStyle().clearBottom(); Element tabContentContainerElement = tabBarContainer.getWidgetContainerElement(tabsContent); tabContentContainerElement.getStyle().clearTop(); tabContentContainerElement.getStyle().clearHeight(); tabContentContainerElement.getStyle().clearBottom(); if (tabsOnTop) { tabBarContainer.setWidgetTopHeight(tabBar, 0, Style.Unit.PX, barHeight, barUnit); tabBarContainer.setWidgetTopBottom(tabsContent, barHeight, barUnit, 0, Style.Unit.PX); } else { tabBarContainer.setWidgetBottomHeight(tabBar, 0, Style.Unit.PX, barHeight, barUnit); tabBarContainer.setWidgetTopBottom(tabsContent, 0, Style.Unit.PX, barHeight, barUnit); } Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { tabBar.getElement().getStyle().setProperty("left", tabBarLeft); } }); } } @Override protected void onAttach() { super.onAttach(); adopt(chevron); } @Override protected void onDetach() { orphan(chevron); super.onDetach(); } @Override public void onResize() { tabs.onResize(); Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { updateScrolls(); } }); } protected int calcNewScrollRightPosition() { Widget lastTab = tabs.getWidgetCount() > 0 ? tabs.getTabWidget(tabs.getWidgetCount() - 1) : null; int rightMostX = lastTab != null ? lastTab.getParent().getElement().getOffsetLeft() + lastTab.getParent().getElement().getOffsetWidth() : tabBar.getElement().getOffsetLeft(); int tabBarParentWidth = tabBar.getElement().getParentElement().getOffsetWidth() - chevron.getElement().getOffsetWidth(); int tabBarMostLeft = Math.min(tabBarParentWidth - rightMostX, 0); int nextTabBarLeft = tabBar.getElement().getOffsetLeft() - 100; if (nextTabBarLeft < tabBarMostLeft) nextTabBarLeft = tabBarMostLeft; return nextTabBarLeft; } protected void updateScrolls() { int oldTabBarLeft = tabBar.getElement().getOffsetLeft(); scrollLeft.setEnabled(oldTabBarLeft < 0); int newTabBarLeft = calcNewScrollRightPosition(); scrollRight.setEnabled(newTabBarLeft != oldTabBarLeft); } /** * Adds a widget to the panel. If the Widget is already attached, it will be * moved to the right-most index. * * @param child * the widget to be added * @param text * the text to be shown on its tab * @param asHtml * <code>true</code> to treat the specified text as HTML */ public void add(Widget child, String text, boolean asHtml) { tabs.insert(child, text, asHtml, tabs.getWidgetCount()); } /** * Adds a widget to the panel. If the Widget is already attached, it will be * moved to the right-most index. * * @param child * the widget to be added * @param text * the text to be shown on its tab * @param asHtml * <code>true</code> to treat the specified text as HTML */ public void add(Widget child, String text, boolean asHtml, ImageResource aImage) { tabs.insert(child, new ImageLabel(text, asHtml, aImage), tabs.getWidgetCount()); } /** * Adds a widget to the panel. If the Widget is already attached, it will be * moved to the right-most index. * * @param child * the widget to be added * @param text * the text to be shown on its tab */ public void add(Widget child, String text) { tabs.insert(child, text, tabs.getWidgetCount()); } /** * Adds a widget to the panel. If the Widget is already attached, it will be * moved to the right-most index. * * @param child * the widget to be added * @param html * the html to be shown on its tab */ public void add(Widget child, SafeHtml html) { tabs.add(child, html.asString(), true); } /** * Adds a widget to the panel. If the Widget is already attached, it will be * moved to the right-most index. * * @param child * the widget to be added * @param tab * the widget to be placed in the associated tab */ public void add(Widget child, Widget tab) { tabs.insert(child, tab, tabs.getWidgetCount()); } /** * Inserts a widget into the panel. If the Widget is already attached, it * will be moved to the requested index. * * @param child * the widget to be added * @param beforeIndex * the index before which it will be inserted */ public void insert(Widget child, int beforeIndex) { tabs.insert(child, "", beforeIndex); } /** * Inserts a widget into the panel. If the Widget is already attached, it * will be moved to the requested index. * * @param child * the widget to be added * @param html * the html to be shown on its tab * @param beforeIndex * the index before which it will be inserted */ public void insert(Widget child, SafeHtml html, int beforeIndex) { tabs.insert(child, html.asString(), true, beforeIndex); } /** * Inserts a widget into the panel. If the Widget is already attached, it * will be moved to the requested index. * * @param child * the widget to be added * @param text * the text to be shown on its tab * @param asHtml * <code>true</code> to treat the specified text as HTML * @param beforeIndex * the index before which it will be inserted */ public void insert(Widget child, String text, boolean asHtml, int beforeIndex) { Widget contents; if (asHtml) { contents = new HTML(text); } else { contents = new Label(text); } tabs.insert(child, contents, beforeIndex); } /** * Inserts a widget into the panel. If the Widget is already attached, it * will be moved to the requested index. * * @param child * the widget to be added * @param text * the text to be shown on its tab * @param beforeIndex * the index before which it will be inserted */ public void insert(Widget child, String text, int beforeIndex) { tabs.insert(child, text, false, beforeIndex); } /** * Inserts a widget into the panel. If the Widget is already attached, it * will be moved to the requested index. * * @param child * the widget to be added * @param tab * the widget to be placed in the associated tab * @param beforeIndex * the index before which it will be inserted */ public void insert(Widget child, Widget tab, int beforeIndex) { tabs.insert(child, tab, beforeIndex); } /** * Set the duration of the animated transition between tabs. * * @param duration * the duration in milliseconds. */ public void setAnimationDuration(int duration) { tabs.setAnimationDuration(duration); } /** * Set whether or not transitions slide in vertically or horizontally. * * @param isVertical * true for vertical transitions, false for horizontal */ public void setAnimationVertical(boolean isVertical) { tabs.setAnimationVertical(isVertical); } /** * Sets a tab's HTML contents. * * Use care when setting an object's HTML; it is an easy way to expose * script-based security problems. Consider using * {@link #setTabHTML(int, SafeHtml)} or {@link #setTabText(int, String)} * whenever possible. * * @param index * the index of the tab whose HTML is to be set * @param html * the tab's new HTML contents */ public void setTabHTML(int index, String html) { tabs.setTabHTML(index, html); } /** * Sets a tab's HTML contents. * * @param index * the index of the tab whose HTML is to be set * @param html * the tab's new HTML contents */ public void setTabHTML(int index, SafeHtml html) { tabs.setTabHTML(index, html); } /** * Sets a tab's text contents. * * @param index * the index of the tab whose text is to be set * @param text * the object's new text */ public void setTabText(int index, String text) { tabs.setTabText(index, text); } @Override public boolean remove(Widget w) { return tabs.remove(w); } @Override public Widget getWidget(int index) { return tabs.getWidget(index); } @Override public int getWidgetCount() { return tabs.getWidgetCount(); } @Override public int getWidgetIndex(Widget child) { return tabs.getWidgetIndex(child); } @Override public boolean remove(int aIndex) { return tabs.remove(aIndex); } /** * Programmatically selects the specified tab and fires events. * * @param child * the child whose tab is to be selected */ public void selectTab(Widget child) { tabs.selectTab(child); } /** * Programmatically selects the specified tab. * * @param child * the child whose tab is to be selected * @param fireEvents * true to fire events, false not to */ public void selectTab(Widget child, boolean fireEvents) { tabs.selectTab(child, fireEvents); } /** * Programmatically selects the specified tab and fires events. * * @param index * the index of the tab to be selected */ public void selectTab(int index) { tabs.selectTab(index); } /** * Programmatically selects the specified tab. * * @param index * the index of the tab to be selected * @param fireEvents * true to fire events, false not to */ public void selectTab(int index, boolean fireEvents) { tabs.selectTab(index, fireEvents); } @Override public HandlerRegistration addSelectionHandler(SelectionHandler<Widget> handler) { return addHandler(handler, SelectionEvent.getType()); } }
package org.jbehave.web.selenium; import org.jbehave.core.model.Story; import org.jbehave.core.reporters.NullStoryReporter; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.remote.SessionId; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Authenticator; import java.net.HttpURLConnection; import java.net.PasswordAuthentication; import java.net.URL; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.jbehave.web.selenium.SauceWebDriverProvider.getSauceAccessKey; import static org.jbehave.web.selenium.SauceWebDriverProvider.getSauceUser; public class SauceContextStoryReporter extends NullStoryReporter { private final WebDriverProvider webDriverProvider; private ThreadLocal<String> storyName = new ThreadLocal<String>(); private ThreadLocal<SessionId> sessionIds = new ThreadLocal<SessionId>(); private ThreadLocal<Boolean> passed = new ThreadLocal<Boolean>(); public SauceContextStoryReporter(WebDriverProvider webDriverProvider) { this.webDriverProvider = webDriverProvider; } @Override public void beforeStory(Story story, boolean givenStory) { storyName.set(story.getName()); passed.set(true); } @Override public void beforeScenario(String title) { sessionIds.set(((RemoteWebDriver) webDriverProvider.get()).getSessionId()); } @Override public void failed(String step, Throwable cause) { passed.set(false); } @Override public void afterStory(boolean givenStory) { SessionId sessionId = sessionIds.get(); if (sessionId == null ) { // no executed scenarios, as (most likely) excluded return; } try { String payload = "{\"tags\":[" + getJobTags() + "], \"passed\":\"" + passed.get() + "\",\"name\":\" " + getJobName() + "\"}"; URL url = new URL("http://saucelabs.com/rest/v1/" + getSauceUser() + "/jobs/" + sessionId.toString()); Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(getSauceUser(), getSauceAccessKey().toCharArray()); } }); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("PUT"); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(payload); writer.close(); int rc = connection.getResponseCode(); if (rc == 200) { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String s; // This comes back from Saucelabs: Pattern p = Pattern.compile("http.*\\.flv"); while ((s = reader.readLine()) != null) { Matcher matcher = p.matcher(s); while (matcher.find()) { System.out.println("Saucelabs Video: " + matcher.group()); break; } } } } catch (IOException e) { System.err.println("Error updating Saucelabs job info: " + e.getMessage()); e.printStackTrace(); } } /** * The name of the job. By default this is the story name. * @return the job name */ protected String getJobName() { return storyName.get(); } /** * A set of tags to apply to the job, like so: * "foo", "bar" * * @return a string of comma separated strings in quotes */ protected String getJobTags() { return ""; } }
package org.whattf.syntax; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.MalformedURLException; import nu.validator.gnu.xml.aelfred2.SAXDriver; import nu.validator.htmlparser.sax.HtmlParser; import nu.validator.xml.IdFilter; import nu.validator.xml.SystemErrErrorHandler; import nu.validator.xml.XhtmlIdFilter; import org.whattf.checker.NormalizationChecker; import org.whattf.checker.SignificantInlineChecker; import org.whattf.checker.TextContentChecker; import org.whattf.checker.jing.CheckerValidator; import org.whattf.checker.table.TableChecker; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; import com.thaiopensource.relaxng.impl.CombineValidator; import com.thaiopensource.util.PropertyMap; import com.thaiopensource.util.PropertyMapBuilder; import com.thaiopensource.validate.Schema; import com.thaiopensource.validate.SchemaReader; import com.thaiopensource.validate.ValidateProperty; import com.thaiopensource.validate.Validator; import com.thaiopensource.validate.auto.AutoSchemaReader; import com.thaiopensource.validate.rng.CompactSchemaReader; import com.thaiopensource.validate.rng.RngProperty; import com.thaiopensource.xml.sax.CountingErrorHandler; import com.thaiopensource.xml.sax.Jaxp11XMLReaderCreator; /** * * @version $Id$ * @author hsivonen */ public class Driver { private static final String PATH = "syntax/relaxng/tests/"; private PrintWriter err; private PrintWriter out; private Schema mainSchema; private Schema assertionSchema; private Validator validator; private SystemErrErrorHandler errorHandler = new SystemErrErrorHandler(); private CountingErrorHandler countingErrorHandler = new CountingErrorHandler(); private HtmlParser htmlParser = new HtmlParser(); private XMLReader xmlParser; private boolean failed = false; private boolean verbose; /** * @param basePath */ public Driver(boolean verbose) { this.verbose = verbose; try { this.err = new PrintWriter(new OutputStreamWriter(System.err, "UTF-8")); this.out = new PrintWriter(new OutputStreamWriter(System.out, "UTF-8")); /* * SAXParserFactory factory = SAXParserFactory.newInstance(); * factory.setNamespaceAware(true); factory.setValidating(false); * XMLReader parser = factory.newSAXParser().getXMLReader(); */ this.xmlParser = new IdFilter(new SAXDriver()); } catch (Exception e) { // If this happens, the JDK is too broken anyway throw new RuntimeException(e); } } private Schema schemaByFilename(File name) throws Exception { PropertyMapBuilder pmb = new PropertyMapBuilder(); pmb.put(ValidateProperty.ERROR_HANDLER, errorHandler); pmb.put(ValidateProperty.XML_READER_CREATOR, new Jaxp11XMLReaderCreator()); RngProperty.CHECK_ID_IDREF.add(pmb); PropertyMap jingPropertyMap = pmb.toPropertyMap(); InputSource schemaInput; try { schemaInput = new InputSource(name.toURL().toString()); } catch (MalformedURLException e1) { System.err.println(); e1.printStackTrace(err); failed = true; return null; } SchemaReader sr; if (name.getName().endsWith(".rnc")) { sr = CompactSchemaReader.getInstance(); } else { sr = new AutoSchemaReader(); } return sr.createSchema(schemaInput, jingPropertyMap); } private void checkFile(File file) throws IOException, SAXException { validator.reset(); InputSource is = new InputSource(new FileInputStream(file)); is.setSystemId(file.toURL().toString()); String name = file.getName(); if (name.endsWith(".html") || name.endsWith(".htm")) { is.setEncoding("UTF-8"); if (verbose) { out.println(file); out.flush(); } htmlParser.parse(is); } else if (name.endsWith(".xhtml") || name.endsWith(".xht")) { if (verbose) { out.println(file); out.flush(); } xmlParser.parse(is); } } private boolean isCheckableFile(File file) { String name = file.getName(); return file.isFile() && (name.endsWith(".html") || name.endsWith(".htm") || name.endsWith(".xhtml") || name.endsWith(".xht")); } private void checkValidFiles(File directory) { File[] files = directory.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; if (isCheckableFile(file)) { errorHandler.reset(); try { checkFile(file); } catch (IOException e) { } catch (SAXException e) { } if (errorHandler.isInError()) { failed = true; } } else if (file.isDirectory()) { checkValidFiles(file); } } } private void checkInvalidFiles(File directory) { File[] files = directory.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; if (isCheckableFile(file)) { countingErrorHandler.reset(); try { checkFile(file); } catch (IOException e) { } catch (SAXException e) { } if (!countingErrorHandler.getHadErrorOrFatalError()) { failed = true; try { err.println(file.toURL().toString() + "was supposed to be invalid but was not."); err.flush(); } catch (MalformedURLException e) { throw new RuntimeException(e); } } } else if (file.isDirectory()) { checkInvalidFiles(file); } } } private void checkDirectory(File directory, File schema) throws SAXException { try { mainSchema = schemaByFilename(schema); } catch (Exception e) { err.println("Reading schema failed. Skipping test directory."); e.printStackTrace(); err.flush(); return; } File[] files = directory.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; if ("valid".equals(file.getName())) { setup(errorHandler); checkValidFiles(file); } else if ("invalid".equals(file.getName())) { setup(countingErrorHandler); checkInvalidFiles(file); } } } /** * @throws SAXNotSupportedException * @throws SAXdException * */ private void setup(ErrorHandler eh) throws SAXException { PropertyMapBuilder pmb = new PropertyMapBuilder(); pmb.put(ValidateProperty.ERROR_HANDLER, eh); pmb.put(ValidateProperty.XML_READER_CREATOR, new Jaxp11XMLReaderCreator()); RngProperty.CHECK_ID_IDREF.add(pmb); PropertyMap jingPropertyMap = pmb.toPropertyMap(); validator = mainSchema.createValidator(jingPropertyMap); Validator assertionValidator = assertionSchema.createValidator(jingPropertyMap); validator = new CombineValidator(validator, assertionValidator); validator = new CombineValidator(validator, new CheckerValidator( new TableChecker(), jingPropertyMap)); validator = new CombineValidator(validator, new CheckerValidator( new NormalizationChecker(), jingPropertyMap)); validator = new CombineValidator(validator, new CheckerValidator( new SignificantInlineChecker(), jingPropertyMap)); validator = new CombineValidator(validator, new CheckerValidator( new TextContentChecker(), jingPropertyMap)); htmlParser.setContentHandler(validator.getContentHandler()); htmlParser.setErrorHandler(eh); htmlParser.setFeature("http://xml.org/sax/features/unicode-normalization-checking", true); xmlParser.setContentHandler(validator.getContentHandler()); xmlParser.setErrorHandler(eh); xmlParser.setFeature("http://xml.org/sax/features/unicode-normalization-checking", true); htmlParser.setMappingLangToXmlLang(true); } public boolean check() throws SAXException { try { assertionSchema = schemaByFilename(new File(PATH + "../assertions.sch")); } catch (Exception e) { err.println("Reading schema failed. Terminating."); e.printStackTrace(); err.flush(); return false; } checkDirectory(new File(PATH + "html5core/"), new File(PATH + "../xhtml5core.rnc")); checkDirectory(new File(PATH + "html5core-plus-web-forms2/"), new File( PATH + "../xhtml5core-plus-web-forms2.rnc")); checkDirectory(new File(PATH + "html5full-html/"), new File( PATH + "../html5full.rnc")); checkDirectory(new File(PATH + "html5full-xhtml/"), new File( PATH + "../xhtml5full-xhtml.rnc")); checkDirectory(new File(PATH + "assertions/"), new File( PATH + "../xhtml5full-xhtml.rnc")); checkDirectory(new File(PATH + "tables/"), new File(PATH + "../xhtml5full-xhtml.rnc")); if (verbose) { if (failed) { out.println("Failure!"); } else { out.println("Success!"); } } err.flush(); out.flush(); return !failed; } /** * @param args * @throws SAXException */ public static void main(String[] args) throws SAXException { boolean verbose = ((args.length == 1) && "-v".equals(args[0])); Driver d = new Driver(verbose); if (d.check()) { System.exit(0); } else { System.exit(-1); } } }
import org.jgrapht.alg.DijkstraShortestPath; import org.jgrapht.graph.*; import org.slf4j.*; import java.util.*; public class Tree { Logger logger = LoggerFactory.getLogger(Tree.class); public void treeInitialization(int numUsers) { SimpleDirectedWeightedGraph<Integer, DefaultWeightedEdge> defaultGraph = new SimpleDirectedWeightedGraph<Integer, DefaultWeightedEdge> (DefaultWeightedEdge.class); Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int counter = 0; counter < numUsers; counter++) { Random rdn = new Random(); map.put(counter, rdn.nextInt(85)); defaultGraph.addVertex(counter); logger.info("Vertex - " + counter + " added!"); } logger.info("Pings - " + map.values()); for (int counter = 0; counter < numUsers - 1; counter++) { DefaultWeightedEdge e1 = defaultGraph.addEdge(0, (counter + 1)); defaultGraph.setEdgeWeight(e1, map.get(counter)); } logger.info("Shortest path from 0 to 4 and check what graph build right"); List shortest_path = DijkstraShortestPath.findPathBetween(defaultGraph, 0, 4); System.out.println(shortest_path); } public void treeTrain(int numUsers) { SimpleDirectedWeightedGraph<Integer, DefaultWeightedEdge> trainGraph = new SimpleDirectedWeightedGraph<Integer, DefaultWeightedEdge> (DefaultWeightedEdge.class); Map<Integer, Integer> map = new HashMap<Integer, Integer>(); Random rdn = new Random(); for (int counter = 0; counter < numUsers; counter++) { map.put(counter, rdn.nextInt(85)); trainGraph.addVertex(counter); logger.info("Vertex - " + counter + " added!"); } logger.info("Pings - " + map.values()); Map<Integer, Integer> sortedMap = sortByComparator(map); logger.info("Pings - " + sortedMap.values()); for (int counter = 1; counter < numUsers; counter++) { if (counter % 2 != 0) { DefaultWeightedEdge e1 = trainGraph.addEdge(0, counter); trainGraph.setEdgeWeight(e1, map.get(counter)); } if (counter % 2 == 0) { DefaultWeightedEdge e2 = trainGraph.addEdge(counter - 1, counter); trainGraph.setEdgeWeight(e2, map.get(counter)); } } logger.info("Shortest path from 0 to 4 and check what graph build right"); List shortest_path = DijkstraShortestPath.findPathBetween(trainGraph, 0, 4); System.out.println(shortest_path); } private static Map<Integer, Integer> sortByComparator(Map<Integer, Integer> unsortMap) { // Convert Map to List List<Map.Entry<Integer, Integer>> list = new LinkedList<Map.Entry<Integer, Integer>>(unsortMap.entrySet()); // Sort list with comparator, to compare the Map values Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() { public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); // Convert sorted map back to a Map Map<Integer, Integer> sortedMap = new LinkedHashMap<Integer, Integer>(); for (Iterator<Map.Entry<Integer, Integer>> it = list.iterator(); it.hasNext();) { Map.Entry<Integer, Integer> entry = it.next(); sortedMap.put(entry.getKey(), entry.getValue()); } return sortedMap; } public void starTree(int numUsers) { SimpleDirectedWeightedGraph<Integer, DefaultWeightedEdge> starGraph = new SimpleDirectedWeightedGraph<Integer, DefaultWeightedEdge> (DefaultWeightedEdge.class); Map<Integer, Integer> map = new HashMap<Integer, Integer>(); Random rdn = new Random(); for (int counter = 0; counter < numUsers; counter++) { map.put(counter, rdn.nextInt(85)); starGraph.addVertex(counter); logger.info("Vertex - " + counter + " added!"); } logger.info("Pings - " + map.values()); Map<Integer, Integer> sortedMap = sortByComparator(map); logger.info("Pings - " + sortedMap.values()); for (int counter = 0; counter < numUsers - 1; counter++) { DefaultWeightedEdge e1 = starGraph.addEdge(counter, counter + 1); starGraph.setEdgeWeight(e1, sortedMap.get(counter)); } for (int counter = 0; counter < numUsers/2; counter++) { DefaultWeightedEdge e1 = starGraph.addEdge(0, counter + 2); starGraph.setEdgeWeight(e1, sortedMap.get(counter)); } logger.info("Shortest path from 0 to 4 and check what graph build right"); List shortest_path = DijkstraShortestPath.findPathBetween(starGraph, 0, 8); System.out.println(shortest_path); } }
package org.json.junit; import static org.junit.Assert.*; import org.json.*; import org.junit.Test; /** * Tests for JSON-Java XML.java * Note: noSpace() will be tested by JSONMLTest */ public class XMLTest { @Test(expected=NullPointerException.class) public void shouldHandleNullXML() { String xmlStr = null; JSONObject jsonObject = XML.toJSONObject(xmlStr); assertTrue("jsonObject should be empty", jsonObject.length() == 0); } @Test public void shouldHandleEmptyXML() { String xmlStr = ""; JSONObject jsonObject = XML.toJSONObject(xmlStr); assertTrue("jsonObject should be empty", jsonObject.length() == 0); } @Test public void shouldHandleNonXML() { String xmlStr = "{ \"this is\": \"not xml\"}"; JSONObject jsonObject = XML.toJSONObject(xmlStr); assertTrue("xml string should be empty", jsonObject.length() == 0); } @Test(expected=JSONException.class) public void shouldHandleInvalidSlashInTag() { String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+ "<addresses xmlns:xsi=\"http: " xsi:noNamespaceSchemaLocation='test.xsd'>\n"+ " <address>\n"+ " <name/x>\n"+ " <street>abc street</street>\n"+ " </address>\n"+ "</addresses>"; XML.toJSONObject(xmlStr); } @Test(expected=JSONException.class) public void shouldHandleInvalidBangInTag() { String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+ "<addresses xmlns:xsi=\"http: " xsi:noNamespaceSchemaLocation='test.xsd'>\n"+ " <address>\n"+ " <name/>\n"+ " <!>\n"+ " </address>\n"+ "</addresses>"; XML.toJSONObject(xmlStr); } @Test(expected=JSONException.class) public void shouldHandleInvalidBangNoCloseInTag() { String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+ "<addresses xmlns:xsi=\"http: " xsi:noNamespaceSchemaLocation='test.xsd'>\n"+ " <address>\n"+ " <name/>\n"+ " <!\n"+ " </address>\n"+ "</addresses>"; XML.toJSONObject(xmlStr); } @Test(expected=JSONException.class) public void shouldHandleNoCloseStartTag() { String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+ "<addresses xmlns:xsi=\"http: " xsi:noNamespaceSchemaLocation='test.xsd'>\n"+ " <address>\n"+ " <name/>\n"+ " <abc\n"+ " </address>\n"+ "</addresses>"; XML.toJSONObject(xmlStr); } @Test(expected=JSONException.class) public void shouldHandleInvalidCDATABangInTag() { String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+ "<addresses xmlns:xsi=\"http: " xsi:noNamespaceSchemaLocation='test.xsd'>\n"+ " <address>\n"+ " <name>Joe Tester</name>\n"+ " <![[]>\n"+ " </address>\n"+ "</addresses>"; XML.toJSONObject(xmlStr); } @Test(expected=NullPointerException.class) public void shouldHandleNullJSONXML() { JSONObject jsonObject= null; XML.toString(jsonObject); } @Test public void shouldHandleEmptyJSONXML() { JSONObject jsonObject= new JSONObject(); String xmlStr = XML.toString(jsonObject); assertTrue("xml string should be empty", xmlStr.length() == 0); } @Test public void shouldHandleNoStartTag() { String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+ "<addresses xmlns:xsi=\"http: " xsi:noNamespaceSchemaLocation='test.xsd'>\n"+ " <address>\n"+ " <name/>\n"+ " <nocontent/>>\n"+ " </address>\n"+ "</addresses>"; String expectedStr = "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+ "content\":\">\"},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ "xmlns:xsi\":\"http: JSONObject jsonObject = XML.toJSONObject(xmlStr); JSONObject expectedJsonObject = new JSONObject(expectedStr); Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } @Test public void shouldHandleSimpleXML() { String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+ "<addresses xmlns:xsi=\"http: " xsi:noNamespaceSchemaLocation='test.xsd'>\n"+ " <address>\n"+ " <name>Joe Tester</name>\n"+ " <street>[CDATA[Baker street 5]</street>\n"+ " <NothingHere/>\n"+ " <TrueValue>true</TrueValue>\n"+ " <FalseValue>false</FalseValue>\n"+ " <NullValue>null</NullValue>\n"+ " <PositiveValue>42</PositiveValue>\n"+ " <NegativeValue>-23</NegativeValue>\n"+ " <DoubleValue>-23.45</DoubleValue>\n"+ " <Nan>-23x.45</Nan>\n"+ " <ArrayOfNum>1, 2, 3, 4.1, 5.2</ArrayOfNum>\n"+ " </address>\n"+ "</addresses>"; String expectedStr = "{\"addresses\":{\"address\":{\"street\":\"[CDATA[Baker street 5]\","+ "\"name\":\"Joe Tester\",\"NothingHere\":\"\",TrueValue:true,\n"+ "\"FalseValue\":false,\"NullValue\":null,\"PositiveValue\":42,\n"+ "\"NegativeValue\":-23,\"DoubleValue\":-23.45,\"Nan\":-23x.45,\n"+ "\"ArrayOfNum\":\"1, 2, 3, 4.1, 5.2\"\n"+ "},\"xsi:noNamespaceSchemaLocation\":"+ "\"test.xsd\",\"xmlns:xsi\":\"http: "XMLSchema-instance\"}}"; JSONObject expectedJsonObject = new JSONObject(expectedStr); JSONObject jsonObject = XML.toJSONObject(xmlStr); Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } @Test public void shouldHandleCommentsInXML() { String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+ "<!-- this is a comment -->\n"+ "<addresses>\n"+ " <address>\n"+ " <![CDATA[ this is -- <another> comment ]]>\n"+ " <name>Joe Tester</name>\n"+ " <!-- this is a - multi line \n"+ " comment " <street>Baker street 5</street>\n"+ " </address>\n"+ "</addresses>"; JSONObject jsonObject = XML.toJSONObject(xmlStr); String expectedStr = "{\"addresses\":{\"address\":{\"street\":\"Baker "+ "street 5\",\"name\":\"Joe Tester\",\"content\":\" this is "<another> comment \"}}}"; JSONObject expectedJsonObject = new JSONObject(expectedStr); Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } @Test public void shouldHandleToString() { String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+ "<addresses xmlns:xsi=\"http: " xsi:noNamespaceSchemaLocation='test.xsd'>\n"+ " <address>\n"+ " <name>[CDATA[Joe &amp; T &gt; e &lt; s &quot; t &apos; er]]</name>\n"+ " <street>Baker street 5</street>\n"+ " <ArrayOfNum>1, 2, 3, 4.1, 5.2</ArrayOfNum>\n"+ " </address>\n"+ "</addresses>"; String expectedStr = "{\"addresses\":{\"address\":{\"street\":\"Baker street 5\","+ "\"name\":\"[CDATA[Joe & T > e < s \\\" t \\\' er]]\","+ "\"ArrayOfNum\":\"1, 2, 3, 4.1, 5.2\"\n"+ "},\"xsi:noNamespaceSchemaLocation\":"+ "\"test.xsd\",\"xmlns:xsi\":\"http: "XMLSchema-instance\"}}"; JSONObject jsonObject = XML.toJSONObject(xmlStr); String xmlToStr = XML.toString(jsonObject); JSONObject finalJsonObject = XML.toJSONObject(xmlToStr); JSONObject expectedJsonObject = new JSONObject(expectedStr); Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); } @Test public void shouldHandleContentNoArraytoString() { String expectedStr = "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+ "content\":\">\"},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ "xmlns:xsi\":\"http: JSONObject expectedJsonObject = new JSONObject(expectedStr); String finalStr = XML.toString(expectedJsonObject); String expectedFinalStr = "<addresses><address><name/><nocontent/>&gt;"+ "</address><xsi:noNamespaceSchemaLocation>test.xsd</xsi:noName"+ "spaceSchemaLocation><xmlns:xsi>http: "ma-instance</xmlns:xsi></addresses>"; assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+ finalStr+"]", expectedFinalStr.equals(finalStr)); } @Test public void shouldHandleContentArraytoString() { String expectedStr = "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+ "content\":[1, 2, 3]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ "xmlns:xsi\":\"http: JSONObject expectedJsonObject = new JSONObject(expectedStr); String finalStr = XML.toString(expectedJsonObject); String expectedFinalStr = "<addresses><address><name/><nocontent/>"+ "1\n2\n3"+ "</address><xsi:noNamespaceSchemaLocation>test.xsd</xsi:noName"+ "spaceSchemaLocation><xmlns:xsi>http: "ma-instance</xmlns:xsi></addresses>"; assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+ finalStr+"]", expectedFinalStr.equals(finalStr)); } @Test public void shouldHandleArraytoString() { String expectedStr = "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\","+ "\"something\":[1, 2, 3]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ "xmlns:xsi\":\"http: JSONObject expectedJsonObject = new JSONObject(expectedStr); String finalStr = XML.toString(expectedJsonObject); String expectedFinalStr = "<addresses><address><name/><nocontent/>"+ "<something>1</something><something>2</something><something>3</something>"+ "</address><xsi:noNamespaceSchemaLocation>test.xsd</xsi:noName"+ "spaceSchemaLocation><xmlns:xsi>http: "ma-instance</xmlns:xsi></addresses>"; assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+ finalStr+"]", expectedFinalStr.equals(finalStr)); } @Test public void shouldHandleNestedArraytoString() { String xmlStr = "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\","+ "\"outer\":[[1], [2], [3]]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ "xmlns:xsi\":\"http: JSONObject jsonObject = new JSONObject(xmlStr); String finalStr = XML.toString(jsonObject); JSONObject finalJsonObject = XML.toJSONObject(finalStr); String expectedStr = "<addresses><address><name/><nocontent/>"+ "<outer><array>1</array></outer><outer><array>2</array>"+ "</outer><outer><array>3</array></outer>"+ "</address><xsi:noNamespaceSchemaLocation>test.xsd</xsi:noName"+ "spaceSchemaLocation><xmlns:xsi>http: "ma-instance</xmlns:xsi></addresses>"; JSONObject expectedJsonObject = XML.toJSONObject(expectedStr); Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); } @Test public void shouldHandleIllegalJSONNodeNames() { JSONObject inputJSON = new JSONObject(); inputJSON.append("123IllegalNode", "someValue1"); inputJSON.append("Illegal@node", "someValue2"); String result = XML.toString(inputJSON); String expected = "<123IllegalNode>someValue1</123IllegalNode><Illegal@node>someValue2</Illegal@node>"; assertEquals(expected, result); } @Test public void shouldHandleNullNodeValue() { JSONObject inputJSON = new JSONObject(); inputJSON.put("nullValue", JSONObject.NULL); // This is a possible preferred result // String expectedXML = "<nullValue/>"; /** * This is the current behavior. JSONObject.NULL is emitted as * the string, "null". */ String actualXML = "<nullValue>null</nullValue>"; String resultXML = XML.toString(inputJSON); assertEquals(actualXML, resultXML); } @Test public void contentOperations() { /** * Make sure we understand exactly how the "content" keyword works */ /** * When a standalone <!CDATA[...]] structure is found while parsing XML into a * JSONObject, the contents are placed in a string value with key="content". */ String xmlStr = "<tag1></tag1><![CDATA[if (a < b && a > 0) then return]]><tag2></tag2>"; JSONObject jsonObject = XML.toJSONObject(xmlStr); assertTrue("1. 3 items", 3 == jsonObject.length()); assertTrue("1. empty tag1", "".equals(jsonObject.get("tag1"))); assertTrue("1. empty tag2", "".equals(jsonObject.get("tag2"))); assertTrue("1. content found", "if (a < b && a > 0) then return".equals(jsonObject.get("content"))); // multiple consecutive standalone cdatas are accumulated into an array xmlStr = "<tag1></tag1><![CDATA[if (a < b && a > 0) then return]]><tag2></tag2><![CDATA[here is another cdata]]>"; jsonObject = XML.toJSONObject(xmlStr); assertTrue("2. 3 items", 3 == jsonObject.length()); assertTrue("2. empty tag1", "".equals(jsonObject.get("tag1"))); assertTrue("2. empty tag2", "".equals(jsonObject.get("tag2"))); assertTrue("2. content array found", jsonObject.get("content") instanceof JSONArray); JSONArray jsonArray = jsonObject.getJSONArray("content"); assertTrue("2. array size", jsonArray.length() == 2); assertTrue("2. content array entry 1", "if (a < b && a > 0) then return".equals(jsonArray.get(0))); assertTrue("2. content array entry 2", "here is another cdata".equals(jsonArray.get(1))); /** * text content is accumulated in a "content" inside a local JSONObject. * If there is only one instance, it is saved in the context (a different JSONObject * from the calling code. and the content element is discarded. */ xmlStr = "<tag1>value 1</tag1>"; jsonObject = XML.toJSONObject(xmlStr); assertTrue("3. 2 items", 1 == jsonObject.length()); assertTrue("3. value tag1", "value 1".equals(jsonObject.get("tag1"))); /** * array-style text content (multiple tags with the same name) is * accumulated in a local JSONObject with key="content" and value=JSONArray, * saved in the context, and then the local JSONObject is discarded. */ xmlStr = "<tag1>value 1</tag1><tag1>2</tag1><tag1>true</tag1>"; jsonObject = XML.toJSONObject(xmlStr); assertTrue("4. 1 item", 1 == jsonObject.length()); assertTrue("4. content array found", jsonObject.get("tag1") instanceof JSONArray); jsonArray = jsonObject.getJSONArray("tag1"); assertTrue("4. array size", jsonArray.length() == 3); assertTrue("4. content array entry 1", "value 1".equals(jsonArray.get(0))); assertTrue("4. content array entry 2", jsonArray.getInt(1) == 2); assertTrue("4. content array entry 2", jsonArray.getBoolean(2) == true); /** * Complex content is accumulated in a "content" field. For example, an element * may contain a mix of child elements and text. Each text segment is * accumulated to content. */ xmlStr = "<tag1>val1<tag2/>val2</tag1>"; jsonObject = XML.toJSONObject(xmlStr); assertTrue("5. 1 item", 1 == jsonObject.length()); assertTrue("5. jsonObject found", jsonObject.get("tag1") instanceof JSONObject); jsonObject = jsonObject.getJSONObject("tag1"); assertTrue("5. 2 contained items", 2 == jsonObject.length()); assertTrue("5. contained tag", "".equals(jsonObject.get("tag2"))); assertTrue("5. contained content jsonArray found", jsonObject.get("content") instanceof JSONArray); jsonArray = jsonObject.getJSONArray("content"); assertTrue("5. array size", jsonArray.length() == 2); assertTrue("5. content array entry 1", "val1".equals(jsonArray.get(0))); assertTrue("5. content array entry 2", "val2".equals(jsonArray.get(1))); /** * If there is only 1 complex text content, then it is accumulated in a * "content" field as a string. */ xmlStr = "<tag1>val1<tag2/></tag1>"; jsonObject = XML.toJSONObject(xmlStr); assertTrue("6. 1 item", 1 == jsonObject.length()); assertTrue("6. jsonObject found", jsonObject.get("tag1") instanceof JSONObject); jsonObject = jsonObject.getJSONObject("tag1"); assertTrue("6. contained content found", "val1".equals(jsonObject.get("content"))); assertTrue("6. contained tag2", "".equals(jsonObject.get("tag2"))); } }
package dk.cmol.arduinorgb_controller; import android.os.Bundle; import android.app.Activity; import android.graphics.Color; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.graphics.PorterDuff; public class ArduinoRGBActivity extends Activity { public boolean lamp_toggle[] = {false,false,false,false}; private ArduinoSocket sock = null; private LampParser lp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_arduino_rgb); sock = new ArduinoSocket(this); lp = new LampParser(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.arduino_rgb, menu); return true; } // Toggle lamp sequence public void toggleLamp(View v) { Button button = (Button) v; int pos = Integer.parseInt(button.getText().toString()) - 1; if (lamp_toggle[pos]) { button.getBackground().setColorFilter(Color.LTGRAY, PorterDuff.Mode.MULTIPLY); } else { button.getBackground().setColorFilter(Color.GREEN, PorterDuff.Mode.MULTIPLY); } // Change value of button lamp_toggle[pos] = !lamp_toggle[pos]; TextView tw = (TextView) findViewById(R.id.debug_1); tw.setText(lamp_toggle[pos] ? "TRUE" : "FALSE"); } // React to a pressed color public void colorPress(View v) { TextView tw = (TextView) findViewById(R.id.debug_1); // Check to see if any lamps are toggled on boolean go = false; for (int i = 0; i < lamp_toggle.length; i++) { if (lamp_toggle[i]) { go = true; break; } } if (go) { sock.write(lp.set(lamp_toggle, v.getTag().toString())); } } }
package dr.app.beauti.treespanel; import dr.app.beauti.options.PartitionTreeModel; import dr.app.beauti.options.PartitionTreePrior; import dr.app.beauti.types.TreePriorParameterizationType; import dr.app.beauti.types.TreePriorType; import dr.app.beauti.util.PanelUtils; import dr.app.gui.components.WholeNumberField; import dr.app.util.OSType; import dr.evomodel.coalescent.VariableDemographicModel; import dr.evomodelxml.speciation.BirthDeathModelParser; import dr.evomodelxml.speciation.BirthDeathSerialSamplingModelParser; import jam.panels.OptionsPanel; import javax.swing.*; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.EnumSet; /** * @author Andrew Rambaut * @author Alexei Drummond * @author Walter Xie * @version $Id: PriorsPanel.java,v 1.9 2006/09/05 13:29:34 rambaut Exp $ */ public class PartitionTreePriorPanel extends OptionsPanel { private static final long serialVersionUID = 5016996360264782252L; private JComboBox treePriorCombo = new JComboBox(EnumSet.range(TreePriorType.CONSTANT, TreePriorType.BIRTH_DEATH_SERI_SAMP_ESTIM).toArray()); private JComboBox parameterizationCombo = new JComboBox(EnumSet.range(TreePriorParameterizationType.GROWTH_RATE, TreePriorParameterizationType.DOUBLING_TIME).toArray()); // private JComboBox parameterizationCombo1 = new JComboBox(EnumSet.of(TreePriorParameterizationType.DOUBLING_TIME).toArray()); private JComboBox bayesianSkylineCombo = new JComboBox(EnumSet.range(TreePriorParameterizationType.CONSTANT_SKYLINE, TreePriorParameterizationType.LINEAR_SKYLINE).toArray()); private WholeNumberField groupCountField = new WholeNumberField(2, Integer.MAX_VALUE); private JComboBox extendedBayesianSkylineCombo = new JComboBox( new VariableDemographicModel.Type[]{VariableDemographicModel.Type.LINEAR, VariableDemographicModel.Type.STEPWISE}); private JComboBox gmrfBayesianSkyrideCombo = new JComboBox(EnumSet.range(TreePriorParameterizationType.UNIFORM_SKYRIDE, TreePriorParameterizationType.TIME_AWARE_SKYRIDE).toArray()); // RealNumberField samplingProportionField = new RealNumberField(Double.MIN_VALUE, 1.0); // private BeautiFrame frame = null; // private BeautiOptions options = null; PartitionTreePrior partitionTreePrior; private final TreesPanel treesPanel; private boolean settingOptions = false; public PartitionTreePriorPanel(PartitionTreePrior parTreePrior, TreesPanel parent) { super(12, (OSType.isMac() ? 6 : 24)); this.partitionTreePrior = parTreePrior; this.treesPanel = parent; PanelUtils.setupComponent(treePriorCombo); treePriorCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { partitionTreePrior.setNodeHeightPrior((TreePriorType) treePriorCombo.getSelectedItem()); setupPanel(); } }); PanelUtils.setupComponent(parameterizationCombo); parameterizationCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { partitionTreePrior.setParameterization((TreePriorParameterizationType) parameterizationCombo.getSelectedItem()); } }); // PanelUtils.setupComponent(parameterizationCombo1); // parameterizationCombo1.addItemListener(new ItemListener() { // public void itemStateChanged(ItemEvent ev) { // partitionTreePrior.setParameterization((TreePriorParameterizationType) parameterizationCombo1.getSelectedItem()); PanelUtils.setupComponent(groupCountField); groupCountField.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent ev) { // move to here? } }); PanelUtils.setupComponent(bayesianSkylineCombo); bayesianSkylineCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { partitionTreePrior.setSkylineModel((TreePriorParameterizationType) bayesianSkylineCombo.getSelectedItem()); } }); PanelUtils.setupComponent(extendedBayesianSkylineCombo); extendedBayesianSkylineCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { partitionTreePrior.setExtendedSkylineModel(((VariableDemographicModel.Type) extendedBayesianSkylineCombo.getSelectedItem())); } }); PanelUtils.setupComponent(gmrfBayesianSkyrideCombo); gmrfBayesianSkyrideCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { partitionTreePrior.setSkyrideSmoothing((TreePriorParameterizationType) gmrfBayesianSkyrideCombo.getSelectedItem()); } }); // samplingProportionField.addKeyListener(keyListener); setupPanel(); } private void setupPanel() { removeAll(); JTextArea citationText = new JTextArea(1, 200); citationText.setLineWrap(true); citationText.setEditable(false); citationText.setFont(this.getFont()); // JScrollPane scrollPane = new JScrollPane(citation, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, // JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); // scrollPane.setOpaque(true); String citation = null; addComponentWithLabel("Tree Prior:", treePriorCombo); if (treePriorCombo.getSelectedItem() == TreePriorType.EXPONENTIAL || treePriorCombo.getSelectedItem() == TreePriorType.LOGISTIC || treePriorCombo.getSelectedItem() == TreePriorType.EXPANSION) { addComponentWithLabel("Parameterization for growth:", parameterizationCombo); partitionTreePrior.setParameterization((TreePriorParameterizationType) parameterizationCombo.getSelectedItem()); // } else if (treePriorCombo.getSelectedItem() == TreePriorType.LOGISTIC //) {//TODO Issue 93 // || treePriorCombo.getSelectedItem() == TreePriorType.EXPANSION) { //TODO Issue 266 // addComponentWithLabel("Parameterization for growth:", parameterizationCombo1); // partitionTreePrior.setParameterization((TreePriorParameterizationType) parameterizationCombo1.getSelectedItem()); } else if (treePriorCombo.getSelectedItem() == TreePriorType.SKYLINE) { groupCountField.setColumns(6); addComponentWithLabel("Number of groups:", groupCountField); addComponentWithLabel("Skyline Model:", bayesianSkylineCombo); citation = "Drummond AJ, Rambaut A & Shapiro B and Pybus OG (2005) Mol Biol Evol 22, 1185-1192."; } else if (treePriorCombo.getSelectedItem() == TreePriorType.EXTENDED_SKYLINE) { addComponentWithLabel("Model Type:", extendedBayesianSkylineCombo); treesPanel.linkTreePriorCheck.setSelected(true); treesPanel.updateShareSameTreePriorChanged(); citation = "Insert citation here..."; // treesPanel.getFrame().setupEBSP(); TODO } else if (treePriorCombo.getSelectedItem() == TreePriorType.GMRF_SKYRIDE) { addComponentWithLabel("Smoothing:", gmrfBayesianSkyrideCombo); //For GMRF, one tree prior has to be associated to one tree model. The validation is in BeastGenerator.checkOptions() addLabel("<html>For GMRF, tree model/tree prior combination not implemented by BEAST yet. " + "It is only available for single tree model partition for this release. " + "Please go to Data Partition panel to link all tree models." + "</html>"); citation = "Minin, Bloomquist and Suchard (2008) Mol Biol Evol, 25, 1459-1471."; // treesPanel.linkTreePriorCheck.setSelected(false); // treesPanel.linkTreePriorCheck.setEnabled(false); // treesPanel.linkTreeModel(); // treesPanel.updateShareSameTreePriorChanged(); } else if (treePriorCombo.getSelectedItem() == TreePriorType.BIRTH_DEATH) { // samplingProportionField.setColumns(8); // treePriorPanel.addComponentWithLabel("Proportion of taxa sampled:", samplingProportionField); citation = BirthDeathModelParser.getCitation(); } else if (treePriorCombo.getSelectedItem() == TreePriorType.BIRTH_DEATH_INCOM_SAMP) { citation = BirthDeathModelParser.getCitationRHO(); } else if (treePriorCombo.getSelectedItem() == TreePriorType.BIRTH_DEATH_SERI_SAMP) { citation = BirthDeathSerialSamplingModelParser.getCitationPsiOrg(); } else if (treePriorCombo.getSelectedItem() == TreePriorType.BIRTH_DEATH_SERI_SAMP_ESTIM) { citation = BirthDeathSerialSamplingModelParser.getCitationRT(); } else { // treesPanel.linkTreePriorCheck.setEnabled(true); // treesPanel.linkTreePriorCheck.setSelected(true); // treesPanel.updateShareSameTreePriorChanged(); } if (citation != null) { addComponentWithLabel("Citation:", citationText); citationText.setText(citation); } // getOptions(); // treesPanel.treeModelPanels.get(treesPanel.currentTreeModel).setOptions(); for (PartitionTreeModel model : treesPanel.treeModelPanels.keySet()) { if (model != null) { treesPanel.treeModelPanels.get(model).setOptions(); } } // createTreeAction.setEnabled(options != null && options.dataPartitions.size() > 0); // fireTableDataChanged(); validate(); repaint(); } public void setOptions() { if (partitionTreePrior == null) { return; } settingOptions = true; treePriorCombo.setSelectedItem(partitionTreePrior.getNodeHeightPrior()); groupCountField.setValue(partitionTreePrior.getSkylineGroupCount()); //samplingProportionField.setValue(partitionTreePrior.birthDeathSamplingProportion); parameterizationCombo.setSelectedItem(partitionTreePrior.getParameterization()); bayesianSkylineCombo.setSelectedItem(partitionTreePrior.getSkylineModel()); extendedBayesianSkylineCombo.setSelectedItem(partitionTreePrior.getExtendedSkylineModel()); gmrfBayesianSkyrideCombo.setSelectedItem(partitionTreePrior.getSkyrideSmoothing()); // setupPanel(); settingOptions = false; validate(); repaint(); } public void getOptions() { if (settingOptions) return; // partitionTreePrior.setNodeHeightPrior((TreePriorType) treePriorCombo.getSelectedItem()); if (partitionTreePrior.getNodeHeightPrior() == TreePriorType.SKYLINE) { Integer groupCount = groupCountField.getValue(); if (groupCount != null) { partitionTreePrior.setSkylineGroupCount(groupCount); } else { partitionTreePrior.setSkylineGroupCount(5); } } else if (partitionTreePrior.getNodeHeightPrior() == TreePriorType.BIRTH_DEATH) { // Double samplingProportion = samplingProportionField.getValue(); // if (samplingProportion != null) { // partitionTreePrior.birthDeathSamplingProportion = samplingProportion; // } else { // partitionTreePrior.birthDeathSamplingProportion = 1.0; } // partitionTreePrior.setParameterization(parameterizationCombo.getSelectedIndex()); // partitionTreePrior.setSkylineModel(bayesianSkylineCombo.getSelectedIndex()); // partitionTreePrior.setExtendedSkylineModel(((VariableDemographicModel.Type) extendedBayesianSkylineCombo.getSelectedItem()).toString()); // partitionTreePrior.setSkyrideSmoothing(gmrfBayesianSkyrideCombo.getSelectedIndex()); // the taxon list may not exist yet... this should be set when generating... // partitionTreePrior.skyrideIntervalCount = partitionTreePrior.taxonList.getTaxonCount() - 1; } public void setMicrosatelliteTreePrior() { treePriorCombo.removeAllItems(); treePriorCombo.addItem(TreePriorType.CONSTANT); } public void removeCertainPriorFromTreePriorCombo() { treePriorCombo.removeItem(TreePriorType.YULE); treePriorCombo.removeItem(TreePriorType.BIRTH_DEATH); treePriorCombo.removeItem(TreePriorType.BIRTH_DEATH_INCOM_SAMP); } public void recoveryTreePriorCombo() { if (treePriorCombo.getItemCount() < EnumSet.range(TreePriorType.CONSTANT, TreePriorType.BIRTH_DEATH_SERI_SAMP_ESTIM).size()) { treePriorCombo.removeAllItems(); for (TreePriorType tpt : EnumSet.range(TreePriorType.CONSTANT, TreePriorType.BIRTH_DEATH_SERI_SAMP_ESTIM)) { treePriorCombo.addItem(tpt); } } } }
package dr.evomodel.speciation; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evomodelxml.speciation.BirthDeathModelParser; import dr.inference.model.Parameter; import static org.apache.commons.math.special.Gamma.logGamma; public class BirthDeathGernhard08Model extends UltrametricSpeciationModel { public enum TreeType { UNSCALED, // no coefficient TIMESONLY, ORIENTED, LABELED, // 2^(n-1)/(n-1)! (conditional on root: 2^(n-1)/n!(n-1) ) } public static final String BIRTH_DEATH_MODEL = BirthDeathModelParser.BIRTH_DEATH_MODEL; /* * mu/lambda * * null means default (0), or pure birth (Yule) */ private Parameter relativeDeathRateParameter; /** * lambda - mu */ private Parameter birthDiffRateParameter; private Parameter sampleProbability; private TreeType type; private boolean conditionalOnRoot; /** * rho * */ public BirthDeathGernhard08Model(Parameter birthDiffRateParameter, Parameter relativeDeathRateParameter, Parameter sampleProbability, TreeType type, Type units) { this(BIRTH_DEATH_MODEL, birthDiffRateParameter, relativeDeathRateParameter, sampleProbability, type, units, false); } public BirthDeathGernhard08Model(String modelName, Parameter birthDiffRateParameter, Parameter relativeDeathRateParameter, Parameter sampleProbability, TreeType type, Type units, boolean conditionalOnRoot) { super(modelName, units); this.birthDiffRateParameter = birthDiffRateParameter; addVariable(birthDiffRateParameter); birthDiffRateParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); this.relativeDeathRateParameter = relativeDeathRateParameter; if( relativeDeathRateParameter != null ) { addVariable(relativeDeathRateParameter); relativeDeathRateParameter.addBounds(new Parameter.DefaultBounds(1.0, 0.0, 1)); } this.sampleProbability = sampleProbability; if (sampleProbability != null) { addVariable(sampleProbability); sampleProbability.addBounds(new Parameter.DefaultBounds(1.0, 0.0, 1)); } this.conditionalOnRoot = conditionalOnRoot; if ( conditionalOnRoot && sampleProbability != null) { throw new IllegalArgumentException("Not supported: birth death prior conditional on root with sampling probability."); } this.type = type; } public boolean supportsInternalCalibration() { return relativeDeathRateParameter == null && sampleProbability == null && !conditionalOnRoot; } public double getR() { return birthDiffRateParameter.getParameterValue(0); } public double getA() { return relativeDeathRateParameter != null ? relativeDeathRateParameter.getParameterValue(0) : 0; } public double getRho() { return sampleProbability != null ? sampleProbability.getParameterValue(0) : 1.0; } private double logCoeff(int taxonCount) { switch( type ) { case UNSCALED: break; case TIMESONLY: return logGamma(taxonCount + 1); case ORIENTED: return Math.log(taxonCount); case LABELED: { final double two2nm1 = (taxonCount - 1) * Math.log(2.0); if( ! conditionalOnRoot ) { return two2nm1 - logGamma(taxonCount); } else { return two2nm1 - Math.log(taxonCount-1) - logGamma(taxonCount+1); } } } return 0.0; } public double logTreeProbability(int taxonCount) { double c1 = logCoeff(taxonCount); if( ! conditionalOnRoot ) { c1 += (taxonCount - 1) * Math.log(getR() * getRho()) + taxonCount * Math.log(1 - getA()); } return c1; } @Override public double logCalibrationCorrectionDensity(Tree tree, final double h, int nClade) { double lgp; if( nClade == 1 ) { // for parent of taxon final double twol = 2 * getR(); lgp = -twol * h + Math.log(twol); } else { final double l = getR(); final double lh = l * h; lgp = -3 * lh + (nClade-2) * Math.log(1 - Math.exp(-lh)) + Math.log(l); // root is a special case if( tree.getExternalNodeCount() == nClade ) { // n(n-1) factor left out //lgp = -2 * lh + (nClade-2) * v2 + logLam; lgp += lh; } else { // (n^3-n)/2 factor left out //lgp = -3 * lh + (nClade-2) * v2 + logLam; } } return lgp; } // @Override // public double logCalibrationCorrectionDensity(Tree tree, final double h, int nClade, double[] coefficients) { // double lgp; // if( coefficients != null ) { // final double l = getR(); // final double hLam = -h * l; // lgp = coefficients[0] * hLam + Math.log(l); // final double z = Math.exp(hLam); // double zn = 1.0; // double s = 0.0; // for(int k = 1; k < coefficients.length; ++k) { // s += zn * coefficients[k]; // zn *= z; // lgp += Math.log(s); // } else { // if( nClade == 1 ) { // // for parent of taxon // double twol = 2 * getR(); // lgp = -twol * h + Math.log(twol); // } else { // double l = getR(); // lgp = -3 * l * h + (nClade-2) * Math.log(1 - Math.exp(-l*h)) + Math.log(l); // return lgp; public double logNodeProbability(Tree tree, NodeRef node) { final double height = tree.getNodeHeight(node); final double r = getR(); final double mrh = -r * height; final double a = getA(); if( ! conditionalOnRoot ) { final double rho = getRho(); final double z = Math.log(rho + ((1 - rho) - a) * Math.exp(mrh)); double l = -2 * z + mrh; if( tree.getRoot() == node ) { l += mrh - z; } return l; } else { double l; if( tree.getRoot() != node ) { final double z = Math.log(1 - a * Math.exp(mrh)); l = -2 * z + mrh; } else { // Root dependent coefficient from each internal node final double ca = 1 - a; final double emrh = Math.exp(-mrh); if( emrh != 1.0 ) { l = (tree.getTaxonCount() - 2) * Math.log(r * ca * (1 + ca /(emrh - 1))); } else { // use exp(x)-1 = x for x near 0 l = (tree.getTaxonCount() - 2) * Math.log(ca * (r + ca/height)); } } return l; } } public boolean includeExternalNodesInLikelihoodCalculation() { return false; } }
package eu.e43.impeller.fragment; import eu.e43.impeller.R; import eu.e43.impeller.activity.MainActivity; import eu.e43.impeller.content.ContentUpdateReceiver; import eu.e43.impeller.content.PumpContentProvider; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import android.widget.ViewSwitcher; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import org.json.JSONException; import org.json.JSONObject; public class ObjectContainerFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { public static final String TAG = "ObjectContainerFragment"; public static final String PARAM_ID = "eu.e43.impeller.ObjectContainerFragment.ID"; public static final String PARAM_MODE = "eu.e43.impeller.ObjectContainerFragment.MODE"; String m_id; JSONObject m_object; ObjectFragment m_child; MainActivity.Mode m_mode; public static ObjectContainerFragment newInstance(String id, MainActivity.Mode mode) { ObjectContainerFragment fragment = new ObjectContainerFragment(); Bundle args = new Bundle(); args.putString(PARAM_ID, id); args.putSerializable(PARAM_MODE, mode); fragment.setArguments(args); return fragment; } public MainActivity getMainActivity() { return (MainActivity) getActivity(); } public ObjectContainerFragment() { // Required empty public constructor } public MainActivity.Mode getMode() { return m_mode; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); if (args == null) { throw new RuntimeException("Bad launch of fragment"); } else { m_id = args.getString(PARAM_ID); m_mode = (MainActivity.Mode) args.getSerializable(PARAM_MODE); } if(savedInstanceState != null) { try { m_object = new JSONObject(savedInstanceState.getString("object")); } catch (JSONException e) { // We encoded the damn object! throw new RuntimeException(e); } } getLoaderManager().initLoader(0, null, this); queryForObjectUpdate(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { getMainActivity().onShowObjectFragment(this); LayoutInflater flate = LayoutInflater.from(getActivity()); return flate.inflate(R.layout.fragment_object, null); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if(savedInstanceState != null) { String type = m_object.optString("objectType"); if(type.equals("person")) { m_child = new PersonObjectFragment(); } else { m_child = new StandardObjectFragment(); } m_child = ObjectFragment.prepare(m_child, m_id); m_child.setInitialSavedState((SavedState) savedInstanceState.getParcelable("child")); getChildFragmentManager().beginTransaction() .add(R.id.objectDisplayFragment, m_child) .commit(); } } @Override public void onStart() { super.onStart(); onObjectUpdated(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if(m_object != null) { outState.putString("object", m_object.toString()); } if(m_child != null) { outState.putParcelable("child", getChildFragmentManager().saveFragmentInstanceState(m_child)); } } public void onObjectUpdated() { if(m_object == null) return; Log.i(TAG, "Object " + m_id + " updated"); View rootView = getView(); if(rootView != null) { ViewSwitcher sw = (ViewSwitcher) getView().findViewById(R.id.switcher); if(m_child != null) { if(sw.getCurrentView().getId() != R.id.objectDisplayFragment) sw.showNext(); // Notify the child m_child.objectUpdated(m_object); return; } // Construct the child fragment ObjectFragment frag = null; if("person".equals(m_object.optString("objectType"))) { frag = new PersonObjectFragment(); } else { frag = new StandardObjectFragment(); } FragmentManager mgr = getChildFragmentManager(); m_child = ObjectFragment.prepare(frag, m_id); mgr.beginTransaction() .add(R.id.objectDisplayFragment, m_child) .commit(); sw.showNext(); } else { // Nothing to do - our UI hasn't yet been created // We will update when we have a child } } public void queryForObjectUpdate() { /* BroadcastReceiver updateRx = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if(getResultCode() != Activity.RESULT_OK) return; Bundle ex = getResultExtras(true); JSONObject obj = null; try { obj = new JSONObject(ex.getString("object")); m_object = obj; onObjectUpdated(); } catch (JSONException e) { Log.e(TAG, "Updated object and got bad data", e); } } }; */ getActivity().sendOrderedBroadcast(new Intent( ContentUpdateReceiver.UPDATE_OBJECT, Uri.parse(m_id), getActivity(), ContentUpdateReceiver.class ).putExtra("account", getMainActivity().getAccount()), null, null/*updateRX*/, null, Activity.RESULT_OK, null, null); } public JSONObject getObject() { return m_object; } @Override public void onStop() { super.onStop(); } @Override public void onDestroy() { super.onDestroy(); getMainActivity().onHideObjectFragment(this); } // Loader callbacks @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { Uri uri = Uri.parse(PumpContentProvider.OBJECT_URL) .buildUpon() .appendPath(m_id) .build(); return new CursorLoader(getActivity(), uri, new String[] { "_json" }, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if(loader != null && data != null) { data.setNotificationUri( getActivity().getContentResolver(), ((CursorLoader) loader).getUri()); } if(data == null || data.getCount() == 0) { if(m_object == null) { Toast.makeText(getActivity(), "Unable to fetch object", Toast.LENGTH_SHORT); } else { Log.w(TAG, "No rows returned for object query? " + m_id); } } else { data.moveToFirst(); String objJSON = data.getString(0); JSONObject obj = null; try { obj = new JSONObject(objJSON); } catch (JSONException e) { throw new RuntimeException("Database contained invalid JSON", e); } m_object = obj; onObjectUpdated(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { // Do nothing. } }
package eu.ydp.empiria.player.client.gin; import com.google.gwt.inject.client.GinModules; import com.google.gwt.inject.client.Ginjector; import eu.ydp.empiria.player.client.controller.AssessmentControllerFactory; import eu.ydp.empiria.player.client.controller.Page; import eu.ydp.empiria.player.client.controller.body.IPlayerContainersAccessor; import eu.ydp.empiria.player.client.controller.body.ModuleHandlerManager; import eu.ydp.empiria.player.client.controller.delivery.DeliveryEngine; import eu.ydp.empiria.player.client.controller.extensions.ExtensionsManager; import eu.ydp.empiria.player.client.controller.extensions.internal.bookmark.BookmarkProcessorExtension; import eu.ydp.empiria.player.client.controller.extensions.internal.jsonreport.AssessmentJsonReportExtension; import eu.ydp.empiria.player.client.controller.extensions.internal.stickies.StickiesProcessorExtension; import eu.ydp.empiria.player.client.controller.extensions.internal.workmode.PlayerWorkModeService; import eu.ydp.empiria.player.client.controller.feedback.FeedbackRegistry; import eu.ydp.empiria.player.client.controller.feedback.ModuleFeedbackProcessor; import eu.ydp.empiria.player.client.controller.flow.MainFlowProcessor; import eu.ydp.empiria.player.client.controller.multiview.MultiPageController; import eu.ydp.empiria.player.client.controller.multiview.PanelCache; import eu.ydp.empiria.player.client.controller.multiview.touch.TouchController; import eu.ydp.empiria.player.client.controller.report.AssessmentReportFactory; import eu.ydp.empiria.player.client.gin.factory.*; import eu.ydp.empiria.player.client.gin.module.*; import eu.ydp.empiria.player.client.gin.module.tutor.TutorGinModule; import eu.ydp.empiria.player.client.module.img.events.handlers.TouchHandlerOnImageProvider; import eu.ydp.empiria.player.client.module.media.MediaControllerFactory; import eu.ydp.empiria.player.client.resources.StyleNameConstants; import eu.ydp.empiria.player.client.style.StyleSocket; import eu.ydp.empiria.player.client.util.events.bus.EventsBus; import eu.ydp.empiria.player.client.util.position.PositionHelper; import eu.ydp.empiria.player.client.view.ViewEngine; import eu.ydp.empiria.player.client.view.player.PageControllerCache; import eu.ydp.gwtutil.client.debug.log.Logger; import eu.ydp.gwtutil.client.dom.DOMTreeWalker; import eu.ydp.gwtutil.client.gin.module.AnimationGinModule; import eu.ydp.gwtutil.client.gin.module.UtilGinModule; import eu.ydp.gwtutil.client.ui.GWTPanelFactory; @GinModules(value = {PlayerGinModule.class, UtilGinModule.class, ChoiceGinModule.class, ConnectionGinModule.class, SourceListGinModule.class, TextEntryGinModule.class, SelectionGinModule.class, SimulationGinModule.class, PageScopedModule.class, SlideshowGinModule.class, OrderingGinModule.class, ModuleScopedModule.class, ColorfillGinModule.class, DragGapGinModule.class, TutorGinModule.class, ButtonGinModule.class, AnimationGinModule.class, DrawingGinModule.class, BonusGinModule.class, ProgressBonusGinModule.class, VideoGinModule.class, DictionaryGinModule.class, TextEditorGinModule.class, TestGinModule.class}) public interface PlayerGinjector extends Ginjector { ViewEngine getViewEngine(); DeliveryEngine getDeliveryEngine(); EventsBus getEventsBus(); MultiPageController getMultiPage(); PageControllerCache getPageControllerCache(); StyleNameConstants getStyleNameConstants(); MainFlowProcessor getMainFlowProcessor(); Page getPage(); DOMTreeWalker getDomTreeWalker(); PanelCache getPanelCache(); GWTPanelFactory getPanelFactory(); MediaControllerFactory getControllerFactory(); PageScopeFactory getPageScopeFactory(); PositionHelper getPositionHelper(); ModuleHandlerManager getModuleHandlerManager(); TextTrackFactory getTextTrackFactory(); ModuleFactory getModuleFactory(); ModuleProviderFactory getModuleProviderFactory(); SingleModuleInstanceProvider getSingleModuleInstanceProvider(); FeedbackRegistry getFeedbackRegistry(); ModuleFeedbackProcessor getModuleFeedbackProcessor(); AssessmentControllerFactory getAssessmentControllerFactory(); AssessmentReportFactory getAssessmentReportFactory(); ExtensionsManager getExtensionsManager(); BookmarkProcessorExtension getBookmarkProcessorExtension(); StickiesProcessorExtension getStickiesProcessorExtension(); IPlayerContainersAccessor getPlayerContainersAccessor(); AssessmentJsonReportExtension getAssessmentJsonReportExtension(); TouchController getTouchController(); StyleSocket getStyleSocket(); Logger getLogger(); TouchHandlerOnImageProvider getTouchHandlerOnImageProvider(); PlayerWorkModeService getPlayerWorkModeService(); }
import java.io.*; import java.util.*; public class Correctpony { public static final String DICT_DIRS = "/usr/share/dict:/usr/local/share/dict:~/share/dict"; /** * The version of the program */ public static final String VERSION = "2.0"; /** * Default word separators */ public static final String[] DEFAULT_SEPARATORS = { " " }; /** * Default dictionaries */ public static final String[] DEFAULT_DICTIONARIES = null; /** * Mane method * * @param args Command line arguments, excluding exec * * @throws IOException On I/O error */ public static void main(String... args) throws IOException { } /** * Gets all dictionary files * * @return All dictionary files * * @throws IOException On I/O error */ public static String[] getDictionaries() throws IOException { String[] rc = new String[128]; int rcptr = 0; String HOME = System.getenv("HOME"); if ((HOME == null) || (HOME.length() == 0)) HOME = System.getProperty("user.home"); for (String dir : DICT_DIRS.split(":")) { if (dir.startsWith("~")) dir = HOME + dir.substring(1); File fdir = new File(dir); if (fdir.exists()) fdir = fdir.getCanonicalFile(); if (fdir.exists() && fdir.isDirectory()) for (String file : fdir.list()) { if (rcptr == rc.length) System.arraycopy(rc, 0, rc = new String[rc.length << 1], 0, rcptr); file = (dir + "/" + file).replace(" if ((new File(file)).isFile()) rc[rcptr++] = file; } } System.arraycopy(rc, 0, rc = new String[rcptr], 0, rcptr); return rc; } /** * Gets all unique words in any number of dictionaries * * @param dictionaries Dictionaries by filename, {@code null} for all * @return Unique words, in lower case * * @throws IOException On I/O error */ public static String[] getWords(String[] dictionaries) throws IOException { if (dictionaries == null) dictionaries = getDictionaries(); final HashSet<String> unique = new HashSet<String>(); for (final String dictionary : dictionaries) { final InputStream is = new FileInputStream(dictionary); byte[] buf; int ptr; try { buf = new byte[is.available()]; if (buf.length == 0) buf = new byte[1 << 13]; forever: for (int n;;) { while (ptr < buf.length) { ptr += n = is.read(buf, ptr, buf.length - ptr); if (n <= 0) break forever; } System.arraycopy(buf, 0, buf = new String[buf.length << 1], 0, ptr); } } finally { try { is.close(); } catch (final Throwable ignore) { /* ignore */ } } for (final String word : (new String(buf, 0, ptr, "UTF-8")).split("\n")) if (word.length() != 0) unique.add(word.toLowerCase()); } final String[] rc = new String[unique.size()]; int ptr = 0; for (final String word : unique) rc[ptr++] = word; return rc; } /** * Gets a dictionary's filename by its name * * @parma dictionaries The dictionary by names * @param files All dictionaries by filename * @return The found dictionaries by filename * * @throws IOException On I/O error */ public static String[] getFiles(String[] dictionaries, String[] files) throws IOException { final String[] candidates = new String[files.length]; for (int i = 0, n = files.length; i < n; i++) candidates[i] = "/" + files[i]; String[] rc = new String[dicts.length]; int ptr = 0; for (String dict : dicts) { dict = "/" + dict; for (final String candidate : candidates) if (candidate.endsWith(dict)) { if (ptr == rc.length) System.arraycopy(rc, 0, rc = new String[rc.length << 1], 0, ptr); rc[ptr++] = candidate; } } System.arraycopy(rc, 0, rc = new String[ptr], 0, ptr); return rc; } /** * Joins words * * @param words The words to join * @param separators Separators * @param colour Whether to use colours * @return The result * * @throws IOException On I/O error */ public static String join(String[] words, String[] separators, boolean colour) throws IOException { final StringBuilder rc = new StringBuilder(); int i = 0; for (final String word : words) { if (i > 0) { if (colour) rc.append("\033[31m"); rc.append(separators[random(separators.length)]); } if (colour) rc.append((i & 1) == 0 ? "\033[34m" : "\033[33m"); rc.append(word); i++; } if (colour) rc.append("\033[00m"); return rc.toString(); } /** * Gets a random integer * * @param max The exclusive upper bound * @return A random non-negative integer * * @throws IOException On I/O error */ public static int random(int max) throws IOException { return 0; } /* TODO determine hyphenation for words to determine which letters may be uppercase */ /* TODO occationally use letter translation */ }
package gov.nih.nci.calab.ui.submit; /** * This class uploads a report file and assigns visibility * * @author pansu */ /* CVS $Id: SubmitProtocolAction.java,v 1.11 2007-07-31 20:39:10 pansu Exp $ */ import gov.nih.nci.calab.dto.common.ProtocolBean; import gov.nih.nci.calab.dto.common.ProtocolFileBean; import gov.nih.nci.calab.dto.common.UserBean; import gov.nih.nci.calab.service.search.SearchProtocolService; import gov.nih.nci.calab.service.submit.SubmitProtocolService; import gov.nih.nci.calab.service.util.CaNanoLabConstants; import gov.nih.nci.calab.service.util.StringUtils; import gov.nih.nci.calab.ui.core.AbstractDispatchAction; import gov.nih.nci.calab.ui.core.InitSessionSetup; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.upload.FormFile; import org.apache.struts.util.LabelValueBean; import org.apache.struts.validator.DynaValidatorForm; public class SubmitProtocolAction extends AbstractDispatchAction { public ActionForward submit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = null; ActionMessages msgs = new ActionMessages(); DynaValidatorForm theForm = (DynaValidatorForm) form; String protocolName = (String)theForm.get("protocolId"); String protocolType = (String)theForm.get("protocolType"); ProtocolFileBean fileBean = (ProtocolFileBean) theForm.get("file"); //String version = fileBean.getId(); ProtocolBean pBean = new ProtocolBean(); pBean.setId(protocolName); pBean.setType(protocolType); FormFile uploadedFile = (FormFile) theForm.get("uploadedFile"); fileBean.setProtocolBean(pBean); SubmitProtocolService service = new SubmitProtocolService(); service.createProtocol(fileBean, uploadedFile); if (fileBean.getVisibilityGroups().length == 0) { fileBean .setVisibilityGroups(CaNanoLabConstants.VISIBLE_GROUPS); } request.getSession().removeAttribute("AllProtocolTypeNames"); request.getSession().removeAttribute("AllProtocolTypeIds"); request.getSession().removeAttribute("protocolNames"); request.getSession().removeAttribute("AllProtocolNameVersions"); request.getSession().removeAttribute("AllProtocolNameFileIds"); request.getSession().removeAttribute("protocolVersions"); ActionMessage msg1 = new ActionMessage("message.submitProtocol.secure", StringUtils.join(fileBean.getVisibilityGroups(), ", ")); ActionMessage msg2 = new ActionMessage("message.submitProtocol.file", uploadedFile.getFileName()); msgs.add("message", msg1); msgs.add("message", msg2); saveMessages(request, msgs); request.getSession().setAttribute("newProtocolCreated", "true"); forward = mapping.findForward("success"); return forward; } public ActionForward getFileData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = null; DynaValidatorForm theForm = (DynaValidatorForm) form; ProtocolFileBean fileBean = (ProtocolFileBean) theForm.get("file"); String fileId = fileBean.getId(); SearchProtocolService service = new SearchProtocolService(); ProtocolFileBean anotherBean = service.getProtocolFileBean(fileId); fileBean.setDescription(anotherBean.getDescription()); fileBean.setName(anotherBean.getName()); fileBean.setTitle(anotherBean.getTitle()); fileBean.setVersion(anotherBean.getVersion()); fileBean.setVisibilityGroups(anotherBean.getVisibilityGroups()); request.setAttribute("filename", anotherBean.getName()); updateAfterFileDataRetrieval(request, theForm); forward = mapping.findForward("resetProtocolPage"); return forward; } public ActionForward setup(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); UserBean user = (UserBean) session.getAttribute("user"); InitSessionSetup.getInstance().clearWorkflowSession(session); InitSessionSetup.getInstance().clearSearchSession(session); InitSessionSetup.getInstance().clearInventorySession(session); InitSessionSetup.getInstance().setApplicationOwner(session); InitSessionSetup.getInstance().setProtocolSubmitPage(session, user); InitSessionSetup.getInstance().setAllVisibilityGroups(session); ActionForward forward = mapping.findForward("setup"); return forward; } public ActionForward setupUpdate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); InitSessionSetup.getInstance().clearSearchSession(session); InitSessionSetup.getInstance().setAllVisibilityGroups(session); DynaValidatorForm theForm = (DynaValidatorForm) form; String fileId = request.getParameter("fileId"); if (fileId == null) fileId = (String)request.getAttribute("fileId"); SearchProtocolService service = new SearchProtocolService(); ProtocolFileBean fileBean=service.getWholeProtocolFileBean(fileId); theForm.set("file", fileBean); theForm.set("protocolName", fileBean.getProtocolBean().getName()); theForm.set("protocolType", fileBean.getProtocolBean().getType()); request.setAttribute("filename", fileBean.getName()); return mapping.findForward("setup"); } public ActionForward setupView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return setupUpdate(mapping, form, request, response); } public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionMessages msgs = new ActionMessages(); DynaValidatorForm theForm = (DynaValidatorForm) form; ProtocolFileBean fileBean = (ProtocolFileBean) theForm.get("file"); //FormFile uploadedFile = (FormFile) theForm.get("uploadedFile"); SubmitProtocolService service = new SubmitProtocolService(); try{ service.updateProtocol(fileBean, null); if (fileBean.getVisibilityGroups().length == 0) { fileBean .setVisibilityGroups(CaNanoLabConstants.VISIBLE_GROUPS); } }catch (Exception e){ ActionMessage msg = new ActionMessage("error.updateProtocol", e.getMessage()); msgs.add("message", msg); saveMessages(request, msgs); request.setAttribute("fileId", fileBean.getId()); return setupUpdate(mapping, form, request, response); } ActionMessage msg = new ActionMessage("message.updateProtocol", fileBean .getTitle()); msgs.add("message", msg); saveMessages(request, msgs); //request.getSession().setAttribute("newProtocolCreated", "true"); return mapping.findForward("success"); } public ActionForward reSetup(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; updateEditableDropDownList(request, theForm); return mapping.findForward("setup"); } public boolean loginRequired() { return true; } private void updateEditableDropDownList(HttpServletRequest request, DynaValidatorForm theForm) { HttpSession session = request.getSession(); // update sample source drop-down list to include the new entry String protocolType = (String) theForm.get("protocolType"); SortedSet<String> protocolTypes = (SortedSet) session.getAttribute("protocolTypes"); String protocolName = (String) theForm.get("protocolId"); ProtocolFileBean fileBean = (ProtocolFileBean) theForm.get("file"); String fileId = fileBean.getId(); //Update protocolType list first. //If user entered a brand new protocol type, then added to the protocol type list boolean isNewType = false; if (protocolType != null && protocolType.length()>0 && !protocolTypes.contains(protocolType)) { protocolTypes.add(protocolType); isNewType = true; } //otherwise don't do anything //Update protocol name list. boolean isNewName = false; Map<String, List<String>> typeNamesMap = (Map)session.getAttribute("AllProtocolTypeNames"); Map<String, List<String>> typeIdsMap = (Map)session.getAttribute("AllProtocolTypeIds"); if (protocolName != null && protocolName.length()>0 ){ //if it's a new protocol type, we need to add this protocol name to the above two maps if (isNewType){ List<String> newNameList = new ArrayList<String>(); List<String> newIdList = new ArrayList<String>(); newNameList.add(protocolName); newIdList.add(protocolName); typeNamesMap.put(protocolType, newNameList); typeIdsMap.put(protocolType, newIdList); //always a new name isNewName = true; } //if an old type. if this is a new name then added to the list else{ List<String> newNameList = typeNamesMap.get(protocolType); List<String> newIdList = typeIdsMap.get(protocolType); //A new name if (newNameList == null) isNewName = true; else if (newNameList!= null && !newIdList.contains(protocolName)){ newNameList.add(protocolName); newIdList.add(protocolName); isNewName = true; } } } //Else don't do anything. //Now set the name dropdown box SortedSet<ProtocolBean> protocols = new TreeSet<ProtocolBean>(); if (protocolType != null && protocolType.length()>0){ List<String> protocolNames = typeNamesMap.get(protocolType); List<String> protocolIds = typeIdsMap.get(protocolType); if (protocolNames != null && !protocolNames.isEmpty()){ int i = 0; for (String id : protocolIds){ ProtocolBean pb = new ProtocolBean(); pb.setId(id); pb.setName(protocolNames.get(i)); protocols.add(pb); i++; } } //A protocol type with no protocol created else if (protocolName != null && protocolName.length()>0){ ProtocolBean pb = new ProtocolBean(); pb.setId(protocolName); pb.setName(protocolName); protocols.add(pb); } } else{ if (protocolName != null && protocolName.length()>0 ){ ProtocolBean pb = new ProtocolBean(); pb.setId(protocolName); pb.setName(protocolName); protocols.add(pb); } } session.setAttribute("protocolNames", protocols); //Now deal with the version dropdown box boolean isNewVersion = false; Map<String, List<String>> nameVersionsMap = (Map)session.getAttribute("AllProtocolNameVersions"); Map<String, List<String>> nameIdsMap = (Map)session.getAttribute("AllProtocolNameFileIds"); if (fileId != null && fileId.length()>0 ){ //if it's a new protocol name, we need to add this protocol //version to the above two maps if (isNewName){ List<String> newVersionList = new ArrayList<String>(); List<String> newVersionIdList = new ArrayList<String>(); newVersionList.add(fileId); newVersionIdList.add(fileId); nameVersionsMap.put(protocolName, newVersionList); nameIdsMap.put(protocolName, newVersionIdList); } //if an old name. if this is a new version then added to the list else{ //must check the name field is not empty if (protocolName != null && protocolName.length()>0){ List<String> newVersionList = nameVersionsMap.get(protocolName); List<String> newVersionIdList = nameIdsMap.get(protocolName); if (newVersionIdList!= null && !newVersionIdList.contains(fileId)){ newVersionList.add(fileId); newVersionIdList.add(fileId); } } //else then there is no correlation, but we still add it to the //dropdown box. else { isNewVersion = true; } } } //Let build version dropdown box SortedSet<LabelValueBean> myProtocolFiles = new TreeSet<LabelValueBean>(); if (isNewVersion){ LabelValueBean pfb = new LabelValueBean(fileId, fileId); myProtocolFiles.add(pfb); } else if (protocolName != null && protocolName.length()>0){ List<String> fileVersions = nameVersionsMap.get(protocolName); List<String> fileIds = nameIdsMap.get(protocolName); if (fileVersions != null && !fileVersions.isEmpty()){ int i = 0; for (String version : fileVersions){ LabelValueBean pfb = new LabelValueBean(version, fileIds.get(i)); //pfb.setVersion(version); //pfb.setId(fileIds.get(i)); myProtocolFiles.add(pfb); i++; } } } session.setAttribute("protocolVersions", myProtocolFiles); } private void updateAfterFileDataRetrieval(HttpServletRequest request, DynaValidatorForm theForm) { HttpSession session = request.getSession(); // update sample source drop-down list to include the new entry String protocolType = (String) theForm.get("protocolType"); //List<String> protocolTypes = (List) session.getAttribute("protocolTypes"); String protocolId = (String) theForm.get("protocolId"); Map<String, List<String>> typeNamesMap = (Map)session.getAttribute("AllProtocolTypeNames"); Map<String, List<String>> typeIdsMap = (Map)session.getAttribute("AllProtocolTypeIds"); //Set protocol name dropdown box List<String> protocolNames = typeNamesMap.get(protocolType); List<String> protocolIds = typeIdsMap.get(protocolType); int i = 0; SortedSet<ProtocolBean> protocols = new TreeSet<ProtocolBean>(); for (String id : protocolIds){ ProtocolBean pb = new ProtocolBean(); pb.setId(id); pb.setName(protocolNames.get(i)); protocols.add(pb); i++; } session.setAttribute("protocolNames", protocols); // Now set protocol version dropdown box Map<String, List<String>> nameVersionsMap = (Map)session.getAttribute("AllProtocolNameVersions"); Map<String, List<String>> nameIdsMap = (Map)session.getAttribute("AllProtocolNameFileIds"); List<String> fileVersions = nameVersionsMap.get(protocolId); List<String> fileIds = nameIdsMap.get(protocolId); i = 0; SortedSet<LabelValueBean> myProtocolFiles = new TreeSet<LabelValueBean>(); for (String version : fileVersions){ LabelValueBean pfb = new LabelValueBean(version, fileIds.get(i)); //pfb.setVersion(version); //pfb.setId(fileIds.get(i)); myProtocolFiles.add(pfb); i++; } session.setAttribute("protocolVersions", myProtocolFiles); } }
package hello.suribot.analyze.contracts; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.json.JSONException; import org.json.JSONObject; import hello.suribot.analyze.ApiUrls; import hello.suribot.analyze.IntentsAnalyzer; import hello.suribot.analyze.jsonmemory.JSonMemory; public class ContractAnalyzer { private ContractParams calledMethod; private boolean choice; public ContractAnalyzer() {} public JSONObject analyze(JSONObject entities, String idUser){ resetParams(); JSONObject jsonReturn = new JSONObject(); List<String> missingParams = new ArrayList<>(3); String identifiant; try{ identifiant = getContractId(entities); JSonMemory.putIdContrat(idUser, identifiant); }catch( JSONException | ClassCastException e){ identifiant = JSonMemory.getIdContrat(idUser); } if(identifiant==null || identifiant.isEmpty()){ jsonReturn.put(IntentsAnalyzer.SUCCESS, false); missingParams.add("votre identifiant de contrat"); jsonReturn.put(IntentsAnalyzer.MISSINGPARAMS, missingParams); return jsonReturn; } else { jsonReturn.put(IntentsAnalyzer.SUCCESS, true); String uriToCall = ApiUrls.demande.getUrl()+"ID-"+identifiant+"/"; try{ //String quelMethodeAppeler = recastJson.getString(FakeRecastKeys.METHOD.getName()); calledMethod = getMethodToCall(entities); if(calledMethod==null){ missingParams.add("\n\nvos couvertures"); missingParams.add("\n\nvos prélèvements"); missingParams.add("\n\nle rôle d'un personne"); jsonReturn.put(IntentsAnalyzer.MISSINGPARAMS, missingParams); jsonReturn.put(IntentsAnalyzer.SUCCESS, false); return jsonReturn; } String quelMethodeAppeler = calledMethod.toString(); uriToCall+=ContractParams.valueOf(calledMethod.toString()).getChemin(); String complement = getComplement(entities, calledMethod); if(complement != null){ if(quelMethodeAppeler.equalsIgnoreCase(ContractParams.risk.toString())){ complement=(ContractParams.IDOBJ.getChemin().replaceAll(ContractParams.IDREPLACE.getChemin(), complement)); } else { complement = (ContractParams.IDBILLING.getChemin().replaceAll(ContractParams.IDREPLACE.getChemin(), complement)); } uriToCall+=complement; }else{ choice = true; /* no complements */ } jsonReturn.put(ApiUrls.URITOCALL.name(), uriToCall); }catch(JSONException e){ jsonReturn.put(IntentsAnalyzer.SUCCESS, false); jsonReturn.put(IntentsAnalyzer.MISSINGPARAMS, missingParams); } } return jsonReturn; } private void resetParams(){ calledMethod = null; choice = false; } public ContractParams getCalledMethod() { return calledMethod; } public boolean isChoice() { return choice; } public ContractParams getMethodToCall(JSONObject entities){ if(entities!=null){ Set<String> setKeyEntities = entities.keySet(); if(setKeyEntities==null || setKeyEntities.isEmpty()) return null; if(setKeyEntities.contains("role") || setKeyEntities.contains("person-id")) return ContractParams.role; if(setKeyEntities.contains("risk") || setKeyEntities.contains("object-id")) return ContractParams.risk; if(setKeyEntities.contains("prelevement") || setKeyEntities.contains("prelevement-id")) return ContractParams.billings; } return null; } public String getComplement(JSONObject entities, ContractParams cp){ if(cp == null ) return null; try{ if(cp.toString().equalsIgnoreCase("risk")) return entities.getJSONArray("object-id").getJSONObject(0).getString("raw").replaceAll("[^0-9]+", ""); else if(cp.toString().equalsIgnoreCase("role")) return entities.getJSONArray("person-id").getJSONObject(0).getString("raw").replaceAll("[^0-9]+", ""); else if(cp.toString().equalsIgnoreCase("billings")) return entities.getJSONArray("prelevement-id").getJSONObject(0).getString("raw").replaceAll("[^0-9]+", ""); }catch(JSONException e){} return null; } public String getContractId(JSONObject entities) throws JSONException,ClassCastException{ return entities.getJSONArray("contrat-id").getJSONObject(0).getString("raw").replaceAll("[^0-9]+", ""); } }
// @@@ use lrmc here package ibis.satin.impl.faultTolerance; import ibis.ipl.ReadMessage; import ibis.ipl.StaticProperties; import ibis.ipl.WriteMessage; import ibis.satin.impl.Config; import ibis.satin.impl.Satin; import ibis.satin.impl.communication.Protocol; import ibis.satin.impl.loadBalancing.Victim; import ibis.satin.impl.spawnSync.InvocationRecord; import ibis.satin.impl.spawnSync.Stamp; import ibis.util.Timer; import java.io.IOException; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; final class GlobalResultTable implements Config, Protocol { private Satin s; /** The entries in the global result table. Entries are of type * GlobalResultTableValue. */ private Map entries; /** A list of updates that has to be broadcast to the other nodes. Elements are * of type (Stamp, GlobalResultTableValue). */ private Map toSend; private GlobalResultTableValue pointerValue = new GlobalResultTableValue( GlobalResultTableValue.TYPE_POINTER, null); protected GlobalResultTable(Satin s, StaticProperties requestedProperties) { this.s = s; entries = new Hashtable(); toSend = new Hashtable(); } protected GlobalResultTableValue lookup(Stamp key) { if (key == null) return null; s.stats.lookupTimer.start(); Satin.assertLocked(s); GlobalResultTableValue value = (GlobalResultTableValue) entries .get(key); if (value != null) { grtLogger .debug("SATIN '" + s.ident + "': lookup successful " + key); if (value.type == GlobalResultTableValue.TYPE_POINTER) { if (!s.deadIbises.contains(value.owner)) { s.stats.tableSuccessfulLookups++; s.stats.tableRemoteLookups++; } } else { s.stats.tableSuccessfulLookups++; } } s.stats.tableRemoteLookups++; s.stats.lookupTimer.stop(); return value; } protected void storeResult(InvocationRecord r) { Satin.assertLocked(s); s.stats.updateTimer.start(); GlobalResultTableValue value = new GlobalResultTableValue( GlobalResultTableValue.TYPE_RESULT, r); Stamp key = r.getStamp(); Object oldValue = entries.get(key); entries.put(key, value); s.stats.tableResultUpdates++; if (entries.size() > s.stats.tableMaxEntries) { s.stats.tableMaxEntries = entries.size(); } if (oldValue == null) { toSend.put(key, pointerValue); s.ft.updatesToSend = true; } grtLogger.debug("SATIN '" + s.ident + "': update complete: " + key + "," + value); s.stats.updateTimer.stop(); } protected void updateAll(Map updates) { Satin.assertLocked(s); s.stats.updateTimer.start(); entries.putAll(updates); toSend.putAll(updates); s.stats.tableResultUpdates += updates.size(); if (entries.size() > s.stats.tableMaxEntries) { s.stats.tableMaxEntries = entries.size(); } s.stats.updateTimer.stop(); s.ft.updatesToSend = true; } protected void sendUpdates() { Timer updateTimer = null; Timer tableSerializationTimer = null; int size = 0; synchronized (s) { s.ft.updatesToSend = false; size = s.victims.size(); } if (size == 0) return; updateTimer = Timer.createTimer(); updateTimer.start(); for(int i=0; i<size; i++) { Victim send; WriteMessage m = null; synchronized (s) { send = s.victims.getVictim(i); } try { m = send.newMessage(); } catch (IOException e) { grtLogger.info("Got exception in newMessage()", e); continue; //always happens after a crash } tableSerializationTimer = Timer.createTimer(); tableSerializationTimer.start(); try { m.writeByte(GRT_UPDATE); m.writeObject(toSend); } catch (IOException e) { grtLogger.info("Got exception in writeObject()", e); //always happens after a crash } tableSerializationTimer.stop(); s.stats.tableSerializationTimer.add(tableSerializationTimer); try { long msgSize = m.finish(); grtLogger.debug("SATIN '" + s.ident + "': " + msgSize + " sent in " + s.stats.tableSerializationTimer.lastTimeVal() + " to " + send); } catch (IOException e) { grtLogger.info("Got exception in finish()"); //always happens after a crash } } s.stats.tableUpdateMessages++; updateTimer.stop(); s.stats.updateTimer.add(updateTimer); } // Returns ready to send contents of the table. protected Map getContents() { Satin.assertLocked(s); // Replace "real" results with pointer values. Map newEntries = new HashMap(); Iterator iter = entries.entrySet().iterator(); while (iter.hasNext()) { Map.Entry element = (Map.Entry) iter.next(); GlobalResultTableValue value = (GlobalResultTableValue) element .getValue(); Stamp key = (Stamp) element.getKey(); switch (value.type) { case GlobalResultTableValue.TYPE_RESULT: newEntries.put(key, pointerValue); break; case GlobalResultTableValue.TYPE_POINTER: newEntries.put(key, value); break; default: grtLogger.error("SATIN '" + s.ident + "': EEK invalid value type in getContents()"); } } return newEntries; } protected void addContents(Map contents) { Satin.assertLocked(s); grtLogger.debug("adding contents"); entries.putAll(contents); if (entries.size() > s.stats.tableMaxEntries) { s.stats.tableMaxEntries = entries.size(); } } // no need to finish the message, we don't block // this method does not run exclusively, multiple receiveports can call it at the smae time. protected void handleGRTUpdate(ReadMessage m) { Map map = null; Timer handleUpdateTimer = Timer.createTimer(); Timer tableDeserializationTimer = Timer.createTimer(); handleUpdateTimer.start(); tableDeserializationTimer.start(); try { map = (Map) m.readObject(); } catch (Exception e) { grtLogger.error("SATIN '" + s.ident + "': Global result table - error reading message", e); tableDeserializationTimer.stop(); s.stats.tableDeserializationTimer.add(tableDeserializationTimer); handleUpdateTimer.stop(); s.stats.handleUpdateTimer.add(handleUpdateTimer); return; } tableDeserializationTimer.stop(); s.stats.tableDeserializationTimer.add(tableDeserializationTimer); synchronized (s) { addContents(map); } handleUpdateTimer.stop(); s.stats.handleUpdateTimer.add(handleUpdateTimer); } protected void print(java.io.PrintStream out) { synchronized (s) { out.println("=GRT: " + s.ident + "="); int i = 0; Iterator iter = entries.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); out.println("GRT[" + i + "]= " + entry.getKey() + ";" + entry.getValue()); i++; } out.println("=end of GRT " + s.ident + "="); } } }
package it.unimi.dsi.fastutil.io; import it.unimi.dsi.fastutil.bytes.ByteArrays; import it.unimi.dsi.fastutil.io.RepositionableStream; import java.io.IOException; import java.io.InputStream; import java.nio.channels.FileChannel; import java.util.EnumSet; public class FastBufferedInputStream extends MeasurableInputStream implements RepositionableStream { /** The default size of the internal buffer in bytes (8Ki). */ public final static int DEFAULT_BUFFER_SIZE = 8 * 1024; /** An enumeration of the supported line terminators. */ public static enum LineTerminator { /** A carriage return (CR, ASCII 13). */ CR, /** A line feed (LF, ASCII 10). */ LF, /** A carriage return followed by a line feed (CR/LF, ASCII 13/10). */ CR_LF } /** A set containing <em>all available</em> line terminators. */ public final static EnumSet<LineTerminator> ALL_TERMINATORS = EnumSet.allOf( LineTerminator.class ); /** The underlying input stream. */ protected InputStream is; /** The internal buffer. */ protected byte buffer[]; /** The current position in the buffer. */ protected int pos; /** The number of bytes ever read (reset upon a call to {@link #position(long)}). * In particular, this will always represent the index (in the underlying input stream) * of the first available byte in the buffer. */ protected long readBytes; /** The number of buffer bytes available starting from {@link #pos}. */ protected int avail; /** The cached file channel underlying {@link #is}, if any. */ private FileChannel fileChannel; /** {@link #is} cast to a positionable stream, if possible. */ private RepositionableStream repositionableStream; /** {@link #is} cast to a measurable stream, if possible. */ private MeasurableStream measurableStream; private static int ensureBufferSize( final int bufferSize ) { if ( bufferSize <= 0 ) throw new IllegalArgumentException( "Illegal buffer size: " + bufferSize ); return bufferSize; } /** Creates a new fast buffered input stream by wrapping a given input stream with a given buffer. * * @param is an input stream to wrap. * @param buffer a buffer of positive length. */ public FastBufferedInputStream( final InputStream is, final byte[] buffer ) { this.is = is; ensureBufferSize( buffer.length ); this.buffer = buffer; if ( is instanceof RepositionableStream ) repositionableStream = (RepositionableStream)is; if ( is instanceof MeasurableStream ) measurableStream = (MeasurableStream)is; if ( repositionableStream == null ) { try { fileChannel = (FileChannel)( is.getClass().getMethod( "getChannel", new Class[] {} ) ).invoke( is, new Object[] {} ); } catch( IllegalAccessException e ) {} catch( IllegalArgumentException e ) {} catch( NoSuchMethodException e ) {} catch( java.lang.reflect.InvocationTargetException e ) {} catch( ClassCastException e ) {} } } /** Creates a new fast buffered input stream by wrapping a given input stream with a given buffer size. * * @param is an input stream to wrap. * @param bufferSize the size in bytes of the internal buffer (greater than zero). */ public FastBufferedInputStream( final InputStream is, final int bufferSize ) { this( is, new byte[ ensureBufferSize( bufferSize ) ] ); } /** Creates a new fast buffered input stream by wrapping a given input stream with a buffer of {@link #DEFAULT_BUFFER_SIZE} bytes. * * @param is an input stream to wrap. */ public FastBufferedInputStream( final InputStream is ) { this( is, DEFAULT_BUFFER_SIZE ); } /** Checks whether no more bytes will be returned. * * <p>This method will refill the internal buffer. * * @return true if there are no characters in the internal buffer and * the underlying reader is exhausted. */ protected boolean noMoreCharacters() throws IOException { if ( avail == 0 ) { avail = is.read( buffer ); if ( avail <= 0 ) { avail = 0; return true; } pos = 0; } return false; } public int read() throws IOException { if ( noMoreCharacters() ) return -1; avail readBytes++; return buffer[ pos++ ] & 0xFF; } public int read( final byte b[], final int offset, final int length ) throws IOException { if ( length <= avail ) { System.arraycopy( buffer, pos, b, offset, length ); pos += length; avail -= length; readBytes += length; return length; } final int head = avail; System.arraycopy( buffer, pos, b, offset, head ); pos = avail = 0; readBytes += head; if ( length > buffer.length ) { // We read directly into the destination final int result = is.read( b, offset + head, length - head ); if ( result > 0 ) readBytes += result; return result < 0 ? ( head == 0 ? -1 : head ) : result + head; } if ( noMoreCharacters() ) return head == 0 ? -1 : head; final int toRead = Math.min( length - head, avail ); readBytes += toRead; System.arraycopy( buffer, 0, b, offset + head, toRead ); pos = toRead; avail -= toRead; // Note that head >= 0, and necessarily toRead > 0 return toRead + head; } /** Reads a line into the given byte array using {@linkplain #ALL_TERMINATORS all terminators}. * * @param array byte array where the next line will be stored. * @return the number of bytes actually placed in <code>array</code>, or -1 at end of file. * @see #readLine(byte[], int, int, EnumSet) */ public int readLine( final byte[] array ) throws IOException { return readLine( array, 0, array.length, ALL_TERMINATORS ); } /** Reads a line into the given byte array. * * @param array byte array where the next line will be stored. * @param terminators a set containing the line termination sequences that we want * to consider as valid. * @return the number of bytes actually placed in <code>array</code>, or -1 at end of file. * @see #readLine(byte[], int, int, EnumSet) */ public int readLine( final byte[] array, final EnumSet<LineTerminator> terminators ) throws IOException { return readLine( array, 0, array.length, terminators ); } /** Reads a line into the given byte-array fragment using {@linkplain #ALL_TERMINATORS all terminators}. * * @param array byte array where the next line will be stored. * @param off the first byte to use in <code>array</code>. * @param len the maximum number of bytes to read. * @return the number of bytes actually placed in <code>array</code>, or -1 at end of file. * @see #readLine(byte[], int, int, EnumSet) */ public int readLine( final byte[] array, final int off, final int len ) throws IOException { return readLine( array, off, len, ALL_TERMINATORS ); } /** Reads a line into the given byte-array fragment. * * <P>Reading lines (i.e., characters) out of a byte stream is not always sensible * (methods available to that purpose in old versions of Java have been mercilessly deprecated). * Nonetheless, in several situations, such as when decoding network protocols or headers * known to be ASCII, it is very useful to be able to read a line from a byte stream. * * <p>This method will attempt to read the next line into <code>array</code> starting at <code>off</code>, * reading at most <code>len</code> bytes. The read, however, will be stopped by the end of file or * when meeting a {@linkplain LineTerminator <em>line terminator</em>}. Of course, for this operation * to be sensible the encoding of the text contained in the stream, if any, must not generate spurious * carriage returns or line feeds. Note that the termination detection uses a maximisation * criterion, so if you specify both {@link LineTerminator#CR} and * {@link LineTerminator#CR_LF} meeting a pair CR/LF will consider the whole pair a terminator. * * <p>Terminators are <em>not</em> copied into <em>array</em> or included in the returned count. The * returned integer can be used to check whether the line is complete: if it is smaller than * <code>len</code>, then more bytes might be available, but note that this method (contrarily * to {@link #read(byte[], int, int)}) can legitimately return zero when <code>len</code> * is nonzero just because a terminator was found as the first character. Thus, the intended * usage of this method is to call it on a given array, check whether <code>len</code> bytes * have been read, and if so try again (possibly extending the array) until a number of read bytes * strictly smaller than <code>len</code> (possibly, -1) is returned. * * <p>If you need to guarantee that a full line is read, use the following idiom: * <pre> * int start = off, len; * while( ( len = fbis.readLine( array, start, array.length - start, terminators ) ) == array.length - start ) { * start += len; * array = ByteArrays.grow( array, array.length + 1 ); * } * </pre> * * <p>At the end of the loop, the line will be placed in <code>array</code> starting at * <code>off</code> (inclusive) and ending at <code>start + Math.max( len, 0 )</code> (exclusive). * * @param array byte array where the next line will be stored. * @param off the first byte to use in <code>array</code>. * @param len the maximum number of bytes to read. * @param terminators a set containing the line termination sequences that we want * to consider as valid. * @return the number of bytes actually placed in <code>array</code>, or -1 at end of file. * Note that the returned number will be <code>len</code> if no line termination sequence * specified in <code>terminators</code> has been met before scanning <code>len</code> byte, * and if also we did not meet the end of file. */ public int readLine( final byte[] array, final int off, final int len, final EnumSet<LineTerminator> terminators ) throws IOException { ByteArrays.ensureOffsetLength( array ,off, len ); if ( len == 0 ) return 0; // 0-length reads always return 0 if ( noMoreCharacters() ) return -1; int i, k = 0, remaining = len, read = 0; // The number of bytes still to be read for(;;) { for( i = 0; i < avail && i < remaining && ( k = buffer[ pos + i ] ) != '\n' && k != '\r' ; i++ ); System.arraycopy( buffer, pos, array, off + read, i ); pos += i; avail -= i; read += i; remaining -= i; if ( remaining == 0 ) { readBytes += read; return read; // We did not stop because of a terminator } if ( avail > 0 ) { // We met a terminator if ( k == '\n' ) { // LF first pos++; avail if ( terminators.contains( LineTerminator.LF ) ) { readBytes += read + 1; return read; } else { array[ off + read++ ] = '\n'; remaining } } else if ( k == '\r' ) { // CR first pos++; avail if ( terminators.contains( LineTerminator.CR_LF ) ) { if ( avail > 0 ) { if ( buffer[ pos ] == '\n' ) { // CR/LF with LF already in the buffer. pos ++; avail readBytes += read + 2; return read; } } else { // We must search for the LF. if ( noMoreCharacters() ) { // Not found a matching LF because of end of file, will return CR in buffer if not a terminator if ( ! terminators.contains( LineTerminator.CR ) ) { array[ off + read++ ] = '\r'; remaining readBytes += read; } else readBytes += read + 1; return read; } if ( buffer[ 0 ] == '\n' ) { // Found matching LF, won't return terminators in the buffer pos++; avail readBytes += read + 2; return read; } } } if ( terminators.contains( LineTerminator.CR ) ) { readBytes += read + 1; return read; } array[ off + read++ ] = '\r'; remaining } } else if ( noMoreCharacters() ) { readBytes += read; return read; } } } public void position( long newPosition ) throws IOException { final long position = readBytes; /** Note that this check will succeed also in the case of * an empty buffer and position == newPosition. This behaviour is * intentional, as it delays buffering to when it is actually * necessary and avoids useless class the underlying stream. */ if ( newPosition <= position + avail && newPosition >= position - pos ) { pos += newPosition - position; avail -= newPosition - position; readBytes = newPosition; return; } if ( repositionableStream != null ) repositionableStream.position( newPosition ); else if ( fileChannel != null ) fileChannel.position( newPosition ); else throw new UnsupportedOperationException( "position() can only be called if the underlying byte stream implements the RepositionableStream interface or if the getChannel() method of the underlying byte stream exists and returns a FileChannel" ); readBytes = newPosition; avail = pos = 0; } public long position() throws IOException { return readBytes; } /** Returns the length of the underlying input stream, if it is {@linkplain MeasurableStream measurable}. * * @return the length of the underlying input stream. * @throws UnsupportedOperationException if the underlying input stream is not {@linkplain MeasurableStream measurable} and * cannot provide a {@link FileChannel}. */ public long length() throws IOException { if ( measurableStream != null ) return measurableStream.length(); if ( fileChannel != null ) return fileChannel.size(); throw new UnsupportedOperationException(); } /** Skips the given amount of bytes by repeated reads. * * <strong>Warning</strong>: this method uses destructively the internal buffer. * * @param n the number of bytes to skip. * @return the number of bytes actually skipped. * @see InputStream#skip(long) */ private long skipByReading( final long n ) throws IOException { long toSkip = n; int len; while( toSkip > 0 ) { len = is.read( buffer, 0, (int)Math.min( buffer.length, toSkip ) ); if ( len > 0 ) toSkip -= len; else break; } return n - toSkip; } /** Skips over and discards the given number of bytes of data from this fast buffered input stream. * * <p>As explained in the {@linkplain FastBufferedInputStream class documentation}, the semantics * of {@link InputStream#skip(long)} is fatally flawed. This method provides additional semantics as follows: * it will skip the provided number of bytes, unless the end of file has been reached. * * <p>Additionally, if the underlying input stream is {@link System#in} this method will use * repeated reads instead of invoking {@link InputStream#skip(long)}. * * @param n the number of bytes to skip. * @return the number of bytes actually skipped; it can be smaller than <code>n</code> * only if the end of file has been reached. * @see InputStream#skip(long) */ public long skip( final long n ) throws IOException { if ( n <= avail ) { final int m = (int)n; pos += m; avail -= m; readBytes += n; return n; } long toSkip = n - avail, result = 0; avail = 0; while ( toSkip != 0 && ( result = is == System.in ? skipByReading( toSkip ) : is.skip( toSkip ) ) < toSkip ) { if ( result == 0 ) { if ( is.read() == -1 ) break; toSkip } else toSkip -= result; } final long t = n - ( toSkip - result ); readBytes += t; return t; } public int available() throws IOException { return (int)Math.min( is.available() + (long)avail, Integer.MAX_VALUE ); } public void close() throws IOException { if ( is == null ) return; if ( is != System.in ) is.close(); is = null; buffer = null; } /** Resets the internal logic of this fast buffered input stream, clearing the buffer. * * <p>All buffering information is discarded, and the number of bytes read so far * (and thus, also the {@linkplain #position() current position}) * is adjusted to reflect this fact. * * <p>This method is mainly useful for re-reading * files that have been overwritten externally. */ public void flush() { if ( is == null ) return; readBytes += avail; avail = pos = 0; } /** Resets the internal logic of this fast buffered input stream. * * @deprecated As of <samp>fastutil</samp> 5.0.4, replaced by {@link #flush()}. The old * semantics of this method does not contradict {@link InputStream}'s contract, as * the semantics of {@link #reset()} is undefined if {@link InputStream#markSupported()} * returns false. On the other hand, the name was really a poor choice. */ @Deprecated public void reset() { flush(); } }
// Nenya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.media.timer; import com.samskivert.Log; import com.samskivert.swing.RuntimeAdjust; import com.samskivert.util.Interval; import com.samskivert.util.RunQueue; import com.threerings.media.MediaPrefs; /** * Calibrates timing values from a subclass' implementation of current against those returned by * System.currentTimeMillis. If the subclass timer is moving 1.25 times faster or .75 times slower * than currentTimeMillis, hold it to the values from currentTimeMillis. */ public abstract class CalibratingTimer implements MediaTimer { /** * Initializes this timer. Must be called before the timer is used. * * @param milliDivider - value by which current() must be divided to get milliseconds * @param microDivider - value by which current() must be divided to get microseconds */ protected void init (long milliDivider, long microDivider) { _milliDivider = milliDivider; _microDivider = microDivider; reset(); Log.info("Using " + getClass() + " timer [mfreq=" + _milliDivider + ", ufreq=" + _microDivider + ", start=" + _startStamp + "]."); } // documentation inherited from interface public long getElapsedMicros () { return elapsed() / _microDivider; } // documentation inherited from interface public long getElapsedMillis () { return elapsed() / _milliDivider; } // documentation inherited from interface public void reset () { if (_calibrateInterval != null) { _calibrateInterval.cancel(); _calibrateInterval = null; } _startStamp = _priorCurrent = current(); _driftMilliStamp = System.currentTimeMillis(); _driftTimerStamp = current(); _calibrateInterval = new Interval(RunQueue.AWT) { @Override public void expired () { calibrate(); } }; _calibrateInterval.schedule(5000, true); } /** * Returns the greatest drift ratio we've had to compensate for. */ public double getMaxDriftRatio () { return _maxDriftRatio; } /** * Clears out our remembered max drift. */ public void clearMaxDriftRatio () { _maxDriftRatio = 1.0; } /** Returns the difference between _startStamp and current() */ protected long elapsed () { long current = current(); if (_driftRatio != 1.0) { long elapsed = current - _priorCurrent; _startStamp += (elapsed - (elapsed * _driftRatio)); _priorCurrent = current; } return current - _startStamp; } /** Calculates the drift factor from the time elapsed from the last calibrate call. */ protected void calibrate () { long current = current(); double elapsedTimer = (current - _driftTimerStamp); double elapsedMillis = System.currentTimeMillis() - _driftMilliStamp; double drift = elapsedMillis / (elapsedTimer / _milliDivider); if (_debugCalibrate.getValue()) { Log.warning("Calibrating [timer=" + elapsedTimer + ", millis=" + elapsedMillis + ", drift=" + drift + ", timerstamp=" + _driftTimerStamp + ", millistamp=" + _driftMilliStamp + ", current=" + current + "]"); } if (elapsedTimer < 0) { Log.warning("The timer has decided to live in the past, resetting drift[previousTimer=" + _driftTimerStamp + ", currentTimer=" + current + ", previousMillis=" + _driftMilliStamp + ", currentMillis=" + System.currentTimeMillis() + "]"); _driftRatio = 1.0; } else if (drift > MAX_ALLOWED_DRIFT_RATIO || drift < MIN_ALLOWED_DRIFT_RATIO) { Log.warning("Calibrating [drift=" + drift + "]"); // Keep the drift somewhat sane between .01 and 10 _driftRatio = Math.min(Math.max(.01, drift), 10); if (Math.abs(drift - 1.0) > Math.abs(_maxDriftRatio - 1.0)) { _maxDriftRatio = drift; } } else if (_driftRatio != 1.0) { // If we're within bounds now but we weren't before, reset _driftFactor and log it _driftRatio = 1.0; Log.warning("Calibrating [drift=" + drift + "]"); } _driftMilliStamp = System.currentTimeMillis(); _driftTimerStamp = current(); } /** Return the current value for this timer. */ public abstract long current (); /** The largest drift ratio we'll allow without correcting. */ protected static final double MAX_ALLOWED_DRIFT_RATIO = 1.1; /** The smallest drift ratio we'll allow without correcting. */ protected static final double MIN_ALLOWED_DRIFT_RATIO = 0.9; /** current() value when the timer was started. */ protected long _startStamp; /** current() value when elapsed was called last. */ protected long _priorCurrent; /** Amount by which current() should be divided to get milliseconds. */ protected long _milliDivider; /** Amount by which current() should be divided to get microseconds. */ protected long _microDivider; /** currentTimeMillis() value from the last time we called calibrate. */ protected long _driftMilliStamp = System.currentTimeMillis(); /** current() value from the last time we called calibrate. */ protected long _driftTimerStamp; /** Ratio of currentTimeMillis to timer millis. */ protected double _driftRatio = 1.0; /** The largest drift we've had to adjust for. */ protected double _maxDriftRatio = 1.0; /** Interval that fires every five seconds to run the calibration. */ protected Interval _calibrateInterval; /** A debug hook that toggles dumping of calibration values. */ protected static RuntimeAdjust.BooleanAdjust _debugCalibrate = new RuntimeAdjust.BooleanAdjust( "Toggles calibrations statistics", "narya.media.timer", MediaPrefs.config, false); }
// Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.parlor.card.client; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Iterator; import javax.swing.event.MouseInputAdapter; import com.samskivert.util.ObserverList; import com.samskivert.util.QuickSort; import com.threerings.media.FrameManager; import com.threerings.media.VirtualMediaPanel; import com.threerings.media.image.Mirage; import com.threerings.media.sprite.PathAdapter; import com.threerings.media.sprite.Sprite; import com.threerings.media.util.LinePath; import com.threerings.media.util.Path; import com.threerings.media.util.PathSequence; import com.threerings.media.util.Pathable; import com.threerings.parlor.card.Log; import com.threerings.parlor.card.data.Card; import com.threerings.parlor.card.data.CardCodes; import com.threerings.parlor.card.data.Deck; import com.threerings.parlor.card.data.Hand; /** * Extends VirtualMediaPanel to provide services specific to rendering * and manipulating playing cards. */ public abstract class CardPanel extends VirtualMediaPanel implements CardCodes { /** The selection mode in which cards are not selectable. */ public static final int NONE = 0; /** The selection mode in which the user can play a single card. */ public static final int PLAY_SINGLE = 1; /** The selection mode in which the user can select a single card. */ public static final int SELECT_SINGLE = 2; /** The selection mode in which the user can select multiple cards. */ public static final int SELECT_MULTIPLE = 3; /** * A predicate class for {@link CardSprite}s. Provides control over which * cards are selectable, playable, etc. */ public static interface CardSpritePredicate { /** * Evaluates the specified sprite. */ public boolean evaluate (CardSprite sprite); } /** * A listener for card selection/deselection. */ public static interface CardSelectionObserver { /** * Called when a card has been played. */ public void cardSpritePlayed (CardSprite sprite); /** * Called when a card has been selected. */ public void cardSpriteSelected (CardSprite sprite); /** * Called when a card has been deselected. */ public void cardSpriteDeselected (CardSprite sprite); } /** * Constructor. * * @param frameManager the frame manager */ public CardPanel (FrameManager frameManager) { super(frameManager); // add a listener for mouse events CardListener cl = new CardListener(); addMouseListener(cl); addMouseMotionListener(cl); } /** * Returns the full-sized image for the back of a playing card. */ public abstract Mirage getCardBackImage (); /** * Returns the full-sized image for the front of the specified card. */ public abstract Mirage getCardImage (Card card); /** * Returns the small-sized image for the back of a playing card. */ public abstract Mirage getMicroCardBackImage (); /** * Returns the small-sized image for the front of the specified card. */ public abstract Mirage getMicroCardImage (Card card); /** * Sets the location of the hand (the location of the center of the hand's * upper edge). */ public void setHandLocation (int x, int y) { _handLocation.setLocation(x, y); } /** * Sets the horizontal spacing between cards in the hand. */ public void setHandSpacing (int spacing) { _handSpacing = spacing; } /** * Sets the vertical distance to offset cards that are selectable or * playable. */ public void setSelectableCardOffset (int offset) { _selectableCardOffset = offset; } /** * Sets the vertical distance to offset cards that are selected. */ public void setSelectedCardOffset (int offset) { _selectedCardOffset = offset; } /** * Sets the selection mode for the hand (NONE, PLAY_SINGLE, SELECT_SINGLE, * or SELECT_MULTIPLE). Changing the selection mode does not change the * current selection. */ public void setHandSelectionMode (int mode) { _handSelectionMode = mode; // update the offsets of all cards in the hand updateHandOffsets(); } /** * Sets the selection predicate that determines which cards from the hand * may be selected (if null, all cards may be selected). Changing the * predicate does not change the current selection. */ public void setHandSelectionPredicate (CardSpritePredicate pred) { _handSelectionPredicate = pred; // update the offsets of all cards in the hand updateHandOffsets(); } /** * Returns the currently selected hand sprite (null if no sprites are * selected, the first sprite if multiple sprites are selected). */ public CardSprite getSelectedHandSprite () { return _selectedHandSprites.size() == 0 ? null : (CardSprite)_selectedHandSprites.get(0); } /** * Returns an array containing the currently selected hand sprites * (returns an empty array if no sprites are selected). */ public CardSprite[] getSelectedHandSprites () { return (CardSprite[])_selectedHandSprites.toArray( new CardSprite[_selectedHandSprites.size()]); } /** * Programmatically plays a sprite in the hand. */ public void playHandSprite (final CardSprite sprite) { // notify the observers ObserverList.ObserverOp op = new ObserverList.ObserverOp() { public boolean apply (Object obs) { ((CardSelectionObserver)obs).cardSpritePlayed(sprite); return true; } }; _handSelectionObservers.apply(op); } /** * Programmatically selects a sprite in the hand. */ public void selectHandSprite (final CardSprite sprite) { // make sure it's not already selected if (_selectedHandSprites.contains(sprite)) { return; } // if in single card mode and there's another card selected, // deselect it if (_handSelectionMode == SELECT_SINGLE) { CardSprite oldSprite = getSelectedHandSprite(); if (oldSprite != null) { deselectHandSprite(oldSprite); } } // add to list and update offset _selectedHandSprites.add(sprite); sprite.setLocation(sprite.getX(), getHandY(sprite)); // notify the observers ObserverList.ObserverOp op = new ObserverList.ObserverOp() { public boolean apply (Object obs) { ((CardSelectionObserver)obs).cardSpriteSelected(sprite); return true; } }; _handSelectionObservers.apply(op); } /** * Programmatically deselects a sprite in the hand. */ public void deselectHandSprite (final CardSprite sprite) { // make sure it's selected if (!_selectedHandSprites.contains(sprite)) { return; } // remove from list and update offset _selectedHandSprites.remove(sprite); sprite.setLocation(sprite.getX(), getHandY(sprite)); // notify the observers ObserverList.ObserverOp op = new ObserverList.ObserverOp() { public boolean apply (Object obs) { ((CardSelectionObserver)obs).cardSpriteDeselected(sprite); return true; } }; _handSelectionObservers.apply(op); } /** * Clears any existing hand sprite selection. */ public void clearHandSelection () { CardSprite[] sprites = getSelectedHandSprites(); for (int i = 0; i < sprites.length; i++) { deselectHandSprite(sprites[i]); } } /** * Adds an object to the list of observers to notify when cards in the * hand are selected/deselected. */ public void addHandSelectionObserver (CardSelectionObserver obs) { _handSelectionObservers.add(obs); } /** * Removes an object from the hand selection observer list. */ public void removeHandSelectionObserver (CardSelectionObserver obs) { _handSelectionObservers.remove(obs); } /** * Fades a hand of cards in. * * @param hand the hand of cards * @param fadeDuration the amount of time to spend fading in * the entire hand */ public void setHand (Hand hand, long fadeDuration) { // make sure no cards are hanging around clearHand(); // create the sprites int size = hand.size(); for (int i = 0; i < size; i++) { CardSprite cs = new CardSprite(this, (Card)hand.get(i)); _handSprites.add(cs); } // sort them QuickSort.sort(_handSprites); // fade them in at proper locations and layers long cardDuration = fadeDuration / size; for (int i = 0; i < size; i++) { CardSprite cs = (CardSprite)_handSprites.get(i); cs.setLocation(getHandX(size, i), _handLocation.y); cs.setRenderOrder(i); cs.addSpriteObserver(_handSpriteObserver); addSprite(cs); cs.fadeIn(i * cardDuration, cardDuration); } } /** * Fades a hand of cards in face-down. * * @param size the size of the hand * @param fadeDuration the amount of time to spend fading in * each card */ public void setHand (int size, long fadeDuration) { // fill hand will null entries to signify unknown cards Hand hand = new Hand(); for (int i = 0; i < size; i++) { hand.add(null); } setHand(hand, fadeDuration); } /** * Shows a hand that was previous set face-down. * * @param hand the hand of cards */ public void showHand (Hand hand) { // sort the hand QuickSort.sort(hand); // set the sprites int len = Math.min(_handSprites.size(), hand.size()); for (int i = 0; i < len; i++) { CardSprite cs = (CardSprite)_handSprites.get(i); cs.setCard((Card)hand.get(i)); } } /** * Returns the first sprite in the hand that corresponds to the * specified card, or null if the card is not in the hand. */ public CardSprite getHandSprite (Card card) { return getCardSprite(_handSprites, card); } /** * Clears all cards from the hand. */ public void clearHand () { clearHandSelection(); clearSprites(_handSprites); } /** * Clears all cards from the board. */ public void clearBoard () { clearSprites(_boardSprites); } /** * Flies a set of cards from the hand into the ether. Clears any selected * cards. * * @param cards the card sprites to remove from the hand * @param dest the point to fly the cards to * @param flightDuration the duration of the cards' flight * @param fadePortion the amount of time to spend fading out * as a proportion of the flight duration */ public void flyFromHand (CardSprite[] cards, Point dest, long flightDuration, float fadePortion) { // fly each sprite over, removing it from the hand immediately and // from the board when it finishes its path for (int i = 0; i < cards.length; i++) { removeFromHand(cards[i]); LinePath flight = new LinePath(dest, flightDuration); cards[i].addSpriteObserver(_pathEndRemover); cards[i].moveAndFadeOut(flight, flightDuration, fadePortion); } // adjust the hand to cover the hole adjustHand(flightDuration, false); } /** * Flies a set of cards from the ether into the hand. Clears any selected * cards. The cards will first fly to the selected card offset, pause for * the specified duration, and then drop into the hand. * * @param cards the cards to add to the hand * @param src the point to fly the cards from * @param flightDuration the duration of the cards' flight * @param pauseDuration the duration of the pause before dropping into the * hand * @param dropDuration the duration of the cards' drop into the * hand * @param fadePortion the amount of time to spend fading in * as a proportion of the flight duration */ public void flyIntoHand (Card[] cards, Point src, long flightDuration, long pauseDuration, long dropDuration, float fadePortion) { // first create the sprites and add them to the list CardSprite[] sprites = new CardSprite[cards.length]; for (int i = 0; i < cards.length; i++) { sprites[i] = new CardSprite(this, cards[i]); _handSprites.add(sprites[i]); } // settle the hand adjustHand(flightDuration, true); // then set the layers and fly the cards in int size = _handSprites.size(); for (int i = 0; i < sprites.length; i++) { int idx = _handSprites.indexOf(sprites[i]); sprites[i].setLocation(src.x, src.y); sprites[i].setRenderOrder(idx); sprites[i].addSpriteObserver(_handSpriteObserver); addSprite(sprites[i]); // create a path sequence containing flight, pause, and drop ArrayList paths = new ArrayList(); Point hp2 = new Point(getHandX(size, idx), _handLocation.y), hp1 = new Point(hp2.x, hp2.y - _selectedCardOffset); paths.add(new LinePath(hp1, flightDuration)); paths.add(new LinePath(hp1, pauseDuration)); paths.add(new LinePath(hp2, dropDuration)); sprites[i].moveAndFadeIn(new PathSequence(paths), flightDuration + pauseDuration + dropDuration, fadePortion); } } /** * Flies a set of cards from the ether into the ether. * * @param cards the cards to fly across * @param src the point to fly the cards from * @param dest the point to fly the cards to * @param flightDuration the duration of the cards' flight * @param cardDelay the amount of time to wait between cards * @param fadePortion the amount of time to spend fading in and out * as a proportion of the flight duration */ public void flyAcross (Card[] cards, Point src, Point dest, long flightDuration, long cardDelay, float fadePortion) { for (int i = 0; i < cards.length; i++) { // add on top of all board sprites CardSprite cs = new CardSprite(this, cards[i]); cs.setRenderOrder(getHighestBoardLayer() + 1 + i); cs.setLocation(src.x, src.y); addSprite(cs); // prepend an initial delay to all cards after the first Path path; long pathDuration; LinePath flight = new LinePath(dest, flightDuration); if (i > 0) { long delayDuration = cardDelay * i; LinePath delay = new LinePath(src, delayDuration); path = new PathSequence(delay, flight); pathDuration = delayDuration + flightDuration; } else { path = flight; pathDuration = flightDuration; } cs.addSpriteObserver(_pathEndRemover); cs.moveAndFadeInAndOut(path, pathDuration, fadePortion); } } /** * Flies a set of cards from the ether into the ether face-down. * * @param number the number of cards to fly across * @param src the point to fly the cards from * @param dest the point to fly the cards to * @param flightDuration the duration of the cards' flight * @param cardDelay the amount of time to wait between cards * @param fadePortion the amount of time to spend fading in and out * as a proportion of the flight duration */ public void flyAcross (int number, Point src, Point dest, long flightDuration, long cardDelay, float fadePortion) { // use null values to signify unknown cards flyAcross(new Card[number], src, dest, flightDuration, cardDelay, fadePortion); } /** * Flies a card from the hand onto the board. Clears any cards selected. * * @param card the sprite to remove from the hand * @param dest the point to fly the card to * @param flightDuration the duration of the card's flight */ public void flyFromHandToBoard (CardSprite card, Point dest, long flightDuration) { // fly it over LinePath flight = new LinePath(dest, flightDuration); card.move(flight); // lower the board so that the card from hand is on top lowerBoardSprites(card.getRenderOrder() - 1); // move from one list to the other removeFromHand(card); _boardSprites.add(card); // adjust the hand to cover the hole adjustHand(flightDuration, false); } /** * Flies a card from the ether onto the board. * * @param card the card to add to the board * @param src the point to fly the card from * @param dest the point to fly the card to * @param flightDuration the duration of the card's flight * @param fadePortion the amount of time to spend fading in as a * proportion of the flight duration */ public void flyToBoard (Card card, Point src, Point dest, long flightDuration, float fadePortion) { // add it on top of the existing cards CardSprite cs = new CardSprite(this, card); cs.setRenderOrder(getHighestBoardLayer() + 1); cs.setLocation(src.x, src.y); addSprite(cs); _boardSprites.add(cs); // and fly it over LinePath flight = new LinePath(dest, flightDuration); cs.moveAndFadeIn(flight, flightDuration, fadePortion); } /** * Adds a card to the board immediately. * * @param card the card to add to the board * @param dest the point at which to add the card */ public void addToBoard (Card card, Point dest) { CardSprite cs = new CardSprite(this, card); cs.setRenderOrder(getHighestBoardLayer() + 1); cs.setLocation(dest.x, dest.y); addSprite(cs); _boardSprites.add(cs); } /** * Flies a set of cards from the board into the ether. * * @param cards the cards to remove from the board * @param dest the point to fly the cards to * @param flightDuration the duration of the cards' flight * @param fadePortion the amount of time to spend fading out as a * proportion of the flight duration */ public void flyFromBoard (CardSprite[] cards, Point dest, long flightDuration, float fadePortion) { for (int i = 0; i < cards.length; i++) { LinePath flight = new LinePath(dest, flightDuration); cards[i].addSpriteObserver(_pathEndRemover); cards[i].moveAndFadeOut(flight, flightDuration, fadePortion); _boardSprites.remove(cards[i]); } } // documentation inherited protected void paintBehind (Graphics2D gfx, Rectangle dirtyRect) { gfx.setColor(DEFAULT_BACKGROUND); gfx.fill(dirtyRect); super.paintBehind(gfx, dirtyRect); } /** * Flies a set of cards from the board into the ether through an * intermediate point. * * @param cards the cards to remove from the board * @param dest1 the first point to fly the cards to * @param dest2 the final destination of the cards * @param flightDuration the duration of the cards' flight * @param fadePortion the amount of time to spend fading out as a * proportion of the flight duration */ public void flyFromBoard (CardSprite[] cards, Point dest1, Point dest2, long flightDuration, float fadePortion) { for (int i = 0; i < cards.length; i++) { PathSequence flight = new PathSequence( new LinePath(dest1, flightDuration/2), new LinePath(dest1, dest2, flightDuration/2)); cards[i].addSpriteObserver(_pathEndRemover); cards[i].moveAndFadeOut(flight, flightDuration, fadePortion); _boardSprites.remove(cards[i]); } } /** * Returns the first card sprite in the specified list that represents * the specified card, or null if there is no such sprite in the list. */ protected CardSprite getCardSprite (ArrayList list, Card card) { for (int i = 0; i < list.size(); i++) { CardSprite cs = (CardSprite)list.get(i); if (card.equals(cs.getCard())) { return cs; } } return null; } /** * Expands or collapses the hand to accommodate new cards or cover the * space left by removed cards. Skips unmanaged sprites. Clears out * any selected cards. * * @param adjustDuration the amount of time to spend settling the cards * into their new locations * @param updateLayers whether or not to update the layers of the cards */ protected void adjustHand (long adjustDuration, boolean updateLayers) { // clear out selected cards clearHandSelection(); // Sort the hand QuickSort.sort(_handSprites); // Move each card to its proper position (and, optionally, layer) int size = _handSprites.size(); for (int i = 0; i < size; i++) { CardSprite cs = (CardSprite)_handSprites.get(i); if (!isManaged(cs)) { continue; } if (updateLayers) { removeSprite(cs); cs.setRenderOrder(i); addSprite(cs); } LinePath adjust = new LinePath(new Point(getHandX(size, i), _handLocation.y), adjustDuration); cs.move(adjust); } } /** * Removes a card from the hand, deselecting it if selected. */ protected void removeFromHand (CardSprite card) { if (_selectedHandSprites.contains(card)) { deselectHandSprite(card); } _handSprites.remove(card); } /** * Updates the offsets of all the cards in the hand. If there is only * one selectable card, that card will always be raised slightly. */ protected void updateHandOffsets () { int size = _handSprites.size(); for (int i = 0; i < size; i++) { CardSprite cs = (CardSprite)_handSprites.get(i); if (cs.getPath() == null) { cs.setLocation(cs.getX(), getHandY(cs)); } } } /** * Given the location and spacing of the hand, returns the x location of * the card at the specified index within a hand of the specified size. */ protected int getHandX (int size, int idx) { // get the card width from the image if not yet known if (_cardWidth == 0) { _cardWidth = getCardBackImage().getWidth(); } // first compute the width of the entire hand, then use that to // determine the centered location int width = (size - 1) * _handSpacing + _cardWidth; return (_handLocation.x - width/2) + idx * _handSpacing; } /** * Determines the y location of the specified card sprite, given its * selection state. */ protected int getHandY (CardSprite sprite) { if (_selectedHandSprites.contains(sprite)) { return _handLocation.y - _selectedCardOffset; } else if (isSelectable(sprite) && (sprite == _activeCardSprite || isOnlySelectable(sprite))) { return _handLocation.y - _selectableCardOffset; } else { return _handLocation.y; } } /** * Given the current selection mode and predicate, determines if the * specified sprite is selectable. */ protected boolean isSelectable (CardSprite sprite) { return _handSelectionMode != NONE && (_handSelectionPredicate == null || _handSelectionPredicate.evaluate(sprite)); } /** * Determines whether the specified sprite is the only selectable sprite * in the hand according to the selection predicate. */ protected boolean isOnlySelectable (CardSprite sprite) { // if there's no predicate, last remaining card is only selectable if (_handSelectionPredicate == null) { return _handSprites.size() == 1 && _handSprites.contains(sprite); } // otherwise, look for a sprite that fits the predicate and isn't the // parameter int size = _handSprites.size(); for (int i = 0; i < size; i++) { CardSprite cs = (CardSprite)_handSprites.get(i); if (cs != sprite && _handSelectionPredicate.evaluate(cs)) { return false; } } return true; } /** * Lowers all board sprites so that they are rendered at or below the * specified layer. */ protected void lowerBoardSprites (int layer) { // see if they're already lower int highest = getHighestBoardLayer(); if (highest <= layer) { return; } // lower them just enough int size = _boardSprites.size(), adjustment = layer - highest; for (int i = 0; i < size; i++) { CardSprite cs = (CardSprite)_boardSprites.get(i); removeSprite(cs); cs.setRenderOrder(cs.getRenderOrder() + adjustment); addSprite(cs); } } /** * Returns the highest render order of any sprite on the board. */ protected int getHighestBoardLayer () { // must be at least zero, because that's the lowest number we can push // the sprites down to (the layer of the first card in the hand) int size = _boardSprites.size(), highest = 0; for (int i = 0; i < size; i++) { highest = Math.max(highest, ((CardSprite)_boardSprites.get(i)).getRenderOrder()); } return highest; } /** * Clears an array of sprites from the specified list and from the panel. */ protected void clearSprites (ArrayList sprites) { for (Iterator it = sprites.iterator(); it.hasNext(); ) { removeSprite((CardSprite)it.next()); it.remove(); } } /** The width of the playing cards. */ protected int _cardWidth; /** The currently active card sprite (the one that the mouse is over). */ protected CardSprite _activeCardSprite; /** The sprites for cards within the hand. */ protected ArrayList _handSprites = new ArrayList(); /** The sprites for cards within the hand that have been selected. */ protected ArrayList _selectedHandSprites = new ArrayList(); /** The current selection mode for the hand. */ protected int _handSelectionMode; /** The predicate that determines which cards are selectable (if null, all * cards are selectable). */ protected CardSpritePredicate _handSelectionPredicate; /** Observers of hand card selection/deselection. */ protected ObserverList _handSelectionObservers = new ObserverList( ObserverList.FAST_UNSAFE_NOTIFY); /** The location of the center of the hand's upper edge. */ protected Point _handLocation = new Point(); /** The horizontal distance between cards in the hand. */ protected int _handSpacing; /** The vertical distance to offset cards that are selectable. */ protected int _selectableCardOffset; /** The vertical distance to offset cards that are selected. */ protected int _selectedCardOffset; /** The sprites for cards on the board. */ protected ArrayList _boardSprites = new ArrayList(); /** The hand sprite observer instance. */ protected HandSpriteObserver _handSpriteObserver = new HandSpriteObserver(); /** A path observer that removes the sprite at the end of its path. */ protected PathAdapter _pathEndRemover = new PathAdapter() { public void pathCompleted (Sprite sprite, Path path, long when) { removeSprite(sprite); } }; /** Listens for interactions with cards in hand. */ protected class HandSpriteObserver extends PathAdapter implements CardSpriteObserver { public void pathCompleted (Sprite sprite, Path path, long when) { maybeUpdateOffset((CardSprite)sprite); } public void cardSpriteClicked (CardSprite sprite, MouseEvent me) { // select, deselect, or play card in hand if (_selectedHandSprites.contains(sprite) && _handSelectionMode != NONE) { deselectHandSprite(sprite); } else if (_handSprites.contains(sprite) && isSelectable(sprite)) { if (_handSelectionMode == PLAY_SINGLE) { playHandSprite(sprite); } else { selectHandSprite(sprite); } } } public void cardSpriteEntered (CardSprite sprite, MouseEvent me) { maybeUpdateOffset(sprite); } public void cardSpriteExited (CardSprite sprite, MouseEvent me) { maybeUpdateOffset(sprite); } public void cardSpriteDragged (CardSprite sprite, MouseEvent me) {} protected void maybeUpdateOffset (CardSprite sprite) { // update the offset if it's in the hand and isn't moving if (_handSprites.contains(sprite) && sprite.getPath() == null) { sprite.setLocation(sprite.getX(), getHandY(sprite)); } } }; /** Listens for mouse interactions with cards. */ protected class CardListener extends MouseInputAdapter { public void mousePressed (MouseEvent me) { if (_activeCardSprite != null && isManaged(_activeCardSprite)) { _handleX = _activeCardSprite.getX() - me.getX(); _handleY = _activeCardSprite.getY() - me.getY(); _hasBeenDragged = false; } } public void mouseReleased (MouseEvent me) { if (_activeCardSprite != null && isManaged(_activeCardSprite) && _hasBeenDragged) { _activeCardSprite.queueNotification( new CardSpriteDraggedOp(_activeCardSprite, me) ); } } public void mouseClicked (MouseEvent me) { if (_activeCardSprite != null && isManaged(_activeCardSprite)) { _activeCardSprite.queueNotification( new CardSpriteClickedOp(_activeCardSprite, me) ); } } public void mouseMoved (MouseEvent me) { Sprite newHighestHit = _spritemgr.getHighestHitSprite( me.getX(), me.getY()); CardSprite newActiveCardSprite = (newHighestHit instanceof CardSprite ? (CardSprite)newHighestHit : null); if (_activeCardSprite != newActiveCardSprite) { if (_activeCardSprite != null && isManaged(_activeCardSprite)) { _activeCardSprite.queueNotification( new CardSpriteExitedOp(_activeCardSprite, me) ); } _activeCardSprite = newActiveCardSprite; if (_activeCardSprite != null) { _activeCardSprite.queueNotification( new CardSpriteEnteredOp(_activeCardSprite, me) ); } } } public void mouseDragged (MouseEvent me) { if (_activeCardSprite != null && isManaged(_activeCardSprite) && _activeCardSprite.isDraggable()) { _activeCardSprite.setLocation( me.getX() + _handleX, me.getY() + _handleY ); _hasBeenDragged = true; } else { mouseMoved(me); } } protected int _handleX, _handleY; protected boolean _hasBeenDragged; } /** Calls CardSpriteObserver.cardSpriteClicked. */ protected static class CardSpriteClickedOp implements ObserverList.ObserverOp { public CardSpriteClickedOp (CardSprite sprite, MouseEvent me) { _sprite = sprite; _me = me; } public boolean apply (Object observer) { if (observer instanceof CardSpriteObserver) { ((CardSpriteObserver)observer).cardSpriteClicked(_sprite, _me); } return true; } protected CardSprite _sprite; protected MouseEvent _me; } /** Calls CardSpriteObserver.cardSpriteEntered. */ protected static class CardSpriteEnteredOp implements ObserverList.ObserverOp { public CardSpriteEnteredOp (CardSprite sprite, MouseEvent me) { _sprite = sprite; _me = me; } public boolean apply (Object observer) { if (observer instanceof CardSpriteObserver) { ((CardSpriteObserver)observer).cardSpriteEntered(_sprite, _me); } return true; } protected CardSprite _sprite; protected MouseEvent _me; } /** Calls CardSpriteObserver.cardSpriteExited. */ protected static class CardSpriteExitedOp implements ObserverList.ObserverOp { public CardSpriteExitedOp (CardSprite sprite, MouseEvent me) { _sprite = sprite; _me = me; } public boolean apply (Object observer) { if (observer instanceof CardSpriteObserver) { ((CardSpriteObserver)observer).cardSpriteExited(_sprite, _me); } return true; } protected CardSprite _sprite; protected MouseEvent _me; } /** Calls CardSpriteObserver.cardSpriteDragged. */ protected static class CardSpriteDraggedOp implements ObserverList.ObserverOp { public CardSpriteDraggedOp (CardSprite sprite, MouseEvent me) { _sprite = sprite; _me = me; } public boolean apply (Object observer) { if (observer instanceof CardSpriteObserver) { ((CardSpriteObserver)observer).cardSpriteDragged(_sprite, _me); } return true; } protected CardSprite _sprite; protected MouseEvent _me; } /** A nice default green card table background color. */ protected static Color DEFAULT_BACKGROUND = new Color(0x326D36); }
package Engine; import java.util.ArrayList; import java.util.List; public class Hand { private List<Card> cards = new ArrayList<Card>(); // Constructor public Hand(ArrayList<Card> cards) { this.cards = cards; } // Called when player wants to hit public void addCard(Card card) { cards.add(card); } // Returns an array of length 1 or 2 containing possible values of the hand public int[] getValues() { int val0 = 0; // Hand value assuming first ace is valued at 1 int val1 = 0; // Hand value assuming first ace is valued at 11 boolean hasAce = false; int[] cardValue; for(int i=0; i<cards.size(); i++) { cardValue = cards.get(i).getValues(); // If Ace if(cardValue.length == 2) { // If Ace already exists in hand, just add 1 if(hasAce) { val0 += cardValue[0]; val1 += cardValue[0]; } else { val0 += cardValue[0]; val1 += cardValue[1]; hasAce = true; } } // Otherwise single-value cards (2-10, J, Q, K) else { val0 += cardValue[0]; val1 += cardValue[0]; } } if(val0 == val1) { return new int[] { val0 }; } else { return new int[] {val0, val1}; } } // TODO public Hand split() { if(cards.size() != 2) { return null; } Hand[] newHands = new Hand[2]; ArrayList<Card> cardForHand0 = new ArrayList<Card>(); ArrayList<Card> cardForHand1 = new ArrayList<Card>(); } }
// $Id: Communicator.java,v 1.30 2003/06/05 00:29:45 ray Exp $ package com.threerings.presents.client; import java.io.EOFException; import java.io.IOException; import java.io.InterruptedIOException; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.net.InetAddress; import java.net.InetSocketAddress; import com.samskivert.io.NestableIOException; import com.samskivert.util.Interval; import com.samskivert.util.IntervalManager; import com.samskivert.util.LoopingThread; import com.samskivert.util.Queue; import com.samskivert.util.RuntimeAdjust; import com.threerings.io.FramedInputStream; import com.threerings.io.FramingOutputStream; import com.threerings.io.ObjectInputStream; import com.threerings.io.ObjectOutputStream; import com.threerings.presents.Log; import com.threerings.presents.dobj.DObjectManager; import com.threerings.presents.net.AuthRequest; import com.threerings.presents.net.AuthResponse; import com.threerings.presents.net.AuthResponseData; import com.threerings.presents.net.DownstreamMessage; import com.threerings.presents.net.ForwardEventRequest; import com.threerings.presents.net.LogoffRequest; import com.threerings.presents.net.PingRequest; import com.threerings.presents.net.SubscribeRequest; import com.threerings.presents.net.UnsubscribeRequest; import com.threerings.presents.net.UpstreamMessage; /** * The client performs all network I/O on separate threads (one for * reading and one for writing). The communicator class encapsulates that * functionality. * * <pre> * Logon synopsis: * * Client.logon(): * - Calls Communicator.start() * Communicator.start(): * - spawn Reader thread * Reader.run(): * { - connect * - authenticate * } if either fail, notify observers of failed logon * - start writer thread * - notify observers that we're logged on * - read loop * Writer.run(): * - write loop * </pre> */ public class Communicator { /** * Creates a new communicator instance which is associated with the * supplied client. */ public Communicator (Client client) { _client = client; } /** * Returns the distributed object manager in effect for this session. * This instance is only valid while the client is connected to the * server. */ public DObjectManager getDObjectManager () { return _omgr; } /** * Logs on to the server and initiates our full-duplex message * exchange. */ public void logon () { // make sure things are copacetic if (_reader != null) { throw new RuntimeException("Communicator already started."); } // start up the reader thread. it will connect to the server and // start up the writer thread if everything went successfully _reader = new Reader(); _reader.start(); // register an interval to send pings when appropriate _piid = IntervalManager.register(new Interval() { public void intervalExpired (int id, Object arg) { if (checkNeedsPing()) { postMessage(new PingRequest()); } } }, 5000L, null, true); } /** * Delivers a logoff notification to the server and shuts down the * network connection. Also causes all communication threads to * terminate. */ public synchronized void logoff () { // if our socket is already closed, we've already taken care of // this business if (_channel == null) { return; } stopPingInterval(); // post a logoff message postMessage(new LogoffRequest()); // let our reader and writer know that it's time to go if (_reader != null) { // if logoff() is being called by the client as part of a // normal shutdown, this will cause the reader thread to be // interrupted and shutdown gracefully. if logoff is being // called by the reader thread as a result of a failed socket, // it won't interrupt itself as it is already shutting down // gracefully. if the JVM is buggy and calling interrupt() on // a thread that is blocked on a socket doesn't wake it up, // then when we close() the socket a bit further down, we have // another chance that the reader thread will wake up; this // time slightly less gracefully because it will think there's // a network error when in fact we're just shutting down, but // at least it will cleanly exit _reader.shutdown(); } if (_writer != null) { // shutting down the writer thread is simpler because we can // post a termination message on the queue and be sure that it // will receive it. when the writer thread has delivered our // logoff request and exited, we will complete the logoff // process by closing our socket and invoking the // clientDidLogoff callback _writer.shutdown(); } } /** * Queues up the specified message for delivery upstream. */ public void postMessage (UpstreamMessage msg) { // simply append the message to the queue _msgq.append(msg); } /** * Callback called by the reader when the authentication process * completes successfully. Here we extract the bootstrap information * for the client and start up the writer thread to manage the other * half of our bi-directional message stream. */ protected synchronized void logonSucceeded (AuthResponseData data) { Log.debug("Logon succeeded: " + data); // create our distributed object manager _omgr = new ClientDObjectMgr(this, _client); // create a new writer thread and start it up if (_writer != null) { throw new RuntimeException("Writer already started!?"); } _writer = new Writer(); _writer.start(); // wait for the bootstrap notification before we claim that we're // actually logged on } /** * Callback called by the reader or writer thread when something goes * awry with our socket connection to the server. */ protected synchronized void connectionFailed (IOException ioe) { // make sure the socket isn't already closed down (meaning we've // already dealt with the failed connection) if (_channel == null) { return; } Log.info("Connection failed: " + ioe); Log.logStackTrace(ioe); // let the client know that things went south _client.notifyObservers(Client.CLIENT_CONNECTION_FAILED, ioe); // and request that we go through the motions of logging off logoff(); } /** * Callback called by the reader if the server closes the other end of * the connection. */ protected synchronized void connectionClosed () { // make sure the socket isn't already closed down (meaning we've // already dealt with the closed connection) if (_channel == null) { return; } Log.debug("Connection closed."); // now do the whole logoff thing logoff(); } /** * Callback called by the reader thread when it goes away. */ protected synchronized void readerDidExit () { // clear out our reader reference _reader = null; // in case we haven't already done it. stopPingInterval(); if (_writer == null) { // there's no writer during authentication, so we may be // responsible for closing the socket channel closeChannel(); // let the client know when we finally go away _client.communicatorDidExit(); } Log.debug("Reader thread exited."); } /** * Callback called by the writer thread when it goes away. */ protected synchronized void writerDidExit () { // clear out our writer reference _writer = null; Log.debug("Writer thread exited."); // let the client observers know that we're logged off _client.notifyObservers(Client.CLIENT_DID_LOGOFF, null); // now that the writer thread has gone away, we can safely close // our socket and let the client know that the logoff process has // completed closeChannel(); // let the client know when we finally go away if (_reader == null) { _client.communicatorDidExit(); } } /** * Closes the socket channel that we have open to the server. Called * by either {@link #readerDidExit} or {@link #writerDidExit} * whichever is called last. */ protected void closeChannel () { if (_channel != null) { Log.debug("Closing socket channel."); try { _channel.close(); } catch (IOException ioe) { Log.warning("Error closing failed socket: " + ioe); } _channel = null; // clear these out because they are probably large and in charge _oin = null; _oout = null; } } /** * Writes the supplied message to the socket. */ protected void sendMessage (UpstreamMessage msg) throws IOException { if (_logMessages.getValue()) { Log.info("SEND " + msg); } // first we write the message so that we can measure it's length _oout.writeObject(msg); _oout.flush(); // then write the framed message to actual output stream try { ByteBuffer buffer = _fout.frameAndReturnBuffer(); int wrote = _channel.write(buffer); if (wrote != buffer.limit()) { Log.warning("Aiya! Couldn't write entire message [msg=" + msg + ", size=" + buffer.limit() + ", wrote=" + wrote + "]."); // } else { // Log.info("Wrote " + wrote + " bytes."); } } finally { _fout.resetFrame(); } // make a note of our most recent write time updateWriteStamp(); } /** * Makes a note of the time at which we last communicated with the * server. */ protected synchronized void updateWriteStamp () { _lastWrite = System.currentTimeMillis(); } /** * Checks to see if we need to send a ping to the server because we * haven't communicated in sufficiently long. */ protected synchronized boolean checkNeedsPing () { long now = System.currentTimeMillis(); return (now - _lastWrite > PingRequest.PING_INTERVAL); } /** * Stops our ping interval. */ protected void stopPingInterval () { if (_piid != -1) { IntervalManager.remove(_piid); _piid = -1; } } /** * Reads a new message from the socket (blocking until a message has * arrived). */ protected DownstreamMessage receiveMessage () throws IOException { // read in the next message frame (readFrame() can return false // meaning it only read part of the frame from the network, in // which case we simply call it again because we can't do anything // until it has a whole frame; it will throw an exception if it // hits EOF or if something goes awry) while (!_fin.readFrame(_channel)); try { DownstreamMessage msg = (DownstreamMessage)_oin.readObject(); if (_logMessages.getValue()) { Log.info("RECEIVE " + msg); } return msg; } catch (ClassNotFoundException cnfe) { throw new NestableIOException( "Unable to decode incoming message.", cnfe); } } /** * Callback called by the reader thread when it has parsed a new * message from the socket and wishes to have it processed. */ protected void processMessage (DownstreamMessage msg) { // post this message to the dobjmgr queue _omgr.processMessage(msg); } /** * The reader encapsulates the authentication and message reading * process. It calls back to the <code>Communicator</code> class to do * things, but the general flow of the reader thread is encapsulated * in this class. */ protected class Reader extends LoopingThread { protected void willStart () { // first we connect and authenticate with the server try { // connect to the server connect(); // then authenticate logon(); } catch (Exception e) { Log.debug("Logon failed: " + e); Log.logStackTrace(e); // let the observers know that we've failed _client.notifyObservers(Client.CLIENT_FAILED_TO_LOGON, e); // and terminate our communicator thread shutdown(); } } protected void connect () throws IOException { // if we're already connected, we freak out if (_channel != null) { throw new IOException("Already connected."); } // look up the address of the target server InetAddress host = InetAddress.getByName(_client.getHostname()); int port = _client.getPort(); // establish a socket connection to said server Log.debug("Connecting [host=" + host + ", port=" + port + "]."); _channel = SocketChannel.open(new InetSocketAddress(host, port)); _channel.configureBlocking(true); // our messages are framed (preceded by their length), so we // use these helper streams to manage the framing _fin = new FramedInputStream(); _fout = new FramingOutputStream(); // create our object input and output streams _oin = new ObjectInputStream(_fin); _oout = new ObjectOutputStream(_fout); } protected void logon () throws IOException, LogonException { // construct an auth request and send it AuthRequest req = new AuthRequest(_client.getCredentials(), _client.getVersion()); sendMessage(req); // now wait for the auth response Log.debug("Waiting for auth response."); AuthResponse rsp = (AuthResponse)receiveMessage(); AuthResponseData data = rsp.getData(); Log.debug("Got auth response: " + data); // if the auth request failed, we want to let the communicator // know by throwing a logon exception if (!data.code.equals(AuthResponseData.SUCCESS)) { throw new LogonException(data.code); } // we're all clear. let the communicator know that we're in logonSucceeded(data); } // now that we're authenticated, we manage the reading // half of things by continuously reading messages from // the socket and processing them protected void iterate () { DownstreamMessage msg = null; try { // read the next message from the socket msg = receiveMessage(); // process the message processMessage(msg); } catch (InterruptedIOException iioe) { // somebody set up us the bomb! we've been interrupted // which means that we're being shut down, so we just // report it and return from iterate() like a good monkey Log.debug("Reader thread woken up in time to die."); } catch (EOFException eofe) { // let the communicator know that our connection was // closed connectionClosed(); // and shut ourselves down shutdown(); } catch (IOException ioe) { // let the communicator know that our connection failed connectionFailed(ioe); // and shut ourselves down shutdown(); } catch (Exception e) { Log.warning("Error processing message [msg=" + msg + ", error=" + e + "]."); } } protected void handleIterateFailure (Exception e) { Log.warning("Uncaught exception it reader thread."); Log.logStackTrace(e); } protected void didShutdown () { // let the communicator know when we finally go away readerDidExit(); } protected void kick () { // we want to interrupt the reader thread as it may be blocked // listening to the socket; this is only called if the reader // thread doesn't shut itself down // interrupt(); } } /** * The writer encapsulates the message writing process. It calls back * to the <code>Communicator</code> class to do things, but the * general flow of the writer thread is encapsulated in this class. */ protected class Writer extends LoopingThread { protected void iterate () { // fetch the next message from the queue UpstreamMessage msg = (UpstreamMessage)_msgq.get(); // if this is a termination message, we're being // requested to exit, so we want to bail now rather // than continuing if (msg instanceof TerminationMessage) { return; } try { // write the message out the socket sendMessage(msg); } catch (IOException ioe) { // let the communicator know if we have any // problems connectionFailed(ioe); // and bail shutdown(); } } protected void handleIterateFailure (Exception e) { Log.warning("Uncaught exception it writer thread."); Log.logStackTrace(e); } protected void didShutdown () { writerDidExit(); } protected void kick () { // post a bogus message to the outgoing queue to ensure that // the writer thread notices that it's time to go postMessage(new TerminationMessage()); } } /** This is used to terminate the writer thread. */ protected static class TerminationMessage extends UpstreamMessage { } protected Client _client; protected Reader _reader; protected Writer _writer; protected SocketChannel _channel; protected Queue _msgq = new Queue(); protected int _piid == -1; protected long _lastWrite; /** We use this to frame our upstream messages. */ protected FramingOutputStream _fout; protected ObjectOutputStream _oout; /** We use this to frame our downstream messages. */ protected FramedInputStream _fin; protected ObjectInputStream _oin; protected ClientDObjectMgr _omgr; /** Used to control low-level message logging. */ protected static RuntimeAdjust.BooleanAdjust _logMessages = new RuntimeAdjust.BooleanAdjust( "Toggles whether or not all sent and received low-level " + "network events are logged.", "narya.presents.log_events", PresentsPrefs.config, false); }
// Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.presents.util; import java.util.logging.Level; import com.samskivert.util.Invoker; import com.threerings.presents.client.InvocationService; import com.threerings.presents.data.InvocationCodes; import com.threerings.presents.server.InvocationException; import static com.threerings.presents.Log.log; /** * Simplifies a common pattern which is to post an {@link Invoker} unit which does some database * operation and then calls back to an {@link InvocationService.InvocationListener} of some * sort. If the database operation fails, the error will be logged and the result listener will be * replied to with {@link InvocationCodes#INTERNAL_ERROR}. */ public abstract class PersistingUnit extends Invoker.Unit { public PersistingUnit (InvocationService.InvocationListener listener) { this("UnknownPersistingUnit", listener); } public PersistingUnit (String name, InvocationService.InvocationListener listener) { super(name); _listener = listener; } /** * This method is where the unit performs its persistent actions. Any persistence exception * will be caught and logged along with the output from {@link #getFailureMessage}, if any. */ public abstract void invokePersistent () throws Exception; /** * Handles the success case, which by default is to do nothing. */ public void handleSuccess () { } /** * Handles the failure case by logging the error and reporting an internal error to the * listener. */ public void handleFailure (Exception error) { if (error instanceof InvocationException) { _listener.requestFailed(error.getMessage()); } else { log.log(Level.WARNING, getFailureMessage(), error); _listener.requestFailed(InvocationCodes.INTERNAL_ERROR); } } @Override // from Invoker.Unit public boolean invoke () { try { invokePersistent(); } catch (Exception pe) { _error = pe; } return true; } @Override // from Invoker.Unit public void handleResult () { if (_error != null) { handleFailure(_error); } else { handleSuccess(); } } /** * Provides a custom failure message in the event that the persistent action fails. This will * be logged along with the exception. */ protected String getFailureMessage () { return this + " failed."; } protected InvocationService.InvocationListener _listener; protected Exception _error; }
package fr.paris.lutece.portal.service.init; /** * this class provides informations about application version */ public final class AppInfo { /** Defines the current version of the application */ private static final String APP_VERSION = "7.0.5-SNAPSHOT"; static final String LUTECE_BANNER_VERSION = "\n _ _ _ _____ ___ ___ ___ ____\n" + "| | | | | | |_ _| | __| / __| | __| |__ |\n" + "| |__ | |_| | | | | _| | (__ | _| / / \n" + "|____| \\___/ |_| |___| \\___| |___| /_/ "; static final String LUTECE_BANNER_SERVER = "\n _ _ _ _____ ___ ___ ___ ___ ___ ___ __ __ ___ ___ \n" + "| | | | | | |_ _| | __| / __| | __| / __| | __| | _ \\ \\ \\ / / | __| | _ \\\n" + "| |__ | |_| | | | | _| | (__ | _| \\__ \\ | _| | / \\ V / | _| | /\n" + "|____| \\___/ |_| |___| \\___| |___| |___/ |___| |_|_\\ \\_/ |___| |_|_\\"; /** * Creates a new AppInfo object. */ private AppInfo( ) { } /** * Returns the current version of the application * * @return APP_VERSION The current version of the application */ public static String getVersion( ) { return APP_VERSION; } }
package net.kaleidos.hibernate.usertype; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.apache.commons.lang.ObjectUtils; import org.hibernate.HibernateException; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.usertype.UserType; import java.io.Serializable; import java.lang.reflect.Type; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.HashMap; import java.util.Map; public class JsonMapType implements UserType { public static int SQLTYPE = 90021; private final Type userType = Map.class; private final Gson gson = new GsonBuilder().serializeNulls().create(); @Override public int[] sqlTypes() { return new int[]{SQLTYPE}; } @Override public Class<?> returnedClass() { return userType.getClass(); } @Override public boolean equals(Object x, Object y) throws HibernateException { return ObjectUtils.equals(x, y); } @Override public int hashCode(Object x) throws HibernateException { return x == null ? 0 : x.hashCode(); } @Override public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException { String jsonString = rs.getString(names[0]); return gson.fromJson(jsonString, userType); } @Override public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException { if (value == null) { st.setNull(index, Types.OTHER); } else { st.setObject(index, gson.toJson(value, userType), Types.OTHER); } } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public Object deepCopy(Object value) throws HibernateException { if (value == null) { return null; } Map m = (Map) value; return new HashMap(m); } @Override public boolean isMutable() { return true; } @Override public Serializable disassemble(Object value) throws HibernateException { return gson.toJson(value, userType); } @Override public Object assemble(Serializable cached, Object owner) throws HibernateException { return gson.fromJson((String) cached, userType); } @Override public Object replace(Object original, Object target, Object owner) throws HibernateException { return original; } }
//This library is free software; you can redistribute it and/or //modify it under the terms of the GNU Lesser General Public //This library is distributed in the hope that it will be useful, //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //You should have received a copy of the GNU Lesser General Public //Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. package opennlp.tools.coref.resolver; import java.io.DataInputStream; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import opennlp.maxent.Event; import opennlp.maxent.GIS; import opennlp.maxent.MaxentModel; import opennlp.maxent.io.BinaryGISModelReader; import opennlp.maxent.io.SuffixSensitiveGISModelReader; import opennlp.maxent.io.SuffixSensitiveGISModelWriter; import opennlp.tools.coref.DiscourseEntity; import opennlp.tools.coref.DiscourseModel; import opennlp.tools.coref.Linker; import opennlp.tools.coref.mention.MentionContext; import opennlp.tools.coref.mention.Parse; import opennlp.tools.coref.sim.GenderEnum; import opennlp.tools.coref.sim.NumberEnum; import opennlp.tools.coref.sim.TestSimilarityModel; import opennlp.tools.util.CollectionEventStream; /** * Provides common functionality used by classes which implement the {@link Resolver} class and use maximum entropy models to make resolution decisions. */ public abstract class MaxentResolver extends AbstractResolver { /** Outcomes when two mentions are coreferent. */ public static final String SAME = "same"; /** Outcome when two mentions are not corefernt. */ public static final String DIFF = "diff"; /** Default feature value. */ public static final String DEFAULT = "default"; private static final Pattern ENDS_WITH_PERIOD = Pattern.compile("\\.$"); private static final double MIN_SIM_PROB = 0.60; private static final String SIM_COMPATIBLE = "sim.compatible"; private static final String SIM_INCOMPATIBLE = "sim.incompatible"; private static final String SIM_UNKNOWN = "sim.unknown"; private static final String NUM_COMPATIBLE = "num.compatible"; private static final String NUM_INCOMPATIBLE = "num.incompatible"; private static final String NUM_UNKNOWN = "num.unknown"; private static final String GEN_COMPATIBLE = "gen.compatible"; private static final String GEN_INCOMPATIBLE = "gen.incompatible"; private static final String GEN_UNKNOWN = "gen.unknown"; private static boolean debugOn=false; private static boolean loadAsResource=false; private String modelName; private MaxentModel model; private double[] candProbs; private int sameIndex; private ResolverMode mode; private List events; /** When true, this designates that the resolver should use the first referent encountered which it * more preferable than non-reference. When false all non-excluded referents within this resolvers range * are considered. */ protected boolean preferFirstReferent; /** When true, this designates that training should consist of a single positive and a single negitive example * (when possible) for each mention. */ protected boolean pairedSampleSelection; /** When true, this designates that the same maximum entropy model should be used non-reference * events (the pairing of a mention and the "null" reference) as is used for potentially * referential pairs. When false a seperate model is created for these events. */ protected boolean useSameModelForNonRef; private static TestSimilarityModel simModel = null; /** The model for computing non-referential probabilities. */ protected NonReferentialResolver nonReferentialResolver; private static final String modelExtension = ".bin.gz"; /** * Creates a maximum-entropy-based resolver which will look the specified number of entities back for a referent. * This constructor is only used for unit testing. * @param numberOfEntitiesBack * @param preferFirstReferent */ protected MaxentResolver(int numberOfEntitiesBack, boolean preferFirstReferent) { super(numberOfEntitiesBack); this.preferFirstReferent = preferFirstReferent; } /** * Creates a maximum-entropy-based resolver with the specified model name, using the * specified mode, which will look the specified number of entities back for a referent and * prefer the first referent if specified. * @param modelDirectory The name of the directory where the resover models are stored. * @param name The name of the file where this model will be read or written. * @param mode The mode this resolver is being using in (training, testing). * @param numberOfEntitiesBack The number of entities back in the text that this resolver will look * for a referent. * @param preferFirstReferent Set to true if the resolver should prefer the first referent which is more * likly than non-reference. This only affects testing. * @param nonReferentialResolver Determines how likly it is that this entity is non-referential. * @throws IOException If the model file is not found or can not be written to. */ public MaxentResolver(String modelDirectory, String name, ResolverMode mode, int numberOfEntitiesBack, boolean preferFirstReferent, NonReferentialResolver nonReferentialResolver) throws IOException { super(numberOfEntitiesBack); this.preferFirstReferent = preferFirstReferent; this.nonReferentialResolver = nonReferentialResolver; this.mode = mode; this.modelName = modelDirectory+"/"+name; if (ResolverMode.TEST == this.mode) { if (loadAsResource) { model = (new BinaryGISModelReader(new DataInputStream(this.getClass().getResourceAsStream(modelName+modelExtension)))).getModel(); } else { model = (new SuffixSensitiveGISModelReader(new File(modelName+modelExtension))).getModel(); } sameIndex = model.getIndex(SAME); } else if (ResolverMode.TRAIN == this.mode) { events = new ArrayList(); } else { System.err.println("Unknown mode: " + this.mode); } //add one for non-referent possibility candProbs = new double[getNumEntities() + 1]; } /** * Creates a maximum-entropy-based resolver with the specified model name, using the * specified mode, which will look the specified number of entities back for a referent. * @param modelDirectory The name of the directory where the resover models are stored. * @param modelName The name of the file where this model will be read or written. * @param mode The mode this resolver is being using in (training, testing). * @param numberEntitiesBack The number of entities back in the text that this resolver will look * for a referent. * @throws IOException If the model file is not found or can not be written to. */ public MaxentResolver(String modelDirectory, String modelName, ResolverMode mode, int numberEntitiesBack) throws IOException { this(modelDirectory, modelName, mode, numberEntitiesBack, false); } public MaxentResolver(String modelDirectory, String modelName, ResolverMode mode, int numberEntitiesBack, NonReferentialResolver nonReferentialResolver) throws IOException { this(modelDirectory, modelName, mode, numberEntitiesBack, false,nonReferentialResolver); } public MaxentResolver(String modelDirectory, String modelName, ResolverMode mode, int numberEntitiesBack, boolean preferFirstReferent) throws IOException { //this(projectName, modelName, mode, numberEntitiesBack, preferFirstReferent, SingletonNonReferentialResolver.getInstance(projectName,mode)); this(modelDirectory, modelName, mode, numberEntitiesBack, preferFirstReferent, new DefaultNonReferentialResolver(modelDirectory, modelName, mode)); } public MaxentResolver(String modelDirectory, String modelName, ResolverMode mode, int numberEntitiesBack, boolean preferFirstReferent, double nonReferentialProbability) throws IOException { //this(projectName, modelName, mode, numberEntitiesBack, preferFirstReferent, SingletonNonReferentialResolver.getInstance(projectName,mode)); this(modelDirectory, modelName, mode, numberEntitiesBack, preferFirstReferent, new FixedNonReferentialResolver(nonReferentialProbability)); } /** * Specifies whether the models should be loaded from a resource. * @param lar boolean which if true indicates that the model should be loaded as a resource. */ public static void loadAsResource(boolean lar) { loadAsResource = lar; } /** * Returns whether the models should be loaded from a file or from a resource. * @return whether the models should be loaded from a file or from a resource. */ public static boolean loadAsResource() { return loadAsResource; } public DiscourseEntity resolve(MentionContext ec, DiscourseModel dm) { DiscourseEntity de; int ei = 0; double nonReferentialProbability = nonReferentialResolver.getNonReferentialProbability(ec); if (debugOn) { System.err.println(this +".resolve: " + ec.toText() + " -> " + "null "+nonReferentialProbability); } for (; ei < getNumEntities(dm); ei++) { de = (DiscourseEntity) dm.getEntity(ei); if (outOfRange(ec, de)) { break; } if (excluded(ec, de)) { candProbs[ei] = 0; if (debugOn) { System.err.println("excluded "+this +".resolve: " + ec.toText() + " -> " + de + " " + candProbs[ei]); } } else { List lfeatures = getFeatures(ec, de); String[] features = (String[]) lfeatures.toArray(new String[lfeatures.size()]); try { candProbs[ei] = model.eval(features)[sameIndex]; } catch (ArrayIndexOutOfBoundsException e) { candProbs[ei] = 0; } if (debugOn) { System.err.println(this +".resolve: " + ec.toText() + " -> " + de + " ("+ec.getGender()+","+de.getGender()+") " + candProbs[ei] + " " + lfeatures); } } if (preferFirstReferent && candProbs[ei] > nonReferentialProbability) { ei++; //update for nonRef assignment break; } } candProbs[ei] = nonReferentialProbability; // find max int maxCandIndex = 0; for (int k = 1; k <= ei; k++) { if (candProbs[k] > candProbs[maxCandIndex]) { maxCandIndex = k; } } if (maxCandIndex == ei) { // no referent return (null); } else { de = (DiscourseEntity) dm.getEntity(maxCandIndex); return (de); } } /* protected double getNonReferentialProbability(MentionContext ec) { if (useFixedNonReferentialProbability) { if (debugOn) { System.err.println(this +".resolve: " + ec.toText() + " -> " + null +" " + fixedNonReferentialProbability); System.err.println(); } return fixedNonReferentialProbability; } List lfeatures = getFeatures(ec, null); String[] features = (String[]) lfeatures.toArray(new String[lfeatures.size()]); if (features == null) { System.err.println("features=null in " + this); } if (model == null) { System.err.println("model=null in " + this); } double[] dist = nrModel.eval(features); if (dist == null) { System.err.println("dist=null in " + this); } if (debugOn) { System.err.println(this +".resolve: " + ec.toText() + " -> " + null +" " + dist[nrSameIndex] + " " + lfeatures); System.err.println(); } return (dist[nrSameIndex]); } */ /** * Returns whether the specified entity satisfies the criteria for being a default referent. * This criteria is used to perform sample selection on the training data and to select a single * non-referent entity. Typcically the criteria is a hueristic for a likly referent. * @param de The discourse entity being considered for non-reference. * @return True if the entity should be used as a default referent, false otherwise. */ protected boolean defaultReferent(DiscourseEntity de) { MentionContext ec = de.getLastExtent(); if (ec.getNounPhraseSentenceIndex() == 0) { return (true); } return (false); } public DiscourseEntity retain(MentionContext mention, DiscourseModel dm) { //System.err.println(this+".retain("+ec+") "+mode); if (ResolverMode.TRAIN == mode) { DiscourseEntity de = null; boolean referentFound = false; boolean hasReferentialCandidate = false; boolean nonReferentFound = false; for (int ei = 0; ei < getNumEntities(dm); ei++) { DiscourseEntity cde = (DiscourseEntity) dm.getEntity(ei); MentionContext entityMention = cde.getLastExtent(); if (outOfRange(mention, cde)) { if (mention.getId() != -1 && !referentFound) { //System.err.println("retain: Referent out of range: "+ec.toText()+" "+ec.parse.getSpan()); } break; } if (excluded(mention, cde)) { if (showExclusions) { if (mention.getId() != -1 && entityMention.getId() == mention.getId()) { System.err.println(this +".retain: Referent excluded: (" + mention.getId() + ") " + mention.toText() + " " + mention.getIndexSpan() + " -> (" + entityMention.getId() + ") " + entityMention.toText() + " " + entityMention.getSpan() + " " + this); } } } else { hasReferentialCandidate = true; boolean useAsDifferentExample = defaultReferent(cde); //if (!sampleSelection || (mention.getId() != -1 && entityMention.getId() == mention.getId()) || (!nonReferentFound && useAsDifferentExample)) { List features = getFeatures(mention, cde); //add Event to Model if (debugOn) { System.err.println(this +".retain: " + mention.getId() + " " + mention.toText() + " -> " + entityMention.getId() + " " + cde); } if (mention.getId() != -1 && entityMention.getId() == mention.getId()) { referentFound = true; events.add(new Event(SAME, (String[]) features.toArray(new String[features.size()]))); de = cde; //System.err.println("MaxentResolver.retain: resolved at "+ei); distances.add(new Integer(ei)); } else if (!pairedSampleSelection || (!nonReferentFound && useAsDifferentExample)) { nonReferentFound = true; events.add(new Event(DIFF, (String[]) features.toArray(new String[features.size()]))); } } if (pairedSampleSelection && referentFound && nonReferentFound) { break; } if (preferFirstReferent && referentFound) { break; } } // doesn't refer to anything if (hasReferentialCandidate) { nonReferentialResolver.addEvent(mention); } return (de); } else { return (super.retain(mention, dm)); } } protected String getMentionCountFeature(DiscourseEntity de) { if (de.getNumMentions() >= 5) { return ("mc=5+"); } else { return ("mc=" + de.getNumMentions()); } } /** * Returns a list of features for deciding whether the specificed mention refers to the specified discourse entity. * @param mention the mention being considers as possibly referential. * @param entity The disource entity with which the mention is being considered referential. * @return a list of features used to predict reference between the specified mention and entity. */ protected List getFeatures(MentionContext mention, DiscourseEntity entity) { List features = new ArrayList(); features.add(DEFAULT); features.addAll(getCompatibilityFeatures(mention, entity)); return features; } public void train() throws IOException { if (ResolverMode.TRAIN == mode) { if (debugOn) { System.err.println(this +" referential"); FileWriter writer = new FileWriter(modelName+".events"); for (Iterator ei=events.iterator();ei.hasNext();) { Event e = (Event) ei.next(); writer.write(e.toString()+"\n"); } writer.close(); } (new SuffixSensitiveGISModelWriter(GIS.trainModel(new CollectionEventStream(events),100,10),new File(modelName+modelExtension))).persist(); nonReferentialResolver.train(); } } public static void setSimilarityModel(TestSimilarityModel sm) { simModel = sm; } private String getSemanticCompatibilityFeature(MentionContext ec, DiscourseEntity de) { if (simModel != null) { double best = 0; for (Iterator xi = de.getMentions(); xi.hasNext();) { MentionContext ec2 = (MentionContext) xi.next(); double sim = simModel.compatible(ec, ec2); if (debugOn) { System.err.println("MaxentResolver.getSemanticCompatibilityFeature: sem-compat " + sim + " " + ec.toText() + " " + ec2.toText()); } if (sim > best) { best = sim; } } if (best > MIN_SIM_PROB) { return SIM_COMPATIBLE; } else if (best > (1 - MIN_SIM_PROB)) { return SIM_UNKNOWN; } else { return SIM_INCOMPATIBLE; } } else { System.err.println("MaxentResolver: Uninitialized Semantic Model"); return SIM_UNKNOWN; } } private String getGenderCompatibilityFeature(MentionContext ec, DiscourseEntity de) { GenderEnum eg = de.getGender(); //System.err.println("getGenderCompatibility: mention="+ec.getGender()+" entity="+eg); if (eg == GenderEnum.UNKNOWN || ec.getGender() == GenderEnum.UNKNOWN) { return GEN_UNKNOWN; } else if (ec.getGender() == eg) { return GEN_COMPATIBLE; } else { return GEN_INCOMPATIBLE; } } private String getNumberCompatibilityFeature(MentionContext ec, DiscourseEntity de) { NumberEnum en = de.getNumber(); if (en == NumberEnum.UNKNOWN || ec.getNumber() == NumberEnum.UNKNOWN) { return NUM_UNKNOWN; } else if (ec.getNumber() == en) { return NUM_COMPATIBLE; } else { return NUM_INCOMPATIBLE; } } /** * Returns features indicating whether the specified mention and the specified entity are compatible. * @param mention The mention. * @param entity The entity. * @return list of features indicating whether the specified mention and the specified entity are compatible. */ private List getCompatibilityFeatures(MentionContext mention, DiscourseEntity entity) { List compatFeatures = new ArrayList(); String semCompatible = getSemanticCompatibilityFeature(mention, entity); compatFeatures.add(semCompatible); String genCompatible = getGenderCompatibilityFeature(mention, entity); compatFeatures.add(genCompatible); String numCompatible = getNumberCompatibilityFeature(mention, entity); compatFeatures.add(numCompatible); if (semCompatible.equals(SIM_COMPATIBLE) && genCompatible.equals(GEN_COMPATIBLE) && numCompatible.equals(NUM_COMPATIBLE)) { compatFeatures.add("all.compatible"); } else if (semCompatible.equals(SIM_INCOMPATIBLE) || genCompatible.equals(GEN_INCOMPATIBLE) || numCompatible.equals(NUM_INCOMPATIBLE)) { compatFeatures.add("some.incompatible"); } return compatFeatures; } /** * Returns a list of features based on the surrounding context of the specified mention. * @param mention he mention whose surround context the features model. * @return a list of features based on the surrounding context of the specified mention */ public static List getContextFeatures(MentionContext mention) { List features = new ArrayList(); if (mention.getPreviousToken() != null) { features.add("pt=" + mention.getPreviousToken().getSyntacticType()); features.add("pw=" + mention.getPreviousToken().toString()); } else { features.add("pt=BOS"); features.add("pw=BOS"); } if (mention.getNextToken() != null) { features.add("nt=" + mention.getNextToken().getSyntacticType()); features.add("nw=" + mention.getNextToken().toString()); } else { features.add("nt=EOS"); features.add("nw=EOS"); } if (mention.getNextTokenBasal() != null) { features.add("bnt=" + mention.getNextTokenBasal().getSyntacticType()); features.add("bnw=" + mention.getNextTokenBasal().toString()); } else { features.add("bnt=EOS"); features.add("bnw=EOS"); } return (features); } private Set constructModifierSet(Parse[] tokens, int headIndex) { Set modSet = new HashSet(); for (int ti = 0; ti < headIndex; ti++) { Parse tok = tokens[ti]; modSet.add(tok.toString().toLowerCase()); } return (modSet); } /** * Returns whether the specified token is a definite article. * @param tok The token. * @param tag The pos-tag for the specified token. * @return whether the specified token is a definite article. */ protected boolean definiteArticle(String tok, String tag) { tok = tok.toLowerCase(); if (tok.equals("the") || tok.equals("these") || tok.equals("these") || tag.equals("PRP$")) { return (true); } return (false); } private boolean isSubstring(String ecStrip, String xecStrip) { //System.err.println("MaxentResolver.isSubstring: ec="+ecStrip+" xec="+xecStrip); int io = xecStrip.indexOf(ecStrip); if (io != -1) { //check boundries if (io != 0 && xecStrip.charAt(io - 1) != ' ') { return false; } int end = io + ecStrip.length(); if (end != xecStrip.length() && xecStrip.charAt(end) != ' ') { return false; } return true; } return false; } protected boolean excluded(MentionContext ec, DiscourseEntity de) { if (super.excluded(ec, de)) { return true; } return false; /* else { if (GEN_INCOMPATIBLE == getGenderCompatibilityFeature(ec,de)) { return true; } else if (NUM_INCOMPATIBLE == getNumberCompatibilityFeature(ec,de)) { return true; } else if (SIM_INCOMPATIBLE == getSemanticCompatibilityFeature(ec,de)) { return true; } return false; } */ } /** * Returns distance features for the specified mention and entity. * @param mention The mention. * @param entity The entity. * @return list of distance features for the specified mention and entity. */ protected List getDistanceFeatures(MentionContext mention, DiscourseEntity entity) { List features = new ArrayList(); MentionContext cec = entity.getLastExtent(); int entityDistance = mention.getNounPhraseDocumentIndex()- cec.getNounPhraseDocumentIndex(); int sentenceDistance = mention.getSentenceNumber() - cec.getSentenceNumber(); int hobbsEntityDistance; if (sentenceDistance == 0) { hobbsEntityDistance = cec.getNounPhraseSentenceIndex(); } else { //hobbsEntityDistance = entityDistance - (entities within sentence from mention to end) + (entities within sentence form start to mention) //hobbsEntityDistance = entityDistance - (cec.maxNounLocation - cec.getNounPhraseSentenceIndex) + cec.getNounPhraseSentenceIndex; hobbsEntityDistance = entityDistance + (2 * cec.getNounPhraseSentenceIndex()) - cec.getMaxNounPhraseSentenceIndex(); } features.add("hd=" + hobbsEntityDistance); features.add("de=" + entityDistance); features.add("ds=" + sentenceDistance); //features.add("ds=" + sdist + pronoun); //features.add("dn=" + cec.sentenceNumber); //features.add("ep=" + cec.nounLocation); return (features); } private Map getPronounFeatureMap(String pronoun) { Map pronounMap = new HashMap(); if (Linker.malePronounPattern.matcher(pronoun).matches()) { pronounMap.put("gender","male"); } else if (Linker.femalePronounPattern.matcher(pronoun).matches()) { pronounMap.put("gender","female"); } else if (Linker.neuterPronounPattern.matcher(pronoun).matches()) { pronounMap.put("gender","neuter"); } if (Linker.singularPronounPattern.matcher(pronoun).matches()) { pronounMap.put("number","singular"); } else if (Linker.pluralPronounPattern.matcher(pronoun).matches()) { pronounMap.put("number","plural"); } /* if (Linker.firstPersonPronounPattern.matcher(pronoun).matches()) { pronounMap.put("person","first"); } else if (Linker.secondPersonPronounPattern.matcher(pronoun).matches()) { pronounMap.put("person","second"); } else if (Linker.thirdPersonPronounPattern.matcher(pronoun).matches()) { pronounMap.put("person","third"); } */ return pronounMap; } /** * Returns features indicating whether the specified mention is compatible with the pronouns * of the specified entity. * @param mention The mention. * @param entity The entity. * @return list of features indicating whether the specified mention is compatible with the pronouns * of the specified entity. */ protected List getPronounMatchFeatures(MentionContext mention, DiscourseEntity entity) { boolean foundCompatiblePronoun = false; boolean foundIncompatiblePronoun = false; if (mention.getHeadTokenTag().startsWith("PRP")) { Map pronounMap = getPronounFeatureMap(mention.getHeadTokenText()); //System.err.println("getPronounMatchFeatures.pronounMap:"+pronounMap); for (Iterator mi=entity.getMentions();mi.hasNext();) { MentionContext candidateMention = (MentionContext) mi.next(); if (candidateMention.getHeadTokenTag().startsWith("PRP")) { if (mention.getHeadTokenText().equalsIgnoreCase(candidateMention.getHeadTokenText())) { foundCompatiblePronoun = true; break; } else { Map candidatePronounMap = getPronounFeatureMap(candidateMention.getHeadTokenText()); //System.err.println("getPronounMatchFeatures.candidatePronounMap:"+candidatePronounMap); boolean allKeysMatch = true; for (Iterator ki = pronounMap.keySet().iterator(); ki.hasNext();) { Object key = ki.next(); Object cfv = candidatePronounMap.get(key); if (cfv != null) { if (!pronounMap.get(key).equals(cfv)) { foundIncompatiblePronoun = true; allKeysMatch = false; } } else { allKeysMatch = false; } } if (allKeysMatch) { foundCompatiblePronoun = true; } } } } } List pronounFeatures = new ArrayList(); if (foundCompatiblePronoun) { pronounFeatures.add("compatiblePronoun"); } if (foundIncompatiblePronoun) { pronounFeatures.add("incompatiblePronoun"); } return pronounFeatures; } /** * Returns string-match features for the the specified mention and entity. * @param mention The mention. * @param entity The entity. * @return list of string-match features for the the specified mention and entity. */ protected List getStringMatchFeatures(MentionContext mention, DiscourseEntity entity) { boolean sameHead = false; boolean modsMatch = false; boolean titleMatch = false; boolean nonTheModsMatch = false; List features = new ArrayList(); Parse[] mtokens = mention.getTokenParses(); Set ecModSet = constructModifierSet(mtokens, mention.getHeadTokenIndex()); String mentionHeadString = mention.getHeadTokenText().toLowerCase(); Set featureSet = new HashSet(); for (Iterator ei = entity.getMentions(); ei.hasNext();) { MentionContext entityMention = (MentionContext) ei.next(); String exactMatchFeature = getExactMatchFeature(entityMention, mention); if (exactMatchFeature != null) { featureSet.add(exactMatchFeature); } else if (entityMention.getParse().isCoordinatedNounPhrase() && !mention.getParse().isCoordinatedNounPhrase()) { featureSet.add("cmix"); } else { String mentionStrip = stripNp(mention); String entityMentionStrip = stripNp(entityMention); if (mentionStrip != null && entityMentionStrip != null) { if (isSubstring(mentionStrip, entityMentionStrip)) { featureSet.add("substring"); } } } Parse[] xtoks = entityMention.getTokenParses(); int headIndex = entityMention.getHeadTokenIndex(); //if (!mention.getHeadTokenTag().equals(entityMention.getHeadTokenTag())) { // //System.err.println("skipping "+mention.headTokenText+" with "+xec.headTokenText+" because "+mention.headTokenTag+" != "+xec.headTokenTag); // continue; //} want to match NN NNP String entityMentionHeadString = entityMention.getHeadTokenText().toLowerCase(); // model lexical similarity if (mentionHeadString.equals(entityMentionHeadString)) { sameHead = true; featureSet.add("hds=" + mentionHeadString); if (!modsMatch || !nonTheModsMatch) { //only check if we haven't already found one which is the same modsMatch = true; nonTheModsMatch = true; Set entityMentionModifierSet = constructModifierSet(xtoks, headIndex); for (Iterator mi = ecModSet.iterator(); mi.hasNext();) { String mw = (String) mi.next(); if (!entityMentionModifierSet.contains(mw)) { modsMatch = false; if (!mw.equals("the")) { nonTheModsMatch = false; featureSet.add("mmw=" + mw); } } } } } Set descModSet = constructModifierSet(xtoks, entityMention.getNonDescriptorStart()); if (descModSet.contains(mentionHeadString)) { titleMatch = true; } } if (!featureSet.isEmpty()) { features.addAll(featureSet); } if (sameHead) { features.add("sameHead"); if (modsMatch) { features.add("modsMatch"); } else if (nonTheModsMatch) { features.add("nonTheModsMatch"); } else { features.add("modsMisMatch"); } } if (titleMatch) { features.add("titleMatch"); } return features; } private String mentionString(MentionContext ec) { StringBuffer sb = new StringBuffer(); Object[] mtokens = ec.getTokens(); sb.append(mtokens[0].toString()); for (int ti = 1, tl = mtokens.length; ti < tl; ti++) { String token = mtokens[ti].toString(); sb.append(" ").append(token); } //System.err.println("mentionString "+ec+" == "+sb.toString()+" mtokens.length="+mtokens.length); return sb.toString(); } private String excludedTheMentionString(MentionContext ec) { StringBuffer sb = new StringBuffer(); boolean first = true; Object[] mtokens = ec.getTokens(); for (int ti = 0, tl = mtokens.length; ti < tl; ti++) { String token = mtokens[ti].toString(); if (!token.equals("the") && !token.equals("The") && !token.equals("THE")) { if (!first) { sb.append(" "); } sb.append(token); first = false; } } return sb.toString(); } private String excludedHonorificMentionString(MentionContext ec) { StringBuffer sb = new StringBuffer(); boolean first = true; Object[] mtokens = ec.getTokens(); for (int ti = 0, tl = mtokens.length; ti < tl; ti++) { String token = mtokens[ti].toString(); if (!Linker.honorificsPattern.matcher(token).matches()) { if (!first) { sb.append(" "); } sb.append(token); first = false; } } return sb.toString(); } private String excludedDeterminerMentionString(MentionContext ec) { StringBuffer sb = new StringBuffer(); boolean first = true; Parse[] mtokens = ec.getTokenParses(); for (int ti = 0, tl = mtokens.length; ti < tl; ti++) { Parse token = mtokens[ti]; String tag = token.getSyntacticType(); if (!tag.equals("DT")) { if (!first) { sb.append(" "); } sb.append(token.toString()); first = false; } } return sb.toString(); } private String getExactMatchFeature(MentionContext ec, MentionContext xec) { //System.err.println("getExactMatchFeature: ec="+mentionString(ec)+" mc="+mentionString(xec)); if (mentionString(ec).equals(mentionString(xec))) { return "exactMatch"; } else if (excludedHonorificMentionString(ec).equals(excludedHonorificMentionString(xec))) { return "exactMatchNoHonor"; } else if (excludedTheMentionString(ec).equals(excludedTheMentionString(xec))) { return "exactMatchNoThe"; } else if (excludedDeterminerMentionString(ec).equals(excludedDeterminerMentionString(xec))) { return "exactMatchNoDT"; } return null; } /** * Returns a list of word features for the specified tokens. * @param token The token for which fetures are to be computed. * @return a list of word features for the specified tokens. */ public static List getWordFeatures(Parse token) { List wordFeatures = new ArrayList(); String word = token.toString().toLowerCase(); String wf = ""; if (ENDS_WITH_PERIOD.matcher(word).find()) { wf = ",endWithPeriod"; } String tokTag = token.getSyntacticType(); wordFeatures.add("w=" + word + ",t=" + tokTag + wf); wordFeatures.add("t=" + tokTag + wf); return (wordFeatures); } }
package parking.business; /* Import */ import parking.exception.*; import parking.gui.Vue; import java.util.ArrayList; import java.util.Date; public class Parking { /* Debut Donnees Membres */ /** * Numero de place, servant a remplir le parking. Il permet de savoir le nulmero de la derniere place ajoutee. */ static private int numeroPlace = 0; /** * Nombre de place maximum du parking. */ static private int nbPlacesMax; /** * Nom du parking. */ private static String nom; /** * Liste des vehicule du parking. * Type de collection a definir ... */ private static ArrayList<Place> listeVehicules = new ArrayList<Place>(); private static ArrayList<Client> listeClients = new ArrayList<Client>(); private static ArrayList<Facture> listeFacture; private static ArrayList<Vue> listeVue = new ArrayList<Vue>(); private static double tarif_particulier; private static double tarif_transporteur; private static int numeroFacture; private static boolean appelInterne; /** * Initialisation des informations generales du parking. En static car le parking est unique. */ static { nom = "Mon Parking"; nbPlacesMax = 20; numeroFacture = 0; tarif_particulier = 1; tarif_transporteur = 1.5; appelInterne = false; } /* Getter */ /** * Methode renvoyant le numero de la derniere place ajoutee au parking. * * @return le numero de la derniere place ajoutee. */ public static int getNumeroPlace() { return numeroPlace; }// getNumeroPlace() /** * Methode renvoyant le nombre de place maximal du parking. * * @return Nombre de place max du parking. */ public static int getNbPlacesMax() { return nbPlacesMax; }// getNbPlacesMax() public static ArrayList<Place> getListeVehicules() { return listeVehicules; } public static double getTarif_transporteur() { return tarif_transporteur; } public static double getTarif_particulier() { return tarif_particulier; } public static int getNumeroFacture() {return numeroFacture; } /* Setter */ /** * Methode permettant de modifier la valeur de la derniere place ajoutee. * * @param numeroPlace * Numero de la derniere place ajouter au parking. */ public static void setNumeroPlace(int numeroPlace) { Parking.numeroPlace = numeroPlace; }// setNumeroPlace() public static void setTarif_transporteur(double tarif_transporteur) { Parking.tarif_transporteur = tarif_transporteur; } public static void setTarif_particulier(double tarif_particulier) { Parking.tarif_particulier = tarif_particulier; } public static void setNumeroFacture(int numeroFacture) { Parking.numeroFacture = numeroFacture; } public void addFacture(Facture facture) { listeFacture.add(facture); } /* Methodes */ public static void addVue(Vue v) { listeVue.add(v); } public static void notifier() { for (Vue v : listeVue) { System.out.println("Modification notifier"); v.mettreAJour(); } } public static void addClient(Client c){ listeClients.add(c); } /** * Methode toString() permettant de connaitre toutes les informations detaillees sur le parking. * * @return rencoie une chaine de caracteres contenant les informatiosn sur le parking. */ @Override public String toString() { return "Parking [nom=" + nom + ", listeVehicules=" + listeVehicules + "]"; }// toString() /** * Methode permettant d'ajouter une place dans le parking. * * @param p * la place a ajoutee. */ public static void ajouterPlace(Place p){ try { if(Parking.getNbPlacesMax() == Parking.getNumeroPlace()) throw new NombrePlacesMaxException(); p.setNumero(Parking.getNumeroPlace()); Parking.setNumeroPlace(Parking.getNumeroPlace()+1); Parking.listeVehicules.add(p); notifier(); } catch (NombrePlacesMaxException e) { System.out.println("Le parking a atteint le nombre maximal de places"); } }// ajouterPlace() /** * Methode testant l'existance d'un vehicule dans le parking. * * @param v * Vehicule a recherche dans le parking. * @return Renvoie un booleen indiquant si le vehicule est present ou non. */ public static boolean vehiculeExiste(Vehicule v){ for(Place p : Parking.listeVehicules ){ if(p.getVehicule() == v) return true; } return false; }// vehiculeExiste() /** * Methode permettant de retirer un vehicule de sa place sur le parking. * * @param numeroPlace * Numero de la place ou retirer le vehicule. * @return renvoie le vehicule retire. */ public static Vehicule unpark(int numeroPlace) { for(Place p : Parking.listeVehicules ){ if (numeroPlace == p.getNumero()) try { if (!appelInterne) { System.out.println(new Facture(p)); } return p.retirerVehicule(); } catch (PlaceLibreException e) { System.out.println("La place est déja vide !"); return null; } finally { notifier(); } } return null; }// unpark() /** * Methode permettant de garrer un vehicule sur une place de parking. La fonction va * chercher la place du meme type que le vehicule a garer, sinon elle le placera sur une place * du type transporteur si il y en a une de disponible. * * @param vehicule * Vehicule a garer su rle parking. */ public static void park(Vehicule vehicule) { try { String typePlace = "Transporteur"; if (vehicule.getType().equals("Voiture")) { typePlace = "Particulier"; } for (Place p : Parking.listeVehicules) { if (p.getVehicule() == null && !(p.getReservation())) { if (p.getType().equals(typePlace)) { p.setVehicule(vehicule); if (!appelInterne) p.getVehicule().setDateArrivee(new Date()); return; } } } for (Place p : Parking.listeVehicules) { if (p.getVehicule() == null && !(p.getReservation())) { p.setVehicule(vehicule); return; } } throw new PlusAucunePlaceException(); } catch(PlaceOccupeeException e){ System.out.println("La place est dj occupe et/ou n'est pas adapte ce vhicule"); } catch (PlaceReserverException e) { System.out.println("La place " + numeroPlace + " est réservée !"); } catch (PlusAucunePlaceException e) { System.out.println("Le parking est complet !"); } finally { notifier(); } } // park() public static void etatParking() { System.out.println("Debut de l'affichage du parking !"); for(Place p : Parking.listeVehicules ) { System.out.println("La place numero : " + p.getNumero() + " du type : " + p.getType()); if (p.getVehicule() != null) System.out.println("La place a pour vehicule : " + p.getVehicule() + "\n"); else System.out.println("La place n'a pas de vehicule ! Elle " + p.getReserver() + "\n"); } System.out.println("Fin de l'affichage du parking !\n"); } // etatParking() /** * Methode permettant de reserver une place disponible sur le parking * * @return La place reserver. */ public static Place bookPlace() { try { for (Place p : Parking.listeVehicules) { if (p.getVehicule() == null) { p.setReservation(true); return p; } } throw new PlusAucunePlaceException(); } catch (PlusAucunePlaceException e) { System.out.println("Aucune place disponble"); return null; } finally { notifier(); } } // bookPlace() /** * Methode permettant de liberer une place reserver sur le parking. * * @param numeroPlace * Numero de la place a dereserver. * @return la place de nouveau libre. */ public static Place freePlace(int numeroPlace) { try { for (Place p : Parking.listeVehicules) { if (p.getNumero() == numeroPlace ) { if (p.getReservation()) { p.setReservation(false); return p; } else throw new PlaceDisponibleException(); } } return null; } catch (PlaceDisponibleException e) { System.out.println("place déja disponible ! (pas réservée)"); return null; } finally { notifier(); } } // freePlace() /** * Permet de connaitre la place ou se situe un vehicule a partir de son numero d'immatriculation. * * @param numeroImmatriculation * numero d'immatriculation du vehicule a recherche. * @return le numero ou le vehicule se trouve sur le parking. */ public static int getLocation(String numeroImmatriculation) { for (Place p : Parking.listeVehicules) { if (p.getVehicule() != null && (p.getVehicule().getImmatriculation()).equals(numeroImmatriculation)) { return p.getNumero(); } } return -1; } // getlocation() /** * Methode permettant de retirer un vehicule d'une place a partir de son numero d'immatriculation. * * @param numeroImmatriculation * Numero d'immatriculation du vehicule a retirer. * @return le vehivule retirer de sa place de parking. */ public static Vehicule retirerVehicule(String numeroImmatriculation) { int numPlace = getLocation(numeroImmatriculation); if (numPlace == -1) return null; else return unpark(numPlace); } // retirerVehicule() /** * Methode reorganisant les places de parking apres le depart d'un vehicule. * par exemple si une place du type particulier c'est liberer et q'une voiture et sur une * place du type camion , on va alors la deplacer sur la place libre. */ public static void reorganiserPlaces() { appelInterne = true; for (Place p : Parking.listeVehicules) { if (p.getType().equals("Transporteur") && p.getVehicule() != null) { if (p.getVehicule().getType().equals("Voiture")) { Vehicule vretire = unpark(p.getNumero()); Parking.park(vretire); } } } notifier(); appelInterne = false; } // reorganiserPlaces() /* Main */ } // Parking class
package Game; import java.awt.Color; import java.awt.Frame; import java.awt.Graphics; import java.awt.Rectangle; //Extending rectangle is bad practice, don't do it public class Player extends Rectangle{ double dy; double doublex; double doubley; boolean jumping = false; boolean grounded = true; boolean isLeft; boolean isRight; boolean isUp; double xVelocity = 0; public Player(){ width = 160; height = 40; //Place the Player on top of highest Block x = 0; doublex = 0; for(int i = 0;i < World.worldHeight;i++){ for(int j = 0;j < World.worldWidth;j++){ if(World.squares[j][i].ID == Value.squareSpawn){ this.x = j*World.blockSize + width/2; this.y = i*World.blockSize - height + World.blockSize; System.out.println(x + " " + y); doublex = x; doubley = y; break; } } } } public void jump(){ isUp = true; if(grounded){ dy = -3; grounded = false; } System.out.println("jump"); } public void left(){ isLeft = true; isRight = false; System.out.println("left"); } public void right(){ isRight = true; isLeft = false; System.out.println("right"); } public void doGravity(double gravity){ dy += gravity; doubley+=dy; y=(int)doubley; boolean collision = false; for(int i = 0;i < World.worldHeight;i++){ for(int j = 0;j < World.worldWidth;j++){ while(this.intersects(World.squares[j][i]) && World.squares[j][i].solid){ if(dy > 0){ y } if(dy < 0){ y++; } collision = true; } if(collision){ doubley = y; dy = 0; break; } } } } public void doXFriction(double friction){ if (xVelocity > 0){ xVelocity -= friction/100; if (xVelocity < 0){ xVelocity = 0; } } else { xVelocity += friction/100; if (xVelocity > 0){ xVelocity = 0; } } } public void calculateOffset(){ if(x - (World.screenWidth/2) > 0 && x + (World.screenWidth/2) < World.worldWidth*World.blockSize){ World.offset = x - (World.screenWidth/2); } else if(x - (World.screenWidth/2) < 0){ World.offset = 0; } else if(x + (World.screenWidth/2) > World.worldWidth*World.blockSize){ World.offset = World.worldWidth*World.blockSize - World.screenWidth; } } public void act(){ //calculate 2 squares below Square squareLowerLeft = null; Square squareLowerRight = null; Square squareCentre = null; Square squareBelow = null; for(int i = 0;i < World.worldHeight;i++){ for(int j = 0;j < World.worldWidth;j++){ if(World.squares[j][i].contains(x, y + height + 1)){ squareLowerLeft = World.squares[j][i]; break; } } } for(int i = 0;i < World.worldHeight;i++){ for(int j = 0;j < World.worldWidth;j++){ if(World.squares[j][i].contains(x + width - 1, y + height + 1)){ squareLowerRight = World.squares[j][i]; break; } } } for(int i = 0;i < World.worldHeight;i++){ for(int j = 0;j < World.worldWidth;j++){ if(World.squares[j][i].contains(x + (width-1)/2, y + (height + 1)/2)){ squareCentre = World.squares[j][i]; break; } } } for(int i = 0;i < World.worldHeight;i++){ for(int j = 0;j < World.worldWidth;j++){ if(World.squares[j][i].contains(x + (width-1)/2, y + height + 1)){ squareBelow = World.squares[j][i]; break; } } } double maxXSpeed; double acceleration; double friction; if(grounded){ maxXSpeed = squareBelow.maxXSpeed; acceleration = squareBelow.acceleration; friction = squareBelow.friction; } else{ maxXSpeed = squareCentre.maxXSpeed; acceleration = squareCentre.acceleration; friction = squareCentre.friction; } if(isRight){ if(xVelocity < 0){ xVelocity += acceleration*2; } else if(xVelocity < maxXSpeed){ xVelocity += acceleration; } } else if(isLeft){ if(xVelocity > 0){ xVelocity -= acceleration*2; } if(xVelocity > -maxXSpeed){ xVelocity -= acceleration; } } else if(xVelocity != 0){ doXFriction(friction); } if(Math.abs(xVelocity) > maxXSpeed){ // for high speeds doXFriction(friction); } doublex += xVelocity; x = (int)doublex; //Check collisions from x changes boolean collision = false; for(int i = 0;i < World.worldHeight;i++){ for(int j = 0;j < World.worldWidth;j++){ while(this.intersects(World.squares[j][i]) && World.squares[j][i].solid){ if(xVelocity > 0){ x } if(xVelocity < 0){ x++; } collision = true; } if(collision){ xVelocity = 0; doublex = x; break; } } } doGravity(squareCentre.gravity); grounded = squareLowerLeft.solid | squareLowerRight.solid; calculateOffset(); //Check edges of world if(x<0){ x = 0; doublex = 0; xVelocity = 0; } if(doublex > World.worldWidth*World.blockSize - width){ doublex = World.worldWidth*World.blockSize - width; x = (int)doublex; xVelocity = 0; } if(y<0){ //player hits top of world and stops y = 0; doubley = 0; dy = 0; } if(y > World.worldHeight*World.blockSize - height - 2){ doubley = World.worldHeight*World.blockSize - height - 2; //most likely dead y = (int)doubley; dy = 0; } } public void draw(Graphics g){ g.setColor(Color.BLUE); g.drawRect(x - (int)World.offset, y, width, height); } }
package ij.gui; import static org.junit.Assert.*; import org.junit.Test; import java.awt.*; import ij.process.*; public class TextRoiTest { TextRoi t; @Test public void testTextRoiIntIntString() { t = new TextRoi(0,0,""); assertEquals(new Rectangle(0,0,1,1), t.getBounds()); assertEquals("", t.getText()); t = new TextRoi(1,3,"Super-sandwich-man's high, \"round\" shoes!"); assertEquals(new Rectangle(1,3,1,1), t.getBounds()); assertEquals("Super-sandwich-man's high, \"round\" shoes!\n", t.getText()); } @Test public void testTextRoiIntIntStringFont() { Font font = new Font("SansBatootie",4,3); t = new TextRoi(0,0,"",font); assertEquals(new Rectangle(0,0,1,1), t.getBounds()); assertEquals("", t.getText()); t = new TextRoi(1,3,"Super-sandwich-man's high, \"round\" shoes!",font); assertEquals(new Rectangle(1,3,1,1), t.getBounds()); assertEquals("Super-sandwich-man's high, \"round\" shoes!\n", t.getText()); } @Test public void testTextRoiIntIntImagePlus() { // note - can't test - needs an active imagecanvas } @Test public void testClone() { t = new TextRoi(1,3,"Super-sandwich-man's high, \"round\" shoes!"); TextRoi roi = (TextRoi) t.clone(); assertEquals(t,roi); } @Test public void testDraw() { // note - can't test - needs a graphics context } @Test public void testDrawPixelsImageProcessor() { t = new TextRoi(1,3,"Ab4"); int size = 30; ImageProcessor proc = new ByteProcessor(size,size,new byte[size*size],null); proc.setColor(Color.red); t.drawPixels(proc); int[] expectedNonZeroes = new int[]{194,195,196,216,217,218,224,225,226,245,246,247,248,254,255,256,269,275,276,277,278,279, 284,285,286,298,299,304,305,306,307,308,309,314,315,316,328,329,334,335,336,337,338,339, 344,345,346,347,348,349,350,351,357,358,359,364,365,366,367,368,369,370,374,375,376,377, 378,379,380,381,382,386,387,388,389,393,394,395,398,399,400,404,405,406,407,410,411,412, 413,416,417,418,423,424,425,428,429,430,434,435,436,441,442,443,445,446,447,453,454,455, 456,457,458,459,460,461,464,465,466,471,472,473,474,475,476,477,478,479,482,483,484,485, 486,487,488,489,490,491,494,495,496,501,502,503,504,505,506,507,508,509,512,513,514,515, 516,517,518,519,520,521,522,524,525,526,531,532,533,534,535,536,537,538,539,541,542,543, 550,551,552,554,555,556,560,561,562,571,572,573,580,581,582,584,585,586,587,588,589,590, 591,592,601,602,603,610,611,612,613,614,615,616,617,618,619,620,621,644,645,646,648,649, 650}; //RoiHelpers.printNonzeroIndices(proc); RoiHelpers.validateNonzeroResult(proc, expectedNonZeroes); } @Test public void testIsDrawingTool() { t = new TextRoi(1,3,"Ab4"); assertTrue(t.isDrawingTool()); // true of all TextRois } private void validateAddChars(String charSeq, String result) { t = new TextRoi(1,3,""); t.setImage(RoiHelpers.getCalibratedImagePlus()); // needed to avoid runtime crash for (int i = 0; i < charSeq.length(); i++) t.addChar(charSeq.charAt(i)); assertEquals(result, t.getText()); } @Test public void testAddChar() { // Wayne has said this should not be tested. He has updated documentation to tell people not to use it. /* // EMPTY string tests // backspace //validateAddChars("\b",""); //TODO - crash // newline validateAddChars("\n",""); // try to add all other nonprinting chars for (int i = 0; i < 32; i++) if ( ((char)i != '\n') && ((char)i != '\b') ) validateAddChars(""+(char)i,""); // ONE CHAR string tests // backspace //validateAddChars("X\b",""); // TODO - return val is "null\n" rather than empty string // newline validateAddChars("X\n","X\n"); // TODO: this is broken as well: "nullX\n\n" I think // try to add all other nonprinting chars for (int i = 0; i < 32; i++) if ( ((char)i != '\n') && ((char)i != '\b') ) validateAddChars("X"+(char)i,"X"); // Some general cases // TODO */ } @Test public void testSetFont1() { // test setFont(3 params) // save static values to avoid side effects later String savedFontName = TextRoi.getFont(); int savedSize = TextRoi.getSize(); int savedStyle = TextRoi.getStyle(); assertEquals("SansSerif", savedFontName); assertEquals(18, savedSize); assertEquals(Font.PLAIN, savedStyle); TextRoi.setFont("Parp", 93, Font.BOLD); assertEquals("Parp",TextRoi.getFont()); assertEquals(93,TextRoi.getSize()); assertEquals(Font.BOLD,TextRoi.getStyle()); // restore so we don't mess up other tests TextRoi.setFont(savedFontName,savedSize,savedStyle); } @Test public void testSetFont2() { // test setFont(4 params) // save static values to avoid side effects later String savedFontName = TextRoi.getFont(); int savedSize = TextRoi.getSize(); int savedStyle = TextRoi.getStyle(); boolean saveAnti = TextRoi.isAntialiased(); assertEquals("SansSerif", savedFontName); assertEquals(18, savedSize); assertEquals(Font.PLAIN, savedStyle); assertEquals(true, saveAnti); TextRoi.setFont("Parp", 93, Font.BOLD, !saveAnti); assertEquals("Parp",TextRoi.getFont()); assertEquals(93,TextRoi.getSize()); assertEquals(Font.BOLD,TextRoi.getStyle()); assertEquals(!saveAnti, TextRoi.isAntialiased()); // restore so we don't mess up other tests TextRoi.setFont(savedFontName,savedSize,savedStyle,saveAnti); } @Test public void testIsAntialiased() { // save static values to avoid side effects later String savedFontName = TextRoi.getFont(); int savedSize = TextRoi.getSize(); int savedStyle = TextRoi.getStyle(); TextRoi.setFont("Parp", 93, Font.BOLD, true); assertTrue(TextRoi.isAntialiased()); TextRoi.setFont("Parp", 93, Font.BOLD, false); assertFalse(TextRoi.isAntialiased()); // restore so we don't mess up other tests TextRoi.setFont(savedFontName,savedSize,savedStyle); } @Test public void testSetAndGetCurrentFont() { Font font1 = new Font("Brietastic",14,5); Font font2 = new Font("Cheddarburg",14,5); t = new TextRoi(10000,0,"",font1); assertEquals(font1,t.getCurrentFont()); t.setCurrentFont(font2); assertEquals(font2,t.getCurrentFont()); } @Test public void testGetMacroCode() { // save static values to avoid side effects later String savedFontName = TextRoi.getFont(); int savedSize = TextRoi.getSize(); int savedStyle = TextRoi.getStyle(); ImageProcessor proc = new ShortProcessor(104,77,new short[104*77],null); Font font = new Font("Goudaland",44,15); t = new TextRoi(0,1500,"Glaphound",font); TextRoi.setFont("Hork",64,Font.BOLD+Font.ITALIC,false); assertEquals("setFont(\"Hork\", 64, \"plain\");\nmakeText(\"Glaphound\", 0, 1515);\n//drawString(\"Glaphound\", 0, 1515);\n", t.getMacroCode(proc)); assertEquals("makeText(\"Glaphound\", 0, 1515);\n//drawString(\"Glaphound\", 0, 1515);\n", t.getMacroCode(proc)); TextRoi.setFont("Glook",32,Font.PLAIN,true); assertEquals("setFont(\"Glook\", 32, \" antialiased\");\nmakeText(\"Glaphound\", 0, 1515);\n//drawString(\"Glaphound\", 0, 1515);\n", t.getMacroCode(proc)); assertEquals("makeText(\"Glaphound\", 0, 1515);\n//drawString(\"Glaphound\", 0, 1515);\n", t.getMacroCode(proc)); // restore so we don't mess up other tests TextRoi.setFont(savedFontName,savedSize,savedStyle); } @Test public void testGetText() { t = new TextRoi(10000,0,""); assertEquals("",t.getText()); t = new TextRoi(10000,0,"Oooch"); assertEquals("Oooch\n",t.getText()); t = new TextRoi(10000,0,"Weekend\nweather\n\n"); assertEquals("Weekend\nweather\n\n",t.getText()); } @Test public void testRecordSetFont() { t = new TextRoi(-1,19,"Klezmer"); assertEquals("setFont(\"SansSerif\", 18, \" antialiased\");\nmakeText(\"Klezmer\", -1, 34);\n//drawString(\"Klezmer\", -1, 34);\n", t.getMacroCode(new ByteProcessor(2,2,new byte[2*2],null))); assertEquals("makeText(\"Klezmer\", -1, 34);\n//drawString(\"Klezmer\", -1, 34);\n", t.getMacroCode(new ByteProcessor(2,2,new byte[2*2],null))); TextRoi.recordSetFont(); assertEquals("setFont(\"SansSerif\", 18, \" antialiased\");\nmakeText(\"Klezmer\", -1, 34);\n//drawString(\"Klezmer\", -1, 34);\n", t.getMacroCode(new ByteProcessor(2,2,new byte[2*2],null))); } }
package org.xbill.DNS; import java.io.*; import java.util.*; import java.lang.ref.*; /** * A cache of DNS records. The cache obeys TTLs, so items are purged after * their validity period is complete. Negative answers are cached, to * avoid repeated failed DNS queries. The credibility of each RRset is * maintained, so that more credible records replace less credible records, * and lookups can specify the minimum credibility of data they are requesting. * @see RRset * @see Credibility * * @author Brian Wellington */ public class Cache { private abstract static class Element implements TypedObject { int credibility; int expire; protected void setValues(int credibility, long ttl) { this.credibility = credibility; this.expire = (int)((System.currentTimeMillis() / 1000) + ttl); if (this.expire < 0 || this.expire > Integer.MAX_VALUE) this.expire = Integer.MAX_VALUE; } public final boolean expired() { int now = (int)(System.currentTimeMillis() / 1000); return (now >= expire); } public abstract int getType(); } private static class PositiveElement extends Element { RRset rrset; public PositiveElement(RRset r, int cred, long maxttl) { rrset = r; long ttl = r.getTTL(); if (maxttl >= 0 && maxttl < ttl) ttl = maxttl; setValues(cred, ttl); } public int getType() { return rrset.getType(); } public String toString() { StringBuffer sb = new StringBuffer(); sb.append(rrset); sb.append(" cl = "); sb.append(credibility); return sb.toString(); } } private static class NegativeElement extends Element { int type; Name name; SOARecord soa; public NegativeElement(Name name, int type, SOARecord soa, int cred, long maxttl) { this.name = name; this.type = type; this.soa = soa; long cttl = 0; if (soa != null) { cttl = soa.getMinimum(); if (maxttl >= 0 && maxttl < cttl) cttl = maxttl; } setValues(cred, cttl); } public int getType() { return type; } public String toString() { StringBuffer sb = new StringBuffer(); if (type == 0) sb.append("NXDOMAIN " + name); else sb.append("NXRRSET " + name + " " + Type.string(type)); sb.append(" cl = "); sb.append(credibility); return sb.toString(); } } private static class CacheCleaner extends Thread { private Reference cacheref; private long interval; public CacheCleaner(Cache cache, int cleanInterval) { this.cacheref = new WeakReference(cache); this.interval = (long)cleanInterval * 60 * 1000; setDaemon(true); setName("org.xbill.DNS.Cache.CacheCleaner"); start(); } private boolean clean(Cache cache) { Iterator it = cache.data.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry; try { entry = (Map.Entry) it.next(); } catch (ConcurrentModificationException e) { return false; } Name name = (Name) entry.getKey(); Element [] elements = cache.allElements(entry.getValue()); for (int i = 0; i < elements.length; i++) { Element element = elements[i]; if (element.expired()) cache.removeElement(name, element.getType()); } } return true; } public void run() { while (true) { long now = System.currentTimeMillis(); long next = now + interval; while (now < next) { try { Thread.sleep(next - now); } catch (InterruptedException e) { return; } now = System.currentTimeMillis(); } Cache cache = (Cache) cacheref.get(); if (cache == null) { return; } for (int i = 0; i < 4; i++) if (clean(cache)) break; } } } private static final int defaultCleanInterval = 30; private Map data; private int maxncache = -1; private int maxcache = -1; private CacheCleaner cleaner; private int dclass; /** * Creates an empty Cache * * @param dclass The dns class of this cache * @param cleanInterval The interval between cache cleanings, in minutes. * @see #setCleanInterval(int) */ public Cache(int dclass, int cleanInterval) { data = new HashMap(); this.dclass = dclass; setCleanInterval(cleanInterval); } /** * Creates an empty Cache * * @param dclass The dns class of this cache * @see DClass */ public Cache(int dclass) { this(dclass, defaultCleanInterval); } /** * Creates an empty Cache for class IN. * @see DClass */ public Cache() { this(DClass.IN, defaultCleanInterval); } /** * Creates a Cache which initially contains all records in the specified file. */ public Cache(String file) throws IOException { data = new HashMap(); cleaner = new CacheCleaner(this, defaultCleanInterval); Master m = new Master(file); Record record; while ((record = m.nextRecord()) != null) addRecord(record, Credibility.HINT, m); } private synchronized Object exactName(Name name) { return data.get(name); } private synchronized void removeName(Name name) { data.remove(name); } private synchronized Element [] allElements(Object types) { if (types instanceof List) { List typelist = (List) types; int size = typelist.size(); return (Element []) typelist.toArray(new Element[size]); } else { Element set = (Element) types; return new Element[] {set}; } } private synchronized Element oneElement(Name name, Object types, int type, int minCred) { Element found = null; if (type == Type.ANY) throw new IllegalArgumentException("oneElement(ANY)"); if (types instanceof List) { List list = (List) types; for (int i = 0; i < list.size(); i++) { Element set = (Element) list.get(i); if (set.getType() == type) { found = set; break; } } } else { Element set = (Element) types; if (set.getType() == type) found = set; } if (found == null) return null; if (found.expired()) { removeElement(name, type); return null; } if (found.credibility < minCred) return null; return found; } private synchronized Element findElement(Name name, int type, int minCred) { Object types = exactName(name); if (types == null) return null; return oneElement(name, types, type, minCred); } private synchronized void addElement(Name name, Element element) { Object types = data.get(name); if (types == null) { data.put(name, element); return; } int type = element.getType(); if (types instanceof List) { List list = (List) types; for (int i = 0; i < list.size(); i++) { Element elt = (Element) list.get(i); if (elt.getType() == type) { list.set(i, element); return; } } list.add(element); } else { Element elt = (Element) types; if (elt.getType() == type) data.put(name, element); else { LinkedList list = new LinkedList(); list.add(elt); list.add(element); data.put(name, list); } } } private synchronized void removeElement(Name name, int type) { Object types = data.get(name); if (types == null) { return; } if (types instanceof List) { List list = (List) types; for (int i = 0; i < list.size(); i++) { Element elt = (Element) list.get(i); if (elt.getType() == type) { list.remove(i); if (list.size() == 0) data.remove(name); return; } } } else { Element elt = (Element) types; if (elt.getType() != type) return; data.remove(name); } } /** Empties the Cache. */ public void clearCache() { synchronized (this) { data.clear(); } } /** * Adds a record to the Cache. * @param r The record to be added * @param cred The credibility of the record * @param o The source of the record (this could be a Message, for example) * @see Record */ public void addRecord(Record r, int cred, Object o) { Name name = r.getName(); int type = r.getRRsetType(); if (!Type.isRR(type)) return; Element element = findElement(name, type, cred); if (element == null) { RRset rrset = new RRset(); rrset.addRR(r); addRRset(rrset, cred); } else if (cred == element.credibility) { if (element instanceof PositiveElement) { PositiveElement pe = (PositiveElement) element; pe.rrset.addRR(r); } } } /** * Adds an RRset to the Cache. * @param rrset The RRset to be added * @param cred The credibility of these records * @see RRset */ public void addRRset(RRset rrset, int cred) { long ttl = rrset.getTTL(); Name name = rrset.getName(); int type = rrset.getType(); Element element = findElement(name, type, cred); if (ttl == 0) { if (element != null && cred > element.credibility) removeElement(name, type); } else { if (element == null) addElement(name, new PositiveElement(rrset, cred, maxcache)); } } /** * Adds a negative entry to the Cache. * @param name The name of the negative entry * @param type The type of the negative entry * @param soa The SOA record to add to the negative cache entry, or null. * The negative cache ttl is derived from the SOA. * @param cred The credibility of the negative entry */ public void addNegative(Name name, int type, SOARecord soa, int cred) { long ttl = 0; if (soa != null) ttl = soa.getTTL(); Element element = findElement(name, type, cred); if (ttl == 0) { if (element != null && cred > element.credibility) removeElement(name, type); } else { if (element == null) addElement(name, new NegativeElement(name, type, soa, cred, maxncache)); } } /** * Finds all matching sets or something that causes the lookup to stop. */ protected synchronized SetResponse lookup(Name name, int type, int minCred) { int labels; int tlabels; Element element; PositiveElement pe; Name tname; Object types; SetResponse sr; labels = name.labels(); for (tlabels = labels; tlabels >= 1; tlabels boolean isRoot = (tlabels == 1); boolean isExact = (tlabels == labels); if (isRoot) tname = Name.root; else if (isExact) tname = name; else tname = new Name(name, labels - tlabels); types = data.get(tname); if (types == null) continue; /* If this is an ANY lookup, return everything. */ if (isExact && type == Type.ANY) { sr = new SetResponse(SetResponse.SUCCESSFUL); Element [] elements = allElements(types); int added = 0; for (int i = 0; i < elements.length; i++) { element = elements[i]; if (element.expired()) { removeElement(tname, element.getType()); continue; } if (element instanceof NegativeElement) continue; if (element.credibility < minCred) continue; pe = (PositiveElement) element; sr.addRRset(pe.rrset); added++; } /* There were positive entries */ if (added > 0) return sr; } /* Look for an NS */ element = oneElement(tname, types, Type.NS, minCred); if (element != null && element instanceof PositiveElement) { pe = (PositiveElement) element; return new SetResponse(SetResponse.DELEGATION, pe.rrset); } /* * If this is the name, look for the actual type or a CNAME. * Otherwise, look for a DNAME. */ if (isExact) { element = oneElement(tname, types, type, minCred); if (element != null && element instanceof PositiveElement) { pe = (PositiveElement) element; sr = new SetResponse(SetResponse.SUCCESSFUL); sr.addRRset(pe.rrset); return sr; } else if (element != null) { sr = new SetResponse(SetResponse.NXRRSET); return sr; } element = oneElement(tname, types, Type.CNAME, minCred); if (element != null && element instanceof PositiveElement) { pe = (PositiveElement) element; return new SetResponse(SetResponse.CNAME, pe.rrset); } } else { element = oneElement(tname, types, Type.DNAME, minCred); if (element != null && element instanceof PositiveElement) { pe = (PositiveElement) element; return new SetResponse(SetResponse.DNAME, pe.rrset); } } /* Check for the special NXDOMAIN element. */ if (isExact) { element = oneElement(tname, types, 0, minCred); if (element != null) return SetResponse.ofType(SetResponse.NXDOMAIN); } } return SetResponse.ofType(SetResponse.UNKNOWN); } /** * Looks up Records in the Cache. This follows CNAMEs and handles negatively * cached data. * @param name The name to look up * @param type The type to look up * @param minCred The minimum acceptable credibility * @return A SetResponse object * @see SetResponse * @see Credibility */ public SetResponse lookupRecords(Name name, int type, int minCred) { return lookup(name, type, minCred); } private RRset [] findRecords(Name name, int type, int minCred) { SetResponse cr = lookupRecords(name, type, minCred); if (cr.isSuccessful()) return cr.answers(); else return null; } /** * Looks up credible Records in the Cache (a wrapper around lookupRecords). * Unlike lookupRecords, this given no indication of why failure occurred. * @param name The name to look up * @param type The type to look up * @return An array of RRsets, or null * @see Credibility */ public RRset [] findRecords(Name name, int type) { return findRecords(name, type, Credibility.NORMAL); } /** * Looks up Records in the Cache (a wrapper around lookupRecords). Unlike * lookupRecords, this given no indication of why failure occurred. * @param name The name to look up * @param type The type to look up * @return An array of RRsets, or null * @see Credibility */ public RRset [] findAnyRecords(Name name, int type) { return findRecords(name, type, Credibility.GLUE); } private final int getCred(int section, boolean isAuth) { if (section == Section.ANSWER) { if (isAuth) return Credibility.AUTH_ANSWER; else return Credibility.NONAUTH_ANSWER; } else if (section == Section.AUTHORITY) { if (isAuth) return Credibility.AUTH_AUTHORITY; else return Credibility.NONAUTH_AUTHORITY; } else if (section == Section.ADDITIONAL) { return Credibility.ADDITIONAL; } else throw new IllegalArgumentException("getCred: invalid section"); } private static void markAdditional(RRset rrset, Set names) { Record first = rrset.first(); if (first.getAdditionalName() == null) return; Iterator it = rrset.rrs(); while (it.hasNext()) { Record r = (Record) it.next(); Name name = r.getAdditionalName(); if (name != null) names.add(name); } } /** * Adds all data from a Message into the Cache. Each record is added with * the appropriate credibility, and negative answers are cached as such. * @param in The Message to be added * @return A SetResponse that reflects what would be returned from a cache * lookup, or null if nothing useful could be cached from the message. * @see Message */ public SetResponse addMessage(Message in) { boolean isAuth = in.getHeader().getFlag(Flags.AA); Record question = in.getQuestion(); Name qname; Name curname; int qtype; int qclass; int cred; int rcode = in.getHeader().getRcode(); boolean haveAnswer = false; boolean completed = false; RRset [] answers, auth, addl; SetResponse response = null; boolean verbose = Options.check("verbosecache"); HashSet additionalNames; if ((rcode != Rcode.NOERROR && rcode != Rcode.NXDOMAIN) || question == null) return null; qname = question.getName(); qtype = question.getType(); qclass = question.getDClass(); curname = qname; additionalNames = new HashSet(); answers = in.getSectionRRsets(Section.ANSWER); for (int i = 0; i < answers.length; i++) { if (answers[i].getDClass() != qclass) continue; int type = answers[i].getType(); Name name = answers[i].getName(); cred = getCred(Section.ANSWER, isAuth); if ((type == qtype || qtype == Type.ANY) && name.equals(curname)) { addRRset(answers[i], cred); completed = true; haveAnswer = true; if (curname == qname) { if (response == null) response = new SetResponse( SetResponse.SUCCESSFUL); response.addRRset(answers[i]); } markAdditional(answers[i], additionalNames); } else if (type == Type.CNAME && name.equals(curname)) { CNAMERecord cname; addRRset(answers[i], cred); if (curname == qname) response = new SetResponse(SetResponse.CNAME, answers[i]); cname = (CNAMERecord) answers[i].first(); curname = cname.getTarget(); haveAnswer = true; } else if (type == Type.DNAME && curname.subdomain(name)) { DNAMERecord dname; addRRset(answers[i], cred); if (curname == qname) response = new SetResponse(SetResponse.DNAME, answers[i]); dname = (DNAMERecord) answers[i].first(); try { curname = curname.fromDNAME(dname); } catch (NameTooLongException e) { break; } haveAnswer = true; } } auth = in.getSectionRRsets(Section.AUTHORITY); RRset soa = null, ns = null; for (int i = 0; i < auth.length; i++) { if (auth[i].getType() == Type.SOA && curname.subdomain(auth[i].getName())) soa = auth[i]; else if (auth[i].getType() == Type.NS && curname.subdomain(auth[i].getName())) ns = auth[i]; } if (!completed) { /* This is a negative response or a referral. */ int cachetype = (rcode == Rcode.NXDOMAIN) ? 0 : qtype; if (soa != null || ns == null) { /* Negative response */ cred = getCred(Section.AUTHORITY, isAuth); SOARecord soarec = null; if (soa != null) soarec = (SOARecord) soa.first(); addNegative(curname, cachetype, soarec, cred); if (response == null) { int responseType; if (rcode == Rcode.NXDOMAIN) responseType = SetResponse.NXDOMAIN; else responseType = SetResponse.NXRRSET; response = SetResponse.ofType(responseType); } /* NXT records are not cached yet. */ } else { /* Referral response */ cred = getCred(Section.AUTHORITY, isAuth); addRRset(ns, cred); markAdditional(ns, additionalNames); if (response == null) response = new SetResponse( SetResponse.DELEGATION, ns); } } else if (rcode == Rcode.NOERROR && ns != null) { /* Cache the NS set from a positive response. */ cred = getCred(Section.AUTHORITY, isAuth); addRRset(ns, cred); markAdditional(ns, additionalNames); } addl = in.getSectionRRsets(Section.ADDITIONAL); for (int i = 0; i < addl.length; i++) { int type = addl[i].getType(); if (type != Type.A && type != Type.AAAA && type != Type.A6) continue; Name name = addl[i].getName(); if (!additionalNames.contains(name)) continue; cred = getCred(Section.ADDITIONAL, isAuth); addRRset(addl[i], cred); } if (verbose) System.out.println("addMessage: " + response); return (response); } /** * Flushes an RRset from the cache * @param name The name of the records to be flushed * @param type The type of the records to be flushed * @see RRset */ public void flushSet(Name name, int type) { removeElement(name, type); } /** * Flushes all RRsets with a given name from the cache * @param name The name of the records to be flushed * @see RRset */ public void flushName(Name name) { removeName(name); } /** * Sets the maximum length of time that a negative response will be stored * in this Cache. A negative value disables this feature (that is, sets * no limit). */ public void setMaxNCache(int seconds) { maxncache = seconds; } /** * Sets the maximum length of time that records will be stored in this * Cache. A negative value disables this feature (that is, sets no limit). */ public void setMaxCache(int seconds) { maxcache = seconds; } /** * Sets the periodic interval (in minutes) that all expired records will be * expunged from the cache. The default is 30 minutes. 0 or a negative value * disables this feature. * @param cleanInterval The interval between cache cleanings, in minutes. */ public void setCleanInterval(int cleanInterval) { if (cleaner != null) { cleaner.interrupt(); } if (cleanInterval > 0) cleaner = new CacheCleaner(this, cleanInterval); } protected void finalize() throws Throwable { try { setCleanInterval(0); } finally { super.finalize(); } } }
package Honeybadger; import java.util.concurrent.*; import java.io.*; import com.google.gson.*; import com.google.gson.stream.*; import java.net.*; import javax.net.ssl.HttpsURLConnection; public class Honeybadger implements Thread.UncaughtExceptionHandler{ private final String HONEY_BADGER_URL = "https://api.honeybadger.io/v1/notices"; private String apiKey; private String envName; public Honeybadger(){ apiKey = System.getenv("HONEYBADGER_API_KEY"); //set this environmental variable to your api key envName = System.getenv("RACK_ENV"); //set this env var to your environment...development or production Thread.setDefaultUncaughtExceptionHandler(this);//report all uncaught exceptions to honey badger } /* In your main function add the following 2 lines HoneyBadger honeyBadger = new HoneyBadger(); */ public void uncaughtException(Thread thread, Throwable error) { reportErrorToHoneyBadger(error); } /* You can send a throwable to honeybadger */ public void reportErrorToHoneyBadger(Throwable error){ Gson myGson = new Gson(); JsonObject jsonError = new JsonObject(); jsonError.add("notifier", makeNotifier()); jsonError.add("error", makeError(error)); /* If you need to add more information to your errors add it here */ jsonError.add("server", makeServer()); int responseCode = sendToHoneyBadger(myGson.toJson(jsonError)); if(responseCode!=201) System.err.println("ERROR: Honeybadger did not respond with the correct code. Response was = "+responseCode); else System.err.println("Honeybadger logged error: "+error); } /* Identify the notifier */ private JsonObject makeNotifier(){ JsonObject notifier = new JsonObject(); notifier.addProperty("name", "Honeybadger-java Notifier"); notifier.addProperty("url", "www.mytastebud.com"); notifier.addProperty("version", "1.3.0"); return notifier; } /* Format the throwable into a json object */ private JsonObject makeError(Throwable error){ JsonObject jsonError = new JsonObject(); jsonError.addProperty("class", error.toString()); JsonArray backTrace = new JsonArray(); for(StackTraceElement trace : error.getStackTrace()){ JsonObject jsonTraceElement = new JsonObject(); jsonTraceElement.addProperty("number", trace.getLineNumber()); jsonTraceElement.addProperty("file", trace.getFileName()); jsonTraceElement.addProperty("method", trace.getMethodName()); backTrace.add(jsonTraceElement); } jsonError.add("backtrace", backTrace); return jsonError; } /* Establish the environment */ private JsonObject makeServer(){ JsonObject jsonServer = new JsonObject(); jsonServer.addProperty("environment_name", envName); return jsonServer; } /* Send the json string error to honeybadger */ private int sendToHoneyBadger(String jsonError){ URL obj = null; HttpsURLConnection con = null; DataOutputStream wr = null; BufferedReader in = null; int responseCode = -1; try{ obj = new URL(HONEY_BADGER_URL); con = (HttpsURLConnection) obj.openConnection(); //add request header con.setRequestMethod("POST"); con.setRequestProperty("X-API-Key", apiKey); con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("Accept", "application/json"); // Send post request con.setDoOutput(true); wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(jsonError); wr.flush(); responseCode = con.getResponseCode(); in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } } catch(MalformedURLException e){ System.err.println("Bad url "+HONEY_BADGER_URL+" "+e); } catch(IOException e){ System.err.println("Bad io "+HONEY_BADGER_URL+" "+e); } finally{ try{ if(in!=null) in.close(); if(wr!=null) wr.close(); } catch(Exception e){ System.err.println("Failure to close honey badger "+e); } } return responseCode; } }
package org.xbill.DNS; import org.xbill.DNS.utils.*; /** * Constants and functions relating to DNS rcodes (error values) * * @author Brian Wellington */ public final class Rcode { private static StringValueTable rcodes = new StringValueTable(); private static StringValueTable tsigrcodes = new StringValueTable(); /** No error */ public static final byte NOERROR = 0; /** Format error */ public static final byte FORMERR = 1; /** Server failure */ public static final byte SERVFAIL = 2; /** The name does not exist */ public static final byte NXDOMAIN = 3; /** The operation requested is not implemented */ public static final byte NOTIMPL = 4; /** The operation was refused by the server */ public static final byte REFUSED = 5; /** The name exists */ public static final byte YXDOMAIN = 6; /** The RRset (name, type) exists */ public static final byte YXRRSET = 7; /** The RRset (name, type) does not exist */ public static final byte NXRRSET = 8; /** The requestor is not authorized to perform this operation */ public static final byte NOTAUTH = 9; /** The zone specified is not a zone */ public static final byte NOTZONE = 10; /* EDNS extended rcodes */ /** Unsupported EDNS level */ public static final byte BADVERS = 16; /* TSIG/TKEY only rcodes */ /** The signature is invalid (TSIG/TKEY extended error) */ public static final byte BADSIG = 16; /** The key is invalid (TSIG/TKEY extended error) */ public static final byte BADKEY = 17; /** The time is out of range (TSIG/TKEY extended error) */ public static final byte BADTIME = 18; /** The mode is invalid (TKEY extended error) */ public static final byte BADMODE = 18; static { rcodes.put2(NOERROR, "NOERROR"); rcodes.put2(FORMERR, "FORMERR"); rcodes.put2(SERVFAIL, "SERVFAIL"); rcodes.put2(NXDOMAIN, "NXDOMAIN"); rcodes.put2(NOTIMPL, "NOTIMPL"); rcodes.put2(REFUSED, "REFUSED"); rcodes.put2(YXDOMAIN, "YXDOMAIN"); rcodes.put2(YXRRSET, "YXRRSET"); rcodes.put2(NXRRSET, "NXRRSET"); rcodes.put2(NOTAUTH, "NOTAUTH"); rcodes.put2(NOTZONE, "NOTZONE"); rcodes.put2(BADVERS, "BADVERS"); tsigrcodes.put2(BADSIG, "BADSIG"); tsigrcodes.put2(BADKEY, "BADKEY"); tsigrcodes.put2(BADTIME, "BADTIME"); tsigrcodes.put2(BADMODE, "BADMODE"); } private Rcode() {} /** Converts a numeric Rcode into a String */ public static String string(int i) { String s = rcodes.getString(i); return (s != null) ? s : new Integer(i).toString(); } /** Converts a numeric TSIG extended Rcode into a String */ public static String TSIGstring(int i) { String s = tsigrcodes.getString(i); if (s != null) return s; s = rcodes.getString(i); return (s != null) ? s : new Integer(i).toString(); } /** Converts a String representation of an Rcode into its numeric value */ public static byte value(String s) { byte i = (byte) rcodes.getValue(s.toUpperCase()); if (i >= 0) return i; try { return Byte.parseByte(s); } catch (Exception e) { return (-1); } } }
package org.apache.velocity.runtime.directive; import java.io.Writer; import java.io.IOException; import java.util.TreeMap; import org.apache.velocity.Context; import org.apache.velocity.runtime.parser.node.Node; import org.apache.velocity.runtime.parser.Token; import org.apache.velocity.runtime.Runtime; import org.apache.velocity.runtime.RuntimeConstants; /** * Macro.java * * Macro implements the macro definition directive of VTL. * * example : * * #macro( isnull $i ) * #if( $i ) * $i * #end * #end * * This object is used at parse time to mainly process and register the * macro. It is used inline in the parser when processing a directive. * * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a> * @version $Id: Macro.java,v 1.8 2000/12/20 07:38:16 jvanzyl Exp $ */ public class Macro extends Directive { private static boolean debugMode = false; /** * Return name of this directive. */ public String getName() { return "macro"; } /** * Return type of this directive. */ public int getType() { return BLOCK; } /** * render() doesn't do anything in the final output rendering. * There is no output from a #macro() directive. */ public boolean render(Context context, Writer writer, Node node) throws IOException { /* * do nothing : We never render. The VelocimacroProxy object does that */ return true; } public void init(Context context, Node node) throws Exception { /* * again, don't do squat. We want the AST of the macro * block to hang off of this but we don't want to * init it... it's useless... */ return; } /** * Used by Parser.java to process VMs withing the parsing process * * processAndRegister() doesn't actually render the macro to the output * Processes the macro body into the internal representation used by the * VelocimacroProxy objects, and if not currently used, adds it * to the macro Factory */ public void processAndRegister( Node node, String sourceTemplate ) throws IOException { /* * There must be at least one arg to #macro, * the name of the VM. Note that 0 following * args is ok for naming blocks of HTML */ int numArgs = node.jjtGetNumChildren(); /* * this number is the # of args + 1. The + 1 * is for the block tree */ if (numArgs < 2) { /* * error - they didn't name the macro or * define a block */ Runtime.error("#macro error : Velocimacro must have name as 1st " + "argument to #macro()"); return; } /* * get the arguments to the use of the VM */ String argArray[] = getArgArray( node ); /* * now, try and eat the code block. Pass the root. */ String macroArray[] = getASTAsStringArray( node.jjtGetChild( numArgs - 1) ); /* * make a big string out of our macro */ StringBuffer temp = new StringBuffer(); for( int i=0; i < macroArray.length; i++) temp.append( macroArray[i] ); String macroBody = temp.toString(); /* * now, using the macro body string and the arg list, index * all the tokens in the arglist */ TreeMap argIndexMap = getArgIndexMap( macroBody, argArray ); boolean bRet = Runtime.addVelocimacro( argArray[0], macroBody, argArray, macroArray, argIndexMap, sourceTemplate ); return; } /** * using the macro body and the arg list, creates a TreeMap * of the indices of the args in the body Makes for fast * and efficient patching at runtime */ private TreeMap getArgIndexMap( String macroBody, String argArray[] ) { TreeMap tm = new TreeMap(); /* * run through the buffer for each paramter, and remember * where they go. We have to do this all at once to * avoid confusing later replacement attempts with the * activity of earlier ones */ for (int i=1; i<argArray.length; i++) { /* * keep going until we don't get any matches */ int index = 0; while( ( index = macroBody.indexOf( argArray[i], index )) != -1 ) { tm.put(new Integer( index ), new Integer( i )); index++; } } return tm; } /** * creates an array containing the literal * strings in the macro arguement */ private String[] getArgArray( Node node ) { /* * remember : this includes the block tree */ int numArgs = node.jjtGetNumChildren(); numArgs--; // avoid the block tree... String argArray[] = new String[ numArgs ]; int i = 0; /* * eat the args */ while( i < numArgs ) { argArray[i] = node.jjtGetChild(i).getFirstToken().image; i++; } if ( debugMode ) { System.out.println("Macro.getArgArray() : #args = " + numArgs ); System.out.print( argArray[0] + "(" ); for ( i = 1; i < numArgs; i++) System.out.print(" " + argArray[i] ); System.out.println(" )"); } return argArray; } /** * Returns an array of the literal rep of the AST */ private String [] getASTAsStringArray( Node rootNode ) { /* * this assumes that we are passed in the root * node of the code block */ Token t = rootNode.getFirstToken(); Token tLast = rootNode.getLastToken(); /* * now, run down the part of the tree bounded by * our first and last tokens */ int count = 0; //! Should this use the node.literal() ? while( t != null && t != tLast ) { count++; t = t.next; } /* * account for the last one */ count++; /* * now, do it for real */ String arr[] = new String[count]; count = 0; t = rootNode.getFirstToken(); while( t != tLast ) { arr[count++] = t.image; t = t.next; } /* * make sure we get the last one... */ arr[count] = t.image; return arr; } }
package appium; import java.io.*; import classes.*; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.net.URL; import io.appium.java_client.AppiumDriver; import io.appium.java_client.MobileElement; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.android.AndroidElement; import org.eclipse.jdt.internal.compiler.parser.Scanner; import org.openqa.selenium.By; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; public class AppiumTest { // Default server is localhost (127.0.0.1) on port 4723 public static String DEFAULT_SERVER = "http://localhost"; public static String DEFAULT_PORT = "4723"; public static String DEFAULT_SUFFIX = "/wd/hub"; private static String DEFAULT_APPIUM_DIR = "C:\\Program Files (x86)\\Appium"; /* * Android emulator's attributes. * Needed to connect with Appium. * * Obtain device info by going into "Settings" --> "About phone" on your device/emulator * * (Replace with your own emulator/device info...) */ public static String DEVICE_NAME = "Google Nexus 4 - 5.1.0 - API 22 - 768x1280"; public static String PLATFORM_NAME = "Android"; public static String PLATFORM_VERSION = "5.1"; //public static String GMDICE_DIR = System.getProperty("user.dir") + "\\apk\\gmdice.apk"; public static String GMDICE_DIR = "gmdice.apk"; public static void main( String [] args ) throws IOException, AppiumException, InterruptedException { //used to handle user input into the console BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String directory = null; // Ask user to specify their Appium Directory if not the same as default --> (C:\\Program Files (x86)\\Appium) System.out.println("DEFAULT APPIUM DIRECTORY : C:\\Program Files (x86)\\Appium\n" + "Use default directory? "); String input = in.readLine(); if(input.matches("[y|Y].*")){ System.out.println("Using DEFAULT APPIUM DIRECTORY..."); directory = DEFAULT_APPIUM_DIR; }else if(input.matches("[n|N].*")){ System.out.println("Okay. Enter the absolute path to the Appium directory on your system:"); directory = in.readLine(); }else{ System.out.println("Invalid Choice. Goodbye."); System.exit(-1); } //TODO: Ask user about their google emulator/device options, set other Strings accordingly //TODO: prompt user to select an absolute path for their apk of choice //TODO: prompt user for JSON file to parse with Gson // Start Appium server AppiumServerWorker serverWorker = new AppiumServerWorker(directory); serverWorker.startServer(); // Minimum # of capabilities to run // Remember 'no reset' because you don't want it to install apk every time!! DesiredCapabilities capability = new DesiredCapabilities(); capability.setCapability("deviceName", DEVICE_NAME); capability.setCapability("platformName", PLATFORM_NAME); capability.setCapability("platformVersion", PLATFORM_VERSION); // Specify apk file to test File file = new File("Code\\TranslatorDraft2\\res\\apk", GMDICE_DIR); capability.setCapability("app", file.getAbsolutePath()); URL serverURL = new URL(DEFAULT_SERVER + ":" + DEFAULT_PORT + DEFAULT_SUFFIX); // Connect capability to server // AppiumDriver is the main class that allows us to interact with Appium, // which then interacts with the mobile device AndroidDriver driver = new AndroidDriver(serverURL, capability); // Check that driver was able to connect to emulator/device //serverWorker.getServerResponse(DEFAULT_SERVER + ":" + DEFAULT_PORT + DEFAULT_SUFFIX); performTest(driver); // Quit driver.quit(); serverWorker.stopServer(); System.exit(0); } //borrowed the parse method...TODO: Update to prompt user for JSON file location public static TestCase parse() throws IOException { TestCase list_of_actions = null; //If there's a need to get rid of hard coding, this is where to do it. InputStream stream = new FileInputStream("Code/TranslatorDraft2/gmdice_simple.txt"); System.out.println(stream); Reader reader = new InputStreamReader(stream, "UTF-8"); try{ Gson gson = new GsonBuilder().create(); list_of_actions = gson.fromJson(reader,TestCase.class); System.out.println("Parsing... Succeeds?"); return list_of_actions; } catch (Exception e){ System.out.println("Parsing failed. Returning null."); return list_of_actions; } } public static void performTest(RemoteWebDriver driver) throws IOException, InterruptedException { /* Obtain tap IDs from parse method and JSON file*/ TestCase appiumTest = parse(); int i; for(i=0; i<appiumTest.getSteps().size() ; i++) { //String fullID = appiumTest.getPackageName() + ":" + appiumTest.getSteps().get(i).getComponent().getId(); String fullID = appiumTest.getSteps().get(i).getComponent().getText(); if(appiumTest.getSteps().get(i).getAction().contentEquals("CLICK")){ driver.findElement(By.name(fullID)).click(); Thread.sleep(500); System.out.println("clicked button at " + fullID); }else if(appiumTest.getSteps().get(i).getAction().contentEquals("LONG_CLICK")){ MobileElement button = (MobileElement)driver.findElement(By.name(fullID)); button.tap(1, 1000); Thread.sleep(500); System.out.println("long clicked button at" + fullID); } } } }
package org.jdesktop.swingx.border; import org.jdesktop.swingx.graphics.GraphicsUtilities; import javax.swing.border.Border; import java.awt.*; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.awt.image.ConvolveOp; import java.awt.image.Kernel; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * Implements a DropShadow for components. In general, the DropShadowBorder will * work with any rectangular components that do not have a default border * installed as part of the look and feel, or otherwise. For example, * DropShadowBorder works wonderfully with JPanel, but horribly with JComboBox. * <p> * Note: {@code DropShadowBorder} should usually be added to non-opaque * components, otherwise the background is likely to bleed through.</p> * <p>Note: Since generating drop shadows is relatively expensive operation, * {@code DropShadowBorder} keeps internal static cache that allows sharing * same border for multiple re-rendering and between different instances of the * class. Since this cache is shared at class level and never reset, it might * bleed your app memory in case you tend to create many different borders * rapidly.</p> * @author rbair */ public class DropShadowBorder implements Border, Serializable { private static final long serialVersionUID = 715287754750604058L; private static enum Position {TOP, TOP_LEFT, LEFT, BOTTOM_LEFT, BOTTOM, BOTTOM_RIGHT, RIGHT, TOP_RIGHT} private static final Map<Double,Map<Position,BufferedImage>> CACHE = new HashMap<Double,Map<Position,BufferedImage>>(); private Color shadowColor; public void setShadowColor(Color shadowColor) { this.shadowColor = shadowColor; } public void setShadowSize(int shadowSize) { this.shadowSize = shadowSize; } public void setShadowOpacity(float shadowOpacity) { this.shadowOpacity = shadowOpacity; } public void setCornerSize(int cornerSize) { this.cornerSize = cornerSize; } public void setShowTopShadow(boolean showTopShadow) { this.showTopShadow = showTopShadow; } public void setShowLeftShadow(boolean showLeftShadow) { this.showLeftShadow = showLeftShadow; } public void setShowBottomShadow(boolean showBottomShadow) { this.showBottomShadow = showBottomShadow; } public void setShowRightShadow(boolean showRightShadow) { this.showRightShadow = showRightShadow; } private int shadowSize; private float shadowOpacity; private int cornerSize; private boolean showTopShadow; private boolean showLeftShadow; private boolean showBottomShadow; private boolean showRightShadow; public DropShadowBorder() { this(Color.BLACK, 5); } public DropShadowBorder(Color shadowColor, int shadowSize) { this(shadowColor, shadowSize, .5f, 12, false, false, true, true); } public DropShadowBorder(boolean showLeftShadow) { this(Color.BLACK, 5, .5f, 12, false, showLeftShadow, true, true); } public DropShadowBorder(Color shadowColor, int shadowSize, float shadowOpacity, int cornerSize, boolean showTopShadow, boolean showLeftShadow, boolean showBottomShadow, boolean showRightShadow) { this.shadowColor = shadowColor; this.shadowSize = shadowSize; this.shadowOpacity = shadowOpacity; this.cornerSize = cornerSize; this.showTopShadow = showTopShadow; this.showLeftShadow = showLeftShadow; this.showBottomShadow = showBottomShadow; this.showRightShadow = showRightShadow; } /** * {@inheritDoc} */ public void paintBorder(Component c, Graphics graphics, int x, int y, int width, int height) { /* * 1) Get images for this border * 2) Paint the images for each side of the border that should be painted */ Map<Position,BufferedImage> images = getImages((Graphics2D)graphics); Graphics2D g2 = (Graphics2D)graphics.create(); //The location and size of the shadows depends on which shadows are being //drawn. For instance, if the left & bottom shadows are being drawn, then //the left shadow extends all the way down to the corner, a corner is drawn, //and then the bottom shadow begins at the corner. If, however, only the //bottom shadow is drawn, then the bottom-left corner is drawn to the //right of the corner, and the bottom shadow is somewhat shorter than before. int shadowOffset = 2; //the distance between the shadow and the edge Point topLeftShadowPoint = null; if (showLeftShadow || showTopShadow) { topLeftShadowPoint = new Point(); if (showLeftShadow && !showTopShadow) { topLeftShadowPoint.setLocation(x, y + shadowOffset); } else if (showLeftShadow && showTopShadow) { topLeftShadowPoint.setLocation(x, y); } else if (!showLeftShadow && showTopShadow) { topLeftShadowPoint.setLocation(x + shadowSize, y); } } Point bottomLeftShadowPoint = null; if (showLeftShadow || showBottomShadow) { bottomLeftShadowPoint = new Point(); if (showLeftShadow && !showBottomShadow) { bottomLeftShadowPoint.setLocation(x, y + height - shadowSize - shadowSize); } else if (showLeftShadow && showBottomShadow) { bottomLeftShadowPoint.setLocation(x, y + height - shadowSize); } else if (!showLeftShadow && showBottomShadow) { bottomLeftShadowPoint.setLocation(x + shadowSize, y + height - shadowSize); } } Point bottomRightShadowPoint = null; if (showRightShadow || showBottomShadow) { bottomRightShadowPoint = new Point(); if (showRightShadow && !showBottomShadow) { bottomRightShadowPoint.setLocation(x + width - shadowSize, y + height - shadowSize - shadowSize); } else if (showRightShadow && showBottomShadow) { bottomRightShadowPoint.setLocation(x + width - shadowSize, y + height - shadowSize); } else if (!showRightShadow && showBottomShadow) { bottomRightShadowPoint.setLocation(x + width - shadowSize - shadowSize, y + height - shadowSize); } } Point topRightShadowPoint = null; if (showRightShadow || showTopShadow) { topRightShadowPoint = new Point(); if (showRightShadow && !showTopShadow) { topRightShadowPoint.setLocation(x + width - shadowSize, y + shadowOffset); } else if (showRightShadow && showTopShadow) { topRightShadowPoint.setLocation(x + width - shadowSize, y); } else if (!showRightShadow && showTopShadow) { topRightShadowPoint.setLocation(x + width - shadowSize - shadowSize, y); } } g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED); if (showLeftShadow) { Rectangle leftShadowRect = new Rectangle(x, topLeftShadowPoint.y + shadowSize, shadowSize, bottomLeftShadowPoint.y - topLeftShadowPoint.y - shadowSize); g2.drawImage(images.get(Position.LEFT), leftShadowRect.x, leftShadowRect.y, leftShadowRect.width, leftShadowRect.height, null); } if (showBottomShadow) { Rectangle bottomShadowRect = new Rectangle(bottomLeftShadowPoint.x + shadowSize, y + height - shadowSize, bottomRightShadowPoint.x - bottomLeftShadowPoint.x - shadowSize, shadowSize); g2.drawImage(images.get(Position.BOTTOM), bottomShadowRect.x, bottomShadowRect.y, bottomShadowRect.width, bottomShadowRect.height, null); } if (showRightShadow) { Rectangle rightShadowRect = new Rectangle(x + width - shadowSize, topRightShadowPoint.y + shadowSize, shadowSize, bottomRightShadowPoint.y - topRightShadowPoint.y - shadowSize); g2.drawImage(images.get(Position.RIGHT), rightShadowRect.x, rightShadowRect.y, rightShadowRect.width, rightShadowRect.height, null); } if (showTopShadow) { Rectangle topShadowRect = new Rectangle(topLeftShadowPoint.x + shadowSize, y, topRightShadowPoint.x - topLeftShadowPoint.x - shadowSize, shadowSize); g2.drawImage(images.get(Position.TOP), topShadowRect.x, topShadowRect.y, topShadowRect.width, topShadowRect.height, null); } if (showLeftShadow || showTopShadow) { g2.drawImage(images.get(Position.TOP_LEFT), topLeftShadowPoint.x, topLeftShadowPoint.y, null); } if (showLeftShadow || showBottomShadow) { g2.drawImage(images.get(Position.BOTTOM_LEFT), bottomLeftShadowPoint.x, bottomLeftShadowPoint.y, null); } if (showRightShadow || showBottomShadow) { g2.drawImage(images.get(Position.BOTTOM_RIGHT), bottomRightShadowPoint.x, bottomRightShadowPoint.y, null); } if (showRightShadow || showTopShadow) { g2.drawImage(images.get(Position.TOP_RIGHT), topRightShadowPoint.x, topRightShadowPoint.y, null); } g2.dispose(); } private Map<Position,BufferedImage> getImages(Graphics2D g2) { //first, check to see if an image for this size has already been rendered //if so, use the cache. Else, draw and save Map<Position,BufferedImage> images = CACHE.get(shadowSize + (shadowColor.hashCode() * .3) + (shadowOpacity * .12));//TODO do a real hash if (images == null) { images = new HashMap<Position,BufferedImage>(); /* * To draw a drop shadow, I have to: * 1) Create a rounded rectangle * 2) Create a BufferedImage to draw the rounded rect in * 3) Translate the graphics for the image, so that the rectangle * is centered in the drawn space. The border around the rectangle * needs to be shadowWidth wide, so that there is space for the * shadow to be drawn. * 4) Draw the rounded rect as shadowColor, with an opacity of shadowOpacity * 5) Create the BLUR_KERNEL * 6) Blur the image * 7) copy off the corners, sides, etc into images to be used for * drawing the Border */ int rectWidth = cornerSize + 1; RoundRectangle2D rect = new RoundRectangle2D.Double(0, 0, rectWidth, rectWidth, cornerSize, cornerSize); int imageWidth = rectWidth + shadowSize * 2; BufferedImage image = GraphicsUtilities.createCompatibleTranslucentImage(imageWidth, imageWidth); Graphics2D buffer = (Graphics2D)image.getGraphics(); buffer.setPaint(new Color(shadowColor.getRed(), shadowColor.getGreen(), shadowColor.getBlue(), (int)(shadowOpacity * 255))); // buffer.setColor(new Color(0.0f, 0.0f, 0.0f, shadowOpacity)); buffer.translate(shadowSize, shadowSize); buffer.fill(rect); buffer.dispose(); float blurry = 1.0f / (float)(shadowSize * shadowSize); float[] blurKernel = new float[shadowSize * shadowSize]; for (int i=0; i<blurKernel.length; i++) { blurKernel[i] = blurry; } ConvolveOp blur = new ConvolveOp(new Kernel(shadowSize, shadowSize, blurKernel)); BufferedImage targetImage = GraphicsUtilities.createCompatibleTranslucentImage(imageWidth, imageWidth); ((Graphics2D)targetImage.getGraphics()).drawImage(image, blur, -(shadowSize/2), -(shadowSize/2)); int x = 1; int y = 1; int w = shadowSize; int h = shadowSize; images.put(Position.TOP_LEFT, getSubImage(targetImage, x, y, w, h)); x = 1; y = h; w = shadowSize; h = 1; images.put(Position.LEFT, getSubImage(targetImage, x, y, w, h)); x = 1; y = rectWidth; w = shadowSize; h = shadowSize; images.put(Position.BOTTOM_LEFT, getSubImage(targetImage, x, y, w, h)); x = cornerSize + 1; y = rectWidth; w = 1; h = shadowSize; images.put(Position.BOTTOM, getSubImage(targetImage, x, y, w, h)); x = rectWidth; y = x; w = shadowSize; h = shadowSize; images.put(Position.BOTTOM_RIGHT, getSubImage(targetImage, x, y, w, h)); x = rectWidth; y = cornerSize + 1; w = shadowSize; h = 1; images.put(Position.RIGHT, getSubImage(targetImage, x, y, w, h)); x = rectWidth; y = 1; w = shadowSize; h = shadowSize; images.put(Position.TOP_RIGHT, getSubImage(targetImage, x, y, w, h)); x = shadowSize; y = 1; w = 1; h = shadowSize; images.put(Position.TOP, getSubImage(targetImage, x, y, w, h)); image.flush(); CACHE.put(shadowSize + (shadowColor.hashCode() * .3) + (shadowOpacity * .12), images); //TODO do a real hash } return images; } /** * Returns a new BufferedImage that represents a subregion of the given * BufferedImage. (Note that this method does not use * BufferedImage.getSubimage(), which will defeat image acceleration * strategies on later JDKs.) */ private BufferedImage getSubImage(BufferedImage img, int x, int y, int w, int h) { BufferedImage ret = GraphicsUtilities.createCompatibleTranslucentImage(w, h); Graphics2D g2 = ret.createGraphics(); g2.drawImage(img, 0, 0, w, h, x, y, x+w, y+h, null); g2.dispose(); return ret; } /** * @inheritDoc */ public Insets getBorderInsets(Component c) { int top = showTopShadow ? shadowSize : 0; int left = showLeftShadow ? shadowSize : 0; int bottom = showBottomShadow ? shadowSize : 0; int right = showRightShadow ? shadowSize : 0; return new Insets(top, left, bottom, right); } /** * {@inheritDoc} */ public boolean isBorderOpaque() { return false; } public boolean isShowTopShadow() { return showTopShadow; } public boolean isShowLeftShadow() { return showLeftShadow; } public boolean isShowRightShadow() { return showRightShadow; } public boolean isShowBottomShadow() { return showBottomShadow; } public int getShadowSize() { return shadowSize; } public Color getShadowColor() { return shadowColor; } public float getShadowOpacity() { return shadowOpacity; } public int getCornerSize() { return cornerSize; } }
package me.chanjar.weixin.cp.bean.message; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamConverter; import com.thoughtworks.xstream.annotations.XStreamImplicit; import lombok.Data; import lombok.extern.slf4j.Slf4j; import me.chanjar.weixin.common.api.WxConsts; import me.chanjar.weixin.common.error.WxRuntimeException; import me.chanjar.weixin.common.util.XmlUtils; import me.chanjar.weixin.common.util.xml.IntegerArrayConverter; import me.chanjar.weixin.common.util.xml.LongArrayConverter; import me.chanjar.weixin.common.util.xml.XStreamCDataConverter; import me.chanjar.weixin.cp.config.WxCpConfigStorage; import me.chanjar.weixin.cp.util.crypto.WxCpCryptUtil; import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder; import me.chanjar.weixin.cp.util.xml.XStreamTransformer; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Map; @Data @Slf4j @XStreamAlias("xml") public class WxCpXmlMessage implements Serializable { private static final long serialVersionUID = -1042994982179476410L; /** * dom4jxmlmap. */ private Map<String, Object> allFieldsMap; // xmlelement @XStreamAlias("AgentID") private String agentId; @XStreamAlias("ToUserName") @XStreamConverter(value = XStreamCDataConverter.class) private String toUserName; @XStreamAlias("FromUserName") @XStreamConverter(value = XStreamCDataConverter.class) private String fromUserName; @XStreamAlias("CreateTime") private Long createTime; /** * <pre> * * {@link WxConsts.XmlMsgType#TEXT} * {@link WxConsts.XmlMsgType#IMAGE} * {@link WxConsts.XmlMsgType#VOICE} * {@link WxConsts.XmlMsgType#VIDEO} * {@link WxConsts.XmlMsgType#LOCATION} * {@link WxConsts.XmlMsgType#LINK} * {@link WxConsts.XmlMsgType#EVENT} * * {@link WxConsts.XmlMsgType#TEXT} * {@link WxConsts.XmlMsgType#IMAGE} * {@link WxConsts.XmlMsgType#VOICE} * {@link WxConsts.XmlMsgType#VIDEO} * {@link WxConsts.XmlMsgType#NEWS} * </pre> */ @XStreamAlias("MsgType") @XStreamConverter(value = XStreamCDataConverter.class) private String msgType; @XStreamAlias("Content") @XStreamConverter(value = XStreamCDataConverter.class) private String content; @XStreamAlias("MsgId") private Long msgId; @XStreamAlias("PicUrl") @XStreamConverter(value = XStreamCDataConverter.class) private String picUrl; @XStreamAlias("MediaId") @XStreamConverter(value = XStreamCDataConverter.class) private String mediaId; @XStreamAlias("Format") @XStreamConverter(value = XStreamCDataConverter.class) private String format; @XStreamAlias("ThumbMediaId") @XStreamConverter(value = XStreamCDataConverter.class) private String thumbMediaId; @XStreamAlias("Location_X") private Double locationX; @XStreamAlias("Location_Y") private Double locationY; @XStreamAlias("Scale") private Double scale; @XStreamAlias("Label") @XStreamConverter(value = XStreamCDataConverter.class) private String label; @XStreamAlias("Title") @XStreamConverter(value = XStreamCDataConverter.class) private String title; @XStreamAlias("Description") @XStreamConverter(value = XStreamCDataConverter.class) private String description; @XStreamAlias("Url") @XStreamConverter(value = XStreamCDataConverter.class) private String url; @XStreamAlias("Event") @XStreamConverter(value = XStreamCDataConverter.class) private String event; @XStreamAlias("UpdateDetail") @XStreamConverter(value = XStreamCDataConverter.class) private String updateDetail; @XStreamAlias("JoinScene") @XStreamConverter(value = XStreamCDataConverter.class) private String joinScene; @XStreamAlias("QuitScene") @XStreamConverter(value = XStreamCDataConverter.class) private String quitScene; @XStreamAlias("MemChangeCnt") @XStreamConverter(value = XStreamCDataConverter.class) private String memChangeCnt; @XStreamAlias("Source") @XStreamConverter(value = XStreamCDataConverter.class) private String source; @XStreamAlias("StrategyId") private String strategyId; @XStreamAlias("EventKey") @XStreamConverter(value = XStreamCDataConverter.class) private String eventKey; @XStreamAlias("Ticket") @XStreamConverter(value = XStreamCDataConverter.class) private String ticket; @XStreamAlias("Latitude") private Double latitude; @XStreamAlias("Longitude") private Double longitude; @XStreamAlias("Precision") private Double precision; @XStreamAlias("Recognition") @XStreamConverter(value = XStreamCDataConverter.class) private String recognition; @XStreamAlias("TaskId") @XStreamConverter(value = XStreamCDataConverter.class) private String taskId; /** * . * me.chanjar.weixin.cp.constant.WxCpConsts.ContactChangeType */ @XStreamAlias("ChangeType") @XStreamConverter(value = XStreamCDataConverter.class) private String changeType; /** * UserID. */ @XStreamAlias("UserID") @XStreamConverter(value = XStreamCDataConverter.class) private String userId; /** * userid. */ @XStreamAlias("ExternalUserID") @XStreamConverter(value = XStreamCDataConverter.class) private String externalUserId; /** * state. */ @XStreamAlias("State") @XStreamConverter(value = XStreamCDataConverter.class) private String state; /** * code. */ @XStreamAlias("WelcomeCode") @XStreamConverter(value = XStreamCDataConverter.class) private String welcomeCode; /** * UserIDuserid. */ @XStreamAlias("NewUserID") @XStreamConverter(value = XStreamCDataConverter.class) private String newUserId; @XStreamAlias("Name") @XStreamConverter(value = XStreamCDataConverter.class) private String name; @XStreamAlias("Department") @XStreamConverter(value = LongArrayConverter.class) private Long[] departments; @XStreamAlias("MainDepartment") private Long mainDepartment; @XStreamAlias("Mobile") @XStreamConverter(value = XStreamCDataConverter.class) private String mobile; /** * 0~64. */ @XStreamAlias("Position") @XStreamConverter(value = XStreamCDataConverter.class) private String position; @XStreamAlias("ChatId") @XStreamConverter(value = XStreamCDataConverter.class) private String chatId; @XStreamAlias("Gender") private Integer gender; @XStreamAlias("Email") @XStreamConverter(value = XStreamCDataConverter.class) private String email; @XStreamAlias("BizMail") @XStreamConverter(value = XStreamCDataConverter.class) private String bizMail; @XStreamAlias("Avatar") @XStreamConverter(value = XStreamCDataConverter.class) private String avatar; @XStreamAlias("EnglishName") @XStreamConverter(value = XStreamCDataConverter.class) private String englishName; @XStreamAlias("IsLeader") private Integer isLeader; /** * 0-1-Department. */ @XStreamAlias("IsLeaderInDept") @XStreamConverter(value = IntegerArrayConverter.class) private Integer[] isLeaderInDept; @XStreamAlias("Telephone") @XStreamConverter(value = XStreamCDataConverter.class) private String telephone; @XStreamAlias("Address") @XStreamConverter(value = XStreamCDataConverter.class) private String address; @XStreamAlias("ScheduleId") @XStreamConverter(value = XStreamCDataConverter.class) private String scheduleId; @XStreamAlias("CalId") @XStreamConverter(value = XStreamCDataConverter.class) private String calId; @XStreamAlias("ExtAttr") private ExtAttr extAttrs = new ExtAttr(); /** * Id. * /id */ @XStreamAlias("Id") @XStreamConverter(XStreamCDataConverter.class) private String id; @XStreamAlias("ParentId") @XStreamConverter(value = XStreamCDataConverter.class) private String parentId; @XStreamAlias("Order") @XStreamConverter(value = XStreamCDataConverter.class) private String order; @XStreamAlias("TagId") @XStreamConverter(value = XStreamCDataConverter.class) private String tagId; /** * userid. */ @XStreamAlias("AddUserItems") @XStreamConverter(value = XStreamCDataConverter.class) private String addUserItems; /** * userid. */ @XStreamAlias("DelUserItems") @XStreamConverter(value = XStreamCDataConverter.class) private String delUserItems; @XStreamAlias("AddPartyItems") @XStreamConverter(value = XStreamCDataConverter.class) private String addPartyItems; @XStreamAlias("DelPartyItems") @XStreamConverter(value = XStreamCDataConverter.class) private String delPartyItems; @XStreamAlias("FailReason") @XStreamConverter(XStreamCDataConverter.class) private String failReason; @XStreamAlias("TagType") @XStreamConverter(XStreamCDataConverter.class) private String tagType; /** * . * 1. . * 2. * 1= 2= 4= . */ @XStreamAlias("Status") @XStreamConverter(value = XStreamCDataConverter.class) private String status; /** * group_idopenid_list. */ @XStreamAlias("TotalCount") private Integer totalCount; /** * . * 4filterCount = sentCount + errorCount */ @XStreamAlias("FilterCount") private Integer filterCount; @XStreamAlias("SentCount") private Integer sentCount; @XStreamAlias("ErrorCount") private Integer errorCount; @XStreamAlias("ScanCodeInfo") private ScanCodeInfo scanCodeInfo = new ScanCodeInfo(); @XStreamAlias("SendPicsInfo") private SendPicsInfo sendPicsInfo = new SendPicsInfo(); @XStreamAlias("SendLocationInfo") private SendLocationInfo sendLocationInfo = new SendLocationInfo(); @XStreamAlias("ApprovalInfo") private ApprovalInfo approvalInfo = new ApprovalInfo(); protected static WxCpXmlMessage fromXml(String xml) { xml = xml.replace("</PicList><PicList>", ""); final WxCpXmlMessage xmlMessage = XStreamTransformer.fromXml(WxCpXmlMessage.class, xml); xmlMessage.setAllFieldsMap(XmlUtils.xml2Map(xml)); return xmlMessage; } public static WxCpXmlMessage fromXml(String xml, String agentId) { xml = xml.replace("</PicList><PicList>", ""); final WxCpXmlMessage xmlMessage = fromXml(xml); xmlMessage.setAgentId(agentId); return xmlMessage; } protected static WxCpXmlMessage fromXml(InputStream is) { return XStreamTransformer.fromXml(WxCpXmlMessage.class, is); } public static WxCpXmlMessage fromEncryptedXml(String encryptedXml, WxCpConfigStorage wxCpConfigStorage, String timestamp, String nonce, String msgSignature) { WxCpCryptUtil cryptUtil = new WxCpCryptUtil(wxCpConfigStorage); WxCpXmlMessage wxCpXmlMessage = fromXml(encryptedXml); String plainText = cryptUtil.decrypt(msgSignature, timestamp, nonce, encryptedXml); log.debug("xml{}", plainText); if (StringUtils.isNotEmpty(wxCpXmlMessage.getAgentId())) { return fromXml(plainText, wxCpXmlMessage.getAgentId()); } else { return fromXml(plainText); } } public static WxCpXmlMessage fromEncryptedXml(InputStream is, WxCpConfigStorage wxCpConfigStorage, String timestamp, String nonce, String msgSignature) { try { return fromEncryptedXml(IOUtils.toString(is, StandardCharsets.UTF_8), wxCpConfigStorage, timestamp, nonce, msgSignature); } catch (IOException e) { throw new WxRuntimeException(e); } } @Override public String toString() { return WxCpGsonBuilder.create().toJson(this); } @Data @XStreamAlias("ScanCodeInfo") public static class ScanCodeInfo implements Serializable { private static final long serialVersionUID = 7420078330239763395L; /** * qrcode. */ @XStreamAlias("ScanType") @XStreamConverter(value = XStreamCDataConverter.class) private String scanType; @XStreamAlias("ScanResult") @XStreamConverter(value = XStreamCDataConverter.class) private String scanResult; } @Data public static class ExtAttr implements Serializable { private static final long serialVersionUID = -3418685294606228837L; @XStreamImplicit(itemFieldName = "Item") protected final List<Item> items = new ArrayList<>(); @XStreamAlias("Item") @Data public static class Item implements Serializable { private static final long serialVersionUID = -3418685294606228837L; @XStreamAlias("Name") @XStreamConverter(value = XStreamCDataConverter.class) private String name; @XStreamAlias("Value") @XStreamConverter(value = XStreamCDataConverter.class) private String value; } } @Data @XStreamAlias("SendPicsInfo") public static class SendPicsInfo implements Serializable { private static final long serialVersionUID = -6549728838848064881L; @XStreamAlias("PicList") protected final List<Item> picList = new ArrayList<>(); @XStreamAlias("Count") private Long count; @XStreamAlias("item") @Data public static class Item implements Serializable { private static final long serialVersionUID = -6549728838848064881L; @XStreamAlias("PicMd5Sum") @XStreamConverter(value = XStreamCDataConverter.class) private String picMd5Sum; } } @Data @XStreamAlias("SendLocationInfo") public static class SendLocationInfo implements Serializable { private static final long serialVersionUID = 6319921071637597406L; @XStreamAlias("Location_X") @XStreamConverter(value = XStreamCDataConverter.class) private String locationX; @XStreamAlias("Location_Y") @XStreamConverter(value = XStreamCDataConverter.class) private String locationY; @XStreamAlias("Scale") @XStreamConverter(value = XStreamCDataConverter.class) private String scale; @XStreamAlias("Label") @XStreamConverter(value = XStreamCDataConverter.class) private String label; @XStreamAlias("Poiname") @XStreamConverter(value = XStreamCDataConverter.class) private String poiName; } @XStreamAlias("ApprovalInfo") @Data public static class ApprovalInfo implements Serializable { private static final long serialVersionUID = 8136329462880646091L; @XStreamAlias("SpNo") private String spNo; @XStreamAlias("SpName") @XStreamConverter(value = XStreamCDataConverter.class) private String spName; /** * 1-2-3-4-6-7-10- */ @XStreamAlias("SpStatus") private Integer spStatus; @XStreamAlias("TemplateId") @XStreamConverter(value = XStreamCDataConverter.class) private String templateId; /** * ,Unix */ @XStreamAlias("ApplyTime") private Long applyTime; @XStreamAlias("Applyer") private Applier applier; @XStreamImplicit(itemFieldName = "SpRecord") private List<SpRecord> spRecords; /** * * notifierNotifyer */ @XStreamImplicit(itemFieldName = "Notifyer") private List<Notifier> notifier; @XStreamImplicit(itemFieldName = "Comments") private List<Comment> comments; @XStreamAlias("StatuChangeEvent") private Integer statusChangeEvent; @XStreamAlias("Applyer") @Data public static class Applier implements Serializable { private static final long serialVersionUID = -979255011922209018L; /** * userid */ @XStreamAlias("UserId") private String userId; /** * pid */ @XStreamAlias("Party") private String party; } @XStreamAlias("SpRecord") @Data public static class SpRecord implements Serializable { private static final long serialVersionUID = 1247535623941881764L; /** * 1-2-3-4- */ @XStreamAlias("SpStatus") private String spStatus; @XStreamAlias("ApproverAttr") private String approverAttr; @XStreamImplicit(itemFieldName = "Details") private List<Detail> details; } @XStreamAlias("Details") @Data public static class Detail implements Serializable { private static final long serialVersionUID = -8446107461495047603L; @XStreamAlias("Approver") private Approver approver; @XStreamAlias("Speech") private String speech; /** * 1-2-3-4- */ @XStreamAlias("SpStatus") private String spStatus; @XStreamAlias("SpTime") private Long spTime; /** * media_id- * TODO * allFieldsMap */ // @XStreamAlias("Attach") private String attach; } @Data @XStreamAlias("Approver") public static class Approver implements Serializable { private static final long serialVersionUID = 7360442444186683191L; /** * userid */ @XStreamAlias("UserId") private String userId; } @Data @XStreamAlias("Notifyer") public static class Notifier implements Serializable { private static final long serialVersionUID = -4524071522890013920L; /** * userid */ @XStreamAlias("UserId") private String userId; } @Data @XStreamAlias("Comments") public static class Comment implements Serializable { private static final long serialVersionUID = 6912156206252719485L; @XStreamAlias("CommentUserInfo") private CommentUserInfo commentUserInfo; @XStreamAlias("CommentTime") private String commentTime; @XStreamAlias("CommentContent") private String commentContent; @XStreamAlias("CommentId") private String commentId; } @Data @XStreamAlias("CommentUserInfo") private static class CommentUserInfo implements Serializable { private static final long serialVersionUID = 5031739716823000947L; /** * userid */ @XStreamAlias("UserId") private String userId; } } }
package org.jdesktop.swingx.painter; import java.awt.Color; import java.awt.Composite; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.AffineTransform; import java.util.HashMap; import java.util.Map; import javax.swing.JComponent; import org.jdesktop.swingx.JavaBean; /** * <p>A convenient base class from which concrete Painter implementations may * extend. It extends JavaBean and thus provides property change notification * (which is crucial for the Painter implementations to be available in a * GUI builder). It also saves off the Graphics2D state in its "saveState" method, * and restores that state in the "restoreState" method. Sublasses simply need * to extend AbstractPainter and implement the paintBackground method. * * <p>For example, here is the paintBackground method of BackgroundPainter: * <pre><code> * public void paintBackground(Graphics2D g, JComponent component) { * g.setColor(component.getBackground()); * g.fillRect(0, 0, component.getWidth(), component.getHeight()); * } * </code></pre> * * <p>AbstractPainter provides a very useful default implementation of * the paint method. It: * <ol> * <li>Saves off the old state</li> * <li>Sets any specified rendering hints</li> * <li>Sets the Clip if there is one</li> * <li>Sets the Composite if there is one</li> * <li>Delegates to paintBackground</li> * <li>Restores the original Graphics2D state</li> * <ol></p> * * <p>Specifying rendering hints can greatly improve the visual impact of your * applications. For example, by default Swing doesn't do much in the way of * antialiasing (except for Fonts, but that's another story). Pinstripes don't * look so good without antialiasing. So if I were going to paint pinstripes, I * might do it like this: * <pre><code> * PinstripePainter p = new PinstripePainter(); * p.setAntialiasing(RenderingHints.VALUE_ANTIALIAS_ON); * </code></pre></p> * * <p>You can read more about antialiasing and other rendering hints in the * java.awt.RenderingHints documentation. <strong>By nature, changing the rendering * hints may have an impact on performance. Certain hints require more * computation, others require less</strong></p> * * @author rbair */ public abstract class AbstractPainter extends JavaBean implements Painter { private boolean stateSaved = false; private Paint oldPaint; private Font oldFont; private Stroke oldStroke; private AffineTransform oldTransform; private Composite oldComposite; private Shape oldClip; private Color oldBackground; private Color oldColor; private RenderingHints oldRenderingHints; private Shape clip; private Composite composite; private Map<RenderingHints.Key, Object> renderingHints; /** * Creates a new instance of AbstractPainter */ public AbstractPainter() { renderingHints = new HashMap<RenderingHints.Key,Object>(); } /** * Specifies the Shape to use for clipping the painting area. This * may be null * * @param clip the Shape to use to clip the area. Whatever is inside this * shape will be kept, everything else "clipped". May be null. If * null, the clipping is not set on the graphics object */ public void setClip(Shape clip) { Shape old = getClip(); this.clip = clip; firePropertyChange("clip", old, getClip()); } /** * @returns the clipping shape */ public Shape getClip() { return clip; } /** * Sets the Composite to use. For example, you may specify a specific * AlphaComposite so that when this Painter paints, any content in the * drawing area is handled properly * * @param c The composite to use. If null, then no composite will be * specified on the graphics object */ public void setComposite(Composite c) { Composite old = getComposite(); this.composite = c; firePropertyChange("composite", old, getComposite()); } /** * @returns the composite */ public Composite getComposite() { return composite; } /** * @returns the technique used for interpolating alpha values. May be one * of: * <ul> * <li>RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED</li> * <li>RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY</li> * <li>RenderingHints.VALUE_ALPHA_INTERPOLATION_DEFAULT</li> * </ul> */ public Object getAlphaInterpolation() { return renderingHints.get(RenderingHints.KEY_ALPHA_INTERPOLATION); } /** * Sets the technique used for interpolating alpha values. * * @param alphaInterpolation * May be one of: * <ul> * <li>RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED</li> * <li>RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY</li> * <li>RenderingHints.VALUE_ALPHA_INTERPOLATION_DEFAULT</li> * </ul> */ public void setAlphaInterpolation(Object alphaInterpolation) { if (!RenderingHints.KEY_ALPHA_INTERPOLATION.isCompatibleValue(alphaInterpolation)) { throw new IllegalArgumentException(alphaInterpolation + " is not an acceptable value"); } Object old = getAlphaInterpolation(); renderingHints.put(RenderingHints.KEY_ALPHA_INTERPOLATION, alphaInterpolation); firePropertyChange("alphaInterpolation", old, getAlphaInterpolation()); } /** * @returns whether or not to antialias * May be one of: * <ul> * <li>RenderingHints.VALUE_ANTIALIAS_DEFAULT</li> * <li>RenderingHints.VALUE_ANTIALIAS_OFF</li> * <li>RenderingHints.VALUE_ANTIALIAS_ON</li> * </ul> */ public Object getAntialiasing() { return renderingHints.get(RenderingHints.KEY_ANTIALIASING); } /** * Sets whether or not to antialias * @param antialiasing * May be one of: * <ul> * <li>RenderingHints.VALUE_ANTIALIAS_DEFAULT</li> * <li>RenderingHints.VALUE_ANTIALIAS_OFF</li> * <li>RenderingHints.VALUE_ANTIALIAS_ON</li> * </ul> */ public void setAntialiasing(Object antialiasing) { if (!RenderingHints.KEY_ANTIALIASING.isCompatibleValue(antialiasing)) { throw new IllegalArgumentException(antialiasing + " is not an acceptable value"); } Object old = getAntialiasing(); renderingHints.put(RenderingHints.KEY_ANTIALIASING, antialiasing); firePropertyChange("antialiasing", old, getAntialiasing()); } /** * @returns the technique to use for rendering colors * May be one of: * <ul> * <li>RenderingHints.VALUE_COLOR_RENDER_DEFAULT</li> * <li>RenderingHints.VALUE_RENDER_QUALITY</li> * <li>RenderingHints.VALUE_RENDER_SPEED</li> * </ul> */ public Object getColorRendering() { return renderingHints.get(RenderingHints.KEY_COLOR_RENDERING); } /** * Sets the technique to use for rendering colors * @param colorRendering * May be one of: * <ul> * <li>RenderingHints.VALUE_COLOR_RENDER_DEFAULT</li> * <li>RenderingHints.VALUE_RENDER_QUALITY</li> * <li>RenderingHints.VALUE_RENDER_SPEED</li> * </ul> */ public void setColorRendering(Object colorRendering) { if (!RenderingHints.KEY_COLOR_RENDERING.isCompatibleValue(colorRendering)) { throw new IllegalArgumentException(colorRendering + " is not an acceptable value"); } Object old = getColorRendering(); renderingHints.put(RenderingHints.KEY_COLOR_RENDERING, colorRendering); firePropertyChange("colorRendering", old, getColorRendering()); } /** * @returns whether or not to dither * May be one of: * <ul> * <li>RenderingHints.VALUE_DITHER_DEFAULT</li> * <li>RenderingHints.VALUE_DITHER_ENABLE</li> * <li>RenderingHints.VALUE_DITHER_DISABLE</li> * </ul> */ public Object getDithering() { return renderingHints.get(RenderingHints.KEY_DITHERING); } /** * Sets whether or not to dither * @param dithering * May be one of: * <ul> * <li>RenderingHints.VALUE_DITHER_DEFAULT</li> * <li>RenderingHints.VALUE_DITHER_ENABLE</li> * <li>RenderingHints.VALUE_DITHER_DISABLE</li> * </ul> */ public void setDithering(Object dithering) { if (!RenderingHints.KEY_DITHERING.isCompatibleValue(dithering)) { throw new IllegalArgumentException(dithering + " is not an acceptable value"); } Object old = getDithering(); renderingHints.put(RenderingHints.KEY_DITHERING, dithering); firePropertyChange("dithering", old, getDithering()); } /** * @returns whether or not to use fractional metrics * May be one of: * <ul> * <li>RenderingHints.VALUE_FRACTIONALMETRICS_DEFAULT</li> * <li>RenderingHints.VALUE_FRACTIONALMETRICS_OFF</li> * <li>RenderingHints.VALUE_FRACTIONALMETRICS_ON</li> * </ul> */ public Object getFractionalMetrics() { return renderingHints.get(RenderingHints.KEY_FRACTIONALMETRICS); } /** * Sets whether or not to use fractional metrics * * @param fractionalMetrics * May be one of: * <ul> * <li>RenderingHints.VALUE_FRACTIONALMETRICS_DEFAULT</li> * <li>RenderingHints.VALUE_FRACTIONALMETRICS_OFF</li> * <li>RenderingHints.VALUE_FRACTIONALMETRICS_ON</li> * </ul> */ public void setFractionalMetrics(Object fractionalMetrics) { if (!RenderingHints.KEY_FRACTIONALMETRICS.isCompatibleValue(fractionalMetrics)) { throw new IllegalArgumentException(fractionalMetrics + " is not an acceptable value"); } Object old = getFractionalMetrics(); renderingHints.put(RenderingHints.KEY_FRACTIONALMETRICS, fractionalMetrics); firePropertyChange("fractionalMetrics", old, getFractionalMetrics()); } /** * @returns the technique to use for interpolation (used esp. when scaling) * May be one of: * <ul> * <li>RenderingHints.VALUE_INTERPOLATION_BICUBIC</li> * <li>RenderingHints.VALUE_INTERPOLATION_BILINEAR</li> * <li>RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR</li> * </ul> */ public Object getInterpolation() { return renderingHints.get(RenderingHints.KEY_INTERPOLATION); } /** * Sets the technique to use for interpolation (used esp. when scaling) * @param interpolation * May be one of: * <ul> * <li>RenderingHints.VALUE_INTERPOLATION_BICUBIC</li> * <li>RenderingHints.VALUE_INTERPOLATION_BILINEAR</li> * <li>RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR</li> * </ul> */ public void setInterpolation(Object interpolation) { if (!RenderingHints.KEY_INTERPOLATION.isCompatibleValue(interpolation)) { throw new IllegalArgumentException(interpolation + " is not an acceptable value"); } Object old = getInterpolation(); renderingHints.put(RenderingHints.KEY_INTERPOLATION, interpolation); firePropertyChange("interpolation", old, getInterpolation()); } /** * @returns a hint as to techniques to use with regards to rendering quality vs. speed * May be one of: * <ul> * <li>RenderingHints.VALUE_RENDER_QUALITY</li> * <li>RenderingHints.VALUE_RENDER_SPEED</li> * <li>RenderingHints.VALUE_RENDER_DEFAULT</li> * </ul> */ public Object getRendering() { return renderingHints.get(RenderingHints.KEY_RENDERING); } /** * Specifies a hint as to techniques to use with regards to rendering quality vs. speed * * @param rendering * May be one of: * <ul> * <li>RenderingHints.VALUE_RENDER_QUALITY</li> * <li>RenderingHints.VALUE_RENDER_SPEED</li> * <li>RenderingHints.VALUE_RENDER_DEFAULT</li> * </ul> */ public void setRendering(Object rendering) { if (!RenderingHints.KEY_RENDERING.isCompatibleValue(rendering)) { throw new IllegalArgumentException(rendering + " is not an acceptable value"); } Object old = getRendering(); renderingHints.put(RenderingHints.KEY_RENDERING, rendering); firePropertyChange("rendering", old, getRendering()); } /** * @returns technique for rendering strokes * May be one of: * <ul> * <li>RenderingHints.VALUE_STROKE_DEFAULT</li> * <li>RenderingHints.VALUE_STROKE_NORMALIZE</li> * <li>RenderingHints.VALUE_STROKE_PURE</li> * </ul> */ public Object getStrokeControl() { return renderingHints.get(RenderingHints.KEY_STROKE_CONTROL); } /** * Specifies a technique for rendering strokes * * @param strokeControl * May be one of: * <ul> * <li>RenderingHints.VALUE_STROKE_DEFAULT</li> * <li>RenderingHints.VALUE_STROKE_NORMALIZE</li> * <li>RenderingHints.VALUE_STROKE_PURE</li> * </ul> */ public void setStrokeControl(Object strokeControl) { if (!RenderingHints.KEY_STROKE_CONTROL.isCompatibleValue(strokeControl)) { throw new IllegalArgumentException(strokeControl + " is not an acceptable value"); } Object old = getStrokeControl(); renderingHints.put(RenderingHints.KEY_STROKE_CONTROL, strokeControl); firePropertyChange("strokeControl", old, getStrokeControl()); } /** * @returns technique for anti-aliasing text. * (TODO this needs to be updated for Mustang. You may use the * new Mustang values, and everything will work, but support in * the GUI builder and documentation need to be added once we * branch for Mustang)<br/> * May be one of: * <ul> * <li>RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT</li> * <li>RenderingHints.VALUE_TEXT_ANTIALIAS_OFF</li> * <li>RenderingHints.VALUE_TEXT_ANTIALIAS_ON</li> * </ul> */ public Object getTextAntialiasing() { return renderingHints.get(RenderingHints.KEY_TEXT_ANTIALIASING); } /** * Sets the technique for anti-aliasing text. * (TODO this needs to be updated for Mustang. You may use the * new Mustang values, and everything will work, but support in * the GUI builder and documentation need to be added once we * branch for Mustang)<br/> * * @param textAntialiasing * May be one of: * <ul> * <li>RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT</li> * <li>RenderingHints.VALUE_TEXT_ANTIALIAS_OFF</li> * <li>RenderingHints.VALUE_TEXT_ANTIALIAS_ON</li> * </ul> */ public void setTextAntialiasing(Object textAntialiasing) { if (!RenderingHints.KEY_TEXT_ANTIALIASING.isCompatibleValue(textAntialiasing)) { throw new IllegalArgumentException(textAntialiasing + " is not an acceptable value"); } Object old = getTextAntialiasing(); renderingHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, textAntialiasing); firePropertyChange("textAntialiasing", old, getTextAntialiasing()); } /** * @return the rendering hint associated with the given key. May return null */ public Object getRenderingHint(RenderingHints.Key key) { return renderingHints.get(key); } /** * Set the given hint for the given key. This will end up firing the appropriate * property change event if the key is recognized. For example, if the key is * RenderingHints.KEY_ANTIALIASING, then the setAntialiasing method will be * called firing an "antialiasing" property change event if necessary. If * the key is not recognized, no event will be fired but the key will be saved. * The key must not be null * * @param key cannot be null * @param hint must be a hint compatible with the given key */ public void setRenderingHint(RenderingHints.Key key, Object hint) { if (key == null) { throw new NullPointerException("RenderingHints key cannot be null"); } if (key == RenderingHints.KEY_ALPHA_INTERPOLATION) { setAlphaInterpolation(hint); } else if (key == RenderingHints.KEY_ANTIALIASING) { setAntialiasing(hint); } else if (key == RenderingHints.KEY_COLOR_RENDERING) { setColorRendering(hint); } else if (key == RenderingHints.KEY_DITHERING) { setDithering(hint); } else if (key == RenderingHints.KEY_FRACTIONALMETRICS) { setFractionalMetrics(hint); } else if (key == RenderingHints.KEY_INTERPOLATION) { setInterpolation(hint); } else if (key == RenderingHints.KEY_RENDERING) { setRendering(hint); } else if (key == RenderingHints.KEY_STROKE_CONTROL) { setStrokeControl(hint); } else if (key == RenderingHints.KEY_TEXT_ANTIALIASING) { setTextAntialiasing(hint); } else { renderingHints.put(key, hint); } } /** * @return a copy of the map of rendering hints held by this class. This * returned value will never be null */ public Map<RenderingHints.Key, Object> getRenderingHints() { return new HashMap<RenderingHints.Key, Object>(renderingHints); } /** * Sets the rendering hints to use. This will <strong>replace</strong> the * rendering hints entirely, clearing any hints that were previously set. * * @param renderingHints map of hints. May be null. I null, a new Map of * rendering hints will be created */ public void setRenderingHints(Map<RenderingHints.Key, Object> renderingHints) { Map<RenderingHints.Key,Object> old = this.renderingHints; if (renderingHints != null) { this.renderingHints = new HashMap<RenderingHints.Key, Object>(renderingHints); } else { this.renderingHints = new HashMap<RenderingHints.Key, Object>(); } firePropertyChange("renderingHints", old, getRenderingHints()); } /** * Saves the state in the given Graphics2D object so that it may be * restored later. * * @param g the Graphics2D object who's state will be saved */ protected void saveState(Graphics2D g) { oldPaint = g.getPaint(); oldFont = g.getFont(); oldStroke = g.getStroke(); oldTransform = g.getTransform(); oldComposite = g.getComposite(); oldClip = g.getClip(); oldBackground = g.getBackground(); oldColor = g.getColor(); //save off the old rendering hints oldRenderingHints = g.getRenderingHints(); stateSaved = true; } protected void restoreState(Graphics2D g) { if (!stateSaved) { throw new IllegalStateException("A call to saveState must occur " + "prior to calling restoreState"); } g.setPaint(oldPaint); g.setFont(oldFont); g.setTransform(oldTransform); g.setStroke(oldStroke); g.setComposite(oldComposite); g.setClip(oldClip); g.setBackground(oldBackground); g.setColor(oldColor); //restore the rendering hints g.setRenderingHints(oldRenderingHints); stateSaved = false; } /** * @inheritDoc */ public void paint(Graphics2D g, JComponent component) { saveState(g); //set any non-null rendering hints for (Map.Entry<RenderingHints.Key,Object> entry : renderingHints.entrySet()) { if (entry.getValue() != null) { g.setRenderingHint(entry.getKey(), entry.getValue()); } } if (getComposite() != null) { g.setComposite(getComposite()); } if (getClip() != null) { g.setClip(getClip()); } paintBackground(g, component); restoreState(g); } /** * Subclasses should implement this method and perform custom painting operations * here. Common behavior, such as setting the clip and composite, saving and restoring * state, is performed in the "paint" method automatically, and then delegated here. * * @param g The Graphics2D object in which to paint * @param component The JComponent that the Painter is delegate for. */ protected abstract void paintBackground(Graphics2D g, JComponent component); }
package me.chanjar.weixin.mp.api.impl; import com.thoughtworks.xstream.XStream; import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.crypto.WxCryptUtil; import me.chanjar.weixin.common.util.http.Utf8ResponseHandler; import me.chanjar.weixin.common.util.xml.XStreamInitializer; import me.chanjar.weixin.mp.api.WxMpPayService; import me.chanjar.weixin.mp.bean.result.*; import org.apache.http.Consts; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.helpers.MessageFormatter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; public class WxMpPayServiceImpl implements WxMpPayService { private final Logger log = LoggerFactory.getLogger(WxMpPayServiceImpl.class); private final String[] REQUIRED_ORDER_PARAMETERS = new String[]{"appid", "mch_id", "body", "out_trade_no", "total_fee", "spbill_create_ip", "notify_url", "trade_type"}; private HttpHost httpProxy; private WxMpServiceImpl wxMpService; public WxMpPayServiceImpl(WxMpServiceImpl wxMpService) { this.wxMpService = wxMpService; this.httpProxy = wxMpService.getHttpProxy(); } @Override public WxMpPrepayIdResult getPrepayId(String openId, String outTradeNo, double amt, String body, String tradeType, String ip, String callbackUrl) { Map<String, String> packageParams = new HashMap<>(); packageParams.put("appid", this.wxMpService.getWxMpConfigStorage().getAppId()); packageParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); packageParams.put("body", body); packageParams.put("out_trade_no", outTradeNo); packageParams.put("total_fee", (int) (amt * 100) + ""); packageParams.put("spbill_create_ip", ip); packageParams.put("notify_url", callbackUrl); packageParams.put("trade_type", tradeType); packageParams.put("openid", openId); return getPrepayId(packageParams); } @Override public WxMpPrepayIdResult getPrepayId(final Map<String, String> parameters) { final SortedMap<String, String> packageParams = new TreeMap<>(parameters); packageParams.put("appid", this.wxMpService.getWxMpConfigStorage().getAppId()); packageParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); packageParams.put("nonce_str", System.currentTimeMillis() + ""); checkParameters(packageParams); String sign = WxCryptUtil.createSign(packageParams, this.wxMpService.getWxMpConfigStorage().getPartnerKey()); packageParams.put("sign", sign); StringBuilder request = new StringBuilder("<xml>"); for (Map.Entry<String, String> para : packageParams.entrySet()) { request.append(String.format("<%s>%s</%s>", para.getKey(), para.getValue(), para.getKey())); } request.append("</xml>"); HttpPost httpPost = new HttpPost( "https://api.mch.weixin.qq.com/pay/unifiedorder"); if (this.httpProxy != null) { RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy) .build(); httpPost.setConfig(config); } StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); httpPost.setEntity(entity); try (CloseableHttpResponse response = this.wxMpService.getHttpclient() .execute(httpPost)) { String responseContent = Utf8ResponseHandler.INSTANCE .handleResponse(response); XStream xstream = XStreamInitializer.getInstance(); xstream.alias("xml", WxMpPrepayIdResult.class); return (WxMpPrepayIdResult) xstream.fromXML(responseContent); } catch (IOException e) { throw new RuntimeException("Failed to get prepay id due to IO exception.", e); } finally { httpPost.releaseConnection(); } } private void checkParameters(Map<String, String> parameters) { for (String para : this.REQUIRED_ORDER_PARAMETERS) { if (!parameters.containsKey(para)) { throw new IllegalArgumentException( "Reqiured argument '" + para + "' is missing."); } } if ("JSAPI".equals(parameters.get("trade_type")) && !parameters.containsKey("openid")) { throw new IllegalArgumentException( "Reqiured argument 'openid' is missing when trade_type is 'JSAPI'."); } if ("NATIVE".equals(parameters.get("trade_type")) && !parameters.containsKey("product_id")) { throw new IllegalArgumentException( "Reqiured argument 'product_id' is missing when trade_type is 'NATIVE'."); } } @Override public Map<String, String> getJsapiPayInfo(String openId, String outTradeNo, double amt, String body, String ip, String callbackUrl) throws WxErrorException { Map<String, String> packageParams = new HashMap<>(); packageParams.put("appid", this.wxMpService.getWxMpConfigStorage().getAppId()); packageParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); packageParams.put("body", body); packageParams.put("out_trade_no", outTradeNo); packageParams.put("total_fee", (int) (amt * 100) + ""); packageParams.put("spbill_create_ip", ip); packageParams.put("notify_url", callbackUrl); packageParams.put("trade_type", "JSAPI"); packageParams.put("openid", openId); return getPayInfo(packageParams); } @Override public Map<String, String> getNativePayInfo(String productId, String outTradeNo, double amt, String body, String ip, String callbackUrl) throws WxErrorException { Map<String, String> packageParams = new HashMap<>(); packageParams.put("appid", this.wxMpService.getWxMpConfigStorage().getAppId()); packageParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); packageParams.put("body", body); packageParams.put("out_trade_no", outTradeNo); packageParams.put("total_fee", (int) (amt * 100) + ""); packageParams.put("spbill_create_ip", ip); packageParams.put("notify_url", callbackUrl); packageParams.put("trade_type", "NATIVE"); packageParams.put("product_id", productId); return getPayInfo(packageParams); } @Override public Map<String, String> getPayInfo(Map<String, String> parameters) throws WxErrorException { WxMpPrepayIdResult wxMpPrepayIdResult = getPrepayId(parameters); if (!"SUCCESS".equalsIgnoreCase(wxMpPrepayIdResult.getReturn_code()) || !"SUCCESS".equalsIgnoreCase(wxMpPrepayIdResult.getResult_code())) { WxError error = new WxError(); error.setErrorCode(-1); error.setErrorMsg("return_code:" + wxMpPrepayIdResult.getReturn_code() + ";return_msg:" + wxMpPrepayIdResult.getReturn_msg() + ";result_code:" + wxMpPrepayIdResult.getResult_code() + ";err_code" + wxMpPrepayIdResult.getErr_code() + ";err_code_des" + wxMpPrepayIdResult.getErr_code_des()); throw new WxErrorException(error); } String prepayId = wxMpPrepayIdResult.getPrepay_id(); if (prepayId == null || prepayId.equals("")) { throw new RuntimeException( String.format("Failed to get prepay id due to error code '%s'(%s).", wxMpPrepayIdResult.getErr_code(), wxMpPrepayIdResult.getErr_code_des())); } Map<String, String> payInfo = new HashMap<>(); payInfo.put("appId", this.wxMpService.getWxMpConfigStorage().getAppId()); // jssdktimestamptimeStampS payInfo.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000)); payInfo.put("nonceStr", System.currentTimeMillis() + ""); payInfo.put("package", "prepay_id=" + prepayId); payInfo.put("signType", "MD5"); if ("NATIVE".equals(parameters.get("trade_type"))) { payInfo.put("codeUrl", wxMpPrepayIdResult.getCode_url()); } String finalSign = WxCryptUtil.createSign(payInfo, this.wxMpService.getWxMpConfigStorage().getPartnerKey()); payInfo.put("paySign", finalSign); return payInfo; } @Override public WxMpPayResult getJSSDKPayResult(String transactionId, String outTradeNo) { String nonce_str = System.currentTimeMillis() + ""; SortedMap<String, String> packageParams = new TreeMap<>(); packageParams.put("appid", this.wxMpService.getWxMpConfigStorage().getAppId()); packageParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); if (transactionId != null && !"".equals(transactionId.trim())) { packageParams.put("transaction_id", transactionId); } else if (outTradeNo != null && !"".equals(outTradeNo.trim())) { packageParams.put("out_trade_no", outTradeNo); } else { throw new IllegalArgumentException( "Either 'transactionId' or 'outTradeNo' must be given."); } packageParams.put("nonce_str", nonce_str); packageParams.put("sign", WxCryptUtil.createSign(packageParams, this.wxMpService.getWxMpConfigStorage().getPartnerKey())); StringBuilder request = new StringBuilder("<xml>"); for (Map.Entry<String, String> para : packageParams.entrySet()) { request.append(String.format("<%s>%s</%s>", para.getKey(), para.getValue(), para.getKey())); } request.append("</xml>"); HttpPost httpPost = new HttpPost( "https://api.mch.weixin.qq.com/pay/orderquery"); if (this.httpProxy != null) { RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy) .build(); httpPost.setConfig(config); } StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); httpPost.setEntity(entity); try (CloseableHttpResponse response = this.wxMpService.getHttpclient() .execute(httpPost)) { String responseContent = Utf8ResponseHandler.INSTANCE .handleResponse(response); XStream xstream = XStreamInitializer.getInstance(); xstream.alias("xml", WxMpPayResult.class); return (WxMpPayResult) xstream.fromXML(responseContent); } catch (IOException e) { throw new RuntimeException("Failed to query order due to IO exception.", e); } } @Override public WxMpPayCallback getJSSDKCallbackData(String xmlData) { try { XStream xstream = XStreamInitializer.getInstance(); xstream.alias("xml", WxMpPayCallback.class); return (WxMpPayCallback) xstream.fromXML(xmlData); } catch (Exception e) { e.printStackTrace(); } return new WxMpPayCallback(); } @Override public WxMpPayRefundResult refundPay(Map<String, String> parameters) throws WxErrorException { SortedMap<String, String> refundParams = new TreeMap<>(parameters); refundParams.put("appid", this.wxMpService.getWxMpConfigStorage().getAppId()); refundParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); refundParams.put("nonce_str", System.currentTimeMillis() + ""); refundParams.put("op_user_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); String sign = WxCryptUtil.createSign(refundParams, this.wxMpService.getWxMpConfigStorage().getPartnerKey()); refundParams.put("sign", sign); StringBuilder request = new StringBuilder("<xml>"); for (Map.Entry<String, String> para : refundParams.entrySet()) { request.append(String.format("<%s>%s</%s>", para.getKey(), para.getValue(), para.getKey())); } request.append("</xml>"); HttpPost httpPost = new HttpPost( "https://api.mch.weixin.qq.com/secapi/pay/refund"); if (this.httpProxy != null) { RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy) .build(); httpPost.setConfig(config); } StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); httpPost.setEntity(entity); try (CloseableHttpResponse response = this.wxMpService.getHttpclient() .execute(httpPost)) { String responseContent = Utf8ResponseHandler.INSTANCE .handleResponse(response); XStream xstream = XStreamInitializer.getInstance(); xstream.processAnnotations(WxMpPayRefundResult.class); WxMpPayRefundResult wxMpPayRefundResult = (WxMpPayRefundResult) xstream .fromXML(responseContent); if (!"SUCCESS".equalsIgnoreCase(wxMpPayRefundResult.getResultCode()) || !"SUCCESS".equalsIgnoreCase(wxMpPayRefundResult.getReturnCode())) { WxError error = new WxError(); error.setErrorCode(-1); error.setErrorMsg("return_code:" + wxMpPayRefundResult.getReturnCode() + ";return_msg:" + wxMpPayRefundResult.getReturnMsg() + ";result_code:" + wxMpPayRefundResult.getResultCode() + ";err_code" + wxMpPayRefundResult.getErrCode() + ";err_code_des" + wxMpPayRefundResult.getErrCodeDes()); throw new WxErrorException(error); } return wxMpPayRefundResult; } catch (IOException e) { String message = MessageFormatter .format("Exception happened when sending refund '{}'.", request.toString()) .getMessage(); this.log.error(message, e); throw new WxErrorException( WxError.newBuilder().setErrorMsg(message).build()); } finally { httpPost.releaseConnection(); } } @Override public boolean checkJSSDKCallbackDataSignature(Map<String, String> kvm, String signature) { return signature.equals(WxCryptUtil.createSign(kvm, this.wxMpService.getWxMpConfigStorage().getPartnerKey())); } @Override public WxRedpackResult sendRedpack(Map<String, String> parameters) throws WxErrorException { SortedMap<String, String> packageParams = new TreeMap<>(parameters); packageParams.put("wxappid", this.wxMpService.getWxMpConfigStorage().getAppId()); packageParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); packageParams.put("nonce_str", System.currentTimeMillis() + ""); String sign = WxCryptUtil.createSign(packageParams, this.wxMpService.getWxMpConfigStorage().getPartnerKey()); packageParams.put("sign", sign); StringBuilder request = new StringBuilder("<xml>"); for (Map.Entry<String, String> para : packageParams.entrySet()) { request.append(String.format("<%s>%s</%s>", para.getKey(), para.getValue(), para.getKey())); } request.append("</xml>"); HttpPost httpPost = new HttpPost( "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack"); if (this.httpProxy != null) { RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy) .build(); httpPost.setConfig(config); } StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); httpPost.setEntity(entity); try (CloseableHttpResponse response = this.wxMpService.getHttpclient() .execute(httpPost)) { String responseContent = Utf8ResponseHandler.INSTANCE .handleResponse(response); XStream xstream = XStreamInitializer.getInstance(); xstream.processAnnotations(WxRedpackResult.class); return (WxRedpackResult) xstream.fromXML(responseContent); } catch (IOException e) { String message = MessageFormatter .format("Exception occured when sending redpack '{}'.", request.toString()) .getMessage(); this.log.error(message, e); throw new WxErrorException(WxError.newBuilder().setErrorMsg(message).build()); } finally { httpPost.releaseConnection(); } } }
package org.jdesktop.swingx.painter; import java.awt.Color; import java.awt.Composite; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.Transparency; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.lang.ref.SoftReference; import java.util.HashMap; import java.util.Map; import javax.swing.JComponent; import org.jdesktop.swingx.JavaBean; import org.jdesktop.swingx.util.PaintUtils; /** * <p>A convenient base class from which concrete Painter implementations may * extend. It extends JavaBean and thus provides property change notification * (which is crucial for the Painter implementations to be available in a * GUI builder). It also saves off the Graphics2D state in its "saveState" method, * and restores that state in the "restoreState" method. Sublasses simply need * to extend AbstractPainter and implement the paintBackground method. * * <p>For example, here is the paintBackground method of BackgroundPainter: * <pre><code> * public void paintBackground(Graphics2D g, JComponent component) { * g.setColor(component.getBackground()); * g.fillRect(0, 0, component.getWidth(), component.getHeight()); * } * </code></pre> * * <p>AbstractPainter provides a very useful default implementation of * the paint method. It: * <ol> * <li>Saves off the old state</li> * <li>Sets any specified rendering hints</li> * <li>Sets the Clip if there is one</li> * <li>Sets the Composite if there is one</li> * <li>Delegates to paintBackground</li> * <li>Restores the original Graphics2D state</li> * <ol></p> * * <p>Specifying rendering hints can greatly improve the visual impact of your * applications. For example, by default Swing doesn't do much in the way of * antialiasing (except for Fonts, but that's another story). Pinstripes don't * look so good without antialiasing. So if I were going to paint pinstripes, I * might do it like this: * <pre><code> * PinstripePainter p = new PinstripePainter(); * p.setAntialiasing(RenderingHints.VALUE_ANTIALIAS_ON); * </code></pre></p> * * <p>You can read more about antialiasing and other rendering hints in the * java.awt.RenderingHints documentation. <strong>By nature, changing the rendering * hints may have an impact on performance. Certain hints require more * computation, others require less</strong></p> * * @author rbair */ public abstract class AbstractPainter extends JavaBean implements Painter { private boolean stateSaved = false; private Paint oldPaint; private Font oldFont; private Stroke oldStroke; private AffineTransform oldTransform; private Composite oldComposite; private Shape oldClip; private Color oldBackground; private Color oldColor; private RenderingHints oldRenderingHints; private Shape clip; private Composite composite; private boolean useCache; private RenderingHints renderingHints; private SoftReference<BufferedImage> cachedImage; private Effect[] effects = new Effect[0]; /** * Creates a new instance of AbstractPainter */ public AbstractPainter() { renderingHints = new RenderingHints(new HashMap<RenderingHints.Key,Object>()); } /** * <p>Sets whether to cache the painted image with a SoftReference in a BufferedImage * between calls. If true, and if the size of the component hasn't changed, * then the cached image will be used rather than causing a painting operation.</p> * * <p>This should be considered a hint, rather than absolute. Several factors may * force repainting, including low memory, different component sizes, or possibly * new rendering hint settings, etc.</p> * * @param b whether or not to use the cache */ public void setUseCache(boolean b) { boolean old = isUseCache(); useCache = b; firePropertyChange("useCache", old, isUseCache()); //if there was a cached image and I'm no longer using the cache, blow it away if (cachedImage != null && !isUseCache()) { cachedImage = null; } } /** * @returns whether or not the cache should be used */ public boolean isUseCache() { return useCache; } /** * <p>Sets an array of effects to execute, in order from first to last, on the * results of the AbstractPainter's painting operation. Some common effects * including blurs, shadows, embossing, and so forth. If the given array is * null, an empty array will be created and used instead.</p> * * @param effects the array of Effects that will be executed in order from * first to last on the results of the painting operation */ public void setEffects(Effect... effects) { Effect[] old = getEffects(); this.effects = effects == null ? new Effect[0] : effects; firePropertyChange("effects", old, getEffects()); } /** * @return the array of effects to be applied to the results of the painting * operation. This will never return null; */ public Effect[] getEffects() { return this.effects; } /** * Specifies the Shape to use for clipping the painting area. This * may be null * * @param clip the Shape to use to clip the area. Whatever is inside this * shape will be kept, everything else "clipped". May be null. If * null, the clipping is not set on the graphics object */ public void setClip(Shape clip) { Shape old = getClip(); this.clip = clip; firePropertyChange("clip", old, getClip()); } /** * @returns the clipping shape */ public Shape getClip() { return clip; } /** * Sets the Composite to use. For example, you may specify a specific * AlphaComposite so that when this Painter paints, any content in the * drawing area is handled properly * * @param c The composite to use. If null, then no composite will be * specified on the graphics object */ public void setComposite(Composite c) { Composite old = getComposite(); this.composite = c; firePropertyChange("composite", old, getComposite()); } /** * @returns the composite */ public Composite getComposite() { return composite; } /** * @returns the technique used for interpolating alpha values. May be one * of: * <ul> * <li>RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED</li> * <li>RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY</li> * <li>RenderingHints.VALUE_ALPHA_INTERPOLATION_DEFAULT</li> * </ul> */ public Object getAlphaInterpolation() { return renderingHints.get(RenderingHints.KEY_ALPHA_INTERPOLATION); } /** * Sets the technique used for interpolating alpha values. * * @param alphaInterpolation * May be one of: * <ul> * <li>RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED</li> * <li>RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY</li> * <li>RenderingHints.VALUE_ALPHA_INTERPOLATION_DEFAULT</li> * </ul> */ public void setAlphaInterpolation(Object alphaInterpolation) { if (!RenderingHints.KEY_ALPHA_INTERPOLATION.isCompatibleValue(alphaInterpolation)) { throw new IllegalArgumentException(alphaInterpolation + " is not an acceptable value"); } Object old = getAlphaInterpolation(); renderingHints.put(RenderingHints.KEY_ALPHA_INTERPOLATION, alphaInterpolation); firePropertyChange("alphaInterpolation", old, getAlphaInterpolation()); } /** * @returns whether or not to antialias * May be one of: * <ul> * <li>RenderingHints.VALUE_ANTIALIAS_DEFAULT</li> * <li>RenderingHints.VALUE_ANTIALIAS_OFF</li> * <li>RenderingHints.VALUE_ANTIALIAS_ON</li> * </ul> */ public Object getAntialiasing() { return renderingHints.get(RenderingHints.KEY_ANTIALIASING); } /** * Sets whether or not to antialias * @param antialiasing * May be one of: * <ul> * <li>RenderingHints.VALUE_ANTIALIAS_DEFAULT</li> * <li>RenderingHints.VALUE_ANTIALIAS_OFF</li> * <li>RenderingHints.VALUE_ANTIALIAS_ON</li> * </ul> */ public void setAntialiasing(Object antialiasing) { if (!RenderingHints.KEY_ANTIALIASING.isCompatibleValue(antialiasing)) { throw new IllegalArgumentException(antialiasing + " is not an acceptable value"); } Object old = getAntialiasing(); renderingHints.put(RenderingHints.KEY_ANTIALIASING, antialiasing); firePropertyChange("antialiasing", old, getAntialiasing()); } /** * @returns the technique to use for rendering colors * May be one of: * <ul> * <li>RenderingHints.VALUE_COLOR_RENDER_DEFAULT</li> * <li>RenderingHints.VALUE_RENDER_QUALITY</li> * <li>RenderingHints.VALUE_RENDER_SPEED</li> * </ul> */ public Object getColorRendering() { return renderingHints.get(RenderingHints.KEY_COLOR_RENDERING); } /** * Sets the technique to use for rendering colors * @param colorRendering * May be one of: * <ul> * <li>RenderingHints.VALUE_COLOR_RENDER_DEFAULT</li> * <li>RenderingHints.VALUE_RENDER_QUALITY</li> * <li>RenderingHints.VALUE_RENDER_SPEED</li> * </ul> */ public void setColorRendering(Object colorRendering) { if (!RenderingHints.KEY_COLOR_RENDERING.isCompatibleValue(colorRendering)) { throw new IllegalArgumentException(colorRendering + " is not an acceptable value"); } Object old = getColorRendering(); renderingHints.put(RenderingHints.KEY_COLOR_RENDERING, colorRendering); firePropertyChange("colorRendering", old, getColorRendering()); } /** * @returns whether or not to dither * May be one of: * <ul> * <li>RenderingHints.VALUE_DITHER_DEFAULT</li> * <li>RenderingHints.VALUE_DITHER_ENABLE</li> * <li>RenderingHints.VALUE_DITHER_DISABLE</li> * </ul> */ public Object getDithering() { return renderingHints.get(RenderingHints.KEY_DITHERING); } /** * Sets whether or not to dither * @param dithering * May be one of: * <ul> * <li>RenderingHints.VALUE_DITHER_DEFAULT</li> * <li>RenderingHints.VALUE_DITHER_ENABLE</li> * <li>RenderingHints.VALUE_DITHER_DISABLE</li> * </ul> */ public void setDithering(Object dithering) { if (!RenderingHints.KEY_DITHERING.isCompatibleValue(dithering)) { throw new IllegalArgumentException(dithering + " is not an acceptable value"); } Object old = getDithering(); renderingHints.put(RenderingHints.KEY_DITHERING, dithering); firePropertyChange("dithering", old, getDithering()); } /** * @returns whether or not to use fractional metrics * May be one of: * <ul> * <li>RenderingHints.VALUE_FRACTIONALMETRICS_DEFAULT</li> * <li>RenderingHints.VALUE_FRACTIONALMETRICS_OFF</li> * <li>RenderingHints.VALUE_FRACTIONALMETRICS_ON</li> * </ul> */ public Object getFractionalMetrics() { return renderingHints.get(RenderingHints.KEY_FRACTIONALMETRICS); } /** * Sets whether or not to use fractional metrics * * @param fractionalMetrics * May be one of: * <ul> * <li>RenderingHints.VALUE_FRACTIONALMETRICS_DEFAULT</li> * <li>RenderingHints.VALUE_FRACTIONALMETRICS_OFF</li> * <li>RenderingHints.VALUE_FRACTIONALMETRICS_ON</li> * </ul> */ public void setFractionalMetrics(Object fractionalMetrics) { if (!RenderingHints.KEY_FRACTIONALMETRICS.isCompatibleValue(fractionalMetrics)) { throw new IllegalArgumentException(fractionalMetrics + " is not an acceptable value"); } Object old = getFractionalMetrics(); renderingHints.put(RenderingHints.KEY_FRACTIONALMETRICS, fractionalMetrics); firePropertyChange("fractionalMetrics", old, getFractionalMetrics()); } /** * @returns the technique to use for interpolation (used esp. when scaling) * May be one of: * <ul> * <li>RenderingHints.VALUE_INTERPOLATION_BICUBIC</li> * <li>RenderingHints.VALUE_INTERPOLATION_BILINEAR</li> * <li>RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR</li> * </ul> */ public Object getInterpolation() { return renderingHints.get(RenderingHints.KEY_INTERPOLATION); } /** * Sets the technique to use for interpolation (used esp. when scaling) * @param interpolation * May be one of: * <ul> * <li>RenderingHints.VALUE_INTERPOLATION_BICUBIC</li> * <li>RenderingHints.VALUE_INTERPOLATION_BILINEAR</li> * <li>RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR</li> * </ul> */ public void setInterpolation(Object interpolation) { if (!RenderingHints.KEY_INTERPOLATION.isCompatibleValue(interpolation)) { throw new IllegalArgumentException(interpolation + " is not an acceptable value"); } Object old = getInterpolation(); renderingHints.put(RenderingHints.KEY_INTERPOLATION, interpolation); firePropertyChange("interpolation", old, getInterpolation()); } /** * @returns a hint as to techniques to use with regards to rendering quality vs. speed * May be one of: * <ul> * <li>RenderingHints.VALUE_RENDER_QUALITY</li> * <li>RenderingHints.VALUE_RENDER_SPEED</li> * <li>RenderingHints.VALUE_RENDER_DEFAULT</li> * </ul> */ public Object getRendering() { return renderingHints.get(RenderingHints.KEY_RENDERING); } /** * Specifies a hint as to techniques to use with regards to rendering quality vs. speed * * @param rendering * May be one of: * <ul> * <li>RenderingHints.VALUE_RENDER_QUALITY</li> * <li>RenderingHints.VALUE_RENDER_SPEED</li> * <li>RenderingHints.VALUE_RENDER_DEFAULT</li> * </ul> */ public void setRendering(Object rendering) { if (!RenderingHints.KEY_RENDERING.isCompatibleValue(rendering)) { throw new IllegalArgumentException(rendering + " is not an acceptable value"); } Object old = getRendering(); renderingHints.put(RenderingHints.KEY_RENDERING, rendering); firePropertyChange("rendering", old, getRendering()); } /** * @returns technique for rendering strokes * May be one of: * <ul> * <li>RenderingHints.VALUE_STROKE_DEFAULT</li> * <li>RenderingHints.VALUE_STROKE_NORMALIZE</li> * <li>RenderingHints.VALUE_STROKE_PURE</li> * </ul> */ public Object getStrokeControl() { return renderingHints.get(RenderingHints.KEY_STROKE_CONTROL); } /** * Specifies a technique for rendering strokes * * @param strokeControl * May be one of: * <ul> * <li>RenderingHints.VALUE_STROKE_DEFAULT</li> * <li>RenderingHints.VALUE_STROKE_NORMALIZE</li> * <li>RenderingHints.VALUE_STROKE_PURE</li> * </ul> */ public void setStrokeControl(Object strokeControl) { if (!RenderingHints.KEY_STROKE_CONTROL.isCompatibleValue(strokeControl)) { throw new IllegalArgumentException(strokeControl + " is not an acceptable value"); } Object old = getStrokeControl(); renderingHints.put(RenderingHints.KEY_STROKE_CONTROL, strokeControl); firePropertyChange("strokeControl", old, getStrokeControl()); } /** * @returns technique for anti-aliasing text. * (TODO this needs to be updated for Mustang. You may use the * new Mustang values, and everything will work, but support in * the GUI builder and documentation need to be added once we * branch for Mustang)<br/> * May be one of: * <ul> * <li>RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT</li> * <li>RenderingHints.VALUE_TEXT_ANTIALIAS_OFF</li> * <li>RenderingHints.VALUE_TEXT_ANTIALIAS_ON</li> * </ul> */ public Object getTextAntialiasing() { return renderingHints.get(RenderingHints.KEY_TEXT_ANTIALIASING); } /** * Sets the technique for anti-aliasing text. * (TODO this needs to be updated for Mustang. You may use the * new Mustang values, and everything will work, but support in * the GUI builder and documentation need to be added once we * branch for Mustang)<br/> * * @param textAntialiasing * May be one of: * <ul> * <li>RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT</li> * <li>RenderingHints.VALUE_TEXT_ANTIALIAS_OFF</li> * <li>RenderingHints.VALUE_TEXT_ANTIALIAS_ON</li> * </ul> */ public void setTextAntialiasing(Object textAntialiasing) { if (!RenderingHints.KEY_TEXT_ANTIALIASING.isCompatibleValue(textAntialiasing)) { throw new IllegalArgumentException(textAntialiasing + " is not an acceptable value"); } Object old = getTextAntialiasing(); renderingHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, textAntialiasing); firePropertyChange("textAntialiasing", old, getTextAntialiasing()); } /** * @return the rendering hint associated with the given key. May return null */ public Object getRenderingHint(RenderingHints.Key key) { return renderingHints.get(key); } /** * Set the given hint for the given key. This will end up firing the appropriate * property change event if the key is recognized. For example, if the key is * RenderingHints.KEY_ANTIALIASING, then the setAntialiasing method will be * called firing an "antialiasing" property change event if necessary. If * the key is not recognized, no event will be fired but the key will be saved. * The key must not be null * * @param key cannot be null * @param hint must be a hint compatible with the given key */ public void setRenderingHint(RenderingHints.Key key, Object hint) { if (key == null) { throw new NullPointerException("RenderingHints key cannot be null"); } if (key == RenderingHints.KEY_ALPHA_INTERPOLATION) { setAlphaInterpolation(hint); } else if (key == RenderingHints.KEY_ANTIALIASING) { setAntialiasing(hint); } else if (key == RenderingHints.KEY_COLOR_RENDERING) { setColorRendering(hint); } else if (key == RenderingHints.KEY_DITHERING) { setDithering(hint); } else if (key == RenderingHints.KEY_FRACTIONALMETRICS) { setFractionalMetrics(hint); } else if (key == RenderingHints.KEY_INTERPOLATION) { setInterpolation(hint); } else if (key == RenderingHints.KEY_RENDERING) { setRendering(hint); } else if (key == RenderingHints.KEY_STROKE_CONTROL) { setStrokeControl(hint); } else if (key == RenderingHints.KEY_TEXT_ANTIALIASING) { setTextAntialiasing(hint); } else { renderingHints.put(key, hint); } } /** * @return a copy of the map of rendering hints held by this class. This * returned value will never be null */ public RenderingHints getRenderingHints() { return (RenderingHints)renderingHints.clone(); } /** * Sets the rendering hints to use. This will <strong>replace</strong> the * rendering hints entirely, clearing any hints that were previously set. * * @param renderingHints map of hints. May be null. I null, a new Map of * rendering hints will be created */ public void setRenderingHints(RenderingHints renderingHints) { RenderingHints old = this.renderingHints; if (renderingHints != null) { this.renderingHints = (RenderingHints)renderingHints.clone(); } else { this.renderingHints = new RenderingHints(new HashMap<RenderingHints.Key, Object>()); } firePropertyChange("renderingHints", old, getRenderingHints()); } /** * Saves the state in the given Graphics2D object so that it may be * restored later. * * @param g the Graphics2D object who's state will be saved */ protected void saveState(Graphics2D g) { oldPaint = g.getPaint(); oldFont = g.getFont(); oldStroke = g.getStroke(); oldTransform = g.getTransform(); oldComposite = g.getComposite(); oldClip = g.getClip(); oldBackground = g.getBackground(); oldColor = g.getColor(); //save off the old rendering hints oldRenderingHints = g.getRenderingHints(); stateSaved = true; } protected void restoreState(Graphics2D g) { if (!stateSaved) { throw new IllegalStateException("A call to saveState must occur " + "prior to calling restoreState"); } g.setPaint(oldPaint); g.setFont(oldFont); g.setTransform(oldTransform); g.setStroke(oldStroke); g.setComposite(oldComposite); g.setClip(oldClip); g.setBackground(oldBackground); g.setColor(oldColor); //restore the rendering hints g.setRenderingHints(oldRenderingHints); stateSaved = false; } /** * @inheritDoc */ public void paint(Graphics2D g, JComponent component) { saveState(g); configureGraphics(g); //if I am cacheing, and the cache is not null, and the image has the //same dimensions as the component, then simply paint the image BufferedImage image = cachedImage == null ? null : cachedImage.get(); if (isUseCache() && image != null && image.getWidth() == component.getWidth() && image.getHeight() == component.getHeight()) { g.drawImage(image, 0, 0, null); } else { Effect[] effects = getEffects(); if (effects.length > 0 || isUseCache()) { image = PaintUtils.createCompatibleImage( component.getWidth(), component.getHeight(), Transparency.TRANSLUCENT); Graphics2D gfx = image.createGraphics(); configureGraphics(gfx); paintBackground(gfx, component); gfx.dispose(); for (Effect effect : effects) { effect.apply(image); } g.drawImage(image, 0, 0, null); if (isUseCache()) { cachedImage = new SoftReference<BufferedImage>(image); } } else { paintBackground(g, component); } } restoreState(g); } /** * Utility method for configuring the given Graphics2D with the rendering hints, * composite, and clip */ private void configureGraphics(Graphics2D g) { g.setRenderingHints(getRenderingHints()); if (getComposite() != null) { g.setComposite(getComposite()); } if (getClip() != null) { g.setClip(getClip()); } } /** * Subclasses should implement this method and perform custom painting operations * here. Common behavior, such as setting the clip and composite, saving and restoring * state, is performed in the "paint" method automatically, and then delegated here. * * @param g The Graphics2D object in which to paint * @param component The JComponent that the Painter is delegate for. */ protected abstract void paintBackground(Graphics2D g, JComponent component); }
package org.jdesktop.swingx.painter; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; /** * <p>A Painter implemention that contains an array of Painters, and executes them * in order. This allows you to create a layered series of painters, similar to * the layer design style in Photoshop or other image processing software.</p> * * <p>For example, if I want to create a CompoundPainter that started with a blue * background, had pinstripes on it running at a 45 degree angle, and those * pinstripes appeared to "fade in" from left to right, I would write the following: * <pre><code> * Color blue = new Color(0x417DDD); * Color translucent = new Color(blue.getRed(), blue.getGreen(), blue.getBlue(), 0); * panel.setBackground(blue); * panel.setForeground(Color.LIGHT_GRAY); * GradientPaint blueToTranslucent = new GradientPaint( * new Point2D.Double(.4, 0), * blue, * new Point2D.Double(1, 0), * translucent); * Painter veil = new BasicGradientPainter(blueToTranslucent); * Painter pinstripes = new PinstripePainter(45); * Painter backgroundPainter = new BackgroundPainter(); * Painter p = new CompoundPainter(backgroundPainter, pinstripes, veil); * panel.setBackgroundPainter(p); * </code></pre></p> * * @author rbair */ public class CompoundPainter<T> extends AbstractPainter<T> { private Painter[] painters = new Painter[0]; private AffineTransform transform; private boolean clipPreserved = false; /** Creates a new instance of CompoundPainter */ public CompoundPainter() { } /** * Convenience constructor for creating a CompoundPainter for an array * of painters. A defensive copy of the given array is made, so that future * modification to the array does not result in changes to the CompoundPainter. * * @param painters array of painters, which will be painted in order */ public CompoundPainter(Painter... painters) { this.painters = new Painter[painters == null ? 0 : painters.length]; if (painters != null) { System.arraycopy(painters, 0, this.painters, 0, painters.length); } } private boolean useCaching; public CompoundPainter(boolean useCaching, Painter ... painters) { this(painters); this.useCaching = useCaching; } /** * Sets the array of Painters to use. These painters will be executed in * order. A null value will be treated as an empty array. * * @param painters array of painters, which will be painted in order */ public void setPainters(Painter... painters) { Painter[] old = getPainters(); this.painters = new Painter[painters == null ? 0 : painters.length]; if (painters != null) { System.arraycopy(painters, 0, this.painters, 0, painters.length); } firePropertyChange("painters", old, getPainters()); } /** * Gets the array of painters used by this CompoundPainter * @return a defensive copy of the painters used by this CompoundPainter. * This will never be null. */ public Painter[] getPainters() { Painter[] results = new Painter[painters.length]; System.arraycopy(painters, 0, results, 0, results.length); return results; } /** * Indicates if the clip produced by any painter is left set once it finishes painting. * Normally the clip will be reset between each painter. Setting clipPreserved to * true can be used to let one painter mask other painters that come after it. * @return if the clip should be preserved * @see #setClipPreserved(boolean) */ public boolean isClipPreserved() { return clipPreserved; } /** * Sets if the clip should be preserved. * Normally the clip will be reset between each painter. Setting clipPreserved to * true can be used to let one painter mask other painters that come after it. * * @param shouldRestoreState new value of the clipPreserved property * @see #isClipPreserved() */ public void setClipPreserved(boolean shouldRestoreState) { boolean oldShouldRestoreState = isClipPreserved(); this.clipPreserved = shouldRestoreState; firePropertyChange("shouldRestoreState",oldShouldRestoreState,shouldRestoreState); } /** * @inheritDoc */ @Override public void doPaint(Graphics2D g, T component, int width, int height) { if(getTransform() != null) { g.setTransform(getTransform()); } for (Painter p : getPainters()) { Graphics2D temp = (Graphics2D) g.create(); p.paint(temp, component, width, height); if(isClipPreserved()) { g.setClip(temp.getClip()); } temp.dispose(); } } /** * Gets the current transform applied to all painters in this CompoundPainter. May be null. * @return the current AffineTransform */ public AffineTransform getTransform() { return transform; } /** * Set a transform to be applied to all painters contained in this GradientPainter * @param transform a new AffineTransform */ public void setTransform(AffineTransform transform) { AffineTransform old = getTransform(); this.transform = transform; firePropertyChange("transform",old,transform); } @Override protected boolean isUseCache() { return useCaching; } }
package com.scg.domain; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; /** * @author Brian Stamm * */ public class InvoiceFooterTest { private String testDashes = "=========================================================================\n"; private String testBusiness = "Expeditors"; @Test public void testConstructorToString() { StringBuilder sb = new StringBuilder(); Formatter ft = new Formatter(sb); ft.format("%s\nPage Number: %d\n%s\n", testBusiness,1,testDashes); ft.close(); String testString = sb.toString(); InvoiceFooter footer = new InvoiceFooter(testBusiness); assertEquals(footer.toString(),testString); } @Test public void testIncrementPageNumber(){ StringBuilder sb = new StringBuilder(); Formatter ft = new Formatter(sb); ft.format("%s\nPage Number: %d\n%s\n", testBusiness,5,testDashes); ft.close(); String testString = sb.toString(); InvoiceFooter footer = new InvoiceFooter(testBusiness); for(int i =0; i<4;i++){ footer.incrementPageNumber(); } assertEquals(footer.toString(),testString); } }
package org.knowm.xchange.cexio.service; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.knowm.xchange.Exchange; import org.knowm.xchange.cexio.CexIOAdapters; import org.knowm.xchange.cexio.dto.trade.CexIOArchivedOrder; import org.knowm.xchange.cexio.dto.trade.CexIOOrder; import org.knowm.xchange.dto.Order; import org.knowm.xchange.dto.marketdata.Trades; import org.knowm.xchange.dto.trade.*; import org.knowm.xchange.exceptions.ExchangeException; import org.knowm.xchange.exceptions.NotAvailableFromExchangeException; import org.knowm.xchange.exceptions.NotYetImplementedForExchangeException; import org.knowm.xchange.service.trade.TradeService; import org.knowm.xchange.service.trade.params.TradeHistoryParams; import org.knowm.xchange.service.trade.params.orders.OpenOrdersParamCurrencyPair; import org.knowm.xchange.service.trade.params.orders.OpenOrdersParams; public class CexIOTradeService extends CexIOTradeServiceRaw implements TradeService { /** * Constructor * * @param exchange */ public CexIOTradeService(Exchange exchange) { super(exchange); } @Override public OpenOrders getOpenOrders() throws IOException { return getOpenOrders(createOpenOrdersParams()); } @Override public OpenOrders getOpenOrders( OpenOrdersParams params) throws ExchangeException, NotAvailableFromExchangeException, NotYetImplementedForExchangeException, IOException { List<CexIOOrder> cexIOOrderList; if (params instanceof OpenOrdersParamCurrencyPair) { OpenOrdersParamCurrencyPair o = (OpenOrdersParamCurrencyPair) params; cexIOOrderList = getCexIOOpenOrders(o.getCurrencyPair()); } else { cexIOOrderList = getCexIOOpenOrders(); } return CexIOAdapters.adaptOpenOrders(cexIOOrderList); } @Override public String placeMarketOrder(MarketOrder marketOrder) throws IOException { throw new NotAvailableFromExchangeException(); } @Override public String placeLimitOrder(LimitOrder limitOrder) throws IOException { CexIOOrder order = placeCexIOLimitOrder(limitOrder); return Long.toString(order.getId()); } @Override public boolean cancelOrder(String orderId) throws IOException { return cancelCexIOOrder(orderId); } @Override public UserTrades getTradeHistory(TradeHistoryParams params) throws IOException { List<CexIOArchivedOrder> cexIOArchivedOrders = archivedOrders(params); ArrayList<UserTrade> trades = new ArrayList<>(); for (CexIOArchivedOrder cexIOArchivedOrder : cexIOArchivedOrders) { trades.add(CexIOAdapters.adaptArchivedOrder(cexIOArchivedOrder)); } return new UserTrades(trades, Trades.TradeSortType.SortByTimestamp); } @Override public TradeHistoryParams createTradeHistoryParams() { throw new NotAvailableFromExchangeException(); } @Override public OpenOrdersParams createOpenOrdersParams() { return null; // TODO: return new DefaultOpenOrdersParamCurrencyPair(); } @Override public Collection<Order> getOrder( String... orderIds) throws ExchangeException, NotAvailableFromExchangeException, NotYetImplementedForExchangeException, IOException { throw new NotYetImplementedForExchangeException(); } }
package org.sfm.jdbc.mysql; import java.sql.*; public class MysqlDbHelper { public static Connection objectDb() throws SQLException { Connection c = newMysqlDbConnection(); Statement st = c.createStatement(); try { createDbObject(st); } finally { st.close(); } return c; } private static void createDbObject(Statement st) throws SQLException { st.execute("create table IF NOT EXISTS TEST_DB_OBJECT(" + " id bigint primary key," + " name varchar(100), " + " email varchar(100)," + " creation_Time DATETIME, type_ordinal int, type_name varchar(10) )"); st.execute("create table IF NOT EXISTS TEST_DB_OBJECT_AUTOINC(" + " id bigint AUTO_INCREMENT primary key," + " name varchar(100), " + " email varchar(100)," + " creation_Time DATETIME, type_ordinal int, type_name varchar(10) )"); st.execute("create table IF NOT EXISTS TEST_DB_OBJECT_CKEY(" + " id bigint," + " name varchar(100), " + " email varchar(100)," + " creation_Time DATETIME, type_ordinal int, type_name varchar(10), primary key(id, name) )"); } private static Connection newMysqlDbConnection() throws SQLException { String user = "sfm"; if ("true".equals(System.getenv("TRAVISBUILD"))) { user = "travis"; } return DriverManager.getConnection("jdbc:mysql://localhost:3306/sfm", user, null); } public static void main(String[] args) throws SQLException { Connection connection = MysqlDbHelper.objectDb(); System.out.println("product name = " + connection.getMetaData().getDatabaseProductName()); System.out.println("product name = " + connection.getMetaData().getDatabaseProductVersion()); System.out.println("product name = " + connection.getMetaData().getDatabaseMajorVersion()); System.out.println("product name = " + connection.getMetaData().getDatabaseMinorVersion()); } }
package org.knowm.xchange.exmo.service; import static org.apache.commons.lang3.StringUtils.join; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.knowm.xchange.Exchange; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order; import org.knowm.xchange.dto.trade.LimitOrder; import org.knowm.xchange.dto.trade.UserTrade; import org.knowm.xchange.exceptions.ExchangeException; import org.knowm.xchange.exmo.dto.trade.ExmoUserTrades; import org.knowm.xchange.utils.DateUtils; public class ExmoTradeServiceRaw extends BaseExmoService { protected ExmoTradeServiceRaw(Exchange exchange) { super(exchange); } protected String placeOrder( String type, BigDecimal price, CurrencyPair currencyPair, BigDecimal originalAmount) { Map map = exmo.orderCreate( signatureCreator, apiKey, exchange.getNonceFactory(), ExmoAdapters.format(currencyPair), originalAmount, price, type); Boolean result = (Boolean) map.get("result"); if (!result) throw new ExchangeException("Failed to place order: " + map.get("error")); return map.get("order_id").toString(); } public List<LimitOrder> openOrders() { Map<String, List<Map<String, String>>> map = exmo.userOpenOrders(signatureCreator, apiKey, exchange.getNonceFactory()); List<LimitOrder> openOrders = new ArrayList<>(); for (String market : map.keySet()) { CurrencyPair currencyPair = adaptMarket(market); for (Map<String, String> order : map.get(market)) { Order.OrderType type = ExmoAdapters.adaptOrderType(order); BigDecimal amount = new BigDecimal(order.get("quantity")); String id = order.get("order_id"); BigDecimal price = new BigDecimal(order.get("price")); Date created = DateUtils.fromUnixTime(Long.valueOf(order.get("created"))); openOrders.add(new LimitOrder(type, amount, currencyPair, id, created, price)); } } return openOrders; } public ExmoUserTrades userTrades(String orderId) { Map<String, Object> map = exmo.orderTrades(signatureCreator, apiKey, exchange.getNonceFactory(), orderId); List<UserTrade> userTrades = new ArrayList<>(); Boolean result = (Boolean) map.get("result"); if (result != null && !result) return null; BigDecimal originalAmount = new BigDecimal(map.get("out_amount").toString()); for (Map<String, Object> tradeDatum : (List<Map<String, Object>>) map.get("trades")) { CurrencyPair market = adaptMarket(tradeDatum.get("pair").toString()); Map<String, String> bodge = new HashMap<>(); for (String key : tradeDatum.keySet()) { bodge.put(key, tradeDatum.get(key).toString()); } userTrades.add(ExmoAdapters.adaptTrade(bodge, market)); } return new ExmoUserTrades(originalAmount, userTrades); } public List<UserTrade> trades( Integer limit, Long offset, Collection<CurrencyPair> currencyPairs) { List<String> markets = new ArrayList<>(); for (CurrencyPair currencyPair : currencyPairs) { markets.add(ExmoAdapters.format(currencyPair)); } Map<String, List<Map<String, String>>> map = exmo.userTrades( signatureCreator, apiKey, exchange.getNonceFactory(), join(markets, ","), offset, limit); List<UserTrade> trades = new ArrayList<>(); for (String market : map.keySet()) { for (Map<String, String> tradeDatum : map.get(market)) { trades.add(ExmoAdapters.adaptTrade(tradeDatum, adaptMarket(market))); } } Collections.sort(trades, (o1, o2) -> o2.getTimestamp().compareTo(o1.getTimestamp())); return trades; } }
package rabbit.cache.ncache; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import rabbit.cache.Cache; import rabbit.cache.CacheConfiguration; import rabbit.cache.CacheEntry; import rabbit.cache.CacheException; import rabbit.cache.utils.CacheConfigurationBase; import rabbit.cache.utils.CacheUtils; import rabbit.io.FileHelper; import rabbit.util.SProperties; /** The NCache is like a Map in lookup/insert/delete * The NCache is persistent over sessions (saves itself to disk). * The NCache is selfcleaning, that is it removes old stuff. * * @param <K> the key type of the cache * @param <V> the data resource * * @author <a href="mailto:robo@khelekore.org">Robert Olofsson</a> */ public class NCache<K, V> implements Cache<K, V>, Runnable { private static final String DIR = "/tmp/rabbit/cache"; // standard dir. private static final String DEFAULT_CLEAN_LOOP = "60"; // 1 minute private static final String CACHEINDEX = "cache.index"; // the indexfile. private Configuration configuration = new Configuration (); private boolean changed = false; // have we changed? private Thread cleaner = null; // remover of old stuff. private int cleanLoopTime = 60 * 1000; // sleeptime between cleanups. private long fileNo = 0; private long currentSize = 0; private File dir = null; private Map<FiledKey<K>, NCacheData<K, V>> htab = null; private List<NCacheData<K, V>> vec = null; private File tempdir = null; private final Object dirLock = new Object (); private final Logger logger = Logger.getLogger (getClass ().getName ()); private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock (); private final Lock r = rwl.readLock (); private final Lock w = rwl.writeLock (); private final FileHandler<K> fhk; private final FileHandler<V> fhv; private volatile boolean running = true; /** Create a cache that uses default values. * Note that you must call start to have the cache fully up. * @param props the configuration of the cache * @param fhk the FileHandler for the cache keys * @param fhv the FileHandler for the cache values * @throws IOException if the cache file directory can not be configured */ public NCache (SProperties props, FileHandler<K> fhk, FileHandler<V> fhv) throws IOException { this.fhk = fhk; this.fhv = fhv; htab = new HashMap<FiledKey<K>, NCacheData<K, V>> (); vec = new ArrayList<NCacheData<K, V>> (); setup (props); } /** Start the thread that cleans the cache. */ public void start () { cleaner = new Thread (this, getClass ().getName () + ".cleaner"); cleaner.setDaemon (true); cleaner.start (); } public CacheConfiguration getCacheConfiguration () { return configuration; } private class Configuration extends CacheConfigurationBase { public URL getCacheDir () { r.lock (); try { if (dir == null) return null; return dir.toURI ().toURL (); } catch (MalformedURLException e) { return null; } finally { r.unlock (); } } /** Sets the cachedir. This will flush the cache and make * it try to read in the cache from the new dir. * @param newDir the name of the new directory to use. * @throws IOException if the new cache file directory can not be configured */ private void setCacheDir (String newDir) throws IOException { w.lock (); try { // save old cachedir. if (dir != null) writeCacheIndex (); // does new dir exist? dir = new File (newDir); File dirtest = dir; boolean readCache = true; if (!dirtest.exists ()) { FileHelper.mkdirs (dirtest); if (!dirtest.exists ()) { logger.warning ("could not create cachedir: " + dirtest); } readCache = false; } else if (dirtest.isFile ()) { logger.warning ("Cachedir: " + dirtest + " is a file"); } synchronized (dirLock) { tempdir = new File (dirtest, CacheUtils.TEMPDIR); if (!tempdir.exists ()) { FileHelper.mkdirs (tempdir); if (!tempdir.exists ()) { logger.warning ("could not create cache tempdir: " + tempdir); } } else if (tempdir.isFile ()) { logger.warning ("Cache temp dir is a file: " + tempdir); } } if (readCache) // move to new dir. readCacheIndex (); } finally { w.unlock (); } } } /** Get how long time the cleaner sleeps between cleanups. * @return the number of millis between cleanups */ public int getCleanLoopTime () { return cleanLoopTime; } /** Set how long time the cleaner sleeps between cleanups. * @param newCleanLoopTime the number of miliseconds to sleep. */ public void setCleanLoopTime (int newCleanLoopTime) { cleanLoopTime = newCleanLoopTime; } /** Get the current size of the cache * @return the current size of the cache in bytes. */ public long getCurrentSize () { r.lock (); try { return currentSize; } finally { r.unlock (); } } /** Get the current number of entries in the cache. * @return the current number of entries in the cache. */ public long getNumberOfEntries () { r.lock (); try { return htab.size (); } finally { r.unlock (); } } /** Check that the data hook exists. * @param e the NCacheEntry to check * @return true if the cache data is valid, false otherwise */ private boolean checkHook (NCacheData<K, V> e) { FiledHook<V> hook = e.getDataHook (); if (hook != null) { File entryName = getEntryName (e.getId (), true, "hook"); if (!entryName.exists ()) return false; } return true; } /** Get the CacheEntry assosiated with given object. * @param k the key. * @return the CacheEntry or null (if not found). */ public CacheEntry<K, V> getEntry (K k) throws CacheException { NCacheData<K, V> cacheEntry = getCurrentData (k); if (cacheEntry != null && !checkHook (cacheEntry)) { // bad entry... remove (k); } /* If you want to implement LRU or something like that: if (cacheEntry != null) cacheEntry.setVisited (System.currentTimeMillis ()); */ return getEntry (cacheEntry); } public File getEntryName (long id, boolean real, String extension) { return CacheUtils.getEntryName (dir, id, real, extension); } /** Reserve space for a CacheEntry with key o. * @param k the key for the CacheEntry. * @return a new CacheEntry initialized for the cache. */ public CacheEntry<K, V> newEntry (K k) { long newId = 0; // allocate the id for the new entry. w.lock (); try { newId = fileNo; fileNo++; } finally { w.unlock (); } long now = System.currentTimeMillis (); long expires = now + configuration.getCacheTime (); return new NCacheEntry<K, V> (newId, now, expires, 0, k, null); } /** Get the file handler for the keys. * @return the FileHandler for the key objects */ FileHandler<K> getKeyFileHandler () { return fhk; } /** Get the file handler for the values. * @return the FileHandler for the values */ FileHandler<V> getHookFileHandler () { return fhv; } /** Insert a CacheEntry into the cache. * @param ent the CacheEntry to store. */ public void addEntry (CacheEntry<K, V> ent) throws CacheException { if (ent == null) return; NCacheEntry<K, V> nent = (NCacheEntry<K, V>)ent; addEntry (nent); } private void addEntry (NCacheEntry<K, V> ent) throws CacheException { File cfile = getEntryName (ent.getId (), false, null); if (!cfile.exists()) return; File newName = getEntryName (ent.getId (), true, null); File cacheDir = newName.getParentFile (); synchronized (dirLock) { ensureCacheDirIsValid (cacheDir); if (!cfile.renameTo (newName)) logger.severe ("Failed to renamve file from: " + cfile.getAbsolutePath () + " to" + newName.getAbsolutePath ()); } cfile = newName; NCacheData<K, V> data = getData (ent, cfile); w.lock (); try { remove (ent.getKey ()); htab.put (data.getKey (), data); currentSize += data.getSize () + data.getKeySize () + data.getHookSize (); vec.add (data); } finally { w.unlock (); } changed = true; } private void ensureCacheDirIsValid (File f) { if (f.exists ()) { if (f.isFile ()) logger.warning ("Wanted cachedir is a file: " + f); // good situation... } else { try { FileHelper.mkdirs (f); } catch (IOException e) { logWarning ("Could not create directory: " + f, e); } } } /** Signal that a cache entry have changed. */ public void entryChanged (CacheEntry<K, V> ent, K newKey, V newHook) throws CacheException { NCacheData<K, V> data = getCurrentData (ent.getKey ()); if (data == null) { Thread.dumpStack (); logger.warning ("Failed to find changed entry so ignoring: " + ent.getId ()); return; } try { data.updateExpireAndSize (ent); long id = ent.getId (); FiledWithSize<FiledKey<K>> fkws = storeKey (newKey, id); data.setKey (fkws.t, fkws.size); FiledWithSize<FiledHook<V>> fhws = storeHook (newHook, id); data.setDataHook (fhws.t, fhws.size); } catch (IOException e) { throw new CacheException ("Failed to update entry: entry: " + ent + ", newKey: " + newKey, e); } finally { changed = true; } } private NCacheData<K, V> getCurrentData (K key) { MemoryKey<K> mkey = new MemoryKey<K> (key); r.lock (); try { return htab.get (mkey); } finally { r.unlock (); } } private void removeHook (File base, String extension) throws IOException { String hookName = base.getName () + extension; // remove possible hook before file... File hfile = new File (base.getParentFile (), hookName); if (hfile.exists ()) FileHelper.delete (hfile); } /** Remove the Entry with key k from the cache. * @param k the key for the CacheEntry. */ public void remove (K k) throws CacheException{ NCacheData<K, V> r; w.lock (); try { if (k == null) { // Odd, but seems to happen. Probably removed // by someone else before enumeration gets to it. return; } FiledKey<K> fk = new MemoryKey<K> (k); r = htab.get (fk); if (r != null) { // remove entries while it is still in htab. vec.remove (r); currentSize -= (r.getSize () + r.getKeySize () + r.getHookSize ()); htab.remove (fk); } } finally { w.unlock (); } if (r != null) { // this removes the key => htab.remove can not work.. File entryName = getEntryName (r.getId (), true, null); try { removeHook (entryName, ".hook"); removeHook (entryName, ".key"); r.setDataHook (null, 0); File cfile = entryName; if (cfile.exists ()) { File p = cfile.getParentFile (); FileHelper.delete (cfile); // Until NT does rename in a nice manner check for tempdir. synchronized (dirLock) { if (p.exists () && !p.equals (tempdir)) { String ls[] = p.list (); if (ls != null && ls.length == 0) FileHelper.delete (p); } } } } catch (IOException e) { throw new CacheException ("Failed to remove file, key: " + k, e); } } } /** Clear the Cache from files. */ public void clear () throws CacheException { ArrayList<FiledKey<K>> ls; w.lock (); try { ls = new ArrayList<FiledKey<K>> (htab.keySet ()); for (FiledKey<K> k : ls) { try { remove (k.getData ()); } catch (IOException e) { throw new CacheException ("Failed to remove entry, key: " + k, e); } } vec.clear (); // just to be safe. currentSize = 0; changed = true; } finally { w.unlock (); } } /** Get the CacheEntries in the cache. * Note! some entries may be invalid if you have a corruct cache. * @return a Collection of the CacheEntries. */ public Iterable<NCacheEntry<K, V>> getEntries () { // Defensive copy so that nothing happen when the user iterates r.lock (); try { return new NCacheIterator (htab.values ()); } finally { r.unlock (); } } private class NCacheIterator implements Iterable<NCacheEntry<K, V>>, Iterator<NCacheEntry<K, V>> { private Iterator<NCacheData<K, V>> dataIterator; public NCacheIterator (Collection<NCacheData<K, V>> c) { dataIterator = new ArrayList<NCacheData<K, V>> (c).iterator (); } public Iterator<NCacheEntry<K, V>> iterator () { return this; } public NCacheEntry<K, V> next () { try { return getEntry (dataIterator.next ()); } catch (CacheException e) { throw new RuntimeException ("Failed to get entry", e); } } public boolean hasNext () { return dataIterator.hasNext (); } public void remove () { throw new UnsupportedOperationException (); } } /** Read the info from an old cache. */ private void readCacheIndex () { try { File index = new File (dir, CACHEINDEX); if (index.exists ()) readCacheIndex (index); else logger.info ("No cache index found: " + index + ", treating as empty cache"); } catch (IOException e) { logWarning ("Couldnt read " + dir + File.separator + CACHEINDEX + ". This is bad (but not serius).\nTreating as empty. ", e); } catch (ClassNotFoundException e) { logger.log (Level.SEVERE, "Couldn't find classes", e); } } @SuppressWarnings( "unchecked" ) private void readCacheIndex (File index) throws IOException, ClassNotFoundException { long fileNo; long currentSize; FileInputStream fis = new FileInputStream (index); ObjectInputStream is = new ObjectInputStream (new GZIPInputStream (fis)); fileNo = is.readLong (); currentSize = is.readLong (); int size = is.readInt (); Map<FiledKey<K>, NCacheData<K, V>> htab = new HashMap<FiledKey<K>, NCacheData<K, V>> ((int)(size * 1.2)); for (int i = 0; i < size; i++) { FiledKey<K> fk = (FiledKey<K>)is.readObject (); fk.setCache (this); NCacheData<K, V> entry = (NCacheData<K, V>)is.readObject (); htab.put (fk, entry); } List<NCacheData<K, V>> vec = (List<NCacheData<K, V>>)is.readObject (); is.close (); // Only set internal state if we managed to get it all. this.fileNo = fileNo; this.currentSize = currentSize; this.htab = htab; this.vec = vec; } /** Make sure that the cache is written to the disk. */ public void flush () { writeCacheIndex (); } /** Store the cache to disk so we can reuse it later. */ private void writeCacheIndex () { try { String name = dir + File.separator + CACHEINDEX; FileOutputStream fos = new FileOutputStream (name); ObjectOutputStream os = new ObjectOutputStream (new GZIPOutputStream (fos)); r.lock (); try { os.writeLong (fileNo); os.writeLong (currentSize); os.writeInt (htab.size ()); for (Map.Entry<FiledKey<K>, NCacheData<K, V>> me : htab.entrySet ()) { os.writeObject (me.getKey ()); os.writeObject (me.getValue ()); } os.writeObject (vec); } finally { r.unlock (); } os.close (); } catch (IOException e) { logWarning ("Couldnt write " + dir + File.separator + CACHEINDEX + ", This is serious!\n", e); } } /** Loop in a cleaning loop. */ public void run () { Thread.currentThread ().setPriority (Thread. MIN_PRIORITY); while (running) { try { Thread.sleep (cleanLoopTime); } catch (InterruptedException e) { //System.err.println ("Cache interrupted"); } if (!running) continue; // actually for a busy cache this will lag... // but I dont care for now... long milis = System.currentTimeMillis (); Map<FiledKey<K>, NCacheData<K, V>> hc; r.lock (); try { hc = new HashMap<FiledKey<K>, NCacheData<K, V>> (htab); } finally { r.unlock (); } for (Map.Entry<FiledKey<K>, NCacheData<K, V>> ce : hc.entrySet ()) { try { long exp = ce.getValue ().getExpires (); if (exp < milis) removeKey (ce.getKey ()); } catch (IOException e) { logWarning ("Failed to remove expired entry", e); } catch (CacheException e) { logWarning ("Failed to remove expired entry", e); } } // IF SIZE IS TO BIG REMOVE A RANDOM AMOUNT OF OBJECTS. // What we have to be careful about: we must not remove the same // elements two times in a row, this method remove the "oldest" in // a sense. long maxSize = configuration.getMaxSize (); if (getCurrentSize () > maxSize) changed = true; while (getCurrentSize () > maxSize) { w.lock (); try { removeKey (vec.get (0).getKey ()); } catch (IOException e) { logWarning ("Failed to remove entry", e); } catch (CacheException e) { logWarning ("Failed to remove entry", e); } finally { w.unlock (); } } if (changed) { writeCacheIndex (); changed = false; } } } private void removeKey (FiledKey<K> fk) throws IOException, CacheException { fk.setCache (this); remove (fk.getData ()); } public void stop () { running = false; if (cleaner != null) { try { cleaner.interrupt (); cleaner.join (); } catch (InterruptedException e) { // ignore } } } /** Configure the cache system from the given config. * @param config the properties describing the cache settings. * @throws IOException if the new cache can not be configured correctly */ public void setup (SProperties config) throws IOException { if (config == null) config = new SProperties (); String cachedir = config.getProperty ("directory", DIR); configuration.setCacheDir (cachedir); configuration.setup (logger, config); String ct = config.getProperty ("cleanloop", DEFAULT_CLEAN_LOOP); try { setCleanLoopTime (Integer.parseInt (ct) * 1000); // in seconds. } catch (NumberFormatException e) { logger.warning ("Bad number for cache cleanloop: '" + ct + "'"); } } public Logger getLogger () { return logger; } private NCacheEntry<K, V> getEntry (NCacheData<K, V> data) throws CacheException { if (data == null) return null; try { FiledKey<K> key = data.getKey (); key.setCache (this); K keyData = key.getData (); V hook = data.getDataHook ().getData (this, data, getLogger ()); return new NCacheEntry<K, V> (data.getId (), data.getCacheTime (), data.getExpires (), data.getSize (), keyData, hook); } catch (IOException e) { throw new CacheException ("Failed to get: entry: " + data, e); } } private NCacheData<K, V> getData (NCacheEntry<K, V> entry, File cacheFile) throws CacheException { long id = entry.getId (); long size = cacheFile.length (); try { FiledWithSize<FiledKey<K>> fkws = storeKey (entry.getKey (), id); FiledWithSize<FiledHook<V>> fhws = storeHook (entry.getDataHook (), id); return new NCacheData<K, V> (id, entry.getCacheTime (), entry.getExpires (), size, fkws.t, fkws.size, fhws.t, fhws.size); } catch (IOException e) { // TODO: do we need to clean anything up? throw new CacheException ("Failed to store data", e); } } private FiledWithSize<FiledKey<K>> storeKey (K realKey, long id) throws IOException { FiledKey<K> fk = new FiledKey<K> (); long size = fk.storeKey (this, id, realKey, logger); return new FiledWithSize<FiledKey<K>> (fk, size); } private FiledWithSize<FiledHook<V>> storeHook (V hook, long id) throws IOException { if (hook == null) return null; FiledHook<V> fh = new FiledHook<V> (); long size = fh.storeHook (this, id, getHookFileHandler (), hook, logger); return new FiledWithSize<FiledHook<V>> (fh, size); } private static class FiledWithSize<T> { private final T t; private final long size; public FiledWithSize (T t, long size) { this.t = t; this.size = size; } } private void logWarning (String s, Exception e) { logger.log (Level.WARNING, s, e); } }
package radlab.rain.agent; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import radlab.rain.UnexpectedDeathHandler; import radlab.rain.load.LoadDefinition; import radlab.rain.operation.Generator; import radlab.rain.operation.IOperation; import radlab.rain.operation.OperationExecution; import radlab.rain.scoreboard.IScoreboard; /** * Provides the main loop of the agent thread. */ public class AgentPOL extends Agent { private static Logger logger = LoggerFactory.getLogger(AgentPOL.class); // Scoreboard reference protected IScoreboard scoreboard; // The generator used to create operations for this thread private Generator generator; // The probability of using open loop vs. closed loop private double openLoopProbability; // The random number generator used to decide which loop to use private Random random = new Random(); // Statistic: number of synchronous and asynchronous operations run private long synchOperationsCount = 0; private long asynchOperationsCount = 0; // Interrupted private boolean interrupted = false; public AgentPOL(long targetId, long id) { super(targetId, id); Thread.setDefaultUncaughtExceptionHandler(new UnexpectedDeathHandler()); } /** * Decides whether this thread is active or not. The number of threads is equal to the maximum number of generators. * The actual number of threads varies over time. This is achieved by blocking some threads. If a thread is blocked * is decided by this function. */ private boolean isActive() { LoadDefinition loadProfile = loadManager.getCurrentLoadProfile(); return (id < loadProfile.getNumberOfUsers()); } @Override public void interrupt() { interrupted = true; } @Override public void dispose() { this.generator.dispose(); } private void triggerNextOperation(int lastOperationIndex) throws InterruptedException { threadState = ThreadStates.Active; // Generate next operation using the attached generator IOperation nextOperation = generator.nextRequest(lastOperationIndex); // Execute operation if (nextOperation != null) { // Set operation references nextOperation.setLoadDefinition(loadManager.getCurrentLoadProfile()); // Prepare the operation nextOperation.prepare(); // Update last operation index. lastOperationIndex = nextOperation.getOperationIndex(); // EXECUTE OPERATION // Decide whether to do things open or closed (throw a coin) double randomDouble = random.nextDouble(); if (randomDouble <= openLoopProbability) doAsyncOperation(nextOperation); else doSyncOperation(nextOperation); } } /** * Load generator loop. Runs the generator for each cycle and executes the returned operation. */ public void run() { logger.debug("New agent thread " + super.id); try { // Sleep until its time to start sleepUntil(timing.start); // Last executed operation (required to run markov chains) int lastOperationIndex = -1; // Check if benchmark is still running while (System.currentTimeMillis() <= timing.endRun && !interrupted) { // If generator is not active if (!isActive()) { threadState = ThreadStates.Inactive; // Sleep for 1 second and check active state again Thread.sleep(1000); } else { // Generator is active // IMPORTANT: Next operation is triggered here triggerNextOperation(lastOperationIndex); } } logger.debug("Agent ended - interrupted: " + interrupted); } catch (InterruptedException ie) { logger.error("Load generation thread interrupted exiting!"); } catch (Exception e) { logger.error("Load generation thread died by exception! Reason: " + e.toString()); e.printStackTrace(); } } /** * Runs the provided operation asynchronously and sleeps this thread on the cycle time. */ private void doAsyncOperation(IOperation operation) throws InterruptedException { // Update operation counters asynchOperationsCount++; // Calculate timings long cycleTime = generator.getCycleTime(); long now = System.currentTimeMillis(); // Wait after operation execution cycleTime = waitUntil(now, cycleTime); // Set async flag operation.setAsync(true); // Trigger operation doOperation(operation); // Save the cycle time - if we're in the steady state scoreboard.dropOffWaitTime(now, operation.getOperationName(), cycleTime); } private final class DropoffHandler implements Runnable { private final IOperation wrapped; DropoffHandler(IOperation wrapped) { this.wrapped = wrapped; } @Override public void run() { OperationExecution result = wrapped.run(); scoreboard.dropOffOperation(result); } } @Override protected void submitAsyncOperation(IOperation operation) { DropoffHandler handler = new DropoffHandler(operation); executorService.submit(handler); } @Override protected void runSyncOperation(IOperation operation) { OperationExecution result = operation.run(); scoreboard.dropOffOperation(result); } /** * Runs the provided operation synchronously and sleeps this thread on the think time. */ private void doSyncOperation(IOperation operation) throws InterruptedException { // Update operation counters synchOperationsCount++; // Configure operation operation.setAsync(false); // Trigger operation doOperation(operation); // Calculate timings long thinkTime = generator.getThinkTime(); long now = System.currentTimeMillis(); // Wait after operation execution thinkTime = waitUntil(now, thinkTime); // Save the think time scoreboard.dropOffWaitTime(now, operation.getOperationName(), thinkTime); } private long waitUntil(long now, long deltaTime) throws InterruptedException { long wakeUpTime = now + deltaTime; if (wakeUpTime > timing.endRun) { if (now < timing.start) { deltaTime = timing.startSteadyState - now; sleepUntil(timing.startSteadyState); } else { deltaTime = timing.endRun - now; sleepUntil(timing.endRun); } } else { sleepUntil(wakeUpTime); } return deltaTime; } private void sleepUntil(long time) throws InterruptedException { long preRunSleep = time - System.currentTimeMillis(); if (preRunSleep > 0) Thread.sleep(preRunSleep); } public void setOpenLoopProbability(double openLoopProbability) { this.openLoopProbability = openLoopProbability; } @Override public void setScoreboard(IScoreboard scoreboard) { this.scoreboard = scoreboard; } @Override public void setGenerator(Generator generator) { this.generator = generator; } }
package com.plugin.gcm; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.util.Log; import com.google.android.gcm.GCMBaseIntentService; @SuppressLint("NewApi") public class GCMIntentService extends GCMBaseIntentService { private static final String TAG = "GCMIntentService"; public GCMIntentService() { super("GCMIntentService"); } @Override public void onRegistered(Context context, String regId) { Log.v(TAG, "onRegistered: "+ regId); JSONObject json; try { json = new JSONObject().put("event", "registered"); json.put("regid", regId); Log.v(TAG, "onRegistered: " + json.toString()); // Send this JSON data to the JavaScript application above EVENT should be set to the msg type // In this case this is the registration ID PushPlugin.sendJavascript( json ); } catch( JSONException e) { // No message to the user is sent, JSON failed Log.e(TAG, "onRegistered: JSON exception"); } } @Override public void onUnregistered(Context context, String regId) { Log.d(TAG, "onUnregistered - regId: " + regId); } @Override protected void onMessage(Context context, Intent intent) { Log.d(TAG, "onMessage - context: " + context); // Extract the payload from the message Bundle extras = intent.getExtras(); if (extras != null) { // if we are in the foreground, just surface the payload, else post it to the statusbar if (PushPlugin.isInForeground()) { extras.putBoolean("foreground", true); PushPlugin.sendExtras(extras); } else { extras.putBoolean("foreground", false); // Send a notification if there is a message if (extras.getString("message") != null && extras.getString("message").length() != 0) { createNotification(context, extras); } } } } public void createNotification(Context context, Bundle extras) { NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); String appName = getAppName(this); Intent notificationIntent = new Intent(this, PushHandlerActivity.class); notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); notificationIntent.putExtra("pushBundle", extras); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); int defaults = Notification.DEFAULT_ALL; if (extras.getString("defaults") != null) { try { defaults = Integer.parseInt(extras.getString("defaults")); } catch (NumberFormatException e) {} } NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) .setDefaults(defaults) .setSmallIcon(context.getApplicationInfo().icon) .setGroup(extras.getString("group")) .setWhen(System.currentTimeMillis()) .setContentTitle(extras.getString("title")) .setTicker(extras.getString("title")) .setContentIntent(contentIntent) .setAutoCancel(true); String message = extras.getString("message"); if (message != null) { mBuilder.setContentText(message); } else { mBuilder.setContentText("<missing message content>"); } String msgcnt = extras.getString("msgcnt"); if (msgcnt != null) { mBuilder.setNumber(Integer.parseInt(msgcnt)); } int notId = 0; try { notId = Integer.parseInt(extras.getString("notId")); } catch(NumberFormatException e) { Log.e(TAG, "Number format exception - Error parsing Notification ID: " + e.getMessage()); } catch(Exception e) { Log.e(TAG, "Number format exception - Error parsing Notification ID" + e.getMessage()); } mNotificationManager.notify((String) appName, notId, mBuilder.build()); } private static String getAppName(Context context) { CharSequence appName = context .getPackageManager() .getApplicationLabel(context.getApplicationInfo()); return (String)appName; } @Override public void onError(Context context, String errorId) { Log.e(TAG, "onError - errorId: " + errorId); } }
package com.plugin.gcm; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; /*import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.Icon;*/ import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.util.Log; import java.util.Random; /*import java.io.InputStream;*/ import com.google.android.gcm.GCMBaseIntentService; @SuppressLint("NewApi") public class GCMIntentService extends GCMBaseIntentService { private static final String TAG = "GCMIntentService"; public GCMIntentService() { super("GCMIntentService"); } @Override public void onRegistered(Context context, String regId) { Log.v(TAG, "onRegistered: "+ regId); JSONObject json; try { json = new JSONObject().put("event", "registered"); json.put("regid", regId); Log.v(TAG, "onRegistered: " + json.toString()); // Send this JSON data to the JavaScript application above EVENT should be set to the msg type // In this case this is the registration ID PushPlugin.sendJavascript( json ); } catch( JSONException e) { // No message to the user is sent, JSON failed Log.e(TAG, "onRegistered: JSON exception"); } } @Override public void onUnregistered(Context context, String regId) { Log.d(TAG, "onUnregistered - regId: " + regId); } @Override protected void onMessage(Context context, Intent intent) { Log.d(TAG, "onMessage - context: " + context); // Extract the payload from the message Bundle extras = intent.getExtras(); if (extras != null) { // if we are in the foreground, just surface the payload, else post it to the statusbar if (PushPlugin.isInForeground()) { Log.d(TAG, "onMessage - pushing extras because we're in the foreground"); extras.putBoolean("foreground", true); PushPlugin.sendExtras(extras); } else { extras.putBoolean("foreground", false); // Send a notification if there is a message if (extras.getString("message") != null && extras.getString("message").length() != 0) { Log.d(TAG, "onMessage - create notification because we're in the background"); createNotification(context, extras); //PushPlugin.sendExtras(extras); uncomment for the ecb to fire even if the app is not in foreground } } } } public void createNotification(Context context, Bundle extras) { NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); String appName = getAppName(this); Intent notificationIntent = new Intent(this, PushHandlerActivity.class); notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); notificationIntent.putExtra("pushBundle", extras); int requestCode = new Random().nextInt(); PendingIntent contentIntent = PendingIntent.getActivity(this, requestCode, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); //PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); int defaults = Notification.DEFAULT_ALL; if (extras.getString("defaults") != null) { try { defaults = Integer.parseInt(extras.getString("defaults")); } catch (NumberFormatException e) {} } /*Bitmap iconBitMap = GCMIntentService.getBitmapFromAsset(context, "www/res/icon/android/drawable/small_icon.png"); Icon icon = Icon.createWithBitmap(iconBitMap);*/ NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) .setDefaults(defaults) /*.setSmallIcon(context.getApplicationInfo().icon)*/ .setSmallIcon(context.getResources().getIdentifier("secondary_icon", "drawable", context.getPackageName())) /*.setSmallIcon(icon)*/ .setWhen(System.currentTimeMillis()) .setContentTitle(extras.getString("title")) .setTicker(extras.getString("title")) .setContentIntent(contentIntent) .setAutoCancel(true); String message = extras.getString("message"); if (message != null) { mBuilder.setContentText(message); } else { mBuilder.setContentText("<missing message content>"); } String msgcnt = extras.getString("msgcnt"); if (msgcnt != null) { mBuilder.setNumber(Integer.parseInt(msgcnt)); } int notId = 0; try { notId = Integer.parseInt(extras.getString("notId")); } catch(NumberFormatException e) { Log.e(TAG, "Number format exception - Error parsing Notification ID: " + e.getMessage()); } catch(Exception e) { Log.e(TAG, "Number format exception - Error parsing Notification ID" + e.getMessage()); } mNotificationManager.notify((String) appName, notId, mBuilder.build()); } private static String getAppName(Context context) { CharSequence appName = context .getPackageManager() .getApplicationLabel(context.getApplicationInfo()); return (String)appName; } @Override public void onError(Context context, String errorId) { Log.e(TAG, "onError - errorId: " + errorId); } /* public static Bitmap getBitmapFromAsset(Context context, String filePath) { AssetManager assetManager = context.getAssets(); InputStream istr; Bitmap bitmap = null; try { istr = assetManager.open(filePath); bitmap = BitmapFactory.decodeStream(istr); } catch (IOException e) { // handle exception Log.e(TAG, "Failed to get bitmap using filePath: " + filePath); } return bitmap; }*/ }
package com.cisco.matday.ucsd.hp3par.reports.summary; import com.cisco.matday.ucsd.hp3par.account.HP3ParCredentials; import com.cisco.matday.ucsd.hp3par.account.inventory.HP3ParInventory; import com.cisco.matday.ucsd.hp3par.rest.system.json.SystemResponse; import com.cloupia.model.cIM.ReportContext; import com.cloupia.model.cIM.TabularReport; import com.cloupia.service.cIM.inframgr.TabularReportGeneratorIf; import com.cloupia.service.cIM.inframgr.reportengine.ReportRegistryEntry; import com.cloupia.service.cIM.inframgr.reports.SummaryReportInternalModel; /** * Implemenation of Overview table report * * @author Matt Day * */ public class OverviewTableImpl implements TabularReportGeneratorIf { private static final String SYS_INFO_TABLE = "Overview"; private static final String[] GROUP_ORDER = { SYS_INFO_TABLE }; private static String getAccountName(ReportContext context) { String contextId = context.getId(); String accountName = null; if (contextId != null) { // As the contextId returns as: "account Name;POD Name" accountName = contextId.split(";")[0]; } return accountName; } /** * This method returns implemented tabular report,and also perform cleanup * process and updating report. * * @param reportEntry * This parameter contains Object of ReportRegistryEntry class * which is used to register newly created report * @param context * This parameter contains context of the report * @return report */ @Override public TabularReport getTabularReportReport(ReportRegistryEntry reportEntry, ReportContext context) throws Exception { TabularReport report = new TabularReport(); report.setContext(context); report.setGeneratedTime(System.currentTimeMillis()); report.setReportName(reportEntry.getReportLabel()); SummaryReportInternalModel model = new SummaryReportInternalModel(); HP3ParCredentials credentials = new HP3ParCredentials(context); final SystemResponse systemInfo = HP3ParInventory.getSystemResponse(credentials); // Build the table model.addText("Account Name", getAccountName(context), SYS_INFO_TABLE); model.addText("IP Address", systemInfo.getIPv4Addr(), SYS_INFO_TABLE); model.addText("System Name", systemInfo.getName(), SYS_INFO_TABLE); model.addText("Version", systemInfo.getSystemVersion(), SYS_INFO_TABLE); model.addText("Serial Number", systemInfo.getSerialNumber(), SYS_INFO_TABLE); model.addText("Total Nodes", Short.toString(systemInfo.getTotalNodes()), SYS_INFO_TABLE); model.addText("Total Capacity (GiB)", Double.toString(systemInfo.getTotalCapacityMiB() / 1024d), SYS_INFO_TABLE); model.addText("Free Capacity (GiB)", Double.toString(systemInfo.getFreeCapacityMiB() / 1024d), SYS_INFO_TABLE); // finally perform last clean up steps model.setGroupOrder(GROUP_ORDER); model.updateReport(report); return report; } }
package com.bit6.chatdemo; import com.intel.bit6.Bit6; import com.intel.bit6.Bit6Address; import com.intel.bit6.Bit6CallController; import com.intel.bit6.Bit6CallViewController; import com.intel.bit6.Bit6Conversation; import com.intel.bit6.Bit6FileDownloader; import com.intel.bit6.Bit6Group; import com.intel.bit6.Bit6GroupMember; import com.intel.bit6.Bit6Message; import com.intel.bit6.Bit6OutgoingMessage; import com.intel.bit6.enums.Bit6CallStreams; import com.intel.bit6.enums.Bit6MessageCallChannel; import com.intel.bit6.enums.Bit6MessageCallStatus; import com.intel.bit6.enums.Bit6MessageFileType; import com.intel.bit6.enums.Bit6MessageStatus; import com.intel.bit6.enums.Bit6MessageType; import com.intel.moe.natj.general.NatJ; import com.intel.moe.natj.general.Pointer; import com.intel.moe.natj.general.ann.Generated; import com.intel.moe.natj.general.ann.Mapped; import com.intel.moe.natj.general.ann.NInt; import com.intel.moe.natj.general.ann.Owned; import com.intel.moe.natj.general.ann.RegisterOnStartup; import com.intel.moe.natj.general.ann.Runtime; import com.intel.moe.natj.objc.ObjCRuntime; import com.intel.moe.natj.objc.SEL; import com.intel.moe.natj.objc.ann.ObjCClassBinding; import com.intel.moe.natj.objc.ann.ObjCClassName; import com.intel.moe.natj.objc.ann.Property; import com.intel.moe.natj.objc.ann.Selector; import com.intel.moe.natj.objc.map.ObjCObjectMapper; import ios.coregraphics.struct.CGPoint; import ios.foundation.NSArray; import ios.foundation.NSBundle; import ios.foundation.NSCoder; import ios.foundation.NSData; import ios.foundation.NSDictionary; import ios.foundation.NSError; import ios.foundation.NSIndexPath; import ios.foundation.NSMutableArray; import ios.foundation.NSNotification; import ios.foundation.NSNotificationCenter; import ios.foundation.NSString; import ios.foundation.enums.NSComparisonResult; import ios.uikit.*; import ios.uikit.enums.UIAlertActionStyle; import ios.uikit.enums.UIAlertControllerStyle; import ios.uikit.enums.UIBarButtonItemStyle; import ios.uikit.enums.UIButtonType; import ios.uikit.enums.UIControlEvents; import ios.uikit.enums.UITableViewRowAnimation; import ios.uikit.enums.UITableViewScrollPosition; import com.intel.bit6.Bit6; import static com.bit6.chatdemo.Constants.*; import static ios.uikit.enums.UIAlertActionStyle.Cancel; import static ios.uikit.enums.UIAlertActionStyle.Default; import static ios.uikit.enums.UIAlertControllerStyle.ActionSheet; import static ios.uikit.enums.UIAlertControllerStyle.Alert; import static ios.uikit.enums.UIBarButtonItemStyle.Plain; import static ios.uikit.enums.UIBarButtonSystemItem.Add; @Generated @Runtime(ObjCRuntime.class) @ObjCClassName("ChatsTableViewController") @RegisterOnStartup public class ChatsTableViewController extends UITableViewController { static { NatJ.register(); } @Generated protected ChatsTableViewController(Pointer peer) { super(peer); } @Generated @Owned @Selector("alloc") public static native ChatsTableViewController alloc(); @Generated @Selector("init") public native ChatsTableViewController init(); @Generated @Selector("initWithCoder:") public native ChatsTableViewController initWithCoder(NSCoder aDecoder); @Generated @Selector("initWithNibName:bundle:") public native ChatsTableViewController initWithNibNameBundle(String nibNameOrNil, NSBundle nibBundleOrNil); @Generated @Selector("initWithStyle:") public native ChatsTableViewController initWithStyle(@NInt long style); UIBarButtonItem callItem = null; @Selector("viewDidLoad") public void viewDidLoad() { navigationItem().setPrompt("Logged as " + Bit6.session().activeIdentity().uri()); callItem = UIBarButtonItem.alloc().initWithImageStyleTargetAction(UIImage.imageNamed("bit6ui_phone"), UIBarButtonItemStyle.Plain, this, new SEL("call")); navigationItem().setRightBarButtonItem(callItem); if (_conversation.typingAddress() != null) { typingBarButtonItem().setTitle(_conversation.address().uri() + " is typing..."); } else { typingBarButtonItem().setTitle(""); } } private boolean scroll = false; @Selector("viewWillAppear:") public void viewWillAppear(boolean animated) { super.viewWillAppear(animated); navigationController().setToolbarHiddenAnimated(false, true); if (!scroll) { scroll = true; tableView().reloadData(); tableView().setContentOffsetAnimated(new CGPoint(0,1000000),false); } } @Selector("dealloc") public void dealloc() { Bit6.setCurrentConversation(null); NSNotificationCenter.defaultCenter().removeObserver(this); Bit6.setCurrentConversation(null); } @Selector("tableView:numberOfRowsInSection:") @NInt public long tableViewNumberOfRowsInSection(UITableView tableView,@NInt long section){ return getMessages().size(); } @Selector("tableView:cellForRowAtIndexPath:") public UITableViewCell tableViewCellForRowAtIndexPath(UITableView tableView, NSIndexPath indexPath) { Bit6Message message = getMessages().get((int)indexPath.row()); return tableView.dequeueReusableCellWithIdentifier(message.incoming() ? "textInCell" : "textOutCell"); } @Selector("tableView:willDisplayCell:forRowAtIndexPath:") public void tableViewWillDisplayCellForRowAtIndexPath(UITableView tableView, UITableViewCell cell, NSIndexPath indexPath) { Bit6Message message = getMessages().get((int) indexPath.row()); UILabel textLabel = (UILabel)cell.viewWithTag(1); textLabel.setText(ChatsTableViewController.textContentForMessage(message)); UILabel detailTextLabel = (UILabel)cell.viewWithTag(2); if (detailTextLabel != null) { if (message.type() == Bit6MessageType.Call) { detailTextLabel.setText(""); } else { switch ((int)message.status()) { case (int)Bit6MessageStatus.New : detailTextLabel.setText(""); break; case (int)Bit6MessageStatus.Sending : detailTextLabel.setText("Sending"); break; case (int)Bit6MessageStatus.Sent : detailTextLabel.setText("Sent"); break; case (int)Bit6MessageStatus.Failed : detailTextLabel.setText("Failed"); break; case (int)Bit6MessageStatus.Delivered : detailTextLabel.setText("Delivered"); break; case (int)Bit6MessageStatus.Read : detailTextLabel.setText("Read"); break; } } } } @Selector("call") public void call() { UIAlertController alert = UIAlertController.alertControllerWithTitleMessagePreferredStyle(null, null, ActionSheet); alert.addAction(UIAlertAction.actionWithTitleStyleHandler("Audio", Default, new UIAlertAction.Block_actionWithTitleStyleHandler() { public void call_actionWithTitleStyleHandler(UIAlertAction var1) { Bit6.startCallToStreams(_conversation.address(), Bit6CallStreams.Audio); } }) ); alert.addAction(UIAlertAction.actionWithTitleStyleHandler("Video", Default, new UIAlertAction.Block_actionWithTitleStyleHandler() { public void call_actionWithTitleStyleHandler(UIAlertAction var1) { Bit6.startCallToStreams(_conversation.address(),Bit6CallStreams.Audio|Bit6CallStreams.Video); }}) ); alert.addAction(UIAlertAction.actionWithTitleStyleHandler("Cancel", Cancel, null)); UIPopoverPresentationController popover = alert.popoverPresentationController(); if (popover != null) { popover.setBarButtonItem(callItem); } navigationController().presentViewControllerAnimatedCompletion(alert, true, null); } @Selector("touchedComposeButton:") private void touchedComposeButton(UIBarButtonItem button) { if (!canChat()) { UIAlertController errorAlert = UIAlertController.alertControllerWithTitleMessagePreferredStyle("You have left this group", null, UIAlertControllerStyle.Alert); errorAlert.addAction(UIAlertAction.actionWithTitleStyleHandler("OK", UIAlertActionStyle.Cancel, null)); navigationController().presentViewControllerAnimatedCompletion(errorAlert,true,null); return; } final UIAlertController alert = UIAlertController.alertControllerWithTitleMessagePreferredStyle("Type the message", null, Alert); alert.addTextFieldWithConfigurationHandler(null); alert.addAction(UIAlertAction.actionWithTitleStyleHandler("Send", Default, new UIAlertAction.Block_actionWithTitleStyleHandler() { public void call_actionWithTitleStyleHandler(UIAlertAction var1) { UITextField input = alert.textFields().get(0); String text = input.text(); if (text.length() > 0) { Bit6OutgoingMessage message = Bit6OutgoingMessage.alloc().initWithDestination(_conversation.address()); message.setContent(text); message.sendWithCompletionHandler(new Bit6OutgoingMessage.Block_sendWithCompletionHandler() { public void call_sendWithCompletionHandler(NSDictionary<?, ?> response, NSError error) { if (error != null) { UIAlertController errorAlert = UIAlertController.alertControllerWithTitleMessagePreferredStyle("Error", error.localizedDescription(), UIAlertControllerStyle.Alert); errorAlert.addAction(UIAlertAction.actionWithTitleStyleHandler("OK", UIAlertActionStyle.Cancel, null)); navigationController().presentViewControllerAnimatedCompletion(errorAlert, true, null); } else { System.out.println("Message Sent"); } } }); } } })); alert.addAction(UIAlertAction.actionWithTitleStyleHandler("Cancel", UIAlertActionStyle.Cancel, null)); navigationController().presentViewControllerAnimatedCompletion(alert, true, null); } @Selector("typingBeginNotification:") public void typingBeginNotification(NSNotification notification) { Bit6Address fromAddress = (Bit6Address)notification.userInfo().get(Bit6FromKey); Bit6Address convervationAddress = (Bit6Address)notification.object(); if (convervationAddress.isEqual(_conversation.address())) { typingBarButtonItem().setTitle(fromAddress.uri() + " is typing..."); } } @Selector("typingEndNotification:") public void typingEndNotification(NSNotification notification) { Bit6Address convervationAddress = (Bit6Address)notification.object(); if (convervationAddress.isEqual(_conversation.address())) { typingBarButtonItem().setTitle(""); } } @Selector("groupsChangedNotification:") private void groupsChangedNotification(NSNotification notification) { Bit6Group object = (Bit6Group)notification.userInfo().get(Bit6ObjectKey); String change = (String) notification.userInfo().get(Bit6ChangeKey); if (change.equals(Bit6UpdatedKey) && object.address().isEqual(_conversation.address())) { setTitle(ConversationsViewController.titleForConversation(_conversation)); } } @Selector("messagesChangedNotification:") private void messagesChangedNotification(NSNotification notification) { Bit6Message object = (Bit6Message) notification.userInfo().get(Bit6ObjectKey); String change = (String) notification.userInfo().get(Bit6ChangeKey); if (change.equals(Bit6AddedKey)) { NSIndexPath indexPath = NSIndexPath.indexPathForRowInSection(getMessages().size(),0); getMessages().add(object); NSArray<NSIndexPath> indexes = (NSArray<NSIndexPath>)NSArray.arrayWithObject(indexPath); tableView().insertRowsAtIndexPathsWithRowAnimation(indexes, UITableViewRowAnimation.Automatic); scrollToBottomAnimated(true); } else if (change.equals(Bit6UpdatedKey)) { NSIndexPath indexPath = findMessageIndex(object); if (indexPath != null) { UITableViewCell cell = tableView().cellForRowAtIndexPath(indexPath); if (cell != null) { tableViewWillDisplayCellForRowAtIndexPath(tableView(),cell,indexPath); } } } else if (change.equals(Bit6DeletedKey)) { NSIndexPath indexPath = findMessageIndex(object); if (indexPath != null) { getMessages().removeObjectAtIndex(indexPath.row()); NSArray<NSIndexPath> indexes = (NSArray<NSIndexPath>)NSArray.arrayWithObject(indexPath); tableView().deleteRowsAtIndexPathsWithRowAnimation(indexes, UITableViewRowAnimation.Automatic); } } } private NSIndexPath findMessageIndex(Bit6Message msg) { for (int x=getMessages().size()-1 ; x>=0 ; x if (getMessages().get(x).isEqual(msg)) { return NSIndexPath.indexPathForRowInSection(x, 0); } } return null; } private Bit6Conversation _conversation; public void setConversation(Bit6Conversation conv) { _conversation = conv; Bit6.setCurrentConversation(conv); NSNotificationCenter.defaultCenter().addObserverSelectorNameObject(this, new SEL("messagesChangedNotification:"), Bit6MessagesChangedNotification, conv); NSNotificationCenter.defaultCenter().addObserverSelectorNameObject(this, new SEL("typingBeginNotification:"), Bit6TypingDidBeginRtNotification, null); NSNotificationCenter.defaultCenter().addObserverSelectorNameObject(this, new SEL("typingEndNotification:"), Bit6TypingDidEndRtNotification, null); if (conv.address().isGroup()) { NSNotificationCenter.defaultCenter().addObserverSelectorNameObject(this, new SEL("groupsChangedNotification:"), Bit6GroupsChangedNotification, null); } } //creating the local messages array private NSMutableArray<Bit6Message> _messages; private NSMutableArray<Bit6Message> getMessages() { if (_messages == null && _conversation != null) { _messages = (NSMutableArray<Bit6Message>) NSMutableArray.arrayWithArray(_conversation.messages()); } return _messages; } private void scrollToBottomAnimated(boolean animated) { int size = getMessages().size(); if (size>0) { long section = 0; long lastRow = size - 1; NSIndexPath scrollIndexPath = NSIndexPath.indexPathForRowInSection(lastRow, 0); tableView().scrollToRowAtIndexPathAtScrollPositionAnimated(scrollIndexPath, UITableViewScrollPosition.Bottom,animated); } } //if the user has left the group we disable the chats private boolean canChat() { if (_conversation.address().isGroup()) { Bit6Group group = Bit6Group.groupWithAddress(_conversation.address()); return !group.hasLeft(); } return true; } //we get a nice string to show for text messages and calls private static String textContentForMessage(Bit6Message message) { if (message.type() == Bit6MessageType.Call) { boolean showDuration = false; String status = ""; switch ((int)message.callStatus()) { case (int)Bit6MessageCallStatus.Answer: status = "Answer"; showDuration = true; break; case (int)Bit6MessageCallStatus.Missed: status = "Missed"; break; case (int)Bit6MessageCallStatus.Failed: status = "Failed"; break; case (int)Bit6MessageCallStatus.NoAnswer: status = "No Answer"; break; } NSMutableArray channels = NSMutableArray.arrayWithCapacity(3); if (message.callHasChannel(Bit6MessageCallChannel.Audio)){ channels.addObject("Audio"); } if (message.callHasChannel(Bit6MessageCallChannel.Video)){ channels.addObject("Video"); } if (message.callHasChannel(Bit6MessageCallChannel.Data)){ channels.addObject("Data"); } String channel = channels.componentsJoinedByString(" + "); if (showDuration) { return String.format("%s Call - %ss",channel, message.callDuration().description()); } else { return String.format("%s Call (%s)",channel, status); } } else if (message.type() == Bit6MessageType.Location) { return "Location"; } else if (message.type() == Bit6MessageType.Attachments) { return "Attachment"; } else { return message.content(); } } @Generated @Selector("setTypingBarButtonItem:") public native void setTypingBarButtonItem_unsafe(UIBarButtonItem value); @Generated public void setTypingBarButtonItem(UIBarButtonItem value) { Object __old = typingBarButtonItem(); if (value != null) { com.intel.moe.natj.objc.ObjCRuntime.associateObjCObject(this, value); } setTypingBarButtonItem_unsafe(value); if (__old != null) { com.intel.moe.natj.objc.ObjCRuntime.dissociateObjCObject(this, __old); } } @Generated @Selector("typingBarButtonItem") @Property public native UIBarButtonItem typingBarButtonItem(); }
package news.caughtup.caughtup.ui.prime; import android.app.AlertDialog; import android.app.Fragment; import android.content.CursorLoader; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; import io.fabric.sdk.android.services.network.HttpRequest; import news.caughtup.caughtup.R; import news.caughtup.caughtup.entities.ResponseObject; import news.caughtup.caughtup.entities.User; import news.caughtup.caughtup.ws.remote.Callback; import news.caughtup.caughtup.ws.remote.RestProxy; public class EditProfileFragment extends Fragment { private static final int REQUEST_CAMERA = 1; private static final int SELECT_FILE = 2; private User user; private ImageView profilePicView; private TextView userNameView; private Spinner genderSpinner; private EditText ageView; private EditText fullNameView; private EditText emailView; private EditText locationView; private EditText aboutMeView; private View rootView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment rootView = inflater.inflate(R.layout.fragment_edit_profile, container, false); user = HomeActivity.getCurrentUser(); System.out.println("Email: " + user.getEmail()); System.out.println("Full Name: " + user.getFullName()); //get references to views region profilePicView = (ImageView) rootView.findViewById(R.id.edit_profile_photo_image_view); userNameView = (TextView) rootView.findViewById(R.id.edit_profile_username_text_view); genderSpinner = (Spinner) rootView.findViewById(R.id.edit_profile_gender_edit_text); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.gender_array, android.R.layout.simple_spinner_item); // Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner genderSpinner.setAdapter(adapter); ageView = (EditText) rootView.findViewById(R.id.edit_profile_age_edit_text); fullNameView = (EditText) rootView.findViewById(R.id.edit_profile_full_name_edit_text); emailView = (EditText) rootView.findViewById(R.id.edit_profile_email_edit_text); locationView = (EditText) rootView.findViewById(R.id.edit_profile_location_edit_text); aboutMeView = (EditText) rootView.findViewById(R.id.edit_profile_about_me_edit_text); //end region setUpCurrentUserInfo(); RelativeLayout editProfilePicture = (RelativeLayout) rootView.findViewById(R.id.edit_profile_picture_relative_layout); editProfilePicture.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { selectPhoto(); return false; } }); //region setup button listeners Button changePasswordButton = (Button) rootView.findViewById(R.id.edit_profile_change_password_button); changePasswordButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ChangePasswordFragment changePasswordFragment = new ChangePasswordFragment(); HomeActivity.executeTransaction(changePasswordFragment, "change_password", R.string.change_password_title); } }); Button saveChangesButton = (Button) rootView.findViewById(R.id.edit_profile_save_button); saveChangesButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { RestProxy proxy = RestProxy.getProxy(); Callback callback = getUpdatedUserCallback(); JSONObject jsonObject = createJSON(); Log.e("JSON Object", jsonObject.toString()); if (!validateEmail(emailView.getText().toString())) { Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.invalid_email_address), Toast.LENGTH_SHORT) .show(); } else { proxy.putCall(String.format("/profile/%s?picture=false", user.getName()), jsonObject.toString(), callback); } } }); //end region return rootView; } private void setUpCurrentUserInfo() { // Profile Picture int imageResourceId = user.getProfileImageId(); if(imageResourceId > 0) { profilePicView.setImageDrawable(getActivity().getResources().getDrawable(imageResourceId, null)); } else { profilePicView.setImageDrawable(getActivity().getResources().getDrawable(R.mipmap.profile_pic_2, null)); } // Username userNameView.setText(user.getName()); // Gender String gender = user.getGender(); if(gender != null && !gender.isEmpty()) { switch (gender.toLowerCase()) { case "male": genderSpinner.setSelection(1); break; case "female": genderSpinner.setSelection(2); break; default: genderSpinner.setSelection(0); break; } } // Age int age = user.getAge(); if(age > 1) { ageView.setText(String.format("%d", age)); } // Full Name String fullName = user.getFullName(); if(fullName != null && !fullName.isEmpty()) { fullNameView.setText(user.getFullName()); } // Email String email = user.getEmail(); if(email != null && !email.isEmpty()) { emailView.setText(email); } // Location String location = user.getLocation(); if(location != null && !location.isEmpty()) { locationView.setText(location); } // About me String aboutMe = user.getAboutMe(); if(aboutMe != null && !aboutMe.isEmpty()) { aboutMeView.setText(aboutMe); } } private Callback getUpdatedUserCallback() { return new Callback() { @Override public void process(ResponseObject responseObject) { if (responseObject.getResponseCode() == 200) { JSONObject jsonObject = responseObject.getJsonObject(); try { if (jsonObject.getString("message").equals("Success")) { updateUser(); } else { Toast.makeText(getActivity().getApplicationContext(), getActivity().getResources().getString(R.string.update_user_server_error), Toast.LENGTH_LONG).show(); } } catch (JSONException e) { e.printStackTrace(); } } else { Toast.makeText(getActivity().getApplicationContext(), getActivity().getResources().getString(R.string.update_user_server_error), Toast.LENGTH_LONG).show(); } } }; } private void updateUser() { // Gender String gender = genderSpinner.getSelectedItem().toString(); if(gender != null && !gender.isEmpty()) { user.setGender(gender); } // Age int age = Integer.parseInt(ageView.getText().toString()); if (age > 1) { user.setAge(age); } // Full Name String fullName = fullNameView.getText().toString(); if(fullName != null && !fullName.isEmpty()) { user.setFullName(fullName); } // Email String email = emailView.getText().toString(); if(email != null && !email.isEmpty()) { user.setEmail(email); } // Location String location = locationView.getText().toString(); if(location != null && !location.isEmpty()) { user.setLocation(location); } // About me String aboutMe = aboutMeView.getText().toString(); if(aboutMe != null && !aboutMe.isEmpty()) { user.setAboutMe(aboutMe); } } private JSONObject createJSON() { JSONObject jsonObject = new JSONObject(); // Gender try { String gender = genderSpinner.getSelectedItem().toString(); if(gender != null && !gender.isEmpty()) { jsonObject.put("gender", gender); } // Age int age = Integer.parseInt(ageView.getText().toString()); if (age > 1) { jsonObject.put("age", age); } // Full Name String fullName = fullNameView.getText().toString(); if(fullName != null && !fullName.isEmpty()) { jsonObject.put("fullName", fullName); } // Email String email = emailView.getText().toString(); if(email != null && !email.isEmpty()) { jsonObject.put("email", email); } // Location String location = locationView.getText().toString(); if(location != null && !location.isEmpty()) { jsonObject.put("location", location); } // About me String aboutMe = aboutMeView.getText().toString(); if(aboutMe != null && !aboutMe.isEmpty()) { jsonObject.put("aboutMe", aboutMe); } return jsonObject; } catch (JSONException e) { Log.e("JSONException", "Couldn't create JSON with updated user"); return null; } } /** * Validate an input string as an email * @param email * @return */ private boolean validateEmail(String email) { Pattern p = Pattern.compile(".+@.+\\.[a-z]+"); Matcher m = p.matcher(email); return m.matches(); } private void selectPhoto() { final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" }; AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Add Photo!"); builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int item) { if (items[item].equals("Take Photo")) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, REQUEST_CAMERA); } else if (items[item].equals("Choose from Library")) { Intent intent = new Intent( Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
package de.dominikschadow.sqli.stmt; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import org.owasp.esapi.ESAPI; import org.owasp.esapi.codecs.OracleCodec; import de.dominikschadow.sqli.domain.Customer; public class CharacterEscaping { public static void main(String[] args) { CharacterEscaping sample = new CharacterEscaping(); // normal sample for customer "Maier" List<Customer> customers = sample.findCustomer("Maier"); sample.printCustomer(customers); // failing SQL injection sample with "' OR '1' = '1" customers = sample.findCustomer("' OR '1' = '1"); sample.printCustomer(customers); } private List<Customer> findCustomer(String custName) { String safeCustName = ESAPI.encoder().encodeForSQL(new OracleCodec(), custName); String query = "SELECT * FROM customer WHERE name = '" + safeCustName + "'"; List<Customer> customers = new ArrayList<Customer>(); System.out.println("Query " + query); try { Class.forName("org.hsqldb.jdbcDriver"); } catch (ClassNotFoundException e) { e.printStackTrace(); return customers; } Connection con = null; Statement stmt = null; try { con = DriverManager.getConnection("jdbc:hsqldb:file:src/main/resources/customerDB; shutdown=true", "sa", ""); stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { Customer customer = new Customer(); customer.setCustId(rs.getInt(1)); customer.setName(rs.getString(2)); customer.setStatus(rs.getString(3)); customer.setOrderLimit(rs.getInt(4)); customers.add(customer); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (stmt != null) { stmt.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if (con != null) { con.close(); } } catch (SQLException e) { e.printStackTrace(); } } return customers; } private void printCustomer(List<Customer> customers) { System.out.println("Customer data:"); for (Customer customer : customers) { System.out.println(customer.toString()); } } }
package com.elmakers.mine.bukkit.utility; import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.attribute.Attribute; import org.bukkit.block.Skull; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.logging.Level; import com.google.common.collect.Multimap; public class InventoryUtils extends NMSUtils { public static int MAX_LORE_LENGTH = 24; public static int MAX_PROPERTY_DISPLAY_LENGTH = 50; public static boolean saveTagsToItem(ConfigurationSection tags, ItemStack item) { Object handle = getHandle(item); if (handle == null) return false; Object tag = getTag(handle); if (tag == null) return false; return addTagsToNBT(getMap(tags), tag); } public static boolean saveTagsToItem(Map<String, Object> tags, ItemStack item) { Object handle = getHandle(item); if (handle == null) return false; Object tag = getTag(handle); if (tag == null) return false; return addTagsToNBT(tags, tag); } public static boolean configureSkillItem(ItemStack skillItem, String skillClass, ConfigurationSection skillConfig) { if (skillItem == null) return false; Object handle = getHandle(skillItem); if (handle == null) return false; Object tag = getTag(handle); if (tag == null) return false; setMetaBoolean(tag, "skill", true); Object spellNode = InventoryUtils.getNode(skillItem, "spell"); if (skillClass != null && spellNode != null) { InventoryUtils.setMeta(spellNode, "class", skillClass); } if (skillConfig == null) { return true; } if (skillConfig.getBoolean("undroppable", false)) { setMetaBoolean(tag, "undroppable", true); } if (skillConfig.getBoolean("keep", false)) { setMetaBoolean(tag, "keep", true); } boolean quickCast = skillConfig.getBoolean("quick_cast", true); if (!quickCast && spellNode != null) { InventoryUtils.setMetaBoolean(spellNode, "quick_cast", false); } return true; } public static boolean saveTagsToNBT(ConfigurationSection tags, Object node) { return saveTagsToNBT(tags, node, null); } public static boolean saveTagsToNBT(ConfigurationSection tags, Object node, Set<String> tagNames) { return saveTagsToNBT(getMap(tags), node, tagNames); } public static boolean addTagsToNBT(Map<String, Object> tags, Object node) { if (node == null) { Bukkit.getLogger().warning("Trying to save tags to a null node"); return false; } if (!class_NBTTagCompound.isAssignableFrom(node.getClass())) { Bukkit.getLogger().warning("Trying to save tags to a non-CompoundTag"); return false; } for (Map.Entry<String, Object> tag : tags.entrySet()) { Object value = tag.getValue(); try { Object wrappedTag = wrapInTag(value); if (wrappedTag == null) continue; class_NBTTagCompound_setMethod.invoke(node, tag.getKey(), wrappedTag); } catch (Exception ex) { org.bukkit.Bukkit.getLogger().log(Level.WARNING, "Error saving item data tag " + tag.getKey(), ex); } } return true; } public static boolean saveTagsToNBT(Map<String, Object> tags, Object node, Set<String> tagNames) { if (node == null) { Bukkit.getLogger().warning("Trying to save tags to a null node"); return false; } if (!class_NBTTagCompound.isAssignableFrom(node.getClass())) { Bukkit.getLogger().warning("Trying to save tags to a non-CompoundTag"); return false; } if (tagNames == null) { tagNames = tags.keySet(); } // Remove tags that were not included Set<String> currentTags = getTagKeys(node); if (currentTags != null && !tagNames.containsAll(currentTags)) { // Need to copy this, getKeys returns a live list and bad things can happen. currentTags = new HashSet<>(currentTags); } else { currentTags = null; } for (String tagName : tagNames) { if (currentTags != null) currentTags.remove(tagName); Object value = tags.get(tagName); try { Object wrappedTag = wrapInTag(value); if (wrappedTag == null) continue; class_NBTTagCompound_setMethod.invoke(node, tagName, wrappedTag); } catch (Exception ex) { org.bukkit.Bukkit.getLogger().log(Level.WARNING, "Error saving item data tag " + tagName, ex); } } // Finish removing any remaining properties if (currentTags != null) { for (String currentTag : currentTags) { removeMeta(node, currentTag); } } return true; } public static Object wrapInTag(Object value) throws IllegalAccessException, InvocationTargetException, InstantiationException { if (value == null) return null; Object wrappedValue = null; if (value instanceof Boolean) { wrappedValue = class_NBTTagByte_constructor.newInstance((byte)((boolean)value ? 1 : 0)); } else if (value instanceof Double) { wrappedValue = class_NBTTagDouble_constructor.newInstance((Double)value); } else if (value instanceof Float) { wrappedValue = class_NBTTagFloat_constructor.newInstance((Float)value); } else if (value instanceof Integer) { wrappedValue = class_NBTTagInt_constructor.newInstance((Integer)value); } else if (value instanceof Long) { wrappedValue = class_NBTTagLong_constructor.newInstance((Long)value); } else if (value instanceof ConfigurationSection) { wrappedValue = class_NBTTagCompound_constructor.newInstance(); saveTagsToNBT((ConfigurationSection)value, wrappedValue, null); } else if (value instanceof Map) { wrappedValue = class_NBTTagCompound_constructor.newInstance(); @SuppressWarnings("unchecked") Map<String, Object> valueMap = (Map<String, Object>)value; saveTagsToNBT(valueMap, wrappedValue, null); } else if (value instanceof Collection) { @SuppressWarnings("unchecked") Collection<Object> list = (Collection<Object>)value; Object listMeta = class_NBTTagList_constructor.newInstance(); for (Object item : list) { if (item != null) { addToList(listMeta, wrapInTag(item)); } } wrappedValue = listMeta; } else { wrappedValue = class_NBTTagString_consructor.newInstance(value.toString()); } return wrappedValue; } @SuppressWarnings("unchecked") public static Set<String> getTagKeys(Object tag) { if (tag == null || class_NBTTagCompound_getKeysMethod == null) { return null; } try { return (Set<String>) class_NBTTagCompound_getKeysMethod.invoke(tag); } catch (Exception ex) { ex.printStackTrace(); } return null; } public static Object getMetaObject(Object tag, String key) { try { Object metaBase = class_NBTTagCompound_getMethod.invoke(tag, key); return getTagValue(metaBase); } catch (Exception ex) { ex.printStackTrace(); } return null; } public static Object getTagValue(Object tag) throws IllegalAccessException, InvocationTargetException { if (tag == null) return null; Object value = null; if (class_NBTTagDouble.isAssignableFrom(tag.getClass())) { value = class_NBTTagDouble_dataField.get(tag); } else if (class_NBTTagInt.isAssignableFrom(tag.getClass())) { value = class_NBTTagInt_dataField.get(tag); } else if (class_NBTTagLong.isAssignableFrom(tag.getClass())) { value = class_NBTTagLong_dataField.get(tag); } else if (class_NBTTagFloat.isAssignableFrom(tag.getClass())) { value = class_NBTTagFloat_dataField.get(tag); } else if (class_NBTTagShort.isAssignableFrom(tag.getClass())) { value = class_NBTTagShort_dataField.get(tag); } else if (class_NBTTagByte.isAssignableFrom(tag.getClass())) { // This is kind of nasty. Really need a type-juggling container class for config properties. value = class_NBTTagByte_dataField.get(tag); if (value != null && value.equals((byte)0)) { value = false; } else if (value != null && value.equals((byte)1)) { value = true; } } else if (class_NBTTagList.isAssignableFrom(tag.getClass())) { List<?> items = (List<?>)class_NBTTagList_list.get(tag); List<Object> converted = new ArrayList<>(); for (Object baseTag : items) { Object convertedBase = getTagValue(baseTag); if (convertedBase != null) { converted.add(convertedBase); } } value = converted; } else if (class_NBTTagString.isAssignableFrom(tag.getClass())) { value = class_NBTTagString_dataField.get(tag); } else if (class_NBTTagCompound.isAssignableFrom(tag.getClass())) { Map<String, Object> compoundMap = new HashMap<>(); Set<String> keys = getTagKeys(tag); for (String key : keys) { Object baseTag = class_NBTTagCompound_getMethod.invoke(tag, key); Object convertedBase = getTagValue(baseTag); if (convertedBase != null) { compoundMap.put(key, convertedBase); } } value = compoundMap; } return value; } public static boolean inventorySetItem(Inventory inventory, int index, ItemStack item) { try { Method setItemMethod = class_CraftInventoryCustom.getMethod("setItem", Integer.TYPE, ItemStack.class); setItemMethod.invoke(inventory, index, item); return true; } catch(Throwable ex) { ex.printStackTrace(); } return false; } public static boolean setInventoryResults(Inventory inventory, ItemStack item) { try { Method getResultsMethod = inventory.getClass().getMethod("getResultInventory"); Object inv = getResultsMethod.invoke(inventory); Method setItemMethod = inv.getClass().getMethod("setItem", Integer.TYPE, class_ItemStack); setItemMethod.invoke(inv, 0, getHandle(item)); return true; } catch(Throwable ex) { ex.printStackTrace(); } return false; } public static ItemStack setSkullURL(ItemStack itemStack, String url) { try { return setSkullURL(itemStack, new URL(url), UUID.randomUUID()); } catch (MalformedURLException e) { Bukkit.getLogger().log(Level.WARNING, "Malformed URL: " + url, e); } return itemStack; } public static ItemStack setSkullURLAndName(ItemStack itemStack, URL url, String ownerName, UUID id) { try { itemStack = makeReal(itemStack); Object skullOwner = createNode(itemStack, "SkullOwner"); setMeta(skullOwner, "Name", ownerName); return setSkullURL(itemStack, url, id); } catch (Exception ex) { ex.printStackTrace(); } return itemStack; } public static ItemStack setSkullURL(ItemStack itemStack, URL url, UUID id) { // Old versions of Bukkit would NPE trying to save a skull without an owner name // So we'll use MHF_Question, why not. return setSkullURL(itemStack, url, id, "MHF_Question"); } public static ItemStack setSkullURL(ItemStack itemStack, URL url, UUID id, String name) { try { Object gameProfile = class_GameProfile_constructor.newInstance(id, name); Multimap<String, Object> properties = (Multimap<String, Object>)class_GameProfile_properties.get(gameProfile); if (properties == null) { return itemStack; } itemStack = makeReal(itemStack); String textureJSON = "{textures:{SKIN:{url:\"" + url + "\"}}}"; String encoded = Base64Coder.encodeString(textureJSON); properties.put("textures", class_GameProfileProperty_noSignatureConstructor.newInstance("textures", encoded)); ItemMeta skullMeta = itemStack.getItemMeta(); setSkullProfile(skullMeta, gameProfile); itemStack.setItemMeta(skullMeta); } catch (Exception ex) { ex.printStackTrace(); } return itemStack; } public static String getSkullURL(ItemStack skull) { return SkinUtils.getProfileURL(getSkullProfile(skull.getItemMeta())); } @Deprecated public static String getPlayerSkullURL(String playerName) { return SkinUtils.getOnlineSkinURL(playerName); } public static Object getSkullProfile(ItemMeta itemMeta) { Object profile = null; try { if (itemMeta == null || !class_CraftMetaSkull.isInstance(itemMeta)) return null; profile = class_CraftMetaSkull_profile.get(itemMeta); } catch (Exception ex) { } return profile; } public static boolean setSkullProfile(ItemMeta itemMeta, Object data) { try { if (itemMeta == null || !class_CraftMetaSkull.isInstance(itemMeta)) return false; class_CraftMetaSkull_profile.set(itemMeta, data); return true; } catch (Exception ex) { } return false; } public static Object getSkullProfile(Skull state) { Object profile = null; try { if (state == null || !class_CraftSkull.isInstance(state)) return false; profile = class_CraftSkull_profile.get(state); } catch (Exception ex) { } return profile; } public static boolean setSkullProfile(Skull state, Object data) { try { if (state == null || !class_CraftSkull.isInstance(state)) return false; class_CraftSkull_profile.set(state, data); return true; } catch (Exception ex) { } return false; } public static void wrapText(String text, Collection<String> list) { wrapText(text, MAX_LORE_LENGTH, list); } public static void wrapText(String text, String prefix, Collection<String> list) { wrapText(text, prefix, MAX_LORE_LENGTH, list); } public static void wrapText(String text, int maxLength, Collection<String> list) { wrapText(text, "", maxLength, list); } public static void wrapText(String text, String prefix, int maxLength, Collection<String> list) { String colorPrefix = ""; String[] lines = StringUtils.split(text, "\n\r"); for (String line : lines) { line = prefix + line; while (line.length() > maxLength) { int spaceIndex = line.lastIndexOf(' ', maxLength); if (spaceIndex <= 0) { list.add(colorPrefix + line); return; } String colorText = colorPrefix + line.substring(0, spaceIndex); colorPrefix = ChatColor.getLastColors(colorText); list.add(colorText); line = line.substring(spaceIndex); } list.add(colorPrefix + line); } } public static boolean hasItem(Inventory inventory, String itemName) { if (inventory == null) { return false; } ItemStack[] items = inventory.getContents(); for (ItemStack item : items) { if (item != null && item.hasItemMeta()) { String displayName = item.getItemMeta().getDisplayName(); if (displayName != null && displayName.equals(itemName)) { return true; } } } return false; } public static void openSign(Player player, Location signBlock) { try { Object tileEntity = getTileEntity(signBlock); Object playerHandle = getHandle(player); if (tileEntity != null && playerHandle != null) { class_EntityPlayer_openSignMethod.invoke(playerHandle, tileEntity); } } catch (Exception ex) { ex.printStackTrace(); } } public static void makeKeep(ItemStack itemStack) { setMetaBoolean(itemStack, "keep", true); } public static boolean isKeep(ItemStack itemStack) { return hasMeta(itemStack, "keep"); } public static void applyAttributes(ItemStack item, ConfigurationSection attributeConfig, String slot) { if (item == null || attributeConfig == null) return; Collection<String> attributeKeys = attributeConfig.getKeys(false); for (String attributeKey : attributeKeys) { try { Attribute attribute = Attribute.valueOf(attributeKey.toUpperCase()); double value = attributeConfig.getDouble(attributeKey); if (!CompatibilityUtils.setItemAttribute(item, attribute, value, slot)) { Bukkit.getLogger().warning("Failed to set attribute: " + attributeKey); } } catch (Exception ex) { Bukkit.getLogger().warning("Invalid attribute: " + attributeKey); } } } public static void applyEnchantments(ItemStack item, ConfigurationSection enchantConfig) { if (item == null || enchantConfig == null) return; Collection<String> enchantKeys = enchantConfig.getKeys(false); for (String enchantKey : enchantKeys) { try { Enchantment enchantment = Enchantment.getByName(enchantKey.toUpperCase()); item.addUnsafeEnchantment(enchantment, enchantConfig.getInt(enchantKey)); } catch (Exception ex) { Bukkit.getLogger().warning("Invalid enchantment: " + enchantKey); } } } public static String describeProperty(Object property) { return describeProperty(property, 0); } public static String describeProperty(Object property, int maxLength) { if (property == null) return "(Empty)"; String propertyString; if (property instanceof ConfigurationSection) { ConfigurationSection section = (ConfigurationSection)property; Set<String> keys = section.getKeys(false); StringBuilder full = new StringBuilder("{"); boolean first = true; for (String key : keys) { if (!first) { full.append(','); } first = false; full.append(key).append(':').append(describeProperty(section.get(key))); } propertyString = full.append('}').toString(); } else { propertyString = property.toString(); } if (maxLength > 0 && propertyString.length() > maxLength - 3) { propertyString = propertyString.substring(0, maxLength - 3) + "..."; } return propertyString; } @SuppressWarnings("EqualsReference") public static boolean isSameInstance(ItemStack one, ItemStack two) { return one == two; } public static int getMapId(ItemStack mapItem) { if (isCurrentVersion()) { return getMetaInt(mapItem, "map", 0); } return mapItem.getDurability(); } public static void setMapId(ItemStack mapItem, int id) { if (isCurrentVersion()) { setMetaInt(mapItem, "map", id); } else { mapItem.setDurability((short)id); } } public static void convertIntegers(Map<String, Object> m) { for (Map.Entry<String, Object> entry : m.entrySet()) { Object value = entry.getValue(); if (value != null && value instanceof Double) { double d = (Double) value; if (d == (int)d) { entry.setValue((int)d); } } else if (value != null && value instanceof Float) { float f = (Float) value; if (f == (int)f) { entry.setValue((int)f); } } else if (value != null && value instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>)value; convertIntegers(map); } } } }
package com.elementary.algorithm.tree; public class ThreadBinaryTreeOperator { //use pre order input character constructor a binary tree; public ThreadBinaryTree<Character> constructorBinaryTree(){ index=0; ThreadBinaryTree<Character> root=null; root=constructor(root); preorderTraverse(root); return inorderTraverseThreading(root); } //use preorder traverse to validate the tree's structure; private void preorderTraverse(ThreadBinaryTree<Character> node){ if(node!=null){ visitNode(node); preorderTraverse(node.leftChild); preorderTraverse(node.rightChild); } } //construct the threading binary tree, complete the leaf node's thread; private ThreadBinaryTree<Character> pre; private ThreadBinaryTree<Character> inorderTraverseThreading(ThreadBinaryTree<Character> root){ ThreadBinaryTree<Character> head=new ThreadBinaryTree<Character>(); head.data='@'; head.leftBranch=BranchType.LINE; head.leftChild=root; head.rightBranch=BranchType.THREAD; head.rightChild=head; pre=head; threading(root); head.rightChild=pre; return head; } private void threading(ThreadBinaryTree<Character> node){ if(node!=null){ threading(node.leftChild); if(node.leftChild==null){ node.leftBranch=BranchType.THREAD; node.leftChild=pre; } if(pre.rightChild==null){ pre.rightBranch=BranchType.THREAD; pre.rightChild=node; } pre=node; threading(node.rightChild); } } private void visitNode(ThreadBinaryTree<Character> node){ System.out.print(node.data); } private int index=0; private char getNodeData(int index){ final char[] dataArray={'A','B','C','@','@','D','E','@','G','@','@','F','@','@','@'}; char data=dataArray[index]; return data; } //constructor ThreadBinaryTree basic branch; private ThreadBinaryTree<Character> constructor(ThreadBinaryTree<Character> node){ char data=getNodeData(index++); if(data!='@'){ node =new ThreadBinaryTree<Character>(); node.data=data; ThreadBinaryTree<Character> child=constructor(node.leftChild); node.leftChild=child; if(child!=null){ node.leftBranch=BranchType.LINE; }else{ node.rightBranch=BranchType.THREAD; } child=constructor(node.rightChild); node.rightChild=child; if(child!=null){ node.rightBranch=BranchType.LINE; }else{ node.rightBranch=BranchType.THREAD; } } return node; } public static void main(String[] args) { ThreadBinaryTreeOperator operator=new ThreadBinaryTreeOperator(); ThreadBinaryTree<Character> threadBinaryTreeRoot = operator.constructorBinaryTree(); } }
package it.elasticsearch.script; import static org.fest.assertions.Assertions.assertThat; import it.elasticsearch.models.ComputedHappiness; import it.elasticsearch.models.USAState; import it.elasticsearch.script.facet.HappinessInternalFacet; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.elasticsearch.common.geo.GeoPoint; import org.junit.Test; public class ByStateCombineScriptTest { private double score1 = 7.; private double relevance1 = 1.; private double score2 = 5.; private double relevance2 = 0.5; private double score3 = 4.; private double relevance3 = 0.33; private String stateId1 = "NY"; private String stateName1 = "New York"; private String stateId2 = "CA"; private String stateName2 = "California"; @Test public void shouldRunWorkWhenTwoDifferentStatesPassed() throws IOException { // given USAState state1 = new USAState(stateId1, stateName1); USAState state2 = new USAState(stateId2, stateName2); ComputedHappiness happiness1 = new ComputedHappiness(score1, relevance1, 10., 10.); happiness1.setState(state1); ComputedHappiness happiness2 = new ComputedHappiness(score2, relevance2, 10., 10.); happiness2.setState(state2); List<ComputedHappiness> listFacets = new ArrayList<ComputedHappiness>(); listFacets.add(happiness1); listFacets.add(happiness2); Map<String, Object> params = new HashMap<String, Object>(); params.put(HappinessInternalFacet.FACET_TYPE, listFacets); ByStateCombineScript combineScript = new ByStateCombineScript(params); List<ComputedHappiness> expectedResult = new ArrayList<ComputedHappiness>(); expectedResult.add(happiness1); expectedResult.add(happiness2); // when Object combineResult = combineScript.run(); // then assertThat(combineResult).isNotNull(); assertThat(combineResult).isEqualTo(expectedResult); } @Test public void shouldRunWorkWhenTwoEqualStatesPassed() throws IOException { // given USAState state1 = new USAState(stateId1, stateName1); ComputedHappiness happiness1 = new ComputedHappiness(score1, relevance1, 10., 10.); happiness1.setState(state1); ComputedHappiness happiness2 = new ComputedHappiness(score2, relevance2, 10., 10.); happiness2.setState(state1); List<ComputedHappiness> listFacets = new ArrayList<ComputedHappiness>(); listFacets.add(happiness1); listFacets.add(happiness2); Map<String, Object> params = new HashMap<String, Object>(); params.put(HappinessInternalFacet.FACET_TYPE, listFacets); ByStateCombineScript combineScript = new ByStateCombineScript(params); double expectedScore = (score1 + score2) / 2; double expectedRelevance = (relevance1 + relevance2) / 2; int expectedNumelems = 2; ComputedHappiness expectedHappiness = new ComputedHappiness(expectedScore, expectedRelevance, expectedNumelems); expectedHappiness.setCoordinates(new GeoPoint(10., 10.)); expectedHappiness.setState(state1); List<ComputedHappiness> expectedResult = new ArrayList<ComputedHappiness>(); expectedResult.add(expectedHappiness); // when Object combineResult = combineScript.run(); // then assertThat(combineResult).isNotNull(); assertThat(combineResult).isEqualTo(expectedResult); } @Test public void shouldRunWorkWhenTwoEqualAndOneDifferentStatesPassed() throws IOException { // given USAState state1 = new USAState(stateId1, stateName1); USAState state2 = new USAState(stateId2, stateName2); int elems1 = 10; int elems2 = 5; ComputedHappiness happiness1 = new ComputedHappiness(score1, relevance1, elems1); happiness1.setState(state1); happiness1.setCoordinates(new GeoPoint(10., 10.)); ComputedHappiness happiness2 = new ComputedHappiness(score2, relevance2, elems2); happiness2.setState(state1); happiness2.setCoordinates(new GeoPoint(10., 10.)); ComputedHappiness happiness3 = new ComputedHappiness(score3, relevance3, 1); happiness3.setState(state2); happiness3.setCoordinates(new GeoPoint(10., 10.)); List<ComputedHappiness> listFacets = new ArrayList<ComputedHappiness>(); listFacets.add(happiness1); listFacets.add(happiness2); listFacets.add(happiness3); Map<String, Object> params = new HashMap<String, Object>(); params.put(HappinessInternalFacet.FACET_TYPE, listFacets); ByStateCombineScript combineScript = new ByStateCombineScript(params); int expectedNumelems = elems1 + elems2; double expectedScore = (score1 * elems1 + score2 * elems2) / expectedNumelems; double expectedRelevance = (relevance1 * elems1 + relevance2 * elems2) / expectedNumelems; ComputedHappiness expectedHappiness = new ComputedHappiness(expectedScore, expectedRelevance, expectedNumelems); expectedHappiness.setCoordinates(new GeoPoint(10., 10.)); expectedHappiness.setState(state1); List<ComputedHappiness> expectedResult = new ArrayList<ComputedHappiness>(); expectedResult.add(expectedHappiness); expectedResult.add(happiness3); // when Object combineResult = combineScript.run(); // then assertThat(combineResult).isNotNull(); assertThat(combineResult).isEqualTo(expectedResult); } @Test public void shouldUnwrapWorkForGoodInput() throws IOException { // given USAState state1 = new USAState(stateId1, stateName1); USAState state2 = new USAState(stateId2, stateName2); ComputedHappiness happiness1 = new ComputedHappiness(score1, relevance1, 10., 10.); happiness1.setState(state1); ComputedHappiness happiness2 = new ComputedHappiness(score2, relevance2, 10., 10.); happiness2.setState(state2); List<ComputedHappiness> listFacets = new ArrayList<ComputedHappiness>(); listFacets.add(happiness1); listFacets.add(happiness2); List<Map<String, Object>> expectedResult = new ArrayList<Map<String, Object>>(); Map<String, Object> map1 = happiness1.toMap(); map1.remove(ComputedHappiness.LATITUDE_KEY); map1.remove(ComputedHappiness.LONGITUDE_KEY); expectedResult.add(map1); Map<String, Object> map2 = happiness2.toMap(); map2.remove(ComputedHappiness.LATITUDE_KEY); map2.remove(ComputedHappiness.LONGITUDE_KEY); expectedResult.add(map2); ByStateCombineScript combineScript = new ByStateCombineScript(null); // when Object unwrapResult = combineScript.unwrap(listFacets); // then assertThat(unwrapResult).isNotNull(); assertThat(unwrapResult).isEqualTo(expectedResult); } }
package com.protocolanalyzer.andres; import java.util.List; import org.achartengine.ChartFactory; import org.achartengine.GraphicalView; import org.achartengine.chart.PointStyle; import org.achartengine.model.XYMultipleSeriesDataset; import org.achartengine.model.XYSeries; import org.achartengine.renderer.XYMultipleSeriesRenderer; import org.achartengine.renderer.XYSeriesRenderer; import org.achartengine.util.IndexXYMap; import org.achartengine.util.MathHelper; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.Paint.Align; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Vibrator; import android.preference.PreferenceManager; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.Toast; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.ActionMode; import com.multiwork.andres.R; import com.protocolanalyzer.api.andres.LogicBitSet; import com.protocolanalyzer.api.andres.Protocol; import com.protocolanalyzer.api.andres.TimePosition; @SuppressLint("ValidFragment") public class LogicAnalizerChartFragment extends SherlockFragment implements OnDataDecodedListener, OnDataClearedListener{ /** Debugging */ private static final boolean DEBUG = true; private static final String TAG = "logic:mFragmentChart"; private static final double initialTimeScale = 0.000500d; // 500 uS private static final float yChannel[] = {0, 5, 10, 15, 20, 25, 30, 35}; /** Cuanto se incrementa en el eje Y para hacer un '1' logico */ private static final float bitScale = 1; /** Valor del eje X maximo inicial */ private static final double xMax = 100; /** Valor del eje X minimo inicial */ private static final double xMin = -100; /** Colores de linea para cada canal */ private static final int lineColor[] = {Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, Color.MAGENTA, Color.CYAN, Color.LTGRAY, Color.WHITE}; /** Escala de tiempo (cuanto equivale un cuadro del grafico */ private static final double timeScaleValues[] = { 0.000000001d, // 1nS 0.000000010d, // 10nS 0.000000025d, // 25nS 0.000000050d, // 50nS 0.000000100d, // 100nS 0.000000250d, // 250nS 0.0000025d, // 2.5uS 0.000500d, // 500uS 0.001d, // 1mS 0.01d, // 10mS 0.1d // 1mS }; /** Vibrador del dispositivo */ private static Vibrator mVibrator; /** ActionBar */ private static ActionBar mActionBar; /** Handler para la actualizacion del grafico en el UI Thread */ private static Handler mUpdaterHandler = new Handler(); /** Tiempo transcurrido en mS (eje x) */ private static double time = 0; /** Cuantos segundos representa un cuadrito (una unidad) en el grafico */ private static double timeScale; /** Serie que muestra los '1' y '0' de cada canal */ private static XYSeries[] mSerie; private static XYSeriesRenderer[] mRenderer; /** Rectangulos delimitadores */ private static XYSeries[] rectangleSeries; /** Renderer de los rectangulos */ private static XYSeriesRenderer[] rectangleRenderer; /** Dataset para agrupar las Series */ private static XYMultipleSeriesDataset mSerieDataset; /** Dataser para agrupar los Renderer */ private static XYMultipleSeriesRenderer mRenderDataset; private static GraphicalView mChartView; private static SherlockFragmentActivity mActivity; private static OnActionBarClickListener mActionBarListener; /** Coordenadas de inicio cuando se toco por primera vez el touchscreen */ private static float x = 0, y = 0; /** Indica si se esta deslizando el dedo en vez de mantenerlo apretado */ private static boolean isMoving = false; /** Indica si se esta sosteniendo el dedo sobre la pantalla (long-press) */ private static boolean fingerStillDown = false; /** Protocolo para cada canal */ private static Protocol[] decodedData; private static int samplesNumber = 0; // Constructor public LogicAnalizerChartFragment(Protocol[] data) { if(DEBUG) Log.i(TAG,"LogicAnalizerChartFragment() Constructor"); decodedData = data; } // Constructor por defecto public LogicAnalizerChartFragment() { decodedData = null; } @Override public void onDataDecodedListener(Protocol[] data, boolean isConfig) { if(DEBUG) Log.i(TAG,"onDataDecoded() - isConfig: " + isConfig); // Si se cambiaron las configuraciones las actualizo if(isConfig) setChartPreferences(); else{ decodedData = data; samplesNumber = data[0].getBitsNumber(); if(samplesNumber > 0) mUpdaterHandler.post(mUpdaterTask); } } @Override public void onDataCleared() { if(DEBUG) Log.i(TAG,"onDataCleared()"); restart(); } private void updateXLabels(){ int currentIndex = 0; for(int n = 0; n < timeScaleValues.length; ++n){ if(timeScaleValues[n] == timeScale){ currentIndex = n; break; } } // Si es mayor a 1000uS, lo muestro como mS if(timeScaleValues[currentIndex] * 1E6 >= 1000){ mRenderDataset.setXTitle(getString(R.string.AnalyzerXTitle) + " x" + String.format("%.2f", timeScaleValues[currentIndex]*1E3) + " mS"); } // Si es mayor a 1000nS lo muestro como uS else if(timeScaleValues[currentIndex] * 1E9 >= 1000){ mRenderDataset.setXTitle(getString(R.string.AnalyzerXTitle) + " x" + String.format("%.2f", timeScaleValues[currentIndex]*1E6) + " uS"); } // Sino lo muestro como nS else{ mRenderDataset.setXTitle(getString(R.string.AnalyzerXTitle) + " x" + String.format("%.2f", timeScaleValues[currentIndex]*1E9) + " nS"); } } private void zoomIn(){ int currentIndex = 0; for(int n = 0; n < timeScaleValues.length; ++n){ if(timeScaleValues[n] == timeScale){ currentIndex = n; break; } } if(currentIndex != 0){ double prevTimeScale = timeScale; timeScale = timeScaleValues[currentIndex-1]; double prevX1 = mRenderDataset.getXAxisMin()*prevTimeScale; double prevX2 = mRenderDataset.getXAxisMax()*prevTimeScale; double minX = toCoordinate(prevX1, timeScale); double maxX = toCoordinate(prevX2, timeScale); for(int n = 0; n < mSerie.length; ++n){ XYSeries series = mSerie[n]; @SuppressWarnings("unchecked") IndexXYMap<Double, Double> map = (IndexXYMap<Double, Double>)series.getXYMap().clone(); series.clearSeriesValues(); for(java.util.Map.Entry<Double, Double> entry : map.entrySet()){ series.add(toCoordinate(entry.getKey()*prevTimeScale, timeScale), entry.getValue()); } for(int j = 0; j < series.getAnnotationCount(); ++j){ double x = toCoordinate(series.getAnnotationX(j)*prevTimeScale, timeScale); double y = series.getAnnotationY(j); series.replaceAnnotation(j, series.getAnnotationAt(j), x, y); Double[] cord = rectangleSeries[n].getRectangle(j); x = toCoordinate(cord[0]*prevTimeScale, timeScale); double x2 = toCoordinate(cord[2]*prevTimeScale, timeScale); rectangleSeries[n].replaceRectangle(j, x, cord[1], x2, cord[3]); } } mRenderDataset.setXAxisMax(maxX); mRenderDataset.setXAxisMin(minX); updateXLabels(); if(DEBUG) Log.i(TAG, "Redrawing Zoomed Chart"); mChartView.zoomIn(); } } private void zoomOut(){ int currentIndex = 0; for(int n = 0; n < timeScaleValues.length; ++n){ if(timeScaleValues[n] == timeScale){ currentIndex = n; break; } } if(currentIndex != timeScaleValues.length-1){ double prevTimeScale = timeScale; timeScale = timeScaleValues[currentIndex+1]; double prevX1 = mRenderDataset.getXAxisMin()*prevTimeScale; double prevX2 = mRenderDataset.getXAxisMax()*prevTimeScale; double minX = toCoordinate(prevX1, timeScale); double maxX = toCoordinate(prevX2, timeScale); for(int n = 0; n < mSerie.length; ++n){ XYSeries series = mSerie[n]; @SuppressWarnings("unchecked") IndexXYMap<Double, Double> map = (IndexXYMap<Double, Double>)series.getXYMap().clone(); series.clearSeriesValues(); for(java.util.Map.Entry<Double, Double> entry : map.entrySet()){ series.add(toCoordinate(entry.getKey()*prevTimeScale, timeScale), entry.getValue()); } for(int j = 0; j < series.getAnnotationCount(); ++j){ double x = toCoordinate(series.getAnnotationX(j)*prevTimeScale, timeScale); double y = series.getAnnotationY(j); series.replaceAnnotation(j, series.getAnnotationAt(j), x, y); Double[] cord = rectangleSeries[n].getRectangle(j); x = toCoordinate(cord[0]*prevTimeScale, timeScale); double x2 = toCoordinate(cord[2]*prevTimeScale, timeScale); rectangleSeries[n].replaceRectangle(j, x, cord[1], x2, cord[3]); } } mRenderDataset.setXAxisMax(maxX); mRenderDataset.setXAxisMin(minX); updateXLabels(); if(DEBUG) Log.i(TAG, "Redrawing Zoomed Chart"); mChartView.zoomOut(); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Log.i(TAG, "onActivityCreated()"); mActionBar = mActivity.getSupportActionBar(); // Obtengo el ActionBar mActionBar.setDisplayHomeAsUpEnabled(true); // El icono de la aplicacion funciona como boton HOME mActionBar.setTitle(getString(R.string.AnalyzerName)) ; // Nombre this.setHasOptionsMenu(true); setChartPreferences(); // Obtengo el OnActionBarClickListener de la Activity que creo este Fragment try { mActionBarListener = (OnActionBarClickListener) mActivity; } catch (ClassCastException e) { throw new ClassCastException(mActivity.toString() + " must implement OnActionBarClickListener"); } // Vibrador mVibrator = (Vibrator) mActivity.getSystemService(Context.VIBRATOR_SERVICE); final Runnable longClickRun = new Runnable() { @Override public void run() { if(fingerStillDown && !isMoving) { if(DEBUG) Log.i("Runnable longClickRun()", "LONG CLICK"); mVibrator.vibrate(80); // Vibro e inicio el ActionMode mActivity.startActionMode(new ActionModeEnable()); } } }; mChartView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // Si me movi al menos 20 unidades en cualquier direccion ya se toma como scroll NO long-press if(Math.abs(event.getX() - x) > 20 || Math.abs(event.getY() - y) > 20) { isMoving = true; } // Obtengo las coordenadas iniciales para tomar el movimiento if(event.getAction() == MotionEvent.ACTION_DOWN) { x = event.getX(); y = event.getY(); fingerStillDown = true; isMoving = false; mChartView.postDelayed(longClickRun, 1000); // En 1000mS se iniciara el Long-Press } // Si levanto el dedo ya no cuenta para el long-press else if(event.getAction() == MotionEvent.ACTION_UP){ mChartView.removeCallbacks(longClickRun); // Elimino el postDelayed() fingerStillDown = false; isMoving = false; x = y = 0; } // Sleep por 50mS para que no este continuamente testeando y ahorre recursos (no hace falta gran velocidad) try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } // return false; da lugar a que se analizen otros eventos de touch (como cuando deslizamos el grafico). Si fuera return false; } }); if(decodedData != null){ samplesNumber = decodedData[0].getBitsNumber(); mUpdaterHandler.post(mUpdaterTask); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { menu.clear(); inflater.inflate(R.menu.actionbar_logicchart, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.i(TAG, "onCreateView()"); // Obtengo la Activity que contiene el Fragment mActivity = getSherlockActivity(); mSerieDataset = new XYMultipleSeriesDataset(); mRenderDataset = new XYMultipleSeriesRenderer(); mSerie = new XYSeries[LogicAnalizerActivity.channelsNumber]; rectangleSeries = new XYSeries[LogicAnalizerActivity.channelsNumber]; mRenderer = new XYSeriesRenderer[LogicAnalizerActivity.channelsNumber]; rectangleRenderer = new XYSeriesRenderer[LogicAnalizerActivity.channelsNumber]; for(int n=0; n < LogicAnalizerActivity.channelsNumber; ++n) { // Crea las Serie que es una linea en el grafico (cada una de las entradas) mSerie[n] = new XYSeries(getString(R.string.AnalyzerName) + n); mRenderer[n] = new XYSeriesRenderer(); // Creo el renderer de la Serie mRenderDataset.addSeriesRenderer(mRenderer[n]); // Agrego el renderer al Dataset mSerieDataset.addSeries(mSerie[n]); // Agrego la serie al Dataset mRenderer[n].setColor(lineColor[n]); // Color de la Serie mRenderer[n].setFillPoints(true); mRenderer[n].setPointStyle(PointStyle.CIRCLE); mRenderer[n].setLineWidth(2f); mRenderer[n].setAnnotationsTextSize(10); mRenderer[n].setAnnotationsColor(Color.WHITE); mRenderer[n].setAnnotationsTextAlign(Align.CENTER); // Rectangulos rectangleSeries[n] = new XYSeries(""); rectangleSeries[n].setIsRectangleSeries(true); rectangleRenderer[n] = new XYSeriesRenderer(); rectangleRenderer[n].setColor(lineColor[n]); rectangleRenderer[n].setShowLegendItem(false); mSerieDataset.addSeries(rectangleSeries[n]); mRenderDataset.addSeriesRenderer(rectangleRenderer[n]); } // Configuraciones generales mRenderDataset.setYTitle(getString(R.string.AnalyzerYTitle)); mRenderDataset.setAntialiasing(true); mRenderDataset.setYAxisMax(yChannel[yChannel.length/2]+4); mRenderDataset.setXAxisMin(xMin); mRenderDataset.setXAxisMax(xMax); mRenderDataset.setPanEnabled(true); mRenderDataset.setShowGrid(true); mRenderDataset.setPointSize(4f); mRenderDataset.setExternalZoomEnabled(true); mRenderDataset.setPanEnabled(true, true); mRenderDataset.setZoomEnabled(true, false); mRenderDataset.setPanLimits(new double[] {xMin , Double.MAX_VALUE, -1d, yChannel[yChannel.length-1]+4}); mRenderDataset.setXLabels(20); time = 0; mChartView = ChartFactory.getLineChartView(mActivity, mSerieDataset, mRenderDataset); if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // Renderizado por software, el hardware trae problemas con paths muy largos en el Canvas (bug de Android) mChartView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); } setChartPreferences(); // Renderizo el layout View view = inflater.inflate(R.layout.logicanalizer, container, false); FrameLayout f = (FrameLayout)view.findViewById(R.id.mChart); f.addView(mChartView); return view; } @Override public void onResume() { super.onResume(); if(DEBUG) Log.i(TAG,"onResume()"); } // Activa el ActionMode del ActionBar private final class ActionModeEnable implements ActionMode.Callback { @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { if(DEBUG) Log.i(TAG, "Action Mode onCreate()"); MenuInflater inflater = mActivity.getSupportMenuInflater(); inflater.inflate(R.menu.actionmodelogic, menu); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { if(DEBUG) Log.i(TAG, "Action Mode onPrepare"); return false; } // Al presionar iconos en el ActionMode @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { if(DEBUG) Log.i(TAG, "Item clicked: " + item.getItemId() + " - " + item.getTitle()); switch(item.getItemId()) { case R.id.restartLogic: mActionBarListener.onActionBarClickListener(R.id.restartLogic); restart(); break; case R.id.saveLogic: createDialog(); break; } mode.finish(); return true; } @Override public void onDestroyActionMode(ActionMode mode) { if(DEBUG) Log.i(TAG, "Destroy"); } } // Listener de los items en el ActionBar @Override public boolean onOptionsItemSelected(MenuItem item) { if(DEBUG) Log.i(TAG, "ActionBar -> " + item.getTitle()); switch(item.getItemId()){ case R.id.zoomInLogic: zoomIn(); break; case R.id.zoomOutLogic: zoomOut(); break; } return true; } /** * Viene aqui cuando se vuelve de la Activity de las preferences al ser llamada con startActivityForResult() de este * modo actualizo las preferencias */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(DEBUG) Log.i(TAG, "Activity Result"); if(DEBUG) Log.i(TAG, "resultCode: " + resultCode); if(DEBUG) Log.i(TAG, "requestCode: " + requestCode); } private void restart() { for(int n = 0; n < LogicAnalizerActivity.channelsNumber; ++n) { mSerie[n].clear(); } mRenderDataset.setXAxisMax(xMax); mRenderDataset.setXAxisMin(xMin); time = 0; mChartView.repaint(); Toast.makeText(mActivity, getString(R.string.Reinicio), Toast.LENGTH_SHORT).show(); } private void createDialog() { final CharSequence[] items = {getString(R.string.AnalyzerImagen), getString(R.string.AnalyzerSesion)}; AlertDialog.Builder alert = new AlertDialog.Builder(mActivity); alert.setTitle(getString(R.string.AnalyzerDialogSaveTitle)); alert.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if(item == 0) { // TODO: guardar imagen } else { // TODO: guardar sesion } } }); alert.show(); } final private Runnable mUpdaterTask = new Runnable() { @Override public void run() { if(DEBUG) Log.i(TAG, "Updater Task - Samples: " + samplesNumber); // Borro todos los valores previos for(int n = 0; n < LogicAnalizerActivity.channelsNumber; ++n){ mSerie[n].clear(); rectangleSeries[n].clear(); } final double initTime = 0; time = 0; // Coloco los bits en el canal for(int channel = 0; channel < LogicAnalizerActivity.channelsNumber; ++channel){ LogicBitSet bitsData = decodedData[channel].getChannelBitsData(); boolean bitState = false; // En vez de poner todos los puntos en la serie coloco solo cada vez que se cambia de estado // la performance es muy baja for(int n = 0; n < samplesNumber; ++n){ // Punto inicial if(n == 0){ bitState = bitsData.get(0); if(bitsData.get(n)){ mSerie[channel].add(toCoordinate(time, timeScale), yChannel[channel]+bitScale); } else{ mSerie[channel].add(toCoordinate(time, timeScale), yChannel[channel]); } // Punto si hay un cambio de estado }else if(bitsData.get(n) != bitState){ bitState = bitsData.get(n); double tTime = time - 1.0d/decodedData[0].getSampleFrequency(); // Estado anterior if(bitsData.get(n-1)) mSerie[channel].add(toCoordinate(tTime, timeScale), yChannel[channel]+bitScale); else mSerie[channel].add(toCoordinate(tTime, timeScale), yChannel[channel]); // Estado actual if(bitsData.get(n)) mSerie[channel].add(toCoordinate(time, timeScale), yChannel[channel]+bitScale); else mSerie[channel].add(toCoordinate(time, timeScale), yChannel[channel]); // Punto al final }else if(n == (samplesNumber-1)){ if(bitsData.get(n)) mSerie[channel].add(toCoordinate(time, timeScale), yChannel[channel]+bitScale); else mSerie[channel].add(toCoordinate(time, timeScale), yChannel[channel]); } // Incremento el tiempo time += 1.0d/decodedData[0].getSampleFrequency(); } if(channel < LogicAnalizerActivity.channelsNumber-1) time = initTime; } if(timeScale == initialTimeScale){ mRenderDataset.setXAxisMax(toCoordinate(time, timeScale)+(10*toCoordinate(time, timeScale))/100); mRenderDataset.setXAxisMin(0-(10*toCoordinate(time, timeScale))/100); } // Agrego un espacio para indicar que el buffer de muestreo llego hasta aqui time += (toCoordinate(mSerie[0].getItemCount() * (1d/decodedData[0].getSampleFrequency()), timeScale)*30)/100; for(int n=0; n < LogicAnalizerActivity.channelsNumber; ++n){ if(mSerie[n].getItemCount() > 0){ mSerie[n].add(mSerie[n].getX(mSerie[n].getItemCount()-1), MathHelper.NULL_VALUE); } } // Anotaciones for(int n = 0; n < LogicAnalizerActivity.channelsNumber; ++n){ List<TimePosition> stringData = decodedData[n].getDecodedData(); if(DEBUG) Log.i(TAG, "Channel " + n + " annotations: " + stringData.size()); for(TimePosition timePosition : stringData){ // Agrego el texto en el centro del area de tiempo que contiene el string mSerie[n].addAnnotation(timePosition.getString(), toCoordinate(timePosition.startTime() + (timePosition.endTime() - timePosition.startTime())/2, timeScale), yChannel[n]+2f); // Rectangulos delimitadores rectangleSeries[n].addRectangle(toCoordinate(timePosition.startTime(), timeScale), yChannel[n]+bitScale+3.5f, toCoordinate(timePosition.endTime(), timeScale), yChannel[n]+bitScale+0.5f); } } mChartView.repaint(); // Redibujo el grafico // Cada vez que recibo un buffer del analizador logico, lo muestro todo y pauso mActionBarListener.onActionBarClickListener(R.id.PlayPauseLogic); } }; /** * Convierte el tiempo en segundos a la escala del grafico segun la escala de tiempos * @param time tiempo en segundos * @param timeScale cuantos segundos equivalen a una unidad en el grafico * @return coordenada equivalente */ private static double toCoordinate (double time, double timeScale){ return (time/timeScale); } // Define los parametros de acuerdo a las preferencias private void setChartPreferences() { SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(mActivity); for(int n=0; n < LogicAnalizerActivity.channelsNumber; ++n){ // Seteo el protocolo para cada canal switch(Integer.valueOf(getPrefs.getString("protocol" + (n+1), ""+LogicAnalizerActivity.UART))){ case LogicAnalizerActivity.I2C: // I2C mSerie[n].setTitle(getString(R.string.AnalyzerChannel) + " " + (n+1) + " [I2C]"); break; case LogicAnalizerActivity.UART: // UART mSerie[n].setTitle(getString(R.string.AnalyzerChannel) + " " + (n+1) + " [UART]"); break; case LogicAnalizerActivity.Clock: // CLOCK mSerie[n].setTitle(getString(R.string.AnalyzerChannel) + " " + (n+1) + "[CLK]"); break; case LogicAnalizerActivity.NA: // NONE mSerie[n].setTitle(getString(R.string.AnalyzerChannel) + " " + (n+1) + "[ break; } } // Escala inicial timeScale = initialTimeScale; updateXLabels(); if(DEBUG) Log.i(TAG, "Time Scale: " + timeScale); // Actualizo los datos del grafico mChartView.repaint(); } }
package net.nunnerycode.bukkit.mythicdrops; import com.modcrafting.diablodrops.name.NamesLoader; import java.io.File; import net.nunnerycode.bukkit.libraries.config.CommentedNunneryYamlConfiguration; import net.nunnerycode.bukkit.libraries.config.NunneryConfiguration; import net.nunnerycode.bukkit.mythicdrops.api.MythicDrops; import net.nunnerycode.bukkit.mythicdrops.api.settings.ConfigSettings; import net.nunnerycode.bukkit.mythicdrops.settings.MythicConfigSettings; import net.nunnerycode.java.libraries.cannonball.DebugPrinter; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.java.JavaPlugin; public final class MythicDropsPlugin extends JavaPlugin implements MythicDrops { private static MythicDrops _INSTANCE; private ConfigSettings configSettings; private DebugPrinter debugPrinter; private CommentedNunneryYamlConfiguration configYAML; private CommentedNunneryYamlConfiguration customItemYAML; private CommentedNunneryYamlConfiguration itemGroupYAML; private CommentedNunneryYamlConfiguration languageYAML; private CommentedNunneryYamlConfiguration tierYAML; private NamesLoader namesLoader; public static MythicDrops getInstance() { return _INSTANCE; } @Override public void onEnable() { _INSTANCE = this; debugPrinter = new DebugPrinter(getDataFolder().getPath(), "debug.log"); configSettings = new MythicConfigSettings(); namesLoader = new NamesLoader(this); namesLoader.writeDefault("config.yml", false); namesLoader.writeDefault("customItems.yml", false); namesLoader.writeDefault("itemGroups.yml", false); namesLoader.writeDefault("language.yml", false); namesLoader.writeDefault("tier.yml", false); namesLoader.writeDefault("variables.txt", false); configYAML = new CommentedNunneryYamlConfiguration(new File(getDataFolder(), "config.yml"), YamlConfiguration.loadConfiguration(getResource("config.yml")).getString("version")); configYAML.options().backupOnUpdate(true); configYAML.options().updateOnLoad(true); configYAML.load(); customItemYAML = new CommentedNunneryYamlConfiguration(new File(getDataFolder(), "customItems.yml"), YamlConfiguration.loadConfiguration(getResource("customItems.yml")).getString("version")); customItemYAML.options().backupOnUpdate(true); customItemYAML.options().updateOnLoad(true); customItemYAML.load(); itemGroupYAML = new CommentedNunneryYamlConfiguration(new File(getDataFolder(), "itemGroup.yml"), YamlConfiguration.loadConfiguration(getResource("itemGroup.yml")).getString("version")); itemGroupYAML.options().backupOnUpdate(true); itemGroupYAML.options().updateOnLoad(true); itemGroupYAML.load(); languageYAML = new CommentedNunneryYamlConfiguration(new File(getDataFolder(), "language.yml"), YamlConfiguration.loadConfiguration(getResource("language.yml")).getString("version")); languageYAML.options().backupOnUpdate(true); languageYAML.options().updateOnLoad(true); languageYAML.load(); tierYAML = new CommentedNunneryYamlConfiguration(new File(getDataFolder(), "tier.yml"), YamlConfiguration.loadConfiguration(getResource("config.yml")).getString("version")); tierYAML.options().backupOnUpdate(true); tierYAML.options().updateOnLoad(true); tierYAML.load(); writeResourceFiles(); } private void writeResourceFiles() { namesLoader.writeDefault("/resources/lore/general.txt", false, true); namesLoader.writeDefault("/resources/lore/enchantments/damage_all.txt", false, true); namesLoader.writeDefault("/resources/lore/materials/diamond_sword.txt", false, true); namesLoader.writeDefault("/resources/lore/tiers/legendary.txt", false, true); namesLoader.writeDefault("/resources/prefixes/general.txt", false, true); namesLoader.writeDefault("/resources/prefixes/enchantments/damage_all.txt", false, true); namesLoader.writeDefault("/resources/prefixes/materials/diamond_sword.txt", false, true); namesLoader.writeDefault("/resources/prefixes/tiers/legendary.txt", false, true); namesLoader.writeDefault("/resources/suffixes/general.txt", false, true); namesLoader.writeDefault("/resources/suffixes/enchantments/damage_all.txt", false, true); namesLoader.writeDefault("/resources/suffixes/materials/diamond_sword.txt", false, true); namesLoader.writeDefault("/resources/suffixes/tiers/legendary.txt", false, true); } @Override public ConfigSettings getConfigSettings() { return configSettings; } @Override public DebugPrinter getDebugPrinter() { return debugPrinter; } @Override public NunneryConfiguration getConfigYAML() { return configYAML; } @Override public NunneryConfiguration getCustomItemYAML() { return customItemYAML; } @Override public NunneryConfiguration getItemGroupYAML() { return itemGroupYAML; } @Override public NunneryConfiguration getLanguageYAML() { return languageYAML; } @Override public NunneryConfiguration getTierYAML() { return tierYAML; } }
package com.github.lgooddatepicker.components; import com.github.lgooddatepicker.optionalusertools.PickerUtilities; import com.github.lgooddatepicker.optionalusertools.TimeVetoPolicy; import com.github.lgooddatepicker.zinternaltools.ExtraTimeStrings; import com.github.lgooddatepicker.zinternaltools.InternalConstants; import com.github.lgooddatepicker.zinternaltools.InternalUtilities; import com.privatejgoodies.forms.layout.ColumnSpec; import com.privatejgoodies.forms.layout.ConstantSize; import com.privatejgoodies.forms.layout.FormLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.font.TextAttribute; import java.time.Clock; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.FormatStyle; import java.util.ArrayList; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.TreeSet; import javax.swing.JTextField; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.border.MatteBorder; /** * TimePickerSettings, This holds all the settings that can be customized in a time picker. Most of * the fields of this class are public, so that the settings are easier to customize as needed. The * fields that are not public can be set using the class functions. * * <p>A TimePickerSettings instance may be (optionally) created, customized, and passed to the time * picker constructor. If no settings instance is supplied when a time picker is constructed, then a * settings instance with default settings is automatically generated and used by the time picker * class. * * <p>Each and all of the setting fields are set to a default value when a TimePickerSettings object * is constructed. This means that the programmer does not need to overwrite all (or any) of the * available settings to use this class. They only need to change any particular settings that they * wish to customize. * * <p>This class also contains a small number of settings for the DateTimePicker class. (The * DateTimePicker class combines a date picker with a time picker.) All of those settings begin with * the prefix "zDateTimePicker_". */ public class TimePickerSettings { /** * TimeArea, These enumerations represent areas of the components whose color can be changed. * These values are used with the setColor() function, to set the color of various areas of the * TimePicker. The default color for each area is also defined here. * * <p>Note: A default color of "null" means that the default color for that element is supplied by * the swing component. */ public enum TimeArea { TimePickerTextValidTime(Color.black), TimePickerTextInvalidTime(Color.red), TimePickerTextVetoedTime(Color.black), TimePickerTextDisabled(new Color(109, 109, 109)), TextFieldBackgroundValidTime(Color.white), TextFieldBackgroundInvalidTime(Color.white), TextFieldBackgroundVetoedTime(Color.white), TextFieldBackgroundDisallowedEmptyTime(Color.pink), TextFieldBackgroundDisabled(new Color(240, 240, 240)); TimeArea(Color defaultColor) { this.defaultColor = defaultColor; } public Color defaultColor; } /** * allowEmptyTimes, This indicates whether or not empty times are allowed in the time picker. * Empty times are also called "null times". The default value is true, which allows empty times. * If empty times are not allowed, but TimePickerSettings.initialTime is left set to null, then * the initial time will be set to a default value. (The default value is 7:00am.) */ private boolean allowEmptyTimes = true; /** * allowKeyboardEditing, This indicates whether or not keyboard editing is allowed for this time * picker. If this is true, then times can be entered by either using the keyboard or the mouse. * If this is false, then times can only be selected by using the mouse. When this is false, the * user will be limited to choosing times which have been added to the time drop down menu. The * default value is true. It is generally recommended to leave this setting as "true". * * <p>Accessibility Impact: Disallowing the use of the keyboard, and requiring the use of the * mouse, could impact the accessibility of your program for disabled persons. * * <p>Note: This setting does not impact the automatic enforcement of valid or vetoed times. To * learn about the automatic time validation and enforcement for keyboard entered text, see the * javadocs for the TimePicker class. */ private boolean allowKeyboardEditing = true; /** * borderTimePopup, This allows you to set a custom border for the time picker popup menu. By * default, a simple border is drawn. */ public Border borderTimePopup; /** * clock, A clock used to determine current date and time The default is to use the System Clock */ private Clock clock = Clock.systemDefaultZone(); /** * colors, This hash map holds the current color settings for different areas of the TimePicker. * These colors can be set with the setColor() function, or retrieved with the getColor() * function. By default, this map is populated with a set of default colors. The default colors * for each area are defined the "Area" enums. */ private HashMap<TimePickerSettings.TimeArea, Color> colors; /** * displayToggleTimeMenuButton, This controls whether or not the toggle menu button is displayed * (and enabled), on the time picker. The default value is true. */ private boolean displayToggleTimeMenuButton = true; /** * displaySpinnerButtons, This controls whether or not the spinner buttons are displayed (and * enabled), on the time picker. The default value is false. */ private boolean displaySpinnerButtons = false; /** * fontInvalidTime, This is the text field text font for invalid times. The default font is * normal. */ public Font fontInvalidTime; /** * fontValidTime, This is the text field text font for valid times. The default font is normal. */ public Font fontValidTime; /** * fontVetoedTime, This is the text field text font for vetoed times. The default font crosses out * the vetoed time. (Has a strikethrough font attribute.) */ public Font fontVetoedTime; /** * formatForDisplayTime, This is used to format and display the time values in the main text field * of the time picker. By default, a format is generated from the time picker locale. */ private DateTimeFormatter formatForDisplayTime; /** * formatForMenuTimes, This is used to format and display the time values in the menu of the time * picker. By default, a format is generated from the time picker locale. */ private DateTimeFormatter formatForMenuTimes; /** * formatsForParsing, This holds a list of formats that are used to attempt to parse times that * are typed by the user. When parsing a time, these formats are tried in the order that they * appear in this list. Note that the formatForDisplayTime and formatForMenuTimes are always tried * (in that order) before any other parsing formats. The default values for the formatsForParsing * are generated using the timeLocale, using the enum constants in java.time.format.FormatStyle. */ public ArrayList<DateTimeFormatter> formatsForParsing; /** * gapBeforeButtonPixels, This specifies the desired width for the gap between the time picker and * the toggle time menu button (in pixels). The default value is null. If this is left at null, * then the gap will set to 0 pixels in the time picker constructor. */ private Integer gapBeforeButtonPixels = null; /** * initialTime, This is the time that the time picker will have when it is created. This can be * set to any time, or it can be set to null. The default value for initialTime is null, which * represents an empty time. This setting will only have an effect if it is set before the date * picker is constructed. * * <p>If allowEmptyTimes is false, then a null initialTime will be ignored. More specifically: * When a TimePicker is constructed, if allowEmptyTimes is false and initialTime is null, then the * initialTime will be set to a default value. (The default value is currently 7:00 am.) * * <p>Note: This time can not be vetoed, because a veto policy can not be set until after the * TimePicker is constructed. */ public LocalTime initialTime = null; /** * maximumVisibleMenuRows, This is the maximum number of rows that can be displayed in the time * selection menu without using a scroll bar. In other words, this specifies the default maximum * height of the time selection menu (in rows). The default value is 10 rows. * * <p>If this allows a greater number of rows than the actual number of time entries in the time * drop down menu, then the menu will be made smaller to fit the number of time entries. */ public int maximumVisibleMenuRows = 10; /** * minimumSpinnerButtonWidthInPixels, This sets the minimum width of the spinner buttons. The * default value is 20 pixels. */ private int minimumSpinnerButtonWidthInPixels = 20; /** * minimumToggleTimeMenuButtonWidthInPixels, This sets the minimum width of the toggle menu * button. The default value is 26 pixels. */ private int minimumToggleTimeMenuButtonWidthInPixels = 26; /** * parent, This holds a reference to the parent time picker that is associated with these * settings. This variable is only intended to be set from the time picker constructor. * * <p>This will be null until the TimePicker is constructed (using this settings instance). */ private TimePicker parent; /** * potentialMenuTimes, This is a list of candidate time values for populating the drop down menu. * All of these times that are not vetoed will be added to the drop down menu. Any vetoed times * will be ignored. By default, this contains a list of LocalTime values going from Midnight to * 11:30PM, in 30 minute increments. This variable is private to ensure the validity of the menu * times list. To customize the menu times, call one of the generatePotentialMenuTimes() functions * with your desired parameters. */ private ArrayList<LocalTime> potentialMenuTimes; /** * sizeTextFieldMinimumWidth, This specifies the minimum width, in pixels, of the TimePicker text * field. (The text field is located to the left of the time picker "open time menu" button, and * displays the currently selected time.) * * <p>The default value for this setting is null. When this is set to null, a default width for * the time picker text field will be automatically calculated and applied to fit "the largest * possible time" that can be displayed with the current time picker settings. The settings that * are used to calculate the default text field width include the locale (the language), the * fontValidTime, and the format for valid times. * * <p>See also: "sizeTextFieldMinimumWidthDefaultOverride". */ private Integer sizeTextFieldMinimumWidth = null; /** * sizeTextFieldMinimumWidthDefaultOverride, This specifies how the time picker should choose the * appropriate minimum width for the time picker text field. (As described below.) * * <p>If this is true, then the applied minimum width will be the largest of either the default, * or any programmer supplied, minimum widths. * * <p>If this is false, then any programmer supplied minimum width will always override the * default minimum width. (Even if the programmer supplied width is too small to fit the times * that can be displayed in the TimePicker). * * <p>The default value for this setting is true. This setting only has an effect if * (sizeTextFieldMinimumWidth != null). * * <p>See also: "sizeTextFieldMinimumWidth". */ private boolean sizeTextFieldMinimumWidthDefaultOverride = true; /** * timeLocale, This is the locale of the time picker, which is used to generate some of the other * default values, such as the default time formats. */ private Locale locale; /** * useLowercaseForDisplayTime, This indicates if the display time should always be shown in * lowercase. The default value is true. If this is true, the display time will always be shown in * lowercase text. If this is false, then the text case that is used will be determined by the * default time symbols and default format for the locale. */ public boolean useLowercaseForDisplayTime = true; /** * useLowercaseForMenuTimes, This indicates if the menu times should always be shown in lowercase. * The default value is true. If this is true, the menu times will always be shown in lowercase * text. If this is false, then the text case that is used will be determined by the default time * symbols and default format for the locale. */ public boolean useLowercaseForMenuTimes = true; /** * vetoPolicy, If a veto policy is supplied, it will be used to determine which times can and * cannot be selected in the time picker. Vetoed times can not be selected using the keyboard or * the mouse. By default, there is no veto policy. (The default value is null.) See the * TimeVetoPolicy Javadocs for details regarding when a veto policy is enforced. See the demo * class for an example of constructing a veto policy. */ private TimeVetoPolicy vetoPolicy = null; /** * zDateTimePicker_GapBeforeTimePickerPixels, This setting only applies to the DateTimePicker * class. This specifies the desired width for the gap between the date picker and the time picker * (in pixels). The default value is null. If this is left at null, then the gap will set to 5 * pixels in the DateTimePicker constructor. */ public Integer zDateTimePicker_GapBeforeTimePickerPixels = null; /** * Constructor with Default Locale, This constructs a time picker settings instance using the * system default locale and language. The constructor populates all the settings with default * values. */ public TimePickerSettings() { this(Locale.getDefault()); } /** * Constructor with Custom Locale, This constructs a time picker settings instance using the * supplied locale and language. The constructor populates all the settings with default values. */ public TimePickerSettings(Locale timeLocale) { // Add all the default colors to the colors map. colors = new HashMap<>(); for (TimeArea area : TimeArea.values()) { colors.put(area, area.defaultColor); } // Save the locale. this.locale = timeLocale; // Generate default menu times. generatePotentialMenuTimes(TimeIncrement.ThirtyMinutes, null, null); // Generate a default display and menu formats. formatForDisplayTime = ExtraTimeStrings.getDefaultFormatForDisplayTime(timeLocale); formatForMenuTimes = ExtraTimeStrings.getDefaultFormatForMenuTimes(timeLocale); // Generate default parsing formats. FormatStyle[] allFormatStyles = { FormatStyle.SHORT, FormatStyle.MEDIUM, FormatStyle.LONG, FormatStyle.FULL }; formatsForParsing = new ArrayList<>(); formatsForParsing.add(DateTimeFormatter.ISO_LOCAL_TIME); for (FormatStyle formatStyle : allFormatStyles) { DateTimeFormatter parseFormat = new DateTimeFormatterBuilder() .parseLenient() .parseCaseInsensitive() .appendLocalized(null, formatStyle) .toFormatter(timeLocale); formatsForParsing.add(parseFormat); } // Get any common extra parsing formats for the specified locale, and append them to // the list of parsingFormatters. ArrayList<DateTimeFormatter> extraFormatters = ExtraTimeStrings.getExtraTimeParsingFormatsForLocale(timeLocale); formatsForParsing.addAll(extraFormatters); // Set the default popup border. This can be overridden by the user if they desire. borderTimePopup = new EmptyBorder(0, 0, 0, 0); // Generate the default fonts and text colors. fontValidTime = new JTextField().getFont(); fontInvalidTime = new JTextField().getFont(); fontVetoedTime = new JTextField().getFont(); Map<TextAttribute, Boolean> additionalAttributes = new HashMap<>(); additionalAttributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON); fontVetoedTime = fontVetoedTime.deriveFont(additionalAttributes); } /** * generatePotentialMenuTimes, This will generate a list of menu times for populating the combo * box menu, using a TimePickerSettings.TimeIncrement value. The menu times will always start at * Midnight, and increase according to the increment until the last time before 11:59pm. * * <p>Note: This function can be called before or after setting an optional veto policy. Vetoed * times will never be added to the time picker menu, regardless of whether they are generated by * this function. * * <p>Example usage: generatePotentialMenuTimes(TimeIncrement.FifteenMinutes); * * <p>Number of entries: If no veto policy has been created, the number of entries in the drop * down menu would be determined by the size of the increment as follows; FiveMinutes has 288 * entries. TenMinutes has 144 entries. FifteenMinutes has 96 entries. TwentyMinutes has 72 * entries. ThirtyMinutes has 48 entries. OneHour has 24 entries. */ public void generatePotentialMenuTimes( TimeIncrement timeIncrement, LocalTime optionalStartTime, LocalTime optionalEndTime) { // If either bounding time does does not already exist, then set it to the maximum range. LocalTime startTime = (optionalStartTime == null) ? LocalTime.MIN : optionalStartTime; LocalTime endTime = (optionalEndTime == null) ? LocalTime.MAX : optionalEndTime; // Initialize our needed variables. potentialMenuTimes = new ArrayList<>(); int increment = timeIncrement.minutes; // Start at midnight, which is the earliest time of day for LocalTime values. LocalTime entry = LocalTime.MIDNIGHT; boolean continueLoop = true; while (continueLoop) { if (PickerUtilities.isLocalTimeInRange(entry, startTime, endTime, true)) { potentialMenuTimes.add(entry); } entry = entry.plusMinutes(increment); // Note: This stopping criteria works as long as as ((60 % increment) == 0). continueLoop = (!(LocalTime.MIDNIGHT.equals(entry))); } } /** * generatePotentialMenuTimes, This will generate the menu times for populating the combo box * menu, using the items from a list of LocalTime instances. The list will be sorted and cleaned * of duplicates before use. Null values and duplicate values will not be added. When this * function is complete, the menu will contain one instance of each unique LocalTime that was * supplied to this function, in ascending order going from Midnight to 11.59pm. The drop down * menu will not contain any time values except those supplied in the desiredTimes list. * * <p>Note: This function can be called before or after setting an optional veto policy. Vetoed * times will never be added to the time picker menu, regardless of whether they are generated by * this function. */ public void generatePotentialMenuTimes(ArrayList<LocalTime> desiredTimes) { potentialMenuTimes = new ArrayList<>(); if (desiredTimes == null || desiredTimes.isEmpty()) { return; } TreeSet<LocalTime> timeSet = new TreeSet<>(); for (LocalTime desiredTime : desiredTimes) { if (desiredTime != null) { timeSet.add(desiredTime); } } potentialMenuTimes.addAll(timeSet); } /** * getAllowEmptyTimes, Returns the value of this setting. See the "set" function for setting * information. */ public boolean getAllowEmptyTimes() { return allowEmptyTimes; } /** * getAllowKeyboardEditing, Returns the value of this setting. See the "set" function for setting * information. */ public boolean getAllowKeyboardEditing() { return allowKeyboardEditing; } /** getClock, Returns the currently set clock */ public Clock getClock() { return clock; } /** getColor, This returns the currently set color for the specified area. */ public Color getColor(TimeArea area) { return colors.get(area); } /** * getDisplaySpinnerButtons, Returns the value of this setting. See the "set" function for setting * information. */ public boolean getDisplaySpinnerButtons() { return displaySpinnerButtons; } /** * getDisplayToggleTimeMenuButton, Returns the value of this setting. See the "set" function for * setting information. */ public boolean getDisplayToggleTimeMenuButton() { return displayToggleTimeMenuButton; } /** * getFormatForDisplayTime, Returns the value this setting. See the "set" function for setting * information. */ public DateTimeFormatter getFormatForDisplayTime() { return formatForDisplayTime; } /** * getFormatForMenuTimes, Returns the value this setting. See the "set" function for setting * information. */ public DateTimeFormatter getFormatForMenuTimes() { return formatForMenuTimes; } /** * getGapBeforeButtonPixels, Returns the value of this setting. See the "set" function for setting * information. */ public Integer getGapBeforeButtonPixels() { return gapBeforeButtonPixels; } /** * getLocale, This returns locale setting of the time picker. The locale can only be set in the * TimePickerSettings constructor. */ public Locale getLocale() { return locale; } /** * getMinimumSpinnerButtonWidthInPixels, This returns the minimum width of the spinner buttons. */ public int getMinimumSpinnerButtonWidthInPixels() { return minimumSpinnerButtonWidthInPixels; } /** * getMinimumSpinnerButtonWidthInPixels, This returns the minimum width of the toggle menu button. */ public int getMinimumToggleTimeMenuButtonWidthInPixels() { return minimumToggleTimeMenuButtonWidthInPixels; } /** * getPotentialMenuTimes, This returns a copy of the list of potential menu times. For additional * details, see TimePickerSettings.potentialMenuTimes. */ public ArrayList<LocalTime> getPotentialMenuTimes() { return new ArrayList<>(potentialMenuTimes); } /** * getSizeTextFieldMinimumWidth, Returns the value of this setting. See the "set" function for * setting information. */ public Integer getSizeTextFieldMinimumWidth() { return sizeTextFieldMinimumWidth; } /** * getSizeTextFieldMinimumWidthDefaultOverride, Returns the value of this setting. See the "set" * function for setting information. */ public boolean getSizeTextFieldMinimumWidthDefaultOverride() { return sizeTextFieldMinimumWidthDefaultOverride; } /** getVetoPolicy, This returns the veto policy. */ public TimeVetoPolicy getVetoPolicy() { return vetoPolicy; } /** * isTimeAllowed, This checks to see if the specified time is allowed by any currently set veto * policy, and allowed by the current setting of allowEmptyTimes. * * <p>If allowEmptyTimes is false, and the specified time is null, then this returns false. * * <p>If a veto policy exists, and the specified time is vetoed, then this returns false. * * <p>If the time is not vetoed, or if empty times are allowed and the time is null, then this * returns true. */ public boolean isTimeAllowed(LocalTime time) { if (time == null) { return allowEmptyTimes; } return (!(InternalUtilities.isTimeVetoed(vetoPolicy, time))); } /** * setAllowEmptyTimes, This sets whether or not empty times (null times) are allowed in the time * picker. If this is true, then empty times will be allowed in the time picker. If this is false, * then empty times will not be allowed. * * <p>If setting this function to false, it is recommended to call this function -before- setting * a veto policy. This sequence will guarantee that the TimePicker.getTime() function will never * return a null value, and will guarantee that the setAllowEmptyTimes() function will not throw * an exception. * * <p>If the current time is null and you set allowEmptyTimes to false, then this function will * attempt to initialize the current time to 7am. This function will throw an exception if it * fails to initialize a null time. An exception is only possible if a veto policy is set before * calling this function, and the veto policy vetoes the time "7:00 am". */ public void setAllowEmptyTimes(boolean allowEmptyTimes) { this.allowEmptyTimes = allowEmptyTimes; if (parent != null) { zApplyAllowEmptyTimes(); } } /** * setAllowKeyboardEditing, This sets whether or not keyboard editing is allowed for this time * picker. If this is true, then times can be entered into the time picker either by using the * keyboard or the mouse. If this is false, then times can only be selected by using the mouse. * The default value is true. It is generally recommended to leave this setting as "true". * * <p>Accessibility Impact: Disallowing the use of the keyboard, and requiring the use of the * mouse, could impact the accessibility of your program for disabled persons. * * <p>Note: This setting does not impact the automatic enforcement of valid or vetoed times. To * learn about the automatic time validation and enforcement for keyboard entered text, see the * javadocs for the TimePicker class. */ public void setAllowKeyboardEditing(boolean allowKeyboardEditing) { this.allowKeyboardEditing = allowKeyboardEditing; if (parent != null) { zApplyAllowKeyboardEditing(); } } /** * setClock, This sets the clock to use for determining the current date. By default the system * clock is used. * * @param clock A clock to use */ public void setClock(Clock clock) { this.clock = clock; } /** * setColor, This sets a color for the specified area. Setting an area to null will restore the * default color for that area. */ public void setColor(TimeArea area, Color color) { // If null was supplied, then use the default color. if (color == null) { color = area.defaultColor; } // Save the color to the color map. colors.put(area, color); // Call any "updating functions" that are appropriate for the specified area. if (parent != null) { if (area == TimeArea.TimePickerTextDisabled) { zApplyDisabledTextColor(); } else { parent.zDrawTextFieldIndicators(); } } } /** * setDisplaySpinnerButtons, This sets whether or not the spinner buttons will be displayed (and * enabled), on the time picker. The default value is false. */ public void setDisplaySpinnerButtons(boolean displaySpinnerButtons) { this.displaySpinnerButtons = displaySpinnerButtons; zApplyDisplaySpinnerButtons(); } /** * setDisplayToggleTimeMenuButton, This sets whether or not the toggle menu button will be * displayed (and enabled), on the time picker. The default value is true. */ public void setDisplayToggleTimeMenuButton(boolean showToggleTimeMenuButton) { this.displayToggleTimeMenuButton = showToggleTimeMenuButton; zApplyDisplayToggleTimeMenuButton(); } public void setFormatForDisplayTime(DateTimeFormatter formatForDisplayTime) { this.formatForDisplayTime = formatForDisplayTime; if (parent != null) { parent.setTextFieldToValidStateIfNeeded(); } } public void setFormatForDisplayTime(String patternString) { DateTimeFormatter formatter = PickerUtilities.createFormatterFromPatternString(patternString, locale); setFormatForDisplayTime(formatter); } public void setFormatForMenuTimes(DateTimeFormatter formatForMenuTimes) { this.formatForMenuTimes = formatForMenuTimes; if (parent != null) { parent.setTextFieldToValidStateIfNeeded(); } } public void setFormatForMenuTimes(String patternString) { DateTimeFormatter formatter = PickerUtilities.createFormatterFromPatternString(patternString, locale); setFormatForMenuTimes(formatter); } /** * setGapBeforeButtonPixels, This specifies the desired width for the gap between the time picker * and the toggle menu button (in pixels). The default value is null. If this is left at null, * then the default value is 0 pixels. */ public void setGapBeforeButtonPixels(Integer gapBeforeButtonPixels) { this.gapBeforeButtonPixels = gapBeforeButtonPixels; if (parent != null) { zApplyGapBeforeButtonPixels(); } } /** * setInitialTimeToNow, This sets the initial time for the time picker to the current time. This * function only has an effect before the time picker is constructed. */ public void setInitialTimeToNow() { initialTime = LocalTime.now(clock); } /** setMinimumSpinnerButtonWidthInPixels, This sets the minimum width of the spinner buttons. */ public void setMinimumSpinnerButtonWidthInPixels(int pixels) { this.minimumSpinnerButtonWidthInPixels = pixels; zApplyMinimumSpinnerButtonWidthInPixels(); } /** * setMinimumToggleTimeMenuButtonWidthInPixels, This sets the minimum width of the toggle menu * button. */ public void setMinimumToggleTimeMenuButtonWidthInPixels(int pixels) { this.minimumToggleTimeMenuButtonWidthInPixels = pixels; zApplyMinimumToggleTimeMenuButtonWidthInPixels(); } /** * setParentTimePicker, This sets the parent time picker for these settings. This is only intended * to be called from the constructor of the time picker class. */ void setParentTimePicker(TimePicker parentTimePicker) { this.parent = parentTimePicker; } /** * setSizeTextFieldMinimumWidth, This sets the minimum width in pixels, of the TimePicker text * field. * * <p>The default value for this setting is null. When this is set to null, a default width for * the time picker text field will be automatically calculated and applied to fit "the largest * possible time" that can be displayed with the current time picker settings. The settings used * to calculate the default text field width include the locale (the language), the fontValidTime, * and the format for valid times. */ public void setSizeTextFieldMinimumWidth(Integer minimumWidthInPixels) { this.sizeTextFieldMinimumWidth = minimumWidthInPixels; if (parent != null) { parent.zSetAppropriateTextFieldMinimumWidth(); } } /** * setSizeTextFieldMinimumWidthDefaultOverride, This specifies how the time picker should choose * the appropriate minimum width for the time picker text field. (As described below.) * * <p>If this is true, then the applied minimum width will be the largest of either the default, * or any programmer supplied, minimum widths. * * <p>If this is false, then any programmer supplied minimum width will always override the * default minimum width. (Even if the programmer supplied width is too small to fit the times * that can be displayed in the TimePicker). * * <p>The default value for this setting is true. This setting only has an effect if * (sizeTextFieldMinimumWidth != null). * * <p>See also: "sizeTextFieldMinimumWidth". */ public void setSizeTextFieldMinimumWidthDefaultOverride(boolean defaultShouldOverrideIfNeeded) { this.sizeTextFieldMinimumWidthDefaultOverride = defaultShouldOverrideIfNeeded; if (parent != null) { parent.zSetAppropriateTextFieldMinimumWidth(); } } /** * setVetoPolicy, * * <p>This sets a veto policy for the time picker. Note: This function can only be called after * the time picker is constructed. If this is called before the TimePicker is constructed, then an * exception will be thrown. * * <p>When a veto policy is supplied, it will be used to determine which times can or can not be * selected in the calendar panel. (Vetoed times are also not accepted into the time picker text * field). See the demo class for an example of constructing a veto policy. * * <p>By default, there is no veto policy on a time picker. Setting this function to null will * clear any veto policy that has been set. * * <p>It's possible to set a veto policy that vetoes the current "last valid time". This function * returns true if the last valid time is allowed by the new veto policy and the time picker * settings, or false if the last valid time is vetoed or disallowed. Setting a new veto policy * does not modify the last valid time. Is up to the programmer to resolve any potential conflict * between a new veto policy, and the last valid time stored in the time picker. */ public boolean setVetoPolicy(TimeVetoPolicy vetoPolicy) { if (parent == null) { throw new RuntimeException( "TimePickerSettings.setVetoPolicy(), " + "A veto policy can only be set after constructing the TimePicker."); } this.vetoPolicy = vetoPolicy; return isTimeAllowed(parent.getTime()); } /** * use24HourClockFormat, This can be called to set the TimePicker to use a 24-hour clock format. * This will replace the settings called formatForDisplayTime, and formatForMenuTimes, with the * commonly used 24-hour clock format ("HH:mm"). Any single digit hours will be zero padded in * this format. * * <p>Localization Note: It is not currently known if the 24 hour clock format is the same for all * locales. (Though it is considered likely that this format is the same in most places.) If this * format should be set to a different pattern for a particular locale that is familiar to you, * then please inform the developers. */ public void use24HourClockFormat() { formatForDisplayTime = PickerUtilities.createFormatterFromPatternString("HH:mm", locale); formatForMenuTimes = formatForDisplayTime; } /** * yApplyNeededSettingsAtTimePickerConstruction, This is called from the time picker constructor * to apply various settings in this settings instance to the time picker. Only the settings that * are needed at the time of time picker construction, are applied in this function. */ void yApplyNeededSettingsAtTimePickerConstruction() { // Run the needed "apply" functions. zApplyGapBeforeButtonPixels(); zApplyAllowKeyboardEditing(); zApplyInitialTime(); zApplyAllowEmptyTimes(); zApplyMinimumToggleTimeMenuButtonWidthInPixels(); zApplyMinimumSpinnerButtonWidthInPixels(); zApplyDisplayToggleTimeMenuButton(); zApplyDisplaySpinnerButtons(); zApplyDisabledTextColor(); } /** * zApplyAllowEmptyTimes, This applies the named setting to the parent component. * * <p>Notes: * * <p>The zApplyInitialTime() and zApplyAllowEmptyTimes() functions may theoretically be called in * any order. However, the order is currently zApplyInitialTime() and zApplyAllowEmptyTimes() * because that is more intuitive. * * <p>This cannot throw an exception while the time picker is being constructed, because a veto * policy cannot be set until after the time picker is constructed. */ private void zApplyAllowEmptyTimes() { // Find out if we need to initialize a null time. if ((!allowEmptyTimes) && (parent.getTime() == null)) { // We need to initialize the current time, so find out if the default time is vetoed. LocalTime defaultTime = LocalTime.of(7, 0); if (InternalUtilities.isTimeVetoed(vetoPolicy, defaultTime)) { throw new RuntimeException( "Exception in TimePickerSettings.zApplyAllowEmptyTimes(), " + "Could not initialize a null time to 7am, because 7am is vetoed by " + "the veto policy. To prevent this exception, always call " + "setAllowEmptyTimes() -before- setting a veto policy."); } // Initialize the current time. parent.setTime(defaultTime); } } /** zApplyAllowKeyboardEditing, This applies the named setting to the parent component. */ private void zApplyAllowKeyboardEditing() { // Set the editability of the time picker text field. parent.getComponentTimeTextField().setEditable(allowKeyboardEditing); // Set the text field border color based on whether the text field is editable. Color textFieldBorderColor = (allowKeyboardEditing) ? InternalConstants.colorEditableTextFieldBorder : InternalConstants.colorNotEditableTextFieldBorder; parent .getComponentTimeTextField() .setBorder( new CompoundBorder( new MatteBorder(1, 1, 1, 1, textFieldBorderColor), new EmptyBorder(1, 3, 2, 2))); } /** zApplyDisplaySpinnerButtons, This applies the specified setting to the time picker. */ void zApplyDisplaySpinnerButtons() { if (parent == null) { return; } parent.getComponentDecreaseSpinnerButton().setEnabled(displaySpinnerButtons); parent.getComponentDecreaseSpinnerButton().setVisible(displaySpinnerButtons); parent.getComponentIncreaseSpinnerButton().setEnabled(displaySpinnerButtons); parent.getComponentIncreaseSpinnerButton().setVisible(displaySpinnerButtons); } /** zApplyDisplayToggleTimeMenuButton, This applies the specified setting to the time picker. */ void zApplyDisplayToggleTimeMenuButton() { if (parent == null) { return; } parent.getComponentToggleTimeMenuButton().setEnabled(displayToggleTimeMenuButton); parent.getComponentToggleTimeMenuButton().setVisible(displayToggleTimeMenuButton); } /** zApplyGapBeforeButtonPixels, This applies the named setting to the parent component. */ private void zApplyGapBeforeButtonPixels() { int gapPixels = (gapBeforeButtonPixels == null) ? 0 : gapBeforeButtonPixels; ConstantSize gapSizeObject = new ConstantSize(gapPixels, ConstantSize.PIXEL); ColumnSpec columnSpec = ColumnSpec.createGap(gapSizeObject); FormLayout layout = ((FormLayout) parent.getLayout()); layout.setColumnSpec(2, columnSpec); } /** * zApplyInitialTime, This applies the named setting to the parent component. * * <p>Notes: * * <p>This does not need to check the parent for null, because this is always and only called * while the time picker is being constructed. * * <p>This does not need to handle (allowEmptyTimes == false && initialTime == null). That * situation is handled by the zApplyAllowEmptyTimes() function. * * <p>There is no possibility that this can conflict with a veto policy at the time that it is * set, because a veto policy cannot be set until after the construction of a time picker. * * <p>The zApplyInitialTime() and zApplyAllowEmptyTimes() functions may theoretically be called in * any order. However, the order is currently zApplyInitialTime() and zApplyAllowEmptyTimes() * because that is more intuitive. */ private void zApplyInitialTime() { if (allowEmptyTimes == true && initialTime == null) { parent.setTime(null); } if (initialTime != null) { parent.setTime(initialTime); } } /** * zApplyMinimumSpinnerButtonWidthInPixels, The applies the specified setting to the time picker. */ void zApplyMinimumSpinnerButtonWidthInPixels() { if (parent == null) { return; } Dimension decreaseButtonPreferredSize = parent.getComponentDecreaseSpinnerButton().getPreferredSize(); Dimension increaseButtonPreferredSize = parent.getComponentIncreaseSpinnerButton().getPreferredSize(); int width = Math.max(decreaseButtonPreferredSize.width, increaseButtonPreferredSize.width); int height = Math.max(decreaseButtonPreferredSize.height, increaseButtonPreferredSize.height); int minimumWidth = minimumSpinnerButtonWidthInPixels; width = (width < minimumWidth) ? minimumWidth : width; Dimension newSize = new Dimension(width, height); parent.getComponentDecreaseSpinnerButton().setPreferredSize(newSize); parent.getComponentIncreaseSpinnerButton().setPreferredSize(newSize); } /** * zApplyMinimumToggleTimeMenuButtonWidthInPixels, This applies the specified setting to the time * picker. */ void zApplyMinimumToggleTimeMenuButtonWidthInPixels() { if (parent == null) { return; } Dimension menuButtonPreferredSize = parent.getComponentToggleTimeMenuButton().getPreferredSize(); int width = menuButtonPreferredSize.width; int height = menuButtonPreferredSize.height; int minimumWidth = minimumToggleTimeMenuButtonWidthInPixels; width = (width < minimumWidth) ? minimumWidth : width; Dimension newSize = new Dimension(width, height); parent.getComponentToggleTimeMenuButton().setPreferredSize(newSize); } void zApplyDisabledTextColor() { parent .getComponentTimeTextField() .setDisabledTextColor(getColor(TimeArea.TimePickerTextDisabled)); } /** * TimeIncrement, This is a list of increments that can be used with the generateMenuTimes() * function. */ public enum TimeIncrement { FiveMinutes(5), TenMinutes(10), FifteenMinutes(15), TwentyMinutes(20), ThirtyMinutes(30), OneHour(60); /** minutes, This holds the number of minutes represented by the time increment. */ public final int minutes; /** Constructor. This takes the number of minutes represented by the time increment. */ TimeIncrement(int minutes) { this.minutes = minutes; if ((60 % minutes) != 0) { throw new RuntimeException( "TimePickerSettings.TimeIncrement Constructor, " + "All time increments must divide evenly into 60."); } } } }
package beast.evolution.operators; import java.text.DecimalFormat; import beast.core.Distribution; import beast.core.Evaluator; import beast.core.Description; import beast.core.Input; import beast.core.Input.Validate; import beast.core.Operator; import beast.core.parameter.RealParameter; import beast.util.Randomizer; @Description("A random walk operator that selects a random dimension of the real parameter and perturbs the value a " + "random amount within +/- windowSize.") public class SliceOperator extends Operator { public Input<RealParameter> parameterInput = new Input<RealParameter>("parameter", "the parameter to operate a random walk on.", Validate.REQUIRED); public Input<Double> windowSizeInput = new Input<Double>("windowSize", "the size of the step for finding the slice boundaries", Input.Validate.REQUIRED); public Input<Distribution> sliceDensityInput = new Input<Distribution>("sliceDensity", "The density to sample from using slice sampling.", Input.Validate.REQUIRED); Double totalDelta; int totalNumber; int n_learning_iterations; double W; double windowSize = 1; Distribution g; public void initAndValidate() { totalDelta = 0.0; totalNumber = 0; n_learning_iterations = 100; W=0.0; windowSize = windowSizeInput.get(); g = sliceDensityInput.get(); } boolean in_range(RealParameter X, double x) { return (X.getLower() < x && x < X.getUpper()); } boolean below_lower_bound(RealParameter X, double x) { return (x < X.getLower()); } boolean above_upper_bound(RealParameter X, double x) { return (x > X.getUpper()); } public Distribution getEvaluatorDistribution() { return g; } Double evaluate(Evaluator E) { return E.evaluate(); } Double evaluate(Evaluator E, RealParameter X, double x) { X.setValue(0,x); return evaluate(E); } Double[] find_slice_boundaries_stepping_out(Evaluator E, RealParameter X, double logy, double w,int m) { double x0 = X.getValue(0); assert in_range(X,x0); double u = Randomizer.nextDouble()*w; Double L = x0 - u; Double R = x0 + (w-u); // Expand the interval until its ends are outside the slice, or until // the limit on steps is reached. if (m>1) { int J = (int)Math.floor(Randomizer.nextDouble()*m); int K = (m-1)-J; while (J>0 && (!below_lower_bound(X,L)) && evaluate(E,X,L)>logy) { L -= w; J } while (K>0 && (!above_upper_bound(X,R)) && evaluate(E,X,R)>logy) { R += w; K } } else { while ((!below_lower_bound(X,L)) && evaluate(E,X,L)>logy) L -= w; while ((!above_upper_bound(X,R)) && evaluate(E,X,R)>logy) R += w; } // Shrink interval to lower and upper bounds. if (below_lower_bound(X,L)) L = X.getLower(); if (above_upper_bound(X,R)) R = X.getUpper(); assert L < R; Double[] range = {L,R}; return range; } // Does this x0 really need to be the original point? // I think it just serves to let you know which way the interval gets shrunk... double search_interval(Evaluator E, double x0, RealParameter X, Double L, Double R, double logy) { // assert evaluate(E,x0) > evaluate(E,L) && evaluate(E,x0) > evaluate(E,R); assert evaluate(E,X,x0) >= logy; assert L < R; assert L <= x0 && x0 <= R; double L0 = L, R0 = R; double gx0 = evaluate(E,X,x0); assert logy < gx0; double x1 = x0; for(int i=0;i<200;i++) { x1 = L + Randomizer.nextDouble()*(R-L); double gx1 = evaluate(E,X,x1); // System.err.println(" L0 = " + L0 + " x0 = " + x0 + " R0 = " + R0 + " gx0 = " + gx0); // System.err.println(" L = " + L + " x1 = " + x1 + " R = " + R0 + " gx1 = " + gx1); // System.err.println(" logy = " + logy); if (gx1 >= logy) return x1; if (x1 > x0) R = x1; else L = x1; } System.err.println("Warning! Is size of the interval really ZERO?"); // double logy_x0 = evaluate(E,X,x0); System.err.println(" L0 = " + L0 + " x0 = " + x0 + " R0 = " + R0 + " gx0 = " + gx0); System.err.println(" L = " + L + " x1 = " + x1 + " R = " + R0 + " gx1 = " + evaluate(E)); return x0; } @Override public double proposal() { return 0; } /** * override this for proposals, * returns log of hastingRatio, or Double.NEGATIVE_INFINITY if proposal should not be accepted * */ @Override public double proposal(Evaluator E) { int m = 100; RealParameter X = parameterInput.get(); // Find the density at the current point Double gx0 = evaluate(E); // System.err.println("gx0 = " + gx0); // Get the 1st element Double x0 = X.getValue(0); // System.err.println("x0 = " + x0); // Determine the slice level, in log terms. double logy = gx0 - Randomizer.nextExponential(1); // Find the initial interval to sample from. Double[] range = find_slice_boundaries_stepping_out(E, X, logy, windowSize, m); Double L=range[0]; Double R=range[1]; // Sample from the interval, shrinking it on each rejection double x_new = search_interval(E, x0, X, L, R, logy); X.setValue(x_new); if (n_learning_iterations > 0) { n_learning_iterations totalDelta += Math.abs(x_new - x0); totalNumber++; double W_predicted = totalDelta/totalNumber*4.0; if (totalNumber > 3) { W = 0.95*W + 0.05*W_predicted; windowSize = W; } // System.err.println("W = " + W); } return Double.POSITIVE_INFINITY; } @Override public double getCoercableParameterValue() { return windowSize; } @Override public void setCoercableParameterValue(double fValue) { windowSize = fValue; } /** * called after every invocation of this operator to see whether * a parameter can be optimised for better acceptance hence faster * mixing * * @param logAlpha difference in posterior between previous state & proposed state + hasting ratio */ @Override public void optimize(double logAlpha) { // must be overridden by operator implementation to have an effect double fDelta = calcDelta(logAlpha); fDelta += Math.log(windowSize); windowSize = Math.exp(fDelta); } @Override public final String getPerformanceSuggestion() { // new scale factor double newWindowSize = totalDelta/totalNumber * 4; if (newWindowSize/windowSize < 0.8 || newWindowSize/windowSize > 1.2) { DecimalFormat formatter = new DecimalFormat(" return "Try setting window size to about " + formatter.format(newWindowSize); } else return ""; } } // class IntRandomWalkOperator
package com.battlelancer.seriesguide.ui; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.Loader; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.PopupMenu; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; import com.battlelancer.seriesguide.R; import com.battlelancer.seriesguide.SgApp; import com.battlelancer.seriesguide.adapters.MoviesAdapter; import com.battlelancer.seriesguide.adapters.MoviesDiscoverAdapter; import com.battlelancer.seriesguide.enums.MoviesDiscoverLink; import com.battlelancer.seriesguide.loaders.TmdbMoviesLoader; import com.battlelancer.seriesguide.provider.SeriesGuideContract; import com.battlelancer.seriesguide.util.AutoGridLayoutManager; import com.battlelancer.seriesguide.util.MovieTools; import com.battlelancer.seriesguide.util.Utils; import com.battlelancer.seriesguide.widgets.EmptyView; import com.battlelancer.seriesguide.widgets.EmptyViewSwipeRefreshLayout; /** * Integrates with a search interface and displays movies based on query results. Can pre-populate * the displayed movies based on a sent link. */ public class MoviesSearchFragment extends Fragment { public interface OnSearchClickListener { void onSearchClick(); } private static final String ARG_SEARCH_QUERY = "search_query"; private static final String ARG_ID_LINK = "linkId"; @BindView(R.id.swipeRefreshLayoutMoviesSearch) EmptyViewSwipeRefreshLayout swipeRefreshLayout; @BindView(R.id.recyclerViewMoviesSearch) RecyclerView recyclerView; @BindView(R.id.emptyViewMoviesSearch) EmptyView emptyView; @Nullable private MoviesDiscoverLink link; private OnSearchClickListener searchClickListener; private MoviesAdapter adapter; private Unbinder unbinder; public static MoviesSearchFragment newInstance(@NonNull MoviesDiscoverLink link) { MoviesSearchFragment f = new MoviesSearchFragment(); Bundle args = new Bundle(); args.putInt(ARG_ID_LINK, link.id); f.setArguments(args); return f; } @Override public void onAttach(Context context) { super.onAttach(context); try { searchClickListener = (OnSearchClickListener) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString() + " must implement OnSearchClickListener"); } } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); link = MoviesDiscoverLink.fromId(getArguments().getInt(ARG_ID_LINK)); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_movies_search, container, false); unbinder = ButterKnife.bind(this, v); swipeRefreshLayout.setSwipeableChildren(R.id.scrollViewMoviesSearch, R.id.recyclerViewMoviesSearch); swipeRefreshLayout.setOnRefreshListener(onRefreshListener); Utils.setSwipeRefreshLayoutColors(getActivity().getTheme(), swipeRefreshLayout); // setup grid view AutoGridLayoutManager layoutManager = new AutoGridLayoutManager(getContext(), R.dimen.movie_grid_columnWidth, 1, 1); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(layoutManager); // setup empty view button emptyView.setButtonClickListener(new OnClickListener() { @Override public void onClick(View v) { searchClickListener.onSearchClick(); } }); return v; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // setup adapter adapter = new MoviesAdapter(getContext(), new MovieItemClickListener(getActivity())); recyclerView.setAdapter(adapter); swipeRefreshLayout.setRefreshing(true); getLoaderManager().initLoader(MoviesActivity.SEARCH_LOADER_ID, buildLoaderArgs(null), searchLoaderCallbacks); } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } @NonNull private Bundle buildLoaderArgs(@Nullable String query) { Bundle args = new Bundle(); args.putInt(ARG_ID_LINK, link == null ? -1 : link.id); args.putString(ARG_SEARCH_QUERY, query); return args; } public void search(String query) { if (!swipeRefreshLayout.isRefreshing()) { swipeRefreshLayout.setRefreshing(true); } getLoaderManager().restartLoader(MoviesActivity.SEARCH_LOADER_ID, buildLoaderArgs(query), searchLoaderCallbacks); } private LoaderCallbacks<TmdbMoviesLoader.Result> searchLoaderCallbacks = new LoaderCallbacks<TmdbMoviesLoader.Result>() { @Override public Loader<TmdbMoviesLoader.Result> onCreateLoader(int id, Bundle args) { MoviesDiscoverLink link = MoviesDiscoverAdapter.DISCOVER_LINK_DEFAULT; String query = null; if (args != null) { link = MoviesDiscoverLink.fromId(args.getInt(ARG_ID_LINK)); query = args.getString(ARG_SEARCH_QUERY); } return new TmdbMoviesLoader(SgApp.from(getActivity()), link, query); } @Override public void onLoadFinished(Loader<TmdbMoviesLoader.Result> loader, TmdbMoviesLoader.Result data) { if (!isAdded()) { return; } emptyView.setMessage(data.emptyText); boolean hasNoResults = data.results == null || data.results.size() == 0; emptyView.setVisibility(hasNoResults ? View.VISIBLE : View.GONE); recyclerView.setVisibility(hasNoResults ? View.GONE : View.VISIBLE); adapter.updateMovies(data.results); swipeRefreshLayout.setRefreshing(false); } @Override public void onLoaderReset(Loader<TmdbMoviesLoader.Result> loader) { adapter.updateMovies(null); } }; private SwipeRefreshLayout.OnRefreshListener onRefreshListener = new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { searchClickListener.onSearchClick(); } }; public static class MovieItemClickListener implements MoviesAdapter.ItemClickListener { private Activity activity; public MovieItemClickListener(Activity activity) { this.activity = activity; } public Activity getActivity() { return activity; } @Override public void onClickMovie(int movieTmdbId, ImageView posterView) { // launch details activity Intent intent = new Intent(getActivity(), MovieDetailsActivity.class); intent.putExtra(MovieDetailsFragment.InitBundle.TMDB_ID, movieTmdbId); // transition poster Utils.startActivityWithTransition(getActivity(), intent, posterView, R.string.transitionNameMoviePoster); } @Override public void onClickMovieMoreOptions(final int movieTmdbId, View anchor) { PopupMenu popupMenu = new PopupMenu(anchor.getContext(), anchor); popupMenu.inflate(R.menu.movies_popup_menu); // check if movie is already in watchlist or collection boolean isInWatchlist = false; boolean isInCollection = false; Cursor movie = getActivity().getContentResolver().query( SeriesGuideContract.Movies.buildMovieUri(movieTmdbId), new String[] { SeriesGuideContract.Movies.IN_WATCHLIST, SeriesGuideContract.Movies.IN_COLLECTION }, null, null, null ); if (movie != null) { if (movie.moveToFirst()) { isInWatchlist = movie.getInt(0) == 1; isInCollection = movie.getInt(1) == 1; } movie.close(); } Menu menu = popupMenu.getMenu(); menu.findItem(R.id.menu_action_movies_watchlist_add).setVisible(!isInWatchlist); menu.findItem(R.id.menu_action_movies_watchlist_remove).setVisible(isInWatchlist); menu.findItem(R.id.menu_action_movies_collection_add).setVisible(!isInCollection); menu.findItem(R.id.menu_action_movies_collection_remove).setVisible(isInCollection); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.menu_action_movies_watchlist_add: { MovieTools.addToWatchlist(SgApp.from(getActivity()), movieTmdbId); return true; } case R.id.menu_action_movies_watchlist_remove: { MovieTools.removeFromWatchlist(SgApp.from(getActivity()), movieTmdbId); return true; } case R.id.menu_action_movies_collection_add: { MovieTools.addToCollection(SgApp.from(getActivity()), movieTmdbId); return true; } case R.id.menu_action_movies_collection_remove: { MovieTools.removeFromCollection(SgApp.from(getActivity()), movieTmdbId); return true; } } return false; } }); popupMenu.show(); } } }
package com.hubspot.singularity; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.inject.name.Names.named; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import javax.inject.Inject; import javax.inject.Provider; import javax.servlet.http.HttpServletRequest; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.leader.LeaderLatch; import org.apache.curator.framework.recipes.leader.LeaderLatchListener; import org.apache.curator.framework.state.ConnectionStateListener; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.s3.AmazonS3Client; import com.codahale.metrics.Meter; import com.codahale.metrics.MetricRegistry; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import com.google.common.net.HostAndPort; import com.google.inject.Binder; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.Provides; import com.google.inject.ProvisionException; import com.google.inject.Scopes; import com.google.inject.Singleton; import com.google.inject.multibindings.Multibinder; import com.google.inject.name.Named; import com.google.inject.name.Names; import com.hubspot.mesos.JavaUtils; import com.hubspot.singularity.config.CustomExecutorConfiguration; import com.hubspot.singularity.config.HistoryPurgingConfiguration; import com.hubspot.singularity.config.MesosConfiguration; import com.hubspot.singularity.config.S3Configuration; import com.hubspot.singularity.config.S3GroupConfiguration; import com.hubspot.singularity.config.SMTPConfiguration; import com.hubspot.singularity.config.SentryConfiguration; import com.hubspot.singularity.config.SingularityConfiguration; import com.hubspot.singularity.config.SingularityTaskMetadataConfiguration; import com.hubspot.singularity.config.UIConfiguration; import com.hubspot.singularity.config.ZooKeeperConfiguration; import com.hubspot.singularity.guice.DropwizardMetricRegistryProvider; import com.hubspot.singularity.helpers.SingularityS3Service; import com.hubspot.singularity.helpers.SingularityS3Services; import com.hubspot.singularity.hooks.AbstractWebhookChecker; import com.hubspot.singularity.hooks.LoadBalancerClient; import com.hubspot.singularity.hooks.LoadBalancerClientImpl; import com.hubspot.singularity.hooks.SingularityWebhookPoller; import com.hubspot.singularity.hooks.SingularityWebhookSender; import com.hubspot.singularity.hooks.SnsWebhookManager; import com.hubspot.singularity.hooks.SnsWebhookRetryer; import com.hubspot.singularity.hooks.WebhookQueueType; import com.hubspot.singularity.managed.SingularityLifecycleManaged; import com.hubspot.singularity.mesos.OfferCache; import com.hubspot.singularity.mesos.SingularityMesosStatusUpdateHandler; import com.hubspot.singularity.mesos.SingularityNoOfferCache; import com.hubspot.singularity.mesos.SingularityOfferCache; import com.hubspot.singularity.metrics.SingularityGraphiteReporter; import com.hubspot.singularity.resources.SingularityServiceUIModule; import com.hubspot.singularity.scheduler.SingularityLeaderOnlyPoller; import com.hubspot.singularity.scheduler.SingularityUsageHelper; import com.hubspot.singularity.sentry.NotifyingExceptionMapper; import com.hubspot.singularity.sentry.SingularityExceptionNotifier; import com.hubspot.singularity.sentry.SingularityExceptionNotifierManaged; import com.hubspot.singularity.smtp.MailTemplateHelpers; import com.hubspot.singularity.smtp.NoopMailer; import com.hubspot.singularity.smtp.SingularityMailRecordCleaner; import com.hubspot.singularity.smtp.SingularityMailer; import com.hubspot.singularity.smtp.SingularitySmtpSender; import com.hubspot.singularity.smtp.SmtpMailer; import com.ning.http.client.AsyncHttpClient; import de.neuland.jade4j.JadeConfiguration; import de.neuland.jade4j.template.ClasspathTemplateLoader; import de.neuland.jade4j.template.JadeTemplate; import io.dropwizard.jetty.ConnectorFactory; import io.dropwizard.jetty.HttpConnectorFactory; import io.dropwizard.jetty.HttpsConnectorFactory; import io.dropwizard.server.DefaultServerFactory; import io.dropwizard.server.SimpleServerFactory; import okhttp3.OkHttpClient; public class SingularityMainModule implements Module { public static final String TASK_TEMPLATE = "task.template"; public static final String REQUEST_IN_COOLDOWN_TEMPLATE = "request.in.cooldown.template"; public static final String REQUEST_MODIFIED_TEMPLATE = "request.modified.template"; public static final String RATE_LIMITED_TEMPLATE = "rate.limited.template"; public static final String DISASTERS_TEMPLATE = "disasters.template"; public static final String REPLACEMENT_TASKS_FAILING_TEMPLATE = "replacement.tasks.failing.template"; public static final String SERVER_ID_PROPERTY = "singularity.server.id"; public static final String HOST_NAME_PROPERTY = "singularity.host.name"; public static final String HTTP_HOST_AND_PORT = "http.host.and.port"; public static final String CURRENT_HTTP_REQUEST = "_singularity_current_http_request"; public static final String LOST_TASKS_METER = "singularity.lost.tasks.meter"; public static final String STATUS_UPDATE_DELTA_30S_AVERAGE = "singularity.status.update.delta.minute.average"; public static final String STATUS_UPDATE_DELTAS = "singularity.status.update.deltas"; public static final String LAST_MESOS_MASTER_HEARTBEAT_TIME = "singularity.last.mesos.master.heartbeat.time"; private final SingularityConfiguration configuration; public SingularityMainModule(final SingularityConfiguration configuration) { this.configuration = configuration; } @Override public void configure(Binder binder) { binder.bind(HostAndPort.class).annotatedWith(named(HTTP_HOST_AND_PORT)).toProvider(SingularityHostAndPortProvider.class).in(Scopes.SINGLETON); binder.bind(LeaderLatch.class).to(SingularityLeaderLatch.class).in(Scopes.SINGLETON); binder.bind(CuratorFramework.class).toProvider(SingularityCuratorProvider.class).in(Scopes.SINGLETON); Multibinder<ConnectionStateListener> connectionStateListeners = Multibinder.newSetBinder(binder, ConnectionStateListener.class); connectionStateListeners.addBinding().to(SingularityAbort.class).in(Scopes.SINGLETON); Multibinder<LeaderLatchListener> leaderLatchListeners = Multibinder.newSetBinder(binder, LeaderLatchListener.class); leaderLatchListeners.addBinding().to(SingularityLeaderController.class).in(Scopes.SINGLETON); binder.bind(SingularityLeaderController.class).in(Scopes.SINGLETON); if (configuration.getSmtpConfigurationOptional().isPresent()) { binder.bind(SingularityMailer.class).to(SmtpMailer.class).in(Scopes.SINGLETON); } else { binder.bind(SingularityMailer.class).toInstance(NoopMailer.getInstance()); } binder.bind(SingularitySmtpSender.class).in(Scopes.SINGLETON); binder.bind(MailTemplateHelpers.class).in(Scopes.SINGLETON); binder.bind(SingularityExceptionNotifier.class).in(Scopes.SINGLETON); binder.bind(LoadBalancerClient.class).to(LoadBalancerClientImpl.class).in(Scopes.SINGLETON); binder.bind(SingularityMailRecordCleaner.class).in(Scopes.SINGLETON); binder.bind(SingularityWebhookPoller.class).in(Scopes.SINGLETON); binder.bind(SingularityAbort.class).in(Scopes.SINGLETON); binder.bind(SingularityExceptionNotifierManaged.class).in(Scopes.SINGLETON); if (configuration.getWebhookQueueConfiguration().getQueueType() == WebhookQueueType.SNS) { binder.bind(SnsWebhookManager.class).in(Scopes.SINGLETON); binder.bind(AbstractWebhookChecker.class).to(SnsWebhookRetryer.class).in(Scopes.SINGLETON); } else { binder.bind(AbstractWebhookChecker.class).to(SingularityWebhookSender.class).in(Scopes.SINGLETON); } binder.bind(SingularityUsageHelper.class).in(Scopes.SINGLETON); binder.bind(NotifyingExceptionMapper.class).in(Scopes.SINGLETON); binder.bind(MetricRegistry.class).toProvider(DropwizardMetricRegistryProvider.class).in(Scopes.SINGLETON); binder.bind(AsyncHttpClient.class).to(SingularityAsyncHttpClient.class).in(Scopes.SINGLETON); binder.bind(OkHttpClient.class).to(SingularityOkHttpClient.class).in(Scopes.SINGLETON); binder.bind(ServerProvider.class).in(Scopes.SINGLETON); binder.bind(SingularityDropwizardHealthcheck.class).in(Scopes.SINGLETON); binder.bindConstant().annotatedWith(Names.named(SERVER_ID_PROPERTY)).to(UUID.randomUUID().toString()); binder.bind(SingularityManagedScheduledExecutorServiceFactory.class).in(Scopes.SINGLETON); binder.bind(SingularityManagedCachedThreadPoolFactory.class).in(Scopes.SINGLETON); binder.bind(SingularityGraphiteReporter.class).in(Scopes.SINGLETON); binder.bind(SingularityMesosStatusUpdateHandler.class).in(Scopes.SINGLETON); binder.bind(SingularityLifecycleManaged.class).asEagerSingleton(); if (configuration.isCacheOffers()) { binder.bind(OfferCache.class).to(SingularityOfferCache.class).in(Scopes.SINGLETON); } else { binder.bind(OfferCache.class).to(SingularityNoOfferCache.class).in(Scopes.SINGLETON); } } @Provides @Named(HOST_NAME_PROPERTY) @Singleton public String getHostname(final SingularityConfiguration configuration) { if (configuration.getHostname().isPresent()) { return configuration.getHostname().get(); } try { InetAddress addr = InetAddress.getLocalHost(); return addr.getHostName(); } catch (UnknownHostException e) { throw new RuntimeException("No local hostname found, unable to start without functioning local networking (or configured hostname)", e); } } public static class SingularityHostAndPortProvider implements Provider<HostAndPort> { private final String hostname; private final int httpPort; @Inject SingularityHostAndPortProvider(final SingularityConfiguration configuration, @Named(HOST_NAME_PROPERTY) String hostname) { checkNotNull(configuration, "configuration is null"); this.hostname = configuration.getHostname().orElse(hostname); Integer port = null; if (configuration.getServerFactory() instanceof SimpleServerFactory) { SimpleServerFactory simpleServerFactory = (SimpleServerFactory) configuration.getServerFactory(); HttpConnectorFactory httpFactory = (HttpConnectorFactory) simpleServerFactory.getConnector(); port = httpFactory.getPort(); } else { DefaultServerFactory defaultServerFactory = (DefaultServerFactory) configuration.getServerFactory(); for (ConnectorFactory connectorFactory : defaultServerFactory.getApplicationConnectors()) { // Currently we will default to needing an http connector for service -> service communication if (connectorFactory instanceof HttpConnectorFactory && !(connectorFactory instanceof HttpsConnectorFactory)) { HttpConnectorFactory httpFactory = (HttpConnectorFactory) connectorFactory; port = httpFactory.getPort(); } } } if (port == null) { throw new RuntimeException("Could not determine http port"); } this.httpPort = port; } @Override public HostAndPort get() { return HostAndPort.fromParts(hostname, httpPort); } } @Provides @Named(SingularityServiceUIModule.SINGULARITY_URI_BASE) String getSingularityUriBase(final SingularityConfiguration configuration) { final String singularityUiPrefix; if (configuration.getServerFactory() instanceof SimpleServerFactory) { singularityUiPrefix = configuration.getUiConfiguration().getBaseUrl().orElse(((SimpleServerFactory) configuration.getServerFactory()).getApplicationContextPath()); } else { singularityUiPrefix = configuration.getUiConfiguration().getBaseUrl().orElse(((DefaultServerFactory) configuration.getServerFactory()).getApplicationContextPath()); } return (singularityUiPrefix.endsWith("/")) ? singularityUiPrefix.substring(0, singularityUiPrefix.length() - 1) : singularityUiPrefix; } @Provides @Singleton public ZooKeeperConfiguration zooKeeperConfiguration(final SingularityConfiguration config) { return config.getZooKeeperConfiguration(); } @Provides @Singleton public Optional<SentryConfiguration> sentryConfiguration(final SingularityConfiguration config) { return config.getSentryConfigurationOptional(); } @Provides @Singleton public SingularityTaskMetadataConfiguration taskMetadataConfiguration(SingularityConfiguration config) { return config.getTaskMetadataConfiguration(); } @Provides @Singleton public SingularityS3Services provideS3Services(Optional<S3Configuration> config) { if (!config.isPresent()) { return new SingularityS3Services(); } final ImmutableList.Builder<SingularityS3Service> s3ServiceBuilder = ImmutableList.builder(); for (Map.Entry<String, S3GroupConfiguration> entry : config.get().getGroupOverrides().entrySet()) { s3ServiceBuilder.add(new SingularityS3Service(entry.getKey(), entry.getValue().getS3Bucket(), new AmazonS3Client(new BasicAWSCredentials(entry.getValue().getS3AccessKey(), entry.getValue().getS3SecretKey())))); } for (Map.Entry<String, S3GroupConfiguration> entry : config.get().getGroupS3SearchConfigs().entrySet()) { s3ServiceBuilder.add(new SingularityS3Service(entry.getKey(), entry.getValue().getS3Bucket(), new AmazonS3Client(new BasicAWSCredentials(entry.getValue().getS3AccessKey(), entry.getValue().getS3SecretKey())))); } SingularityS3Service defaultService = new SingularityS3Service(SingularityS3FormatHelper.DEFAULT_GROUP_NAME, config.get().getS3Bucket(), new AmazonS3Client(new BasicAWSCredentials(config.get().getS3AccessKey(), config.get().getS3SecretKey()))); return new SingularityS3Services(s3ServiceBuilder.build(), defaultService); } @Provides @Singleton public MesosConfiguration mesosConfiguration(final SingularityConfiguration config) { return config.getMesosConfiguration(); } @Provides @Singleton public UIConfiguration uiConfiguration(final SingularityConfiguration config) { return config.getUiConfiguration(); } @Provides @Singleton public CustomExecutorConfiguration customExecutorConfiguration(final SingularityConfiguration config) { return config.getCustomExecutorConfiguration(); } @Provides @Singleton public Optional<SMTPConfiguration> smtpConfiguration(final SingularityConfiguration config) { return config.getSmtpConfigurationOptional(); } @Provides @Singleton public Optional<S3Configuration> s3Configuration(final SingularityConfiguration config) { return config.getS3ConfigurationOptional(); } @Provides @Singleton public HistoryPurgingConfiguration historyPurgingConfiguration(final SingularityConfiguration config) { return config.getHistoryPurgingConfiguration(); } private JadeTemplate getJadeTemplate(String name) throws IOException { JadeConfiguration config = new JadeConfiguration(); config.setTemplateLoader(new ClasspathTemplateLoader()); return config.getTemplate("templates/" + name); } @Provides @Singleton @Named(TASK_TEMPLATE) public JadeTemplate getTaskTemplate() throws IOException { return getJadeTemplate("task"); } @Provides @Singleton @Named(REQUEST_IN_COOLDOWN_TEMPLATE) public JadeTemplate getRequestPausedTemplate() throws IOException { return getJadeTemplate("request_in_cooldown"); } @Provides @Singleton @Named(REQUEST_MODIFIED_TEMPLATE) public JadeTemplate getRequestModifiedTemplate() throws IOException { return getJadeTemplate("request_modified"); } @Provides @Singleton @Named(RATE_LIMITED_TEMPLATE) public JadeTemplate getRateLimitedTemplate() throws IOException { return getJadeTemplate("rate_limited"); } @Provides @Singleton @Named(DISASTERS_TEMPLATE) public JadeTemplate getDisastersTemplate() throws IOException { return getJadeTemplate("disaster"); } @Provides @Singleton @Named(REPLACEMENT_TASKS_FAILING_TEMPLATE) public JadeTemplate getReplacementTasksFailingTemplate() throws IOException { return getJadeTemplate("replacement_tasks_failing"); } @Provides @Named(CURRENT_HTTP_REQUEST) public Optional<HttpServletRequest> providesUrl(Provider<HttpServletRequest> requestProvider) { try { return Optional.of(requestProvider.get()); } catch (ProvisionException pe) { // this will happen if we're not in the REQUEST scope return Optional.empty(); } } @Provides @Singleton @Named(LOST_TASKS_METER) public Meter providesLostTasksMeter(MetricRegistry registry) { return registry.meter("com.hubspot.singularity.lostTasks"); } @Provides @Singleton @Named(STATUS_UPDATE_DELTA_30S_AVERAGE) public AtomicLong provideDeltasMap() { return new AtomicLong(0); } @Provides @Singleton @Named(STATUS_UPDATE_DELTAS) public ConcurrentHashMap<Long, Long> provideUpdateDeltasMap() { return new ConcurrentHashMap<>(); } @Provides @Singleton @Named(LAST_MESOS_MASTER_HEARTBEAT_TIME) public AtomicLong provideLastHeartbeatTime() { return new AtomicLong(0); } @Provides @Singleton public Set<SingularityLeaderOnlyPoller> provideLeaderOnlyPollers(Injector injector) { Set<SingularityLeaderOnlyPoller> leaderOnlyPollers = new HashSet<>(); for (Key<?> key : injector.getAllBindings().keySet()) { if (SingularityLeaderOnlyPoller.class.isAssignableFrom(key.getTypeLiteral().getRawType())) { SingularityLeaderOnlyPoller poller = (SingularityLeaderOnlyPoller) injector.getInstance(key); leaderOnlyPollers.add(poller); } } return leaderOnlyPollers; } @Provides @Singleton @Singularity public ObjectMapper providesSingularityObjectMapper() { return JavaUtils.newObjectMapper(); } }
package org.cqframework.cql.cql2elm; import org.cqframework.cql.elm.tracking.TrackBack; import org.hl7.cql_annotations.r1.CqlToElmInfo; import org.hl7.elm.r1.*; import org.testng.annotations.Test; import javax.xml.bind.JAXBException; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Scanner; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; public class TranslationTests { // TODO: sameXMLAs? Couldn't find such a thing in hamcrest, but I don't want this to run on the JSON, I want it to verify the actual XML. @Test(enabled=false) public void testPatientPropertyAccess() throws IOException, JAXBException { File expectedXmlFile = new File(Cql2ElmVisitorTest.class.getResource("PropertyTest_ELM.xml").getFile()); String expectedXml = new Scanner(expectedXmlFile, "UTF-8").useDelimiter("\\Z").next(); File propertyTestFile = new File(Cql2ElmVisitorTest.class.getResource("PropertyTest.cql").getFile()); ModelManager modelManager = new ModelManager(); String actualXml = CqlTranslator.fromFile(propertyTestFile, modelManager, new LibraryManager(modelManager)).toXml(); assertThat(actualXml, is(expectedXml)); } @Test(enabled=false) public void testCMS146v2XML() throws IOException { String expectedXml = ""; File cqlFile = new File(Cql2ElmVisitorTest.class.getResource("CMS146v2_Test_CQM.cql").getFile()); ModelManager modelManager = new ModelManager(); String actualXml = CqlTranslator.fromFile(cqlFile, modelManager, new LibraryManager(modelManager)).toXml(); assertThat(actualXml, is(expectedXml)); } @Test public void testIdentifierLocation() throws IOException { CqlTranslator translator = TestUtils.createTranslator("TranslatorTests/UnknownIdentifier.cql"); assertEquals(1, translator.getErrors().size()); CqlTranslatorException e = translator.getErrors().get(0); TrackBack tb = e.getLocator(); assertEquals(6, tb.getStartLine()); assertEquals(6, tb.getEndLine()); assertEquals(5, tb.getStartChar()); assertEquals(10, tb.getEndChar()); } @Test public void testAnnotationsPresent() throws IOException { CqlTranslator translator = TestUtils.createTranslator("CMS146v2_Test_CQM.cql", CqlTranslator.Options.EnableAnnotations); assertEquals(0, translator.getErrors().size()); List<ExpressionDef> defs = translator.getTranslatedLibrary().getLibrary().getStatements().getDef(); assertNotNull(defs.get(1).getAnnotation()); assertTrue(defs.get(1).getAnnotation().size() > 0); } @Test public void testAnnotationsAbsent() throws IOException { CqlTranslator translator = TestUtils.createTranslator("CMS146v2_Test_CQM.cql"); assertEquals(0, translator.getErrors().size()); List<ExpressionDef> defs = translator.getTranslatedLibrary().getLibrary().getStatements().getDef(); assertTrue(defs.get(1).getAnnotation().size() == 0); } @Test public void testTranslatorOptionsPresent() throws IOException { CqlTranslator translator = TestUtils.createTranslator("CMS146v2_Test_CQM.cql", CqlTranslator.Options.EnableAnnotations); assertEquals(0, translator.getErrors().size()); Library library = translator.getTranslatedLibrary().getLibrary(); assertNotNull(library.getAnnotation()); assertThat(library.getAnnotation().size(), greaterThan(0)); assertThat(library.getAnnotation().get(0), instanceOf(CqlToElmInfo.class)); CqlToElmInfo info = (CqlToElmInfo)library.getAnnotation().get(0); assertThat(info.getTranslatorOptions(), is("EnableAnnotations")); } @Test public void testNoImplicitCasts() throws IOException { CqlTranslator translator = TestUtils.createTranslator("TestNoImplicitCast.cql"); assertEquals(0, translator.getErrors().size()); // Gets the "TooManyCasts" define Expression exp = translator.getTranslatedLibrary().getLibrary().getStatements().getDef().get(2).getExpression(); assertThat(exp, is(instanceOf(Query.class))); Query query = (Query)exp; ReturnClause returnClause = query.getReturn(); assertNotNull(returnClause); assertNotNull(returnClause.getExpression()); assertThat(returnClause.getExpression(), is(instanceOf(FunctionRef.class))); FunctionRef functionRef = (FunctionRef)returnClause.getExpression(); assertEquals(1, functionRef.getOperand().size()); // For a widening cast, no As is required, it should be a direct property access. Expression operand = functionRef.getOperand().get(0); assertThat(operand, is(instanceOf(Property.class))); // Gets the "NeedsACast" define exp = translator.getTranslatedLibrary().getLibrary().getStatements().getDef().get(4).getExpression(); assertThat(exp, is(instanceOf(Query.class))); query = (Query)exp; returnClause = query.getReturn(); assertNotNull(returnClause); assertNotNull(returnClause.getExpression()); assertThat(returnClause.getExpression(), is(instanceOf(FunctionRef.class))); functionRef = (FunctionRef)returnClause.getExpression(); assertEquals(1, functionRef.getOperand().size()); // For narrowing choice casts, an As is expected operand = functionRef.getOperand().get(0); assertThat(operand, is(instanceOf(As.class))); As as = (As)operand; assertThat(as.getAsTypeSpecifier(), is(instanceOf(ChoiceTypeSpecifier.class))); } }
package com.tinapaproject.tinapa.adapters; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.FilterQueryProvider; import android.widget.ImageView; import android.widget.TextView; import com.tinapaproject.tinapa.R; import com.tinapaproject.tinapa.utils.ImageUtils; public class IndividualCursorAdapter extends CursorAdapter { private String imageColumn; private String mainNameColumn; private String secondNameColumn; private Context mContext; private static final int FLAGS = 0; public static final String TAG = "IndividualCursorAdapter"; public IndividualCursorAdapter(Context context, Cursor c, String mainNameColumn, String secondNameColumn, String imageColumn, final Uri uri) { super(context, c, FLAGS); this.mainNameColumn = mainNameColumn; this.secondNameColumn = secondNameColumn; this.imageColumn = imageColumn; this.mContext = context; this.setFilterQueryProvider(new FilterQueryProvider() { @Override public Cursor runQuery(CharSequence constraint) { return mContext.getContentResolver().query(uri, null, String.valueOf(constraint), null, null); } }); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.cell_individual, parent, false); } @Override public void bindView(View view, Context context, Cursor cursor) { ImageView imageView = (ImageView) view.findViewById(R.id.cell_individual_image); String imageUri = cursor.getString(cursor.getColumnIndex(imageColumn)); ImageUtils.loadImage(imageView, imageUri, true); TextView textView = (TextView) view.findViewById(R.id.cell_individual_name); String name; if (!TextUtils.isEmpty(mainNameColumn) && !TextUtils.isEmpty(name = cursor.getString(cursor.getColumnIndex(mainNameColumn)))) { textView.setText(name); } else if (!TextUtils.isEmpty(secondNameColumn)&& !TextUtils.isEmpty(name = cursor.getString(cursor.getColumnIndex(secondNameColumn)))) { textView.setText(name); } else { textView.setText(""); } } }
package com.dafrito.lua.script; import java.io.Reader; import java.io.Writer; import java.util.List; import javax.script.Bindings; import javax.script.ScriptContext; import javax.script.SimpleBindings; import lua.LuaLibrary; import lua.LuaLibrary.lua_State; public class LuaScriptContext implements ScriptContext { private static final Bindings GLOBAL_BINDINGS = new SimpleBindings(); private Bindings globalBindings = GLOBAL_BINDINGS; private Bindings engineBindings; private final lua_State state; public LuaScriptContext() { this.state = LuaLibrary.INSTANCE.luaL_newstate(); this.engineBindings = new LuaBindings(this.state); } @Override public Object getAttribute(String name) { // TODO Auto-generated method stub return null; } @Override public Object getAttribute(String name, int scope) { // TODO Auto-generated method stub return null; } @Override public int getAttributesScope(String name) { // TODO Auto-generated method stub return 0; } @Override public Bindings getBindings(int scope) { switch (scope) { case ScriptContext.ENGINE_SCOPE: return this.engineBindings; case ScriptContext.GLOBAL_SCOPE: return this.globalBindings; default: return null; } } @Override public Writer getErrorWriter() { // TODO Auto-generated method stub return null; } @Override public Reader getReader() { // TODO Auto-generated method stub return null; } @Override public List<Integer> getScopes() { // TODO Auto-generated method stub return null; } @Override public Writer getWriter() { // TODO Auto-generated method stub return null; } @Override public Object removeAttribute(String name, int scope) { // TODO Auto-generated method stub return null; } @Override public void setAttribute(String name, Object value, int scope) { // TODO Auto-generated method stub } @Override public void setBindings(Bindings bindings, int scope) { switch (scope) { case ScriptContext.ENGINE_SCOPE: if(bindings instanceof LuaBindings) { this.engineBindings=bindings; } else { this.engineBindings.putAll(bindings); } break; case ScriptContext.GLOBAL_SCOPE: this.globalBindings=bindings; break; default: throw new IllegalArgumentException("Scope is not supported. Scope: " + scope); } } @Override public void setErrorWriter(Writer writer) { // TODO Auto-generated method stub } @Override public void setReader(Reader reader) { // TODO Auto-generated method stub } @Override public void setWriter(Writer writer) { // TODO Auto-generated method stub } public lua_State getState() { return state; } }
package com.esotericsoftware.kryo.util; import java.util.Arrays; /** A resizable, ordered or unordered int array. Avoids the boxing that occurs with ArrayList<Integer>. If unordered, this class * avoids a memory copy when removing elements (the last element is moved to the removed element's position). * @author Nathan Sweet */ public class IntArray { public int[] items; public int size; public boolean ordered; /** Creates an ordered array with a capacity of 16. */ public IntArray () { this(true, 16); } /** Creates an ordered array with the specified capacity. */ public IntArray (int capacity) { this(true, capacity); } /** @param ordered If false, methods that remove elements may change the order of other elements in the array, which avoids a * memory copy. * @param capacity Any elements added beyond this will cause the backing array to be grown. */ public IntArray (boolean ordered, int capacity) { this.ordered = ordered; items = new int[capacity]; } /** Creates a new array containing the elements in the specific array. The new array will be ordered if the specific array is * ordered. The capacity is set to the number of elements, so any subsequent elements added will cause the backing array to be * grown. */ public IntArray (IntArray array) { this.ordered = array.ordered; size = array.size; items = new int[size]; System.arraycopy(array.items, 0, items, 0, size); } /** Creates a new ordered array containing the elements in the specified array. The capacity is set to the number of elements, * so any subsequent elements added will cause the backing array to be grown. */ public IntArray (int[] array) { this(true, array, 0, array.length); } /** Creates a new array containing the elements in the specified array. The capacity is set to the number of elements, so any * subsequent elements added will cause the backing array to be grown. * @param ordered If false, methods that remove elements may change the order of other elements in the array, which avoids a * memory copy. */ public IntArray (boolean ordered, int[] array, int startIndex, int count) { this(ordered, count); size = count; System.arraycopy(array, startIndex, items, 0, count); } public void add (int value) { int[] items = this.items; if (size == items.length) items = resize(Math.max(8, (int)(size * 1.75f))); items[size++] = value; } public void add (int value1, int value2) { int[] items = this.items; if (size + 1 >= items.length) items = resize(Math.max(8, (int)(size * 1.75f))); items[size] = value1; items[size + 1] = value2; size += 2; } public void add (int value1, int value2, int value3) { int[] items = this.items; if (size + 2 >= items.length) items = resize(Math.max(8, (int)(size * 1.75f))); items[size] = value1; items[size + 1] = value2; items[size + 2] = value3; size += 3; } public void add (int value1, int value2, int value3, int value4) { int[] items = this.items; if (size + 3 >= items.length) items = resize(Math.max(8, (int)(size * 1.8f))); // 1.75 isn't enough when size=5. items[size] = value1; items[size + 1] = value2; items[size + 2] = value3; items[size + 3] = value4; size += 4; } public void addAll (IntArray array) { addAll(array, 0, array.size); } public void addAll (IntArray array, int offset, int length) { if (offset + length > array.size) throw new IllegalArgumentException("offset + length must be <= size: " + offset + " + " + length + " <= " + array.size); addAll(array.items, offset, length); } public void addAll (int... array) { addAll(array, 0, array.length); } public void addAll (int[] array, int offset, int length) { int[] items = this.items; int sizeNeeded = size + length; if (sizeNeeded > items.length) items = resize(Math.max(8, (int)(sizeNeeded * 1.75f))); System.arraycopy(array, offset, items, size, length); size += length; } public int get (int index) { if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size); return items[index]; } public void set (int index, int value) { if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size); items[index] = value; } public void incr (int index, int value) { if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size); items[index] += value; } public void mul (int index, int value) { if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size); items[index] *= value; } public void insert (int index, int value) { if (index > size) throw new IndexOutOfBoundsException("index can't be > size: " + index + " > " + size); int[] items = this.items; if (size == items.length) items = resize(Math.max(8, (int)(size * 1.75f))); if (ordered) System.arraycopy(items, index, items, index + 1, size - index); else items[size] = items[index]; size++; items[index] = value; } public void swap (int first, int second) { if (first >= size) throw new IndexOutOfBoundsException("first can't be >= size: " + first + " >= " + size); if (second >= size) throw new IndexOutOfBoundsException("second can't be >= size: " + second + " >= " + size); int[] items = this.items; int firstValue = items[first]; items[first] = items[second]; items[second] = firstValue; } public boolean contains (int value) { int i = size - 1; int[] items = this.items; while (i >= 0) if (items[i--] == value) return true; return false; } public int indexOf (int value) { int[] items = this.items; for (int i = 0, n = size; i < n; i++) if (items[i] == value) return i; return -1; } public int lastIndexOf (int value) { int[] items = this.items; for (int i = size - 1; i >= 0; i if (items[i] == value) return i; return -1; } public boolean removeValue (int value) { int[] items = this.items; for (int i = 0, n = size; i < n; i++) { if (items[i] == value) { removeIndex(i); return true; } } return false; } /** Removes and returns the item at the specified index. */ public int removeIndex (int index) { if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size); int[] items = this.items; int value = items[index]; size if (ordered) System.arraycopy(items, index + 1, items, index, size - index); else items[index] = items[size]; return value; } /** Removes the items between the specified indices, inclusive. */ public void removeRange (int start, int end) { if (end >= size) throw new IndexOutOfBoundsException("end can't be >= size: " + end + " >= " + size); if (start > end) throw new IndexOutOfBoundsException("start can't be > end: " + start + " > " + end); int[] items = this.items; int count = end - start + 1; if (ordered) System.arraycopy(items, start + count, items, start, size - (start + count)); else { int lastIndex = this.size - 1; for (int i = 0; i < count; i++) items[start + i] = items[lastIndex - i]; } size -= count; } /** Removes from this array all of elements contained in the specified array. * @return true if this array was modified. */ public boolean removeAll (IntArray array) { int size = this.size; int startSize = size; int[] items = this.items; for (int i = 0, n = array.size; i < n; i++) { int item = array.get(i); for (int ii = 0; ii < size; ii++) { if (item == items[ii]) { removeIndex(ii); size break; } } } return size != startSize; } /** Removes and returns the last item. */ public int pop () { return items[--size]; } /** Returns the last item. */ public int peek () { return items[size - 1]; } /** Returns the first item. */ public int first () { if (size == 0) throw new IllegalStateException("Array is empty."); return items[0]; } public void clear () { size = 0; } /** Reduces the size of the backing array to the size of the actual items. This is useful to release memory when many items * have been removed, or if it is known that more items will not be added. * @return {@link #items} */ public int[] shrink () { if (items.length != size) resize(size); return items; } /** Increases the size of the backing array to accommodate the specified number of additional items. Useful before adding many * items to avoid multiple backing array resizes. * @return {@link #items} */ public int[] ensureCapacity (int additionalCapacity) { int sizeNeeded = size + additionalCapacity; if (sizeNeeded > items.length) resize(Math.max(8, sizeNeeded)); return items; } /** Sets the array size, leaving any values beyond the current size undefined. * @return {@link #items} */ public int[] setSize (int newSize) { if (newSize > items.length) resize(Math.max(8, newSize)); size = newSize; return items; } protected int[] resize (int newSize) { int[] newItems = new int[newSize]; int[] items = this.items; System.arraycopy(items, 0, newItems, 0, Math.min(size, newItems.length)); this.items = newItems; return newItems; } public void sort () { Arrays.sort(items, 0, size); } public void reverse () { int[] items = this.items; for (int i = 0, lastIndex = size - 1, n = size / 2; i < n; i++) { int ii = lastIndex - i; int temp = items[i]; items[i] = items[ii]; items[ii] = temp; } } /** Reduces the size of the array to the specified size. If the array is already smaller than the specified size, no action is * taken. */ public void truncate (int newSize) { if (size > newSize) size = newSize; } public int[] toArray () { int[] array = new int[size]; System.arraycopy(items, 0, array, 0, size); return array; } public int hashCode () { if (!ordered) return super.hashCode(); int[] items = this.items; int h = 1; for (int i = 0, n = size; i < n; i++) h = h * 31 + items[i]; return h; } public boolean equals (Object object) { if (object == this) return true; if (!ordered) return false; if (!(object instanceof IntArray)) return false; IntArray array = (IntArray)object; if (!array.ordered) return false; int n = size; if (n != array.size) return false; int[] items1 = this.items; int[] items2 = array.items; for (int i = 0; i < n; i++) if (items[i] != array.items[i]) return false; return true; } public String toString () { if (size == 0) return "[]"; int[] items = this.items; StringBuilder buffer = new StringBuilder(32); buffer.append('['); buffer.append(items[0]); for (int i = 1; i < size; i++) { buffer.append(", "); buffer.append(items[i]); } buffer.append(']'); return buffer.toString(); } public String toString (String separator) { if (size == 0) return ""; int[] items = this.items; StringBuilder buffer = new StringBuilder(32); buffer.append(items[0]); for (int i = 1; i < size; i++) { buffer.append(separator); buffer.append(items[i]); } return buffer.toString(); } /** @see #IntArray(int[]) */ static public IntArray with (int... array) { return new IntArray(array); } }
package com.foxdogstudios.peepers; import java.io.IOException; import android.graphics.ImageFormat; import android.hardware.Camera; import android.util.Log; import android.view.SurfaceHolder; /* package */ final class ImageStreamer extends Object { private static final String TAG = ImageStreamer.class.getSimpleName(); private static final long OPEN_CAMERA_POLL_INTERVAL_MS = 1000L; private final Object mLock = new Object(); private final SurfaceHolder mPreviewDisplay; private boolean mRunning = false; private Thread mWorker = null; private Camera mCamera = null; /* package */ ImageStreamer(final SurfaceHolder previewDisplay) { super(); if (previewDisplay == null) { throw new IllegalArgumentException("previewDisplay must not be null"); } mPreviewDisplay = previewDisplay; } // constructor(SurfaceHolder) /* package */ void start() /** * Stop the image streamer. The camera will be released during the * execution of stop() or shortly after it returns. stop() should * be called on the main thread. */ /* package */ void stop() { synchronized (mLock) { if (!mRunning) { throw new IllegalStateException("ImageStreamer is already stopped"); } mRunning = false; if (mCamera != null) { mCamera.release(); mCamera = null; } } // synchronized } // stop() private void tryStartPreview() throws Exception { while (true) { try { startPreview(); } //try catch (final RuntimeException openCameraFailed) { Log.d(TAG, "Open camera failed, retying in " + OPEN_CAMERA_POLL_INTERVAL_MS + "ms", openCameraFailed); Thread.sleep(OPEN_CAMERA_POLL_INTERVAL_MS); continue; } // catch break; } // while } // tryStartPreview() private void startPreview() throws IOException { // Throws RuntimeException if the camera is currently opened // by another application. final Camera camera = Camera.open(); // Set up callback buffers final Camera.Parameters params = camera.getParameters(); final Camera.Size previewSize = params.getPreviewSize(); final int previewFormat = params.getPreviewFormat(); final int BITS_PER_BYTE = 8; final int bytesPerPixel = ImageFormat.getBitsPerPixel(previewFormat) / BITS_PER_BYTE; // XXX: According to the documentation the buffer size can be // calculated by previewSize.width * previewSize.height // * bytesPerPixel. However, this returned an error saying it // was too small. It always needed to be exactly 1.5 times // larger. final int bufferSize = previewSize.width * previewSize.height * bytesPerPixel * 3 / 2 + 1; final int NUM_BUFFERS = 10; for (int bufferIndex = 0; bufferIndex < NUM_BUFFERS; bufferIndex++) { camera.addCallbackBuffer(new byte[bufferSize]); } // for camera.setPreviewCallbackWithBuffer(mPreviewCallback); synchronized (mLock) { if (!mRunning) { camera.release(); return; } try { camera.setPreviewDisplay(mPreviewDisplay); } // try catch (final IOException e) { camera.release(); throw e; } // catch camera.startPreview(); mCamera = camera; } // synchronized } // startPreview() private final Camera.PreviewCallback mPreviewCallback = new Camera.PreviewCallback() { @Override public void onPreviewFrame(final byte[] data, final Camera camera) { Log.i(TAG, "onPreviewFrame called"); camera.addCallbackBuffer(data); } // onPreviewFrame(byte[], Camera) }; // mPreviewCallback } // class ImageStreamer
package com.fsck.k9.provider; import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.MatrixCursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.ParcelFileDescriptor; import android.util.Log; import com.fsck.k9.Account; import com.fsck.k9.K9; import com.fsck.k9.Preferences; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.internet.MimeUtility; import com.fsck.k9.mail.store.LocalStore; import com.fsck.k9.mail.store.LocalStore.AttachmentInfo; import com.fsck.k9.mail.store.StorageManager; import java.io.*; import java.util.List; /** * A simple ContentProvider that allows file access to attachments. * * <p> * Warning! We make heavy assumptions about the Uris used by the {@link LocalStore} for an * {@link Account} here. * </p> */ public class AttachmentProvider extends ContentProvider { public static final Uri CONTENT_URI = Uri.parse("content://com.fsck.k9.attachmentprovider"); private static final String FORMAT_RAW = "RAW"; private static final String FORMAT_VIEW = "VIEW"; private static final String FORMAT_THUMBNAIL = "THUMBNAIL"; private static final String[] DEFAULT_PROJECTION = new String[] { AttachmentProviderColumns._ID, AttachmentProviderColumns.DATA, }; public static class AttachmentProviderColumns { public static final String _ID = "_id"; public static final String DATA = "_data"; public static final String DISPLAY_NAME = "_display_name"; public static final String SIZE = "_size"; } public static Uri getAttachmentUri(Account account, long id) { return getAttachmentUri(account.getUuid(), id, true); } public static Uri getAttachmentUriForViewing(Account account, long id) { return getAttachmentUri(account.getUuid(), id, false); } public static Uri getAttachmentThumbnailUri(Account account, long id, int width, int height) { return CONTENT_URI.buildUpon() .appendPath(account.getUuid()) .appendPath(Long.toString(id)) .appendPath(FORMAT_THUMBNAIL) .appendPath(Integer.toString(width)) .appendPath(Integer.toString(height)) .build(); } private static Uri getAttachmentUri(String db, long id, boolean raw) { return CONTENT_URI.buildUpon() .appendPath(db) .appendPath(Long.toString(id)) .appendPath(raw ? FORMAT_RAW : FORMAT_VIEW) .build(); } public static void clear(Context context) { /* * We use the cache dir as a temporary directory (since Android doesn't give us one) so * on startup we'll clean up any .tmp files from the last run. */ File[] files = context.getCacheDir().listFiles(); for (File file : files) { try { if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Deleting file " + file.getCanonicalPath()); } } catch (IOException ioe) { /* No need to log failure to log */ } file.delete(); } } /** * Delete the thumbnail of an attachment. * * @param context * The application context. * @param accountUuid * The UUID of the account the attachment belongs to. * @param attachmentId * The ID of the attachment the thumbnail was created for. */ public static void deleteThumbnail(Context context, String accountUuid, String attachmentId) { File file = getThumbnailFile(context, accountUuid, attachmentId); if (file.exists()) { file.delete(); } } private static File getThumbnailFile(Context context, String accountUuid, String attachmentId) { String filename = "thmb_" + accountUuid + "_" + attachmentId + ".tmp"; File dir = context.getCacheDir(); return new File(dir, filename); } @Override public boolean onCreate() { /* * We use the cache dir as a temporary directory (since Android doesn't give us one) so * on startup we'll clean up any .tmp files from the last run. */ final File cacheDir = getContext().getCacheDir(); if (cacheDir == null) { return true; } File[] files = cacheDir.listFiles(); if (files == null) { return true; } for (File file : files) { if (file.getName().endsWith(".tmp")) { file.delete(); } } return true; } @Override public String getType(Uri uri) { List<String> segments = uri.getPathSegments(); String dbName = segments.get(0); String id = segments.get(1); String format = segments.get(2); return getType(dbName, id, format); } @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { File file; List<String> segments = uri.getPathSegments(); String accountUuid = segments.get(0); String attachmentId = segments.get(1); String format = segments.get(2); if (FORMAT_THUMBNAIL.equals(format)) { int width = Integer.parseInt(segments.get(3)); int height = Integer.parseInt(segments.get(4)); file = getThumbnailFile(getContext(), accountUuid, attachmentId); if (!file.exists()) { String type = getType(accountUuid, attachmentId, FORMAT_VIEW); try { FileInputStream in = new FileInputStream(getFile(accountUuid, attachmentId)); try { Bitmap thumbnail = createThumbnail(type, in); if (thumbnail != null) { thumbnail = Bitmap.createScaledBitmap(thumbnail, width, height, true); FileOutputStream out = new FileOutputStream(file); try { thumbnail.compress(Bitmap.CompressFormat.PNG, 100, out); } finally { out.close(); } } } finally { try { in.close(); } catch (Throwable ignore) { /* ignore */ } } } catch (IOException ioe) { return null; } } } else { file = getFile(accountUuid, attachmentId); } return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { String[] columnNames = (projection == null) ? DEFAULT_PROJECTION : projection; List<String> segments = uri.getPathSegments(); String dbName = segments.get(0); String id = segments.get(1); // Versions of K-9 before 3.400 had a database name here, not an // account UID, so implement a bit of backcompat if (dbName.endsWith(".db")) { dbName = dbName.substring(0, dbName.length() - 3); } final AttachmentInfo attachmentInfo; try { final Account account = Preferences.getPreferences(getContext()).getAccount(dbName); attachmentInfo = LocalStore.getLocalInstance(account, K9.app).getAttachmentInfo(id); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to retrieve attachment info from local store for ID: " + id, e); return null; } MatrixCursor ret = new MatrixCursor(columnNames); Object[] values = new Object[columnNames.length]; for (int i = 0, count = columnNames.length; i < count; i++) { String column = columnNames[i]; if (AttachmentProviderColumns._ID.equals(column)) { values[i] = id; } else if (AttachmentProviderColumns.DATA.equals(column)) { values[i] = uri.toString(); } else if (AttachmentProviderColumns.DISPLAY_NAME.equals(column)) { values[i] = attachmentInfo.name; } else if (AttachmentProviderColumns.SIZE.equals(column)) { values[i] = attachmentInfo.size; } } ret.addRow(values); return ret; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { return 0; } @Override public int delete(Uri uri, String arg1, String[] arg2) { return 0; } @Override public Uri insert(Uri uri, ContentValues values) { return null; } private String getType(String dbName, String id, String format) { String type; if (FORMAT_THUMBNAIL.equals(format)) { type = "image/png"; } else { final Account account = Preferences.getPreferences(getContext()).getAccount(dbName); try { final LocalStore localStore = LocalStore.getLocalInstance(account, K9.app); AttachmentInfo attachmentInfo = localStore.getAttachmentInfo(id); if (FORMAT_VIEW.equals(format)) { type = MimeUtility.getMimeTypeForViewing(attachmentInfo.type, attachmentInfo.name); } else { // When accessing the "raw" message we deliver the original MIME type. type = attachmentInfo.type; } } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Unable to retrieve LocalStore for " + account, e); type = null; } } return type; } private File getFile(String dbName, String id) throws FileNotFoundException { Account account = Preferences.getPreferences(getContext()).getAccount(dbName); File attachmentsDir = StorageManager.getInstance(K9.app).getAttachmentDirectory(dbName, account.getLocalStorageProviderId()); File file = new File(attachmentsDir, id); if (!file.exists()) { throw new FileNotFoundException(file.getAbsolutePath()); } return file; } private Bitmap createThumbnail(String type, InputStream data) { /* * Improperly downloaded images, corrupt bitmaps and the like can commonly * cause OOME due to invalid allocation sizes. We're happy with a null bitmap in * that case. If the system is really out of memory we'll know about it soon * enough. */ return null; } catch (Exception e) { return null; } } }
package oata; public class HelloWorld { public static void main(String[] args) { System.out.println("Neal Willbur"); } }
package com.grilledmonkey.niceql.structs; import com.grilledmonkey.niceql.interfaces.SqlColumn; /** * Instances of this class represent definition for single SQLite table column. * Constructor without parameters creates PRIMARY KEY as defined in SQLite. * <p> * <b>Warning!</b> No error checks are performed! * <p> * Supported types: * <ul> * <li>INTEGER</li> * <li>TEXT</li> * <li>REAL</li> * <li>BLOB</li> * </ul> * <p> * All columns should have name and type. NOT NULL is optional. * * @author Aux * */ public class Column extends SqlColumn { private final String name, type; private final boolean notNull, isPrimary; private final int intType; /** * Creates PRIMARY KEY for table definition */ public Column() { this.name = PRIMARY_KEY; this.type = INTEGER; this.intType = TYPE_INTEGER; this.notNull = false; this.isPrimary = true; } /** * Creates column of specified name and type setting NOT NULL attribute to FALSE. * <p> * No error checks are performed, so you can use whatever strings you like. * This is kind of future-compliant, but error-prone. It is advised to use * type constants provided by class. * * @param name is the name of column, which should follow SQLite rules * @param type SQLite supported type of column */ public Column(String name, String type) { this(name, type, false); } /** * Creates column of specified name, type and NOT NULL attribute. * <p> * No error checks are performed, so you can use whatever strings you like. * This is kind of future-compliant, but error-prone. It is advised to use * type constants provided by class. * * @param name is the name of column, which should follow SQLite rules * @param type SQLite supported type of column * @param notNull indicates if column is NOT NULL */ public Column(String name, String type, boolean notNull) { this.name = name; this.type = type; this.notNull = notNull; this.isPrimary = false; if(INTEGER.equals(type)) intType = TYPE_INTEGER; else if(TEXT.equals(type)) intType = TYPE_TEXT; else if(REAL.equals(type)) intType = TYPE_REAL; else if(BLOB.equals(type)) intType = TYPE_BLOB; else intType = TYPE_UNDEFINED; } /** * Returns SQL statement for current column. * * @return generated SQL code */ public String getSql() { StringBuilder result = new StringBuilder(getNameEscaped()); result.append(" " + type); if(isPrimary) result.append(" PRIMARY KEY AUTOINCREMENT"); else if(notNull) result.append(" NOT NULL"); return(result.toString()); } public String getName() { return(name); } public String getType() { return(type); } public int getIntType() { return(intType); } public boolean isNotNull() { return(notNull); } public String getNameEscaped() { return(escape(name)); } }
package com.ibm.nmon.gui.main; import java.util.List; import java.io.File; import java.util.prefs.Preferences; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JSplitPane; import javax.swing.JOptionPane; import java.awt.BorderLayout; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.SwingUtilities; import com.ibm.nmon.NMONVisualizerApp; import com.ibm.nmon.data.DataSet; import com.ibm.nmon.data.transform.name.HostRenamer; import com.ibm.nmon.interval.Interval; import com.ibm.nmon.file.CombinedFileFilter; import com.ibm.nmon.gui.file.ParserRunner; import com.ibm.nmon.gui.interval.IntervalPicker; import com.ibm.nmon.gui.report.ReportFrame; import com.ibm.nmon.gui.tree.TreePanel; import com.ibm.nmon.gui.util.LogViewerDialog; import com.ibm.nmon.parser.HATJParser; import com.ibm.nmon.parser.IOStatParser; import com.ibm.nmon.gui.parse.HATJPostParser; import com.ibm.nmon.gui.parse.IOStatPostParser; import com.ibm.nmon.gui.parse.VerboseGCPreParser; import com.ibm.nmon.report.ReportCache; import com.ibm.nmon.gui.Styles; import com.ibm.nmon.util.FileHelper; import com.ibm.nmon.util.GranularityHelper; import com.ibm.nmon.util.TimeFormatCache; public final class NMONVisualizerGui extends NMONVisualizerApp { public static void main(final String[] args) throws Exception { javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); String temp = System.getProperty("fontSize"); if (temp != null) { try { int fontSize = Integer.parseInt(temp); javax.swing.UIManager.getLookAndFeelDefaults() .put("defaultFont", new javax.swing.plaf.FontUIResource(new java.awt.Font("Dialog", java.awt.Font.PLAIN, fontSize))); } catch (NumberFormatException nfe) { System.err.println("ignoring -DfontSize=" + temp + "; it must be an integer"); } } SwingUtilities.invokeLater(new Runnable() { public void run() { try { NMONVisualizerGui gui = new NMONVisualizerGui(); gui.getMainFrame().setVisible(true); if (args.length > 0) { gui.logger.info("starting with files {}", java.util.Arrays.toString(args)); File[] files = new File[args.length]; for (int i = 0; i < args.length; i++) { files[i] = new File(args[i]); } List<String> toParse = new java.util.ArrayList<String>(); gui.logger.debug("parsing files {}", toParse); FileHelper.recurseDirectories(files, CombinedFileFilter.getInstance(false), toParse); new Thread(new ParserRunner(gui, toParse, gui.getDisplayTimeZone()), getClass().getName() + " Parser").start(); } } catch (Exception e) { e.printStackTrace(); } } }); } private static final String DEFAULT_WINDOW_TITLE = "NMON Visualizer"; private final Preferences preferences; private final JFrame mainFrame; private final MainMenu menu; private final LogViewerDialog logViewer; private VerboseGCPreParser gcPreParser; private IOStatPostParser ioStatPostParser; private HATJPostParser hatJPostParser; private final GranularityHelper granularityHelper; private final ReportCache reportCache; public NMONVisualizerGui() throws Exception { super(); granularityHelper = new GranularityHelper(this); setGranularity(-1); // automatic reportCache = new ReportCache(); preferences = Preferences.userNodeForPackage(NMONVisualizerGui.class); setProperty("chartsDisplayed", true); String systemsNamedBy = preferences.get("systemsNamedBy", null); if (systemsNamedBy != null) { if ("host".equals(systemsNamedBy)) { setHostRenamer(HostRenamer.BY_HOST); } else if ("lpar".equals(systemsNamedBy)) { setHostRenamer(HostRenamer.BY_LPAR); } else if ("run".equals(systemsNamedBy)) { setHostRenamer(HostRenamer.BY_RUN); } else if ("custom".equals(systemsNamedBy)) { // reset back to host if custom since the JSON file to load is not known systemsNamedBy = "host"; } setProperty("systemsNamedBy", systemsNamedBy); } // else NMONVisualizerApp already set HostRenamer to BY_HOST and systemsNamedBy property // NMONVisuzlizerApp already set default value for scaleProcessesByCPUs property setProperty("scaleProcessesByCPUs", preferences.get("scaleProcessesByCPUs", getProperty("scaleProcessesByCPUs"))); setProperty("showStatusBar", preferences.get("showStatusBar", "false")); mainFrame = new JFrame(DEFAULT_WINDOW_TITLE); mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); mainFrame.addWindowListener(windowManager); mainFrame.setIconImage(Styles.IBM_ICON.getImage()); menu = new MainMenu(this); mainFrame.setJMenuBar(menu); logViewer = new LogViewerDialog(this); // tree of parsed files on the left, content on the left JSplitPane lrSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); // never resize tree automatically lrSplitPane.setResizeWeight(0); mainFrame.setContentPane(lrSplitPane); // tree of parsed files on the left, content on the right TreePanel treePanel = new TreePanel(this); JPanel right = new JPanel(new BorderLayout()); lrSplitPane.setLeftComponent(treePanel); lrSplitPane.setRightComponent(right); ChartTableToggle toggle = new ChartTableToggle(this); JPanel top = new JPanel(new BorderLayout()); top.add(new IntervalPicker(this), BorderLayout.CENTER); top.add(toggle, BorderLayout.LINE_END); right.add(top, BorderLayout.PAGE_START); // ViewManager's SummaryView adds the checkbox to the top panel // so top must already be created and added to the gui before the data panel is initialized ViewManager dataPanel = new ViewManager(this); StatusBar statusBar = new StatusBar(this); treePanel.addTreeSelectionListener(dataPanel); treePanel.addTreeSelectionListener(statusBar); right.add(dataPanel, BorderLayout.CENTER); right.add(statusBar, BorderLayout.PAGE_END); mainFrame.pack(); positionMainFrame(); } /** * Gets the Preferences for this application. * * @return the Preferences, which will never be <code>null</code> */ public final Preferences getPreferences() { return preferences; } /** * Gets the main JFrame used by this class. This frame should be considered the "main window" for the application. * * @return the application's main window */ public JFrame getMainFrame() { return mainFrame; } public ViewManager getViewManager() { return (ViewManager) ((JPanel) ((JSplitPane) mainFrame.getContentPane()).getRightComponent()).getComponent(1); } public void showReportFrame() { ReportFrame report = new ReportFrame(this); report.setVisible(true); } public LogViewerDialog getLogViewer() { return logViewer; } public int getGranularity() { return granularityHelper.getGranularity(); } /** * Defines how granular charts will be, i.e. how many seconds will pass between data points. This method causes * either a <code>automaticGranularity</code> or <code>granularity</code> property change event to be fired. * * @param granularity the new granularity, in seconds. A zero or negative value implies that granularity will be * automatically calculated based on the current interval. */ public void setGranularity(int granularity) { int oldGranularity = getGranularity(); if (granularity <= 0) { if (getBooleanProperty("automaticGranularity")) { granularityHelper.recalculate(); } else { granularityHelper.setAutomatic(true); setProperty("automaticGranularity", true); } } else { granularityHelper.setGranularity(granularity); if (getBooleanProperty("automaticGranularity")) { setProperty("automaticGranularity", false); } } if (getGranularity() != oldGranularity) { for (DataSet data : getDataSets()) { getAnalysis(data).setGranularity(getGranularity()); } setProperty("granularity", getGranularity()); } } public ReportCache getReportCache() { return reportCache; } @Override public void currentIntervalChanged(Interval interval) { super.currentIntervalChanged(interval); if (getBooleanProperty("automaticGranularity")) { setGranularity(-1); } updateWindowTitle(interval); } @Override public void intervalRenamed(Interval interval) { super.intervalRenamed(interval); if (getIntervalManager().getCurrentInterval().equals(interval)) { updateWindowTitle(interval); } } private void updateWindowTitle(Interval interval) { if ((getMinSystemTime() > 0) && (getMaxSystemTime() < Long.MAX_VALUE)) { mainFrame.setTitle(DEFAULT_WINDOW_TITLE + " - " + TimeFormatCache.formatInterval(interval)); } else { mainFrame.setTitle(DEFAULT_WINDOW_TITLE); } } /** * Gracefully exits the application. This method asks the user for confirmation through a JOptionPane before * continuing. If the user selects "Yes", the application saves all preferences and calls dispose() on the main * frame. */ void exit() { int confirm = JOptionPane.showConfirmDialog(mainFrame, "Are you sure you want to Exit?", "Exit?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (confirm == 0) { // save the window sizes to the Preferences // if the window is maximized, do not save the sizes -- keep // the old ones so the user can un-maximize later if ((mainFrame.getExtendedState() & JFrame.MAXIMIZED_BOTH) != 0) { getPreferences().putBoolean("WindowMaximized", true); } else { getPreferences().putBoolean("WindowMaximized", false); getPreferences().putInt("WindowPosX", mainFrame.getX()); getPreferences().putInt("WindowPosY", mainFrame.getY()); getPreferences().putInt("WindowSizeX", (int) mainFrame.getSize().getWidth()); getPreferences().putInt("WindowSizeY", (int) mainFrame.getSize().getHeight()); } // close any open custom report windows for (java.awt.Frame frame : java.awt.Frame.getFrames()) { if (frame.getClass() == com.ibm.nmon.gui.report.ReportFrame.class) { ((com.ibm.nmon.gui.report.ReportFrame) frame).setVisible(false); ((com.ibm.nmon.gui.report.ReportFrame) frame).dispose(); } } getPreferences().put("systemsNamedBy", getProperty("systemsNamedBy")); getPreferences().put("scaleProcessesByCPUs", getProperty("scaleProcessesByCPUs")); getPreferences().put("showStatusBar", getProperty("showStatusBar")); logViewer.dispose(); mainFrame.dispose(); try { preferences.sync(); } catch (java.util.prefs.BackingStoreException e) { logger.warn("could not save preferences", e); } } } @Override protected String[] getDataForGCParse(final String fileToParse) { if (gcPreParser == null) { gcPreParser = new VerboseGCPreParser(this); } try { // wait here so parsing does not continue in the background, possibly throwing up more // preparser dialogs SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { java.io.File file = new java.io.File(fileToParse); java.io.File parent = file.getParentFile(); if (parent != null) { gcPreParser.setJVMName(parent.getName()); } parent = parent.getParentFile(); if (parent != null) { gcPreParser.setHostname(parent.getName()); } gcPreParser.parseDataSet(fileToParse); } }); } catch (Exception e) { logger.error("cannot get hostname and JVM name for file '{}'", fileToParse, e); } if (gcPreParser.isSkipped()) { return null; } else { return new String[] { gcPreParser.getHostname(), gcPreParser.getJVMName() }; } } @Override protected Object[] getDataForIOStatParse(final String fileToParse, final String hostname) { if (ioStatPostParser == null) { ioStatPostParser = new IOStatPostParser(this); } try { // wait here so parsing does not continue in the background, possibly throwing up more // postparser dialogs SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { if (!hostname.equals(IOStatParser.DEFAULT_HOSTNAME)) { ioStatPostParser.setHostname(hostname); } ioStatPostParser.parseDataSet(fileToParse); } }); } catch (Exception e) { logger.error("cannot get hostname and time zone for file '{}'", fileToParse, e); } if (ioStatPostParser.isSkipped()) { return null; } else { return new Object[] { ioStatPostParser.getHostname(), ioStatPostParser.getDate() }; } } @Override protected Object[] getDataForHATJParse(final String fileToParse, final String hostname) { if (hatJPostParser == null) { hatJPostParser = new HATJPostParser(this); } try { // wait here so parsing does not continue in the background, possibly throwing up more // postparser dialogs SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { if (!hostname.equals(HATJParser.DEFAULT_HOSTNAME)) { hatJPostParser.setHostname(hostname); } hatJPostParser.parseDataSet(fileToParse); } }); } catch (Exception e) { logger.error("cannot get hostname for file '{}'", fileToParse, e); } if (hatJPostParser.isSkipped()) { return null; } else { return new Object[] { hatJPostParser.getHostname() }; } } private void positionMainFrame() { // load the window position and sizes from the Preferences // use max value here so that first time users / empty prefs create a default sized window // centered on the primary display int x = getPreferences().getInt("WindowPosX", 0); int y = this.getPreferences().getInt("WindowPosY", 0); int xSize = getPreferences().getInt("WindowSizeX", Integer.MAX_VALUE); int ySize = this.getPreferences().getInt("WindowSizeY", Integer.MAX_VALUE); // check to see if the preferred window will be visible with the current screen config // (user could have removed / reconfigured multiple monitors or resolutions) boolean willBeVisible = false; java.awt.Rectangle preferred = new java.awt.Rectangle(x, y, xSize, ySize); GraphicsDevice[] devices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices(); outer: for (GraphicsDevice device : devices) { GraphicsConfiguration[] configs = device.getConfigurations(); for (GraphicsConfiguration config : configs) { if (SwingUtilities.isRectangleContainingRectangle(config.getBounds(), preferred)) { willBeVisible = true; break outer; } } } // if not visible put the window in the middle of the primary monitor if (!willBeVisible) { java.awt.Rectangle defaultScreen = GraphicsEnvironment.getLocalGraphicsEnvironment() .getDefaultScreenDevice().getDefaultConfiguration().getBounds(); // resize if too big if (xSize > defaultScreen.width) { xSize = 800; } if (ySize > defaultScreen.height) { ySize = 600; } // center the window on the screen x = defaultScreen.x + (defaultScreen.width / 2) - (xSize / 2); y = defaultScreen.y + (defaultScreen.height / 2) - (ySize / 2); } mainFrame.setLocation(new java.awt.Point(x, y)); // set the size even if the window will not be maximized to ensure that // the window will be the right size if the user does un-maximize it mainFrame.setSize(xSize, ySize); if (getPreferences().getBoolean("WindowMaximized", false)) { mainFrame.setExtendedState(mainFrame.getExtendedState() | JFrame.MAXIMIZED_BOTH); } } @Override protected void fireDataAdded(final DataSet data) { // fire in the Swing event dispatcher thread if not already running there if (SwingUtilities.isEventDispatchThread()) { super.fireDataAdded(data); if (getBooleanProperty("automaticGranularity")) { setGranularity(-1); } } else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { NMONVisualizerGui.super.fireDataAdded(data); if (getBooleanProperty("automaticGranularity")) { setGranularity(-1); } } }); } } private WindowAdapter windowManager = new WindowAdapter() { @Override public void windowOpened(WindowEvent e) { // can only update the divider location when the window is visible // charts get 80% JSplitPane lrSplitPane = ((JSplitPane) mainFrame.getContentPane()); lrSplitPane.setDividerLocation(0.2); }; @Override public void windowClosing(WindowEvent e) { NMONVisualizerGui.this.exit(); } }; }
package com.mattgmg.miracastwidget; import java.util.List; import android.content.ActivityNotFoundException; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.view.Menu; import android.widget.Toast; public class MainActivity extends Activity { public static final String ACTION_WIFI_DISPLAY_SETTINGS = "android.settings.WIFI_DISPLAY_SETTINGS"; public static final String ACTION_CAST_SETTINGS = "android.settings.CAST_SETTINGS"; public static final String SETTINGS_APP_PACKAGE_NAME = "com.android.settings"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent wifiActionIntent = new Intent(ACTION_WIFI_DISPLAY_SETTINGS); wifiActionIntent.setPackage(SETTINGS_APP_PACKAGE_NAME); Intent castActionIntent = new Intent(ACTION_CAST_SETTINGS); castActionIntent.setPackage(SETTINGS_APP_PACKAGE_NAME); if(isCallable(wifiActionIntent)){ try { startSettingsActivity(wifiActionIntent); } catch (ActivityNotFoundException exception) { showErrorToast(); } } else if(isCallable(castActionIntent)) { try { startSettingsActivity(castActionIntent); } catch (ActivityNotFoundException exception) { showErrorToast(); } } else { showErrorToast(); } finish(); } private void showErrorToast() { String errorMessage = getResources().getString(R.string.error_toast); Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show(); } private boolean isCallable(Intent intent) { List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); return list.size() > 0; } private void startSettingsActivity(Intent intent) { intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the // action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
package com.oakesville.mythling.app; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; import com.oakesville.mythling.R; import com.oakesville.mythling.app.MediaSettings.MediaType; import com.oakesville.mythling.app.MediaSettings.MediaTypeDeterminer; import com.oakesville.mythling.app.MediaSettings.SortType; import com.oakesville.mythling.app.MediaSettings.ViewType; import com.oakesville.mythling.util.HttpHelper; public class AppSettings { public static final String DEVICE_PLAYBACK_CATEGORY = "device_playback_cat"; public static final String FRONTEND_PLAYBACK_CATEGORY = "frontend_playback_cat"; public static final String INTERNAL_BACKEND_CATEGORY = "internal_backend_cat"; public static final String EXTERNAL_BACKEND_CATEGORY = "external_backend_cat"; public static final String MYTHLING_SERVICE_ACCESS_CATEGORY = "mythling_service_access_cat"; public static final String MYTH_BACKEND_INTERNAL_HOST = "mythbe_internal_host"; public static final String MYTH_BACKEND_EXTERNAL_HOST = "mythbe_external_host"; public static final String MEDIA_SERVICES = "media_services"; public static final String MYTHLING_WEB_PORT = "mythling_web_port"; public static final String MYTHLING_WEB_ROOT = "mythling_web_root"; public static final String MYTHTV_SERVICE_PORT = "mythtv_service_port"; public static final String MYTH_FRONTEND_HOST = "mythfe_host"; public static final String MYTH_FRONTEND_PORT = "mythfe_port"; public static final String MEDIA_TYPE = "media_type"; public static final String VIEW_TYPE = "view_type"; public static final String SORT_TYPE = "sort_type"; public static final String PLAYBACK_MODE = "playback_mode"; public static final String VIDEO_PLAYER = "video_player"; public static final String NETWORK_LOCATION = "network_location"; public static final String CATEGORIZE_VIDEOS = "categorize_videos"; public static final String MOVIE_DIRECTORIES = "movie_directories"; public static final String TV_SERIES_DIRECTORIES = "tv_series_directories"; public static final String VIDEO_EXCLUDE_DIRECTORIES = "video_exclude_directories"; public static final String INTERNAL_VIDEO_RES = "internal_video_res"; public static final String EXTERNAL_VIDEO_RES = "external_video_res"; public static final String INTERNAL_VIDEO_BITRATE = "internal_video_bitrate"; public static final String EXTERNAL_VIDEO_BITRATE = "external_video_bitrate"; public static final String INTERNAL_AUDIO_BITRATE = "internal_audio_bitrate"; public static final String EXTERNAL_AUDIO_BITRATE = "external_audio_bitrate"; public static final String BUILT_IN_PLAYER_BUFFER_SIZE = "built_in_player_buffer_size"; public static final String CACHE_EXPIRE_MINUTES = "cache_expiry"; public static final String LAST_LOAD = "last_load"; public static final String RETRIEVE_IP = "retrieve_ip"; public static final String IP_RETRIEVAL_URL = "ip_retrieval_url"; public static final String MYTHTV_SERVICES_AUTH_TYPE = "mythtv_services_auth_type"; public static final String MYTHTV_SERVICES_USER = "mythtv_services_user"; public static final String MYTHTV_SERVICES_PASSWORD = "mythtv_services_password"; public static final String MYTHLING_SERVICES_AUTH_TYPE = "mythling_services_auth_type"; public static final String MYTHLING_SERVICES_USER = "mythling_services_user"; public static final String MYTHLING_SERVICES_PASSWORD = "mythling_services_password"; public static final String TUNER_TIMEOUT = "tuner_timeout"; public static final String TRANSCODE_TIMEOUT = "transcode_timeout"; public static final String MOVIE_CURRENT_POSITION = "movie_current_position"; public static final String DEFAULT_MEDIA_TYPE = "recordings"; public static final String MOVIE_BASE_URL = "movie_base_url"; public static final String TV_BASE_URL = "tv_base_url"; public static final String CUSTOM_BASE_URL = "custom_base_url"; public static final String THEMOVIEDB_BASE_URL = "http: public static final String THETVDB_BASE_URL = "http: private Context appContext; public Context getAppContext() { return appContext; } private SharedPreferences prefs; public SharedPreferences getPrefs() { return prefs; } private static DateFormat dateTimeFormat; public AppSettings(Context appContext) { this.appContext = appContext; this.prefs = PreferenceManager.getDefaultSharedPreferences(appContext); dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); } public URL getMythlingWebBaseUrl() throws MalformedURLException { String ip = getMythlingServiceHost(); int port = getMythlingServicePort(); String root = getMythlingWebRoot(); return new URL("http://" + ip + ":" + port + (root == null || root.length() == 0 ? "" : "/" + root)); } public URL getMediaListUrl(MediaType mediaType) throws MalformedURLException, UnsupportedEncodingException { MediaSettings mediaSettings = getMediaSettings(); String url; if (isMythlingMediaServices()) { url = getMythlingWebBaseUrl() + "/media.php?type=" + mediaType.toString(); url += getVideoTypeParams(); if (mediaSettings.getSortType() == SortType.byYear) url += "&orderBy=year"; else if (mediaSettings.getSortType() == SortType.byRating) url += "&orderBy=userrating%20desc"; } else { url = getMythTvServicesBaseUrl() + "/"; if (mediaType == MediaType.videos || mediaType == MediaType.movies || mediaType == MediaType.tvSeries) url += "Video/GetVideoList"; else if (mediaType == MediaType.recordings) url += "Dvr/GetRecordedList?Descending=true"; else if (mediaType == MediaType.liveTv) { Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); String nowUtc = dateTimeFormat.format(cal.getTime()).replace(' ', 'T'); url += "Guide/GetProgramGuide?StartTime=" + nowUtc + "&EndTime=" + nowUtc; } } return new URL(url); } public URL getMediaListUrl() throws MalformedURLException, UnsupportedEncodingException { return getMediaListUrl(getMediaSettings().getType()); } /** * If not empty, always begins with '&'. */ public String getVideoTypeParams() throws UnsupportedEncodingException { String params = ""; if (getMediaSettings().getTypeDeterminer() == MediaTypeDeterminer.directories) { String movieDirs = getMovieDirectories(); if (movieDirs != null && !movieDirs.trim().isEmpty()) params += "&movieDirs=" + URLEncoder.encode(movieDirs.trim(), "UTF-8"); String tvSeriesDirs = getTvSeriesDirectories(); if (tvSeriesDirs != null && !tvSeriesDirs.trim().isEmpty()) params += "&tvSeriesDirs=" + URLEncoder.encode(tvSeriesDirs.trim(), "UTF-8"); String videoExcludeDirs = getVideoExcludeDirectories(); if (videoExcludeDirs != null && !videoExcludeDirs.trim().isEmpty()) params += "&videoExcludeDirs=" + URLEncoder.encode(videoExcludeDirs.trim(), "UTF-8"); } else if (getMediaSettings().getTypeDeterminer() == MediaTypeDeterminer.metadata) { params += "&categorizeUsingMetadata=true"; } return params; } public URL getSearchUrl(String query) throws MalformedURLException, UnsupportedEncodingException { if (isMythlingMediaServices()) { return new URL(getMythlingWebBaseUrl() + "/media.php?type=search&query=" + URLEncoder.encode(query, "UTF-8") + getVideoTypeParams()); } else { return null; } } public URL getMythTvServicesBaseUrl() throws MalformedURLException { String ip = getMythTvServiceHost(); int servicePort = getMythServicePort(); return new URL("http://" + ip + ":" + servicePort); } public URL getArtworkUrl(String storageGroup, String fileName) throws MalformedURLException { return new URL(getMythTvServicesBaseUrl() + "/Content/GetImageFile?StorageGroup=" + storageGroup + "&FileName=" + fileName); } public int getMythServicePort() { if (isServiceProxy()) return getServiceProxyPort(); else return getMythTvServicePort(); } public int getMythTvServicePort() { return Integer.parseInt(prefs.getString(MYTHTV_SERVICE_PORT, "6544").trim()); } public int getMythlingServicePort() { if (isServiceProxy()) return getServiceProxyPort(); else return getMythlingWebPort(); } public int getMythlingWebPort() { return Integer.parseInt(prefs.getString(MYTHLING_WEB_PORT, "80").trim()); } public String getMythlingWebRoot() { return prefs.getString(MYTHLING_WEB_ROOT, "mythling"); } public String getFrontendHost() { return prefs.getString(MYTH_FRONTEND_HOST, "192.168.0.68").trim(); } public int getFrontendControlPort() { return Integer.parseInt(prefs.getString(MYTH_FRONTEND_PORT, "6546").trim()); } public boolean isDevicePlayback() { return !prefs.getBoolean(PLAYBACK_MODE, false); } public boolean isExternalPlayer() { return !prefs.getBoolean(VIDEO_PLAYER, false); } public boolean isMythlingMediaServices() { return prefs.getBoolean(MEDIA_SERVICES, false); } public int getBuiltInPlayerBufferSize() { return Integer.parseInt(prefs.getString(BUILT_IN_PLAYER_BUFFER_SIZE, "8000")); } public boolean isExternalNetwork() { return prefs.getBoolean(NETWORK_LOCATION, false); } public String getInternalBackendHost() { return prefs.getString(MYTH_BACKEND_INTERNAL_HOST, "192.168.0.70").trim(); } public String getExternalBackendHost() { return prefs.getString(MYTH_BACKEND_EXTERNAL_HOST, "192.168.0.69").trim(); } public String getMovieDirectories() { return prefs.getString(MOVIE_DIRECTORIES, ""); } public String[] getMovieDirs() { String[] movieDirs = getMovieDirectories().split(","); for (int i = 0; i < movieDirs.length; i++) { if (!movieDirs[i].endsWith("/")) movieDirs[i] += "/"; } return movieDirs; } public String getTvSeriesDirectories() { return prefs.getString(TV_SERIES_DIRECTORIES, ""); } public String[] getTvSeriesDirs() { String[] tvDirs = getTvSeriesDirectories().split(","); for (int i = 0; i < tvDirs.length; i++) { if (!tvDirs[i].endsWith("/")) tvDirs[i] += "/"; } return tvDirs; } public String getVideoExcludeDirectories() { return prefs.getString(VIDEO_EXCLUDE_DIRECTORIES, ""); } public String[] getVidExcludeDirs() { String[] vidExcludeDirs = getVideoExcludeDirectories().split(","); for (int i = 0; i < vidExcludeDirs.length; i++) { if (!vidExcludeDirs[i].endsWith("/")) vidExcludeDirs[i] += "/"; } return vidExcludeDirs; } public String getMovieBaseUrl() { return prefs.getString(MOVIE_BASE_URL, THEMOVIEDB_BASE_URL); } public String getTvBaseUrl() { return prefs.getString(TV_BASE_URL, THETVDB_BASE_URL); } public String getCustomBaseUrl() { return prefs.getString(CUSTOM_BASE_URL, ""); } public String getMythTvServiceHost() { if (isServiceProxy()) return getServiceProxyIp(); else return getBackendHost(); } public String getMythlingServiceHost() { if (isServiceProxy()) return getServiceProxyIp(); else return getBackendHost(); } public String getBackendHost() { if (isExternalNetwork()) return getExternalBackendHost(); else return getInternalBackendHost(); } public URL[] getUrls(URL url) throws MalformedURLException { if (isExternalNetwork() && isIpRetrieval()) return new URL[] { url, getIpRetrievalUrl() }; else return new URL[] { url }; } public int getVideoRes() { if (isExternalNetwork()) return getExternalVideoRes(); else return getInternalVideoRes(); } public int getVideoBitrate() { if (isExternalNetwork()) return getExternalVideoBitrate(); else return getInternalVideoBitrate(); } public int getAudioBitrate() { if (isExternalNetwork()) return getExternalAudioBitrate(); else return getInternalAudioBitrate(); } public String getVideoQualityParams() { return "Height=" + getVideoRes() + "&Bitrate=" + getVideoBitrate() + "&AudioBitrate=" + getAudioBitrate(); } public int getInternalVideoRes() { return Integer.parseInt(prefs.getString(INTERNAL_VIDEO_RES, "720")); } public int getExternalVideoRes() { return Integer.parseInt(prefs.getString(EXTERNAL_VIDEO_RES, "240")); } public int getInternalVideoBitrate() { return Integer.parseInt(prefs.getString(INTERNAL_VIDEO_BITRATE, "1600000")); } public int getExternalVideoBitrate() { return Integer.parseInt(prefs.getString(EXTERNAL_VIDEO_BITRATE, "400000")); } public int getInternalAudioBitrate() { return Integer.parseInt(prefs.getString(INTERNAL_AUDIO_BITRATE, "64000")); } public int getExternalAudioBitrate() { return Integer.parseInt(prefs.getString(EXTERNAL_AUDIO_BITRATE, "32000")); } public int[] getVideoResValues() { return stringArrayToIntArray(appContext.getResources().getStringArray(R.array.video_res_values)); } public int[] getVideoBitrateValues() { return stringArrayToIntArray(appContext.getResources().getStringArray(R.array.video_bitrate_values)); } public int[] getAudioBitrateValues() { return stringArrayToIntArray(appContext.getResources().getStringArray(R.array.audio_bitrate_values)); } private int[] stringArrayToIntArray(String[] stringVals) { int[] values = new int[stringVals.length]; for (int i = 0; i < stringVals.length; i++) values[i] = Integer.parseInt(stringVals[i]); return values; } private MediaSettings mediaSettings; public MediaSettings getMediaSettings() { if (mediaSettings == null) { String mediaType = prefs.getString(MEDIA_TYPE, DEFAULT_MEDIA_TYPE); mediaSettings = new MediaSettings(mediaType); String typeDeterminer = prefs.getString(CATEGORIZE_VIDEOS, MediaTypeDeterminer.metadata.toString()); mediaSettings.setTypeDeterminer(typeDeterminer); String viewType = prefs.getString(VIEW_TYPE + ":" + mediaSettings.getType().toString(), "list"); mediaSettings.setViewType(viewType); String sortType = prefs.getString(SORT_TYPE + ":" + mediaSettings.getType().toString(), "byTitle"); mediaSettings.setSortType(sortType); } return mediaSettings; } public boolean setMediaType(MediaType mediaType) { Editor ed = prefs.edit(); ed.putString(MEDIA_TYPE, mediaType.toString()); boolean res = ed.commit(); mediaSettings = null; return res; } public boolean setViewType(ViewType type) { Editor ed = prefs.edit(); ed.putString(VIEW_TYPE + ":" + getMediaSettings().getType().toString(), type.toString()); boolean res = ed.commit(); mediaSettings = null; return res; } public boolean setSortType(SortType type) { Editor ed = prefs.edit(); ed.putString(SORT_TYPE + ":" + getMediaSettings().getType().toString(), type.toString()); boolean res = ed.commit(); mediaSettings = null; return res; } public int getMovieCurrentPosition(String category) { return prefs.getInt(MOVIE_CURRENT_POSITION + ":" + category, 0); } public void setMovieCurrentPosition(String category, int curPos) { Editor ed = prefs.edit(); ed.putInt(MOVIE_CURRENT_POSITION + ":" + category, curPos); ed.apply(); } public int getExpiryMinutes() { return Integer.parseInt(prefs.getString(CACHE_EXPIRE_MINUTES, "30").trim()); } public long getLastLoad() { return prefs.getLong(LAST_LOAD, 0l); } public boolean setLastLoad(long ll) { Editor ed = prefs.edit(); ed.putLong(LAST_LOAD, ll); return ed.commit(); } public URL getIpRetrievalUrl() throws MalformedURLException { return new URL(getIpRetrievalUrlString()); } public String getIpRetrievalUrlString() { return prefs.getString(IP_RETRIEVAL_URL, "").trim(); } public boolean isIpRetrieval() { return prefs.getBoolean(RETRIEVE_IP, false); } public String getMythTvServicesAuthType() { return prefs.getString(MYTHTV_SERVICES_AUTH_TYPE, "None"); } public String getMythTvServicesUser() { return prefs.getString(MYTHTV_SERVICES_USER, "").trim(); } public String getMythTvServicesPassword() { return prefs.getString(MYTHTV_SERVICES_PASSWORD, "").trim(); } public String getMythTvServicesPasswordMasked() { return getMasked(getMythTvServicesPassword()); } public String getMythlingServicesAuthType() { return prefs.getString(MYTHLING_SERVICES_AUTH_TYPE, "None"); } public String getMythlingServicesUser() { return prefs.getString(MYTHLING_SERVICES_USER, "").trim(); } public String getMythlingServicesPassword() { return prefs.getString(MYTHLING_SERVICES_PASSWORD, "").trim(); } public String getMythlingServicesPasswordMasked() { return getMasked(getMythlingServicesPassword()); } public static String getMasked(String in) { String masked = ""; for (int i = 0; i < in.length(); i++) masked += "*"; return masked; } public int getTunerTimeout() { return Integer.parseInt(prefs.getString(TUNER_TIMEOUT, "30").trim()); } public int getTranscodeTimeout() { return Integer.parseInt(prefs.getString(TRANSCODE_TIMEOUT, "30").trim()); } // change these values and recompile to route service calls through a reverse proxy private boolean serviceProxy = false; private String serviceProxyIp = "192.168.0.100"; private int serviceProxyPort = 8888; public boolean isServiceProxy() { return serviceProxy; } public String getServiceProxyIp() { return serviceProxyIp; } public int getServiceProxyPort() { return serviceProxyPort; } public static final String IPADDRESS_PATTERN = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"; private static Pattern ipAddressPattern; public static boolean validateIp(String ip) { if (ipAddressPattern == null) ipAddressPattern = Pattern.compile(IPADDRESS_PATTERN); Matcher matcher = ipAddressPattern.matcher(ip); return matcher.matches(); } public boolean validateHost(String host) { if (host == null) return false; if (Character.isDigit(host.charAt(0))) return validateIp(host); return true; } public void validate() throws BadSettingsException { if (isDevicePlayback()) { if (isExternalNetwork()) { if (isIpRetrieval()) { try { if (getIpRetrievalUrlString().isEmpty()) throw new BadSettingsException("Network > External Backend > IP Retrieval URL"); getIpRetrievalUrl(); } catch (MalformedURLException ex) { try { String withProtocol = "http://" + getIpRetrievalUrlString(); new URL(withProtocol); Editor ed = prefs.edit(); ed.putString(IP_RETRIEVAL_URL, withProtocol); ed.commit(); } catch (MalformedURLException ex2) { throw new BadSettingsException("Network > External Backend > IP Retrieval URL", ex2); } } } else { if (!validateHost(getExternalBackendHost())) throw new BadSettingsException("Network > External Backend > Host"); } } else { if (!validateHost(getInternalBackendHost())) throw new BadSettingsException("Network > Internal Backend > Host"); } // backend ports regardless of internal/external network try { if (getMythTvServicePort() <= 0) throw new BadSettingsException("Connections > Content Services > MythTV Service Port"); } catch (NumberFormatException ex) { throw new BadSettingsException("Connections > Content Services > MythTV Service Port", ex); } try { if (isMythlingMediaServices() && getMythlingWebPort() <= 0) throw new BadSettingsException("Connections > Media Services > Mythling Web Port"); } catch (NumberFormatException ex) { throw new BadSettingsException("Connections > Media Services > Mythling Web Port", ex); } // services only used for device playback if (!getMythTvServicesAuthType().equals("None")) { if (getMythTvServicesUser().isEmpty()) throw new BadSettingsException("Settings > Credentials > MythTV Services > User"); if (getMythTvServicesPassword().isEmpty()) throw new BadSettingsException("Settings > Credentials > MythTV Services > Password"); } } else { if (!validateHost(getFrontendHost())) throw new BadSettingsException("Settings > Playback > Frontend Player > Host"); try { if (getFrontendControlPort() <=0 ) throw new BadSettingsException("Settings > Playback > Frontend Player > Control Port"); } catch (NumberFormatException ex) { throw new BadSettingsException("Settings > Playback > Frontend Player > Control Port", ex); } } if (isMythlingMediaServices() && !getMythlingServicesAuthType().equals("None")) { if (getMythlingServicesUser().isEmpty()) throw new BadSettingsException("Settings > Credentials > Mythling Services > User"); if (getMythlingServicesPassword().isEmpty()) throw new BadSettingsException("Settings > Credentials > Mythling Services > Password"); } try { if (getExpiryMinutes() < 0) throw new BadSettingsException("Settings > Data Caching > Expiry Interval"); } catch (NumberFormatException ex) { throw new BadSettingsException("Settings > Data Caching > Expiry Interval", ex); } } public HttpHelper getMediaListDownloader(URL[] urls) { HttpHelper downloader; if (isMythlingMediaServices()) { downloader = new HttpHelper(urls, getMythlingServicesAuthType(), getPrefs()); downloader.setCredentials(getMythlingServicesUser(), getMythlingServicesPassword()); } else { downloader = new HttpHelper(urls, getMythTvServicesAuthType(), getPrefs()); downloader.setCredentials(getMythTvServicesUser(), getMythTvServicesPassword()); } return downloader; } }
package com.opencms.file.genericSql; import javax.servlet.http.*; import java.util.*; import java.sql.*; import java.security.*; import java.io.*; import source.org.apache.java.io.*; import source.org.apache.java.util.*; import com.opencms.core.*; import com.opencms.file.*; import com.opencms.file.utils.*; import com.opencms.util.*; public class CmsDbAccess implements I_CmsConstants, I_CmsLogChannels { /** * The session-timeout value: * currently six hours. After that time the session can't be restored. */ public static long C_SESSION_TIMEOUT = 6 * 60 * 60 * 1000; /** * The maximum amount of tables. */ protected static int C_MAX_TABLES = 18; /** * Table-key for max-id */ protected static int C_TABLE_SYSTEMPROPERTIES = 0; /** * Table-key for max-id */ protected static int C_TABLE_GROUPS = 1; /** * Table-key for max-id */ protected static int C_TABLE_GROUPUSERS = 2; /** * Table-key for max-id */ protected static int C_TABLE_USERS = 3; /** * Table-key for max-id */ protected static int C_TABLE_PROJECTS = 4; /** * Table-key for max-id */ protected static int C_TABLE_RESOURCES = 5; /** * Table-key for max-id */ protected static int C_TABLE_FILES = 6; /** * Table-key for max-id */ protected static int C_TABLE_PROPERTYDEF = 7; /** * Table-key for max-id */ protected static int C_TABLE_PROPERTIES = 8; /** * Table-key for max-id */ protected static int C_TABLE_TASK = 9; /** * Table-key for max-id */ protected static int C_TABLE_TASKTYPE = 10; /** * Table-key for max-id */ protected static int C_TABLE_TASKPAR = 11; /** * Table-key for max-id */ protected static int C_TABLE_TASKLOG = 12; /** * Table-key for max-id */ protected static int C_TABLE_SITES = 13; /** * Table-key for max-id */ protected static int C_TABLE_SITE_PROJECTS = 14; /** * Table-key for max-id */ protected static int C_TABLE_SITE_URLS = 15; /** * Table-key for max-id */ protected static int C_TABLE_CATEGORY = 16; /** * Table-key for max-id */ protected static int C_TABLE_LANGUAGE = 17; /** * Table-key for max-id */ protected static int C_TABLE_COUNTRY = 18; /** * Constant to get property from configurations. */ protected static String C_CONFIGURATIONS_DRIVER = "driver"; /** * Constant to get property from configurations. */ protected static String C_CONFIGURATIONS_URL = "url"; /** * Constant to get property from configurations. */ protected static String C_CONFIGURATIONS_USER = "user"; /** * Constant to get property from configurations. */ protected static String C_CONFIGURATIONS_PASSWORD = "password"; /** * Constant to get property from configurations. */ protected static String C_CONFIGURATIONS_MAX_CONN = "maxConn"; /** * Constant to get property from configurations. */ protected static String C_CONFIGURATIONS_DIGEST = "digest"; /** * Constant to get property from configurations. */ protected static String C_CONFIGURATIONS_GUARD = "guard"; /** * The prepared-statement-pool. */ protected I_CmsDbPool m_pool = null; /** * The connection guard. */ protected CmsConnectionGuard m_guard = null; /** * A array containing all max-ids for the tables. */ protected int[] m_maxIds; /** * A digest to encrypt the passwords. */ protected MessageDigest m_digest = null; /** * Storage for all exportpoints */ protected Hashtable m_exportpointStorage=null; /** * 'Constants' file. */ protected com.opencms.file.genericSql.CmsQueries m_cq; /** * Creates a serializable object in the systempropertys. * * @param name The name of the property. * @param object The property-object. * * @return object The property-object. * * @exception CmsException Throws CmsException if something goes wrong. */ public Serializable addSystemProperty(String name, Serializable object) throws CmsException { byte[] value; PreparedStatement statement=null; try { // serialize the object ByteArrayOutputStream bout= new ByteArrayOutputStream(); ObjectOutputStream oout=new ObjectOutputStream(bout); oout.writeObject(object); oout.close(); value=bout.toByteArray(); // create the object statement=m_pool.getPreparedStatement(m_cq.C_SYSTEMPROPERTIES_WRITE_KEY); statement.setInt(1,nextId(C_TABLE_SYSTEMPROPERTIES)); statement.setString(2,name); statement.setBytes(3,value); statement.executeUpdate(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e); } catch (IOException e){ throw new CmsException("["+this.getClass().getName()+"]"+CmsException. C_SERIALIZATION, e); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_SYSTEMPROPERTIES_WRITE_KEY, statement); } } return readSystemProperty(name); } /** * Adds a user to the database. * * @param name username * @param password user-password * @param description user-description * @param firstname user-firstname * @param lastname user-lastname * @param email user-email * @param lastlogin user-lastlogin * @param lastused user-lastused * @param flags user-flags * @param additionalInfos user-additional-infos * @param defaultGroup user-defaultGroup * @param address user-defauladdress * @param section user-section * @param type user-type * * @return the created user. * @exception thorws CmsException if something goes wrong. */ public CmsUser addUser(String name, String password, String description, String firstname, String lastname, String email, long lastlogin, long lastused, int flags, Hashtable additionalInfos, CmsGroup defaultGroup, String address, String section, int type) throws CmsException { int id = nextId(C_TABLE_USERS); byte[] value=null; PreparedStatement statement = null; try { // serialize the hashtable ByteArrayOutputStream bout= new ByteArrayOutputStream(); ObjectOutputStream oout=new ObjectOutputStream(bout); oout.writeObject(additionalInfos); oout.close(); value=bout.toByteArray(); // write data to database statement = m_pool.getPreparedStatement(m_cq.C_USERS_ADD_KEY); statement.setInt(1,id); statement.setString(2,name); // crypt the password with MD5 statement.setString(3, digest(password)); statement.setString(4, digest("")); statement.setString(5,checkNull(description)); statement.setString(6,checkNull(firstname)); statement.setString(7,checkNull(lastname)); statement.setString(8,checkNull(email)); statement.setTimestamp(9, new Timestamp(lastlogin)); statement.setTimestamp(10, new Timestamp(lastused)); statement.setInt(11,flags); statement.setBytes(12,value); statement.setInt(13,defaultGroup.getId()); statement.setString(14,checkNull(address)); statement.setString(15,checkNull(section)); statement.setInt(16,type); statement.executeUpdate(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e); } catch (IOException e){ throw new CmsException("[CmsAccessUserInfoMySql/addUserInformation(id,object)]:"+CmsException. C_SERIALIZATION, e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_USERS_ADD_KEY, statement); } } return readUser(id); } /** * Adds a user to a group.<BR/> * * Only the admin can do this.<P/> * * @param userid The id of the user that is to be added to the group. * @param groupid The id of the group. * @exception CmsException Throws CmsException if operation was not succesfull. */ public void addUserToGroup(int userid, int groupid) throws CmsException { PreparedStatement statement = null; // check if user is already in group if (!userInGroup(userid,groupid)) { // if not, add this user to the group try { // create statement statement = m_pool.getPreparedStatement(m_cq.C_GROUPS_ADDUSERTOGROUP_KEY); // write the new assingment to the database statement.setInt(1,groupid); statement.setInt(2,userid); // flag field is not used yet statement.setInt(3,C_UNKNOWN_INT); statement.executeUpdate(); } catch (SQLException e){ throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_GROUPS_ADDUSERTOGROUP_KEY, statement); } } } } /** * Private helper method for publihing into the filesystem. * test if resource must be written to the filesystem * * @param filename Name of a resource in the OpenCms system. * @return key in m_exportpointStorage Hashtable or null. */ protected String checkExport(String filename){ String key = null; String exportpoint = null; Enumeration e = m_exportpointStorage.keys(); while (e.hasMoreElements()) { exportpoint = (String)e.nextElement(); if (filename.startsWith(exportpoint)){ return exportpoint; } } return key; } /** * Checks, if the String was null or is empty. If this is so it returns " ". * * This is for oracle-issues, because in oracle an empty string is the same as null. * @param value the String to check. * @return the value, or " " if needed. */ protected String checkNull(String value) { String ret = " "; if( (value != null) && (value.length() != 0) ) { ret = value; } return ret; } /** * Deletes all files in CMS_FILES without fileHeader in CMS_RESOURCES * * */ protected void clearFilesTable() throws CmsException{ PreparedStatement statementSearch = null; PreparedStatement statementDestroy = null; ResultSet res = null; try{ statementSearch = m_pool.getPreparedStatement(m_cq.C_RESOURCES_GET_LOST_ID_KEY); res = statementSearch.executeQuery(); // delete the lost fileId's statementDestroy = m_pool.getPreparedStatement(m_cq.C_FILE_DELETE_KEY); while (res.next() ){ statementDestroy.setInt(1,res.getInt(m_cq.C_FILE_ID)); statementDestroy.executeUpdate(); statementDestroy.clearParameters(); } res.close(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e); }finally { if( statementSearch != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_GET_LOST_ID_KEY, statementSearch); } if( statementDestroy != null) { m_pool.putPreparedStatement(m_cq.C_FILE_DELETE_KEY, statementDestroy); } } } /** * Copies the file. * * @param project The project in which the resource will be used. * @param onlineProject The online project of the OpenCms. * @param userId The id of the user who wants to copy the file. * @param source The complete path of the sourcefile. * @param parentId The parentId of the resource. * @param destination The complete path of the destinationfile. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void copyFile(CmsProject project, CmsProject onlineProject, int userId, String source, int parentId, String destination) throws CmsException { CmsFile file; // read sourcefile try { file=readFile(project.getId(),source); } catch (SQLException se) { throw new CmsException(CmsException.C_SQL_ERROR,se); } if (file != null) // create destination file createFile(project,onlineProject,file,userId,parentId,destination, true); else throw new CmsException(this.getClass().getName()+".copyFile():" + source, CmsException.C_NOT_FOUND); } // methods working with resources /** * Copies a resource from the online project to a new, specified project.<br> * * @param project The project to be published. * @param onlineProject The online project of the OpenCms. * @param resource The resource to be copied to the offline project. * @exception CmsException Throws CmsException if operation was not succesful. */ public void copyResourceToProject(CmsProject project, CmsProject onlineProject, CmsResource resource) throws CmsException { // get the parent resource in the offline project int id=C_UNKNOWN_ID; try { CmsResource parent=readResource(project,resource.getParent()); id=parent.getResourceId(); } catch (CmsException e) { } resource.setState(C_STATE_UNCHANGED); resource.setParentId(id); createResource(project,onlineProject,resource); } /** * Counts the locked resources in this project. * * @param project The project to be unlocked. * @return the amount of locked resources in this project. * * @exception CmsException Throws CmsException if something goes wrong. */ public int countLockedResources(CmsProject project) throws CmsException { PreparedStatement statement = null; ResultSet res = null; int retValue; try { // create the statement statement = m_pool.getPreparedStatement(m_cq.C_RESOURCES_COUNTLOCKED_KEY); statement.setInt(1,project.getId()); res = statement.executeQuery(); if(res.next()) { retValue = res.getInt(1); } else { res.close(); retValue=0; } res.close(); } catch( Exception exc ) { throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(), CmsException.C_SQL_ERROR, exc); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_COUNTLOCKED_KEY, statement); } } return retValue; } // methods working with properties /** * Returns the amount of properties for a propertydefinition. * * @param metadef The propertydefinition to test. * * @return the amount of properties for a propertydefinition. * * @exception CmsException Throws CmsException if something goes wrong. */ protected int countProperties(CmsPropertydefinition metadef) throws CmsException { ResultSet result = null; PreparedStatement statement = null; int returnValue; try { // create statement statement = m_pool.getPreparedStatement(m_cq.C_PROPERTIES_READALL_COUNT_KEY); statement.setInt(1, metadef.getId()); result = statement.executeQuery(); if( result.next() ) { returnValue = result.getInt(1) ; } else { throw new CmsException("[" + this.getClass().getName() + "] " + metadef.getName(), CmsException.C_UNKNOWN_EXCEPTION); } result.close(); } catch(SQLException exc) { throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(), CmsException.C_SQL_ERROR, exc); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_PROPERTIES_READALL_COUNT_KEY, statement); } } return returnValue; } public CmsCategory createCategory(String name, String description, String shortName, int priority) throws CmsException { CmsCategory category = null; PreparedStatement statement = null; try { statement = m_pool.getPreparedStatement(m_cq.C_CATEGORY_INSERTCATEGORY_KEY); int id = nextId(C_TABLE_CATEGORY); statement.setInt(1, id); statement.setString(2, name); statement.setString(3, checkNull(description)); statement.setString(4, shortName); statement.setInt(5, priority); statement.executeUpdate(); category = new CmsCategory(id, name, description, shortName, priority); } catch (SQLException e) { throw new CmsException("[" + this.getClass().getName() + "] " + e.getMessage(), CmsException.C_SQL_ERROR, e); } finally { if (statement != null) { m_pool.putPreparedStatement(m_cq.C_CATEGORY_INSERTCATEGORY_KEY, statement); } } return category; } public CmsConnectionGuard createCmsConnectionGuard(I_CmsDbPool m_pool, long sleepTime) { return new com.opencms.file.genericSql.CmsConnectionGuard(m_pool, sleepTime); } public I_CmsDbPool createCmsDbPool(String driver, String url, String user, String passwd, int maxConn) throws com.opencms.core.CmsException { return new com.opencms.file.genericSql.CmsDbPool(driver,url,user,passwd,maxConn); } public CmsCountry createCountry(String name, String shortName, int priority) throws com.opencms.core.CmsException { CmsCountry country = null; PreparedStatement statement = null; try { statement = m_pool.getPreparedStatement(m_cq.C_COUNTRY_INSERTCOUNTRY_KEY); int id = nextId(C_TABLE_COUNTRY); statement.setInt(1, id); statement.setString(2, name); statement.setString(3, shortName); statement.setInt(4, priority); statement.executeUpdate(); country = new CmsCountry(id, name, shortName, priority); } catch (SQLException e) { throw new CmsException("[" + this.getClass().getName() + "] " + e.getMessage(), CmsException.C_SQL_ERROR, e); } finally { if (statement != null) { m_pool.putPreparedStatement(m_cq.C_COUNTRY_INSERTCOUNTRY_KEY, statement); } } return country; } /** * Creates a new file from an given CmsFile object and a new filename. * * @param project The project in which the resource will be used. * @param onlineProject The online project of the OpenCms. * @param file The file to be written to the Cms. * @param user The Id of the user who changed the resourse. * @param parentId The parentId of the resource. * @param filename The complete new name of the file (including pathinformation). * * @return file The created file. * * @exception CmsException Throws CmsException if operation was not succesful */ public CmsFile createFile(CmsProject project, CmsProject onlineProject, CmsFile file, int userId, int parentId, String filename, boolean copy) throws CmsException { int state=0; if (project.equals(onlineProject)) { state= file.getState(); } else { state=C_STATE_NEW; } // Test if the file is already there and marked as deleted. // If so, delete it try { CmsResource resource = readFileHeader(project.getId(),filename); if ((resource != null) && (resource.getState() == C_STATE_DELETED)) { removeFile(project.getId(),filename); state=C_STATE_CHANGED; } } catch (SQLException se) { throw new CmsException(CmsException.C_SQL_ERROR,se); } int newFileId = file.getFileId(); int resourceId = nextId(C_TABLE_RESOURCES); if (copy){ PreparedStatement statementFileWrite = null; try { newFileId = nextId(C_TABLE_FILES); statementFileWrite = m_pool.getPreparedStatement(m_cq.C_FILES_WRITE_KEY); statementFileWrite.setInt(1, newFileId); statementFileWrite.setBytes(2, file.getContents()); statementFileWrite.executeUpdate(); } catch (SQLException se) { if(A_OpenCms.isLogging()) { A_OpenCms.log(C_OPENCMS_CRITICAL, "[CmsAccessFileMySql] " + se.getMessage()); se.printStackTrace(); } }finally { if( statementFileWrite != null) { m_pool.putPreparedStatement(m_cq.C_FILES_WRITE_KEY, statementFileWrite); } } } PreparedStatement statementResourceWrite = null; try { statementResourceWrite = m_pool.getPreparedStatement(m_cq.C_RESOURCES_WRITE_KEY); statementResourceWrite.setInt(1,resourceId); statementResourceWrite.setInt(2,parentId); statementResourceWrite.setString(3, filename); statementResourceWrite.setInt(4,file.getType()); statementResourceWrite.setInt(5,file.getFlags()); statementResourceWrite.setInt(6,file.getOwnerId()); statementResourceWrite.setInt(7,file.getGroupId()); statementResourceWrite.setInt(8,project.getId()); statementResourceWrite.setInt(9,newFileId); statementResourceWrite.setInt(10,file.getAccessFlags()); statementResourceWrite.setInt(11,state); statementResourceWrite.setInt(12,file.isLockedBy()); statementResourceWrite.setInt(13,file.getLauncherType()); statementResourceWrite.setString(14,file.getLauncherClassname()); statementResourceWrite.setTimestamp(15,new Timestamp(file.getDateCreated())); statementResourceWrite.setTimestamp(16,new Timestamp(System.currentTimeMillis())); statementResourceWrite.setInt(17,file.getLength()); statementResourceWrite.setInt(18,userId); statementResourceWrite.executeUpdate(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e); }finally { if( statementResourceWrite != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_WRITE_KEY, statementResourceWrite); } } try { return readFile(project.getId(),filename); } catch (SQLException se) { throw new CmsException(CmsException.C_SQL_ERROR,se); } } /** * Creates a new file with the given content and resourcetype. * * @param user The user who wants to create the file. * @param project The project in which the resource will be used. * @param onlineProject The online project of the OpenCms. * @param filename The complete name of the new file (including pathinformation). * @param flags The flags of this resource. * @param parentId The parentId of the resource. * @param contents The contents of the new file. * @param resourceType The resourceType of the new file. * * @return file The created file. * * @exception CmsException Throws CmsException if operation was not succesful */ public CmsFile createFile(CmsUser user, CmsProject project, CmsProject onlineProject, String filename, int flags,int parentId, byte[] contents, CmsResourceType resourceType) throws CmsException { // it is not allowed, that there is no content in the file // TODO: check if this can be done in another way: if(contents.length == 0) { contents = " ".getBytes(); } int state= C_STATE_NEW; // Test if the file is already there and marked as deleted. // If so, delete it try { CmsResource resource = readFileHeader(project.getId(),filename); if ((resource != null) && (resource.getState() == C_STATE_DELETED)) { removeFile(project.getId(),filename); state=C_STATE_CHANGED; } } catch (SQLException se) { throw new CmsException(CmsException.C_SQL_ERROR,se); } int resourceId = nextId(C_TABLE_RESOURCES); int fileId = nextId(C_TABLE_FILES); PreparedStatement statement = null; PreparedStatement statementFileWrite = null; try { statement = m_pool.getPreparedStatement(m_cq.C_RESOURCES_WRITE_KEY); // write new resource to the database statement.setInt(1,resourceId); statement.setInt(2,parentId); statement.setString(3, filename); statement.setInt(4,resourceType.getResourceType()); statement.setInt(5,flags); statement.setInt(6,user.getId()); statement.setInt(7,user.getDefaultGroupId()); statement.setInt(8,project.getId()); statement.setInt(9,fileId); statement.setInt(10,C_ACCESS_DEFAULT_FLAGS); statement.setInt(11,state); statement.setInt(12,C_UNKNOWN_ID); statement.setInt(13,resourceType.getLauncherType()); statement.setString(14,resourceType.getLauncherClass()); statement.setTimestamp(15,new Timestamp(System.currentTimeMillis())); statement.setTimestamp(16,new Timestamp(System.currentTimeMillis())); statement.setInt(17,contents.length); statement.setInt(18,user.getId()); statement.executeUpdate(); statementFileWrite = m_pool.getPreparedStatement(m_cq.C_FILES_WRITE_KEY); statementFileWrite.setInt(1,fileId); statementFileWrite.setBytes(2,contents); statementFileWrite.executeUpdate(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_WRITE_KEY, statement); } if( statementFileWrite != null) { m_pool.putPreparedStatement(m_cq.C_FILES_WRITE_KEY, statementFileWrite); } } try { return readFile(project.getId(),filename); } catch (SQLException se) { throw new CmsException(CmsException.C_SQL_ERROR,se); } } /** * Creates a new folder * * @param user The user who wants to create the folder. * @param project The project in which the resource will be used. * @param parentId The parentId of the folder. * @param fileId The fileId of the folder. * @param foldername The complete path to the folder in which the new folder will * be created. * @param flags The flags of this resource. * * @return The created folder. * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsFolder createFolder(CmsUser user, CmsProject project, int parentId, int fileId, String foldername, int flags) throws CmsException { CmsFolder oldFolder = null; int state = C_STATE_NEW; // Test if the folder is already there and marked as deleted. // If so, delete it try { oldFolder = readFolder(project.getId(), foldername); } catch (SQLException se) { throw new CmsException(CmsException.C_SQL_ERROR,se); } if ((oldFolder != null) && (oldFolder.getState() == C_STATE_DELETED)) { removeFolder(oldFolder); state = C_STATE_CHANGED; } int resourceId = nextId(C_TABLE_RESOURCES); PreparedStatement statement = null; try { // write new resource to the database statement = m_pool.getPreparedStatement(m_cq.C_RESOURCES_WRITE_KEY); statement.setInt(1, resourceId); statement.setInt(2, parentId); statement.setString(3, foldername); statement.setInt(4, C_TYPE_FOLDER); statement.setInt(5, flags); statement.setInt(6, user.getId()); statement.setInt(7, user.getDefaultGroupId()); statement.setInt(8, project.getId()); statement.setInt(9, fileId); statement.setInt(10, C_ACCESS_DEFAULT_FLAGS); statement.setInt(11, state); statement.setInt(12, C_UNKNOWN_ID); statement.setInt(13, C_UNKNOWN_LAUNCHER_ID); statement.setString(14, C_UNKNOWN_LAUNCHER); statement.setTimestamp(15, new Timestamp(System.currentTimeMillis())); statement.setTimestamp(16, new Timestamp(System.currentTimeMillis())); statement.setInt(17, 0); statement.setInt(18, user.getId()); statement.executeUpdate(); } catch (SQLException e) { throw new CmsException("[" + this.getClass().getName() + "] " + e.getMessage(), CmsException.C_SQL_ERROR, e); } finally { if (statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_WRITE_KEY, statement); } } try { return readFolder(project.getId(), foldername); } catch (SQLException se) { throw new CmsException(CmsException.C_SQL_ERROR,se); } } /** * Creates a new folder from an existing folder object. * * @param user The user who wants to create the folder. * @param project The project in which the resource will be used. * @param onlineProject The online project of the OpenCms. * @param folder The folder to be written to the Cms. * @param parentId The parentId of the resource. * * @param foldername The complete path of the new name of this folder. * * @return The created folder. * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsFolder createFolder(CmsUser user, CmsProject project, CmsProject onlineProject, CmsFolder folder, int parentId, String foldername) throws CmsException{ CmsFolder oldFolder = null; int state=0; if (project.equals(onlineProject)) { state=folder.getState(); } else { state=C_STATE_NEW; } // Test if the file is already there and marked as deleted. // If so, delete it try { oldFolder = readFolder(project.getId(),foldername); } catch (SQLException se) { throw new CmsException(CmsException.C_SQL_ERROR,se); } if ((oldFolder != null) && (oldFolder.getState() == C_STATE_DELETED)) { removeFolder(oldFolder); state = C_STATE_CHANGED; } int resourceId = nextId(C_TABLE_RESOURCES); int fileId = nextId(C_TABLE_FILES); PreparedStatement statement = null; try { // write new resource to the database statement = m_pool.getPreparedStatement(m_cq.C_RESOURCES_WRITE_KEY); statement.setInt(1,resourceId); statement.setInt(2,parentId); statement.setString(3, foldername); statement.setInt(4,folder.getType()); statement.setInt(5,folder.getFlags()); statement.setInt(6,folder.getOwnerId()); statement.setInt(7,folder.getGroupId()); statement.setInt(8,project.getId()); statement.setInt(9,fileId); statement.setInt(10,folder.getAccessFlags()); statement.setInt(11,state); statement.setInt(12,folder.isLockedBy()); statement.setInt(13,folder.getLauncherType()); statement.setString(14,folder.getLauncherClassname()); statement.setTimestamp(15,new Timestamp(folder.getDateCreated())); statement.setTimestamp(16,new Timestamp(System.currentTimeMillis())); statement.setInt(17,0); statement.setInt(18,user.getId()); statement.executeUpdate(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_WRITE_KEY, statement); } } //return readFolder(project,folder.getAbsolutePath()); try { return readFolder(project.getId(),foldername); } catch (SQLException se) { throw new CmsException(CmsException.C_SQL_ERROR,se); } } // methods working with users and groups /** * Add a new group to the Cms.<BR/> * * Only the admin can do this.<P/> * * @param name The name of the new group. * @param description The description for the new group. * @int flags The flags for the new group. * @param name The name of the parent group (or null). * * @return Group * * @exception CmsException Throws CmsException if operation was not succesfull. */ public CmsGroup createGroup(String name, String description, int flags,String parent) throws CmsException { int parentId=C_UNKNOWN_ID; CmsGroup group=null; PreparedStatement statement=null; try{ // get the id of the parent group if nescessary if ((parent != null) && (!"".equals(parent))) { parentId=readGroup(parent).getId(); } // create statement statement=m_pool.getPreparedStatement(m_cq.C_GROUPS_CREATEGROUP_KEY); // write new group to the database statement.setInt(1,nextId(C_TABLE_GROUPS)); statement.setInt(2,parentId); statement.setString(3,name); statement.setString(4,checkNull(description)); statement.setInt(5,flags); statement.executeUpdate(); // create the user group by reading it from the database. // this is nescessary to get the group id which is generated in the // database. group=readGroup(name); } catch (SQLException e){ throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_GROUPS_CREATEGROUP_KEY,statement); } } return group; } public CmsLanguage createLanguage(String name, String shortName, int priority) throws com.opencms.core.CmsException { CmsLanguage language = null; PreparedStatement statement = null; try { statement = m_pool.getPreparedStatement(m_cq.C_LANGUAGE_INSERTLANGUAGE_KEY); int id = nextId(C_TABLE_LANGUAGE); statement.setInt(1, id); statement.setString(2, name); statement.setString(3, shortName); statement.setInt(4, priority); statement.executeUpdate(); language = new CmsLanguage(id, name, shortName, priority); } catch (SQLException e) { throw new CmsException("[" + this.getClass().getName() + "] " + e.getMessage(), CmsException.C_SQL_ERROR, e); } finally { if (statement != null) { m_pool.putPreparedStatement(m_cq.C_LANGUAGE_INSERTLANGUAGE_KEY, statement); } } return language; } // methods working with projects /** * Creates a project. * * @param owner The owner of this project. * @param group The group for this project. * @param managergroup The managergroup for this project. * @param task The task. * @param name The name of the project to create. * @param description The description for the new project. * @param flags The flags for the project (e.g. archive). * @param type the type for the project (e.g. normal). * @param parentProject the type for the project (e.g. normal). * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsProject createProject(CmsUser owner, CmsGroup group, CmsGroup managergroup, CmsTask task, String name, String description, int flags, int type, int parentProject) throws CmsException { if ((description==null) || (description.length()<1)) { description=" "; } Timestamp createTime = new Timestamp(new java.util.Date().getTime()); PreparedStatement statement = null; int id = nextId(C_TABLE_PROJECTS); try { // write data to database statement = m_pool.getPreparedStatement(m_cq.C_PROJECTS_CREATE_KEY); statement.setInt(1,id); statement.setInt(2,owner.getId()); statement.setInt(3,group.getId()); statement.setInt(4,managergroup.getId()); statement.setInt(5,task.getId()); statement.setString(6,name); statement.setString(7,description); statement.setInt(8,flags); statement.setTimestamp(9,createTime); statement.setNull(10,Types.TIMESTAMP); statement.setInt(11,C_UNKNOWN_ID); statement.setInt(12,type); statement.setInt(13,parentProject); statement.executeUpdate(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_PROJECTS_CREATE_KEY, statement); } } try { CmsProject project = readProject(id); if (project == null) throw new CmsException(this.getClass().getName()+".createProject(): Project not found", CmsException.C_NOT_FOUND); return project; } catch (SQLException se) { throw new CmsException(CmsException.C_SQL_ERROR,se); } } /** * Creates the propertydefinitions for the resource type.<BR/> * * Only the admin can do this. * * @param name The name of the propertydefinitions to overwrite. * @param resourcetype The resource-type for the propertydefinitions. * @param type The type of the propertydefinitions (normal|mandatory|optional) * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsPropertydefinition createPropertydefinition(String name, CmsResourceType resourcetype, int type) throws CmsException { PreparedStatement statement = null; try { // create statement statement = m_pool.getPreparedStatement(m_cq.C_PROPERTYDEF_CREATE_KEY); statement.setInt(1,nextId(C_TABLE_PROPERTYDEF)); statement.setString(2,name); statement.setInt(3,resourcetype.getResourceType()); statement.setInt(4,type); statement.executeUpdate(); } catch( SQLException exc ) { throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(), CmsException.C_SQL_ERROR, exc); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_PROPERTYDEF_CREATE_KEY, statement); } } return(readPropertydefinition(name, resourcetype)); } /** * Creates a new resource from an given CmsResource object. * * @param project The project in which the resource will be used. * @param onlineProject The online project of the OpenCms. * @param resource The resource to be written to the Cms. * * * @exception CmsException Throws CmsException if operation was not succesful */ public void createResource(CmsProject project, CmsProject onlineProject, CmsResource resource) throws CmsException { PreparedStatement statement = null; try { statement=m_pool.getPreparedStatement(m_cq.C_RESOURCES_WRITE_KEY); int id=nextId(C_TABLE_RESOURCES); // write new resource to the database statement.setInt(1,id); statement.setInt(2,resource.getParentId()); statement.setString(3,resource.getAbsolutePath()); statement.setInt(4,resource.getType()); statement.setInt(5,resource.getFlags()); statement.setInt(6,resource.getOwnerId()); statement.setInt(7,resource.getGroupId()); statement.setInt(8,project.getId()); statement.setInt(9,resource.getFileId()); statement.setInt(10,resource.getAccessFlags()); statement.setInt(11,resource.getState()); statement.setInt(12,resource.isLockedBy()); statement.setInt(13,resource.getLauncherType()); statement.setString(14,resource.getLauncherClassname()); statement.setTimestamp(15,new Timestamp(resource.getDateCreated())); statement.setTimestamp(16,new Timestamp(System.currentTimeMillis())); statement.setInt(17,resource.getLength()); statement.setInt(18,resource.getResourceLastModifiedBy()); statement.executeUpdate(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_WRITE_KEY, statement); } } // return readResource(project,resource.getAbsolutePath()); } // methods working with session-storage /** * This method creates a new session in the database. It is used * for sessionfailover. * * @param sessionId the id of the session. * @return data the sessionData. */ public void createSession(String sessionId, Hashtable data) throws CmsException { byte[] value=null; PreparedStatement statement = null; try { // serialize the hashtable ByteArrayOutputStream bout= new ByteArrayOutputStream(); ObjectOutputStream oout=new ObjectOutputStream(bout); oout.writeObject(data); oout.close(); value=bout.toByteArray(); // write data to database statement = m_pool.getPreparedStatement(m_cq.C_SESSION_CREATE_KEY); statement.setString(1,sessionId); statement.setTimestamp(2,new java.sql.Timestamp(System.currentTimeMillis())); statement.setBytes(3,value); statement.executeUpdate(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e); } catch (IOException e){ throw new CmsException("["+this.getClass().getName()+"]:"+CmsException.C_SERIALIZATION, e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_SESSION_CREATE_KEY, statement); } } } /** * Creates a new task. * rootId Id of the root task project * parentId Id of the parent task * tasktype Type of the task * ownerId Id of the owner * agentId Id of the agent * roleId Id of the role * taskname Name of the Task * wakeuptime Time when the task will be wake up * timeout Time when the task times out * priority priority of the task * * @return The Taskobject of the generated Task * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsTask createTask(int rootId, int parentId, int tasktype, int ownerId, int agentId,int roleId, String taskname, java.sql.Timestamp wakeuptime, java.sql.Timestamp timeout, int priority) throws CmsException { int newId = C_UNKNOWN_ID; CmsTask task = null; PreparedStatement statement = null; try { newId = nextId(C_TABLE_TASK); statement = m_pool.getPreparedStatement(m_cq.C_TASK_TYPE_COPY_KEY); // create task by copying from tasktype table statement.setInt(1,newId); statement.setInt(2,tasktype); statement.executeUpdate(); task = this.readTask(newId); task.setRoot(rootId); task.setParent(parentId); task.setName(taskname); task.setTaskType(tasktype); task.setRole(roleId); if(agentId==C_UNKNOWN_ID){ agentId = findAgent(roleId); } task.setAgentUser(agentId); task.setOriginalUser(agentId); task.setWakeupTime(wakeuptime); task.setTimeOut(timeout); task.setPriority(priority); task.setPercentage(0); task.setState(C_TASK_STATE_STARTED); task.setInitiatorUser(ownerId); task.setStartTime(new java.sql.Timestamp(System.currentTimeMillis())); task.setMilestone(0); task = this.writeTask(task); } catch( SQLException exc ) { System.err.println(exc.getMessage()); throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc); } finally { if(statement != null) { m_pool.putPreparedStatement(m_cq.C_TASK_TYPE_COPY_KEY, statement); } } return task; } /** * Deletes all properties for a file or folder. * * @param resourceId The id of the resource. * * @exception CmsException Throws CmsException if operation was not succesful */ public void deleteAllProperties(int resourceId) throws CmsException { PreparedStatement statement = null; try { // create statement statement = m_pool.getPreparedStatement(m_cq.C_PROPERTIES_DELETEALL_KEY); statement.setInt(1, resourceId); statement.executeQuery(); } catch( SQLException exc ) { throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(), CmsException.C_SQL_ERROR, exc); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_PROPERTIES_DELETEALL_KEY, statement); } } } /** * Deletes the file. * * @param project The project in which the resource will be used. * @param filename The complete path of the file. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void deleteFile(CmsProject project, String filename) throws CmsException { PreparedStatement statement = null; try { statement =m_pool.getPreparedStatement(m_cq.C_RESOURCES_REMOVE_KEY); // mark the file as deleted statement.setInt(1,C_STATE_DELETED); statement.setInt(2,C_UNKNOWN_ID); statement.setString(3, filename); statement.setInt(4,project.getId()); statement.executeUpdate(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_REMOVE_KEY, statement); } } } /** * Deletes the folder. * * Only empty folders can be deleted yet. * * @param project The project in which the resource will be used. * @param orgFolder The folder that will be deleted. * @param force If force is set to true, all sub-resources will be deleted. * If force is set to false, the folder will be deleted only if it is empty. * This parameter is not used yet as only empty folders can be deleted! * * @exception CmsException Throws CmsException if operation was not succesful. */ public void deleteFolder(CmsProject project, CmsFolder orgFolder, boolean force) throws CmsException { // the current implementation only deletes empty folders // check if the folder has any files in it Vector files= getFilesInFolder(orgFolder); files=getUndeletedResources(files); if (files.size()==0) { // check if the folder has any folders in it Vector folders= getSubFolders(orgFolder); folders=getUndeletedResources(folders); if (folders.size()==0) { //this folder is empty, delete it PreparedStatement statement = null; try { // mark the folder as deleted statement=m_pool.getPreparedStatement(m_cq.C_RESOURCES_REMOVE_KEY); statement.setInt(1,C_STATE_DELETED); statement.setInt(2,C_UNKNOWN_ID); statement.setString(3, orgFolder.getAbsolutePath()); statement.setInt(4,project.getId()); statement.executeUpdate(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_REMOVE_KEY, statement); } } } else { throw new CmsException("["+this.getClass().getName()+"] "+orgFolder.getAbsolutePath(),CmsException.C_NOT_EMPTY); } } else { throw new CmsException("["+this.getClass().getName()+"] "+orgFolder.getAbsolutePath(),CmsException.C_NOT_EMPTY); } } /** * Delete a group from the Cms.<BR/> * Only groups that contain no subgroups can be deleted. * * Only the admin can do this.<P/> * * @param delgroup The name of the group that is to be deleted. * @exception CmsException Throws CmsException if operation was not succesfull. */ public void deleteGroup(String delgroup) throws CmsException { PreparedStatement statement = null; try { // create statement statement=m_pool.getPreparedStatement(m_cq.C_GROUPS_DELETEGROUP_KEY); statement.setString(1,delgroup); statement.executeUpdate(); } catch (SQLException e){ throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_GROUPS_DELETEGROUP_KEY,statement); } } } /** * Deletes a project from the cms. * Therefore it deletes all files, resources and properties. * * @param project the project to delete. * @exception CmsException Throws CmsException if something goes wrong. */ public void deleteProject(CmsProject project) throws CmsException { // delete the properties deleteProjectProperties(project); // delete the files and resources deleteProjectResources(project); // finally delete the project PreparedStatement statement = null; try { // create the statement statement = m_pool.getPreparedStatement(m_cq.C_PROJECTS_DELETE_KEY); statement.setInt(1,project.getId()); statement.executeUpdate(); } catch( Exception exc ) { throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(), CmsException.C_SQL_ERROR, exc); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_PROJECTS_DELETE_KEY, statement); } } } /** * Deletes all properties for a project. * * @param project The project to delete. * * @exception CmsException Throws CmsException if operation was not succesful */ public void deleteProjectProperties(CmsProject project) throws CmsException { // get all resources of the project Vector resources = readResources(project); for( int i = 0; i < resources.size(); i++) { // delete the properties for each resource in project deleteAllProperties( ((CmsResource) resources.elementAt(i)).getResourceId()); } } /** * Deletes a specified project * * @param project The project to be deleted. * @exception CmsException Throws CmsException if operation was not succesful. */ public void deleteProjectResources(CmsProject project) throws CmsException { PreparedStatement statement = null; try { // delete all project-resources. statement = m_pool.getPreparedStatement(m_cq.C_RESOURCES_DELETE_PROJECT_KEY); statement.setInt(1,project.getId()); statement.executeQuery(); // delete all project-files. //clearFilesTable(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_DELETE_PROJECT_KEY, statement); } } } /** * Delete the propertydefinitions for the resource type.<BR/> * * Only the admin can do this. * * @param metadef The propertydefinitions to be deleted. * * @exception CmsException Throws CmsException if something goes wrong. */ public void deletePropertydefinition(CmsPropertydefinition metadef) throws CmsException { PreparedStatement statement = null; try { if(countProperties(metadef) != 0) { throw new CmsException("[" + this.getClass().getName() + "] " + metadef.getName(), CmsException.C_MANDATORY_PROPERTY); } // create statement statement = m_pool.getPreparedStatement(m_cq.C_PROPERTYDEF_DELETE_KEY); statement.setInt(1, metadef.getId() ); statement.executeUpdate(); } catch( SQLException exc ) { throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(), CmsException.C_SQL_ERROR, exc); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_PROPERTYDEF_DELETE_KEY, statement); } } } /** * Deletes a property for a file or folder. * * @param meta The property-name of which the property has to be read. * @param resourceId The id of the resource. * @param resourceType The Type of the resource. * * @exception CmsException Throws CmsException if operation was not succesful */ public void deleteProperty(String meta, int resourceId, int resourceType) throws CmsException { CmsPropertydefinition propdef = readPropertydefinition(meta, resourceType); if( propdef == null) { // there is no propdefinition with the overgiven name for the resource throw new CmsException("[" + this.getClass().getName() + "] " + meta, CmsException.C_NOT_FOUND); } else { // delete the metainfo in the db PreparedStatement statement = null; try { // create statement statement = m_pool.getPreparedStatement(m_cq.C_PROPERTIES_DELETE_KEY); statement.setInt(1, propdef.getId()); statement.setInt(2, resourceId); statement.executeUpdate(); } catch(SQLException exc) { throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(), CmsException.C_SQL_ERROR, exc); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_PROPERTIES_DELETE_KEY, statement); } } } } /** * Private helper method to delete a resource. * * @param id the id of the resource to delete. * @exception CmsException Throws CmsException if operation was not succesful. */ protected void deleteResource(int id) throws CmsException { PreparedStatement statement = null; try { // read resource data from database statement = m_pool.getPreparedStatement(m_cq.C_RESOURCES_DELETEBYID_KEY); statement.setInt(1, id); statement.executeUpdate(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_DELETEBYID_KEY, statement); } } } /** * Deletes old sessions. */ public void deleteSessions() { PreparedStatement statement = null; try { statement = m_pool.getPreparedStatement(m_cq.C_SESSION_DELETE_KEY); statement.setTimestamp(1,new java.sql.Timestamp(System.currentTimeMillis() - C_SESSION_TIMEOUT )); statement.execute(); } catch (Exception e){ if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsDbAccess] error while deleting old sessions: " + com.opencms.util.Utils.getStackTrace(e)); } } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_SESSION_READ_KEY, statement); } } } public void deleteSite(int siteId) throws CmsException { PreparedStatement statement = null; try { statement = m_pool.getPreparedStatement(m_cq.C_SITE_DELETESITE_KEY); statement.setInt(1, siteId); statement.executeUpdate(); } catch (SQLException e) { throw new CmsException("[" + this.getClass().getName() + "]" + e.getMessage(), CmsException.C_SQL_ERROR, e); } finally { if (statement != null) { m_pool.putPreparedStatement(m_cq.C_SITE_DELETESITE_KEY, statement); } } } // methods working with systemproperties /** * Deletes a serializable object from the systempropertys. * * @param name The name of the property. * * @exception CmsException Throws CmsException if something goes wrong. */ public void deleteSystemProperty(String name) throws CmsException { PreparedStatement statement = null; try { statement = m_pool.getPreparedStatement(m_cq.C_SYSTEMPROPERTIES_DELETE_KEY); statement.setString(1,name); statement.executeUpdate(); }catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_SYSTEMPROPERTIES_DELETE_KEY, statement); } } } /** * Deletes a user from the database. * * @param userId The Id of the user to delete * @exception thorws CmsException if something goes wrong. */ public void deleteUser(int id) throws CmsException { PreparedStatement statement = null; try { statement = m_pool.getPreparedStatement(m_cq.C_USERS_DELETEBYID_KEY); statement.setInt(1,id); statement.executeUpdate(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_USERS_DELETEBYID_KEY, statement); } } } /** * Deletes a user from the database. * * @param user the user to delete * @exception thorws CmsException if something goes wrong. */ public void deleteUser(String name) throws CmsException { PreparedStatement statement = null; try { statement = m_pool.getPreparedStatement(m_cq.C_USERS_DELETE_KEY); statement.setString(1,name); statement.executeUpdate(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_USERS_DELETE_KEY, statement); } } } /** * Destroys this access-module * @exception throws CmsException if something goes wrong. */ public void destroy() throws CmsException { // stop the connection-guard if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] stop connection guard"); } m_guard.destroy(); if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] destroy the db-pool."); } ( (com.opencms.file.genericSql.CmsDbPool)m_pool ).destroy(); if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] destroy complete."); } } /** * Private method to encrypt the passwords. * * @param value The value to encrypt. * @return The encrypted value. */ protected String digest(String value) { // is there a valid digest? if( m_digest != null ) { return new String(m_digest.digest(value.getBytes())); } else { // no digest - use clear passwords return value; } } /** * Ends a task from the Cms. * * @param taskid Id of the task to end. * * @exception CmsException Throws CmsException if something goes wrong. */ public void endTask(int taskId) throws CmsException { PreparedStatement statement = null; try{ statement = m_pool.getPreparedStatement(m_cq.C_TASK_END_KEY); statement.setInt(1, 100); statement.setTimestamp(2,new java.sql.Timestamp(System.currentTimeMillis())); statement.setInt(3,taskId); statement.executeQuery(); } catch( SQLException exc ) { throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc); } finally { if(statement != null) { m_pool.putPreparedStatement(m_cq.C_TASK_END_KEY, statement); } } } /** * Private method to init all default-resources */ protected void fillDefaults() throws CmsException { if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] fillDefaults() starting NOW!"); } // insert the first Id initId(); // the resourceType "folder" is needed always - so adding it Hashtable resourceTypes = new Hashtable(1); resourceTypes.put(C_TYPE_FOLDER_NAME, new CmsResourceType(C_TYPE_FOLDER, 0, C_TYPE_FOLDER_NAME, "")); // sets the last used index of resource types. resourceTypes.put(C_TYPE_LAST_INDEX, new Integer(C_TYPE_FOLDER)); // add the resource-types to the database addSystemProperty(C_SYSTEMPROPERTY_RESOURCE_TYPE, resourceTypes); // set the mimetypes addSystemProperty(C_SYSTEMPROPERTY_MIMETYPES, initMimetypes()); // set the groups CmsGroup guests = createGroup(C_GROUP_GUEST, "the guest-group", C_FLAG_ENABLED, null); CmsGroup administrators = createGroup(C_GROUP_ADMIN, "the admin-group", C_FLAG_ENABLED | C_FLAG_GROUP_PROJECTMANAGER, null); CmsGroup projectleader = createGroup(C_GROUP_PROJECTLEADER, "the projectmanager-group", C_FLAG_ENABLED | C_FLAG_GROUP_PROJECTMANAGER | C_FLAG_GROUP_PROJECTCOWORKER | C_FLAG_GROUP_ROLE, null); CmsGroup users = createGroup(C_GROUP_USERS, "the users-group to access the workplace", C_FLAG_ENABLED | C_FLAG_GROUP_ROLE | C_FLAG_GROUP_PROJECTCOWORKER, C_GROUP_GUEST); // add the users CmsUser guest = addUser(C_USER_GUEST, "", "the guest-user", " ", " ", " ", 0, 0, C_FLAG_ENABLED, new Hashtable(), guests, " ", " ", C_USER_TYPE_SYSTEMUSER); CmsUser admin = addUser(C_USER_ADMIN, "admin", "the admin-user", " ", " ", " ", 0, 0, C_FLAG_ENABLED, new Hashtable(), administrators, " ", " ", C_USER_TYPE_SYSTEMUSER); addUserToGroup(guest.getId(), guests.getId()); addUserToGroup(admin.getId(), administrators.getId()); CmsTask task = createTask(0, 0, 1, // standart project type, admin.getId(), admin.getId(), administrators.getId(), C_PROJECT_ONLINE, new java.sql.Timestamp(new java.util.Date().getTime()), new java.sql.Timestamp(new java.util.Date().getTime()), C_TASK_PRIORITY_NORMAL); CmsProject online = createProject(admin, guests, projectleader, task, C_PROJECT_ONLINE, "the online-project", C_FLAG_ENABLED, C_PROJECT_TYPE_NORMAL, C_PROJECT_ROOT); // create the root-folder CmsFolder rootFolder = createFolder(admin, online, C_UNKNOWN_ID, C_UNKNOWN_ID, C_ROOT, 0); rootFolder.setGroupId(users.getId()); writeFolder(online, rootFolder, false); /* Inserting some multisite initialization * insert a default site, create relation between default site and the default project * This needs to be done even if you're not using multisite functionality */ if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] filling default multisite resources"); } CmsCategory category = createCategory("Default", "Default category", "def", 0); if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] Created category with ID="+category.getId()); } CmsLanguage language = createLanguage("Default Language", "def", 0); if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] Created language with ID="+language.getLanguageId()); } CmsCountry country = createCountry("Master", "master", 0); if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] Created country with ID="+country.getCountryId()); } CmsSite newSite = newSiteRecord("Default", "Default site", category.getId(), language.getLanguageId(), country.getCountryId(), online.getId()); if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] Created new site with ID="+newSite.getId()); } newSiteProjectsRecord(newSite.getId(), online.getId()); String url = "www.default.cms"; newSiteUrlRecord(url, newSite.getId(), url); } /** * Finds an agent for a given role (group). * @param roleId The Id for the role (group). * * @return A vector with the tasks * * @exception CmsException Throws CmsException if something goes wrong. */ protected int findAgent(int roleid) throws CmsException { int result = C_UNKNOWN_ID; PreparedStatement statement = null; ResultSet res = null; try { statement = m_pool.getPreparedStatement(m_cq.C_TASK_FIND_AGENT_KEY); statement.setInt(1,roleid); res = statement.executeQuery(); if(res.next()) { result = res.getInt(1); } else { System.out.println("No User for role "+ roleid + " found"); } res.close(); } catch( SQLException exc ) { throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc); } catch( Exception exc ) { throw new CmsException(exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc); } finally { if(statement != null) { m_pool.putPreparedStatement(m_cq.C_TASK_FIND_AGENT_KEY, statement); } } return result; } /** * Forwards a task to another user. * * @param taskId The id of the task that will be fowarded. * @param newRoleId The new Group the task belongs to * @param newUserId User who gets the task. * * @exception CmsException Throws CmsException if something goes wrong. */ public void forwardTask(int taskId, int newRoleId, int newUserId) throws CmsException { PreparedStatement statement = null; try{ statement = m_pool.getPreparedStatement(m_cq.C_TASK_FORWARD_KEY); statement.setInt(1,newRoleId); statement.setInt(2,newUserId); statement.setInt(3,taskId); statement.executeUpdate(); } catch( SQLException exc ) { throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc); } finally { if(statement != null) { m_pool.putPreparedStatement(m_cq.C_TASK_FORWARD_KEY, statement); } } } /** * Returns all projects, which are accessible by a group. * * @param group The requesting group. * * @return a Vector of projects. */ public Vector getAllAccessibleProjectsByGroup(CmsGroup group) throws CmsException { Vector projects = new Vector(); ResultSet res; PreparedStatement statement = null; try { // create the statement statement = m_pool.getPreparedStatement(m_cq.C_PROJECTS_READ_BYGROUP_KEY); statement.setInt(1,group.getId()); statement.setInt(2,group.getId()); res = statement.executeQuery(); while(res.next()) projects.addElement(new CmsProject(res,m_cq)); res.close(); } catch( Exception exc ) { throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(), CmsException.C_SQL_ERROR, exc); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_PROJECTS_READ_BYGROUP_KEY, statement); } } return(projects); } /** * Returns all projects, which are manageable by a group. * * @param group The requesting group. * * @return a Vector of projects. */ public Vector getAllAccessibleProjectsByManagerGroup(CmsGroup group) throws CmsException { Vector projects = new Vector(); ResultSet res; PreparedStatement statement = null; try { // create the statement statement = m_pool.getPreparedStatement(m_cq.C_PROJECTS_READ_BYMANAGER_KEY); statement.setInt(1,group.getId()); res = statement.executeQuery(); while(res.next()) projects.addElement(new CmsProject(res,m_cq)); res.close(); } catch( Exception exc ) { throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(), CmsException.C_SQL_ERROR, exc); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_PROJECTS_READ_BYMANAGER_KEY, statement); } } return(projects); } /** * Returns all projects, which are owned by a user. * * @param user The requesting user. * * @return a Vector of projects. */ public Vector getAllAccessibleProjectsByUser(CmsUser user) throws CmsException { Vector projects = new Vector(); ResultSet res; PreparedStatement statement = null; try { // create the statement statement = m_pool.getPreparedStatement(m_cq.C_PROJECTS_READ_BYUSER_KEY); statement.setInt(1,user.getId()); res = statement.executeQuery(); while(res.next()) projects.addElement(new CmsProject(res,m_cq)); res.close(); } catch( Exception exc ) { throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(), CmsException.C_SQL_ERROR, exc); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_PROJECTS_READ_BYUSER_KEY, statement); } } return(projects); } public Vector getAllCategories() throws CmsException { Vector categories = new Vector(); PreparedStatement statement = null; try { statement = m_pool.getPreparedStatement(m_cq.C_CATEGORY_GETALLCATEGORIES_KEY); ResultSet res = statement.executeQuery(); while (res.next()) categories.addElement(new CmsCategory(res.getInt("CATEGORY_ID"), res.getString("NAME"), res.getString("DESCRIPTION"), res.getString("SHORTNAME"), res.getInt("PRIORITY"))); res.close(); } catch (SQLException e) { throw new CmsException("[" + this.getClass().getName() + "]" + e.getMessage(), CmsException.C_SQL_ERROR, e); } catch (Exception e) { throw new CmsException("[" + this.getClass().getName() + "]", e); } finally { if (statement != null) { m_pool.putPreparedStatement(m_cq.C_CATEGORY_GETALLCATEGORIES_KEY, statement); } } return categories; } /** * Returns all countries * @return java.util.Vector all countries * @exception com.opencms.core.CmsException The exception description. */ public Vector getAllCountries() throws CmsException { Vector countries = new Vector(); PreparedStatement statement = null; try { statement = m_pool.getPreparedStatement(m_cq.C_COUNTRY_GETALLCOUNTRIES_KEY); ResultSet res = statement.executeQuery(); while (res.next()) { countries.addElement(new CmsCountry(res.getInt("COUNTRY_ID"), res.getString("NAME"), res.getString("SHORTNAME"), res.getInt("PRIORITY"))); } res.close(); } catch (SQLException e) { throw new CmsException("[" + this.getClass().getName() + "]" + e.getMessage(), CmsException.C_SQL_ERROR, e); } catch (Exception e) { throw new CmsException("[" + this.getClass().getName() + "]", e); } finally { if (statement != null) { m_pool.putPreparedStatement(m_cq.C_COUNTRY_GETALLCOUNTRIES_KEY, statement); } } return countries; } public Vector getAllLanguages() throws CmsException { Vector languages = new Vector(); PreparedStatement statement = null; try { statement = m_pool.getPreparedStatement(m_cq.C_LANGUAGE_GETALLLANGUAGES_KEY); ResultSet res = statement.executeQuery(); while (res.next()) { languages.addElement(new CmsLanguage(res.getInt("LANGUAGE_ID"), res.getString("NAME"), res.getString("SHORTNAME"), res.getInt("PRIORITY"))); } res.close(); } catch (SQLException e) { throw new CmsException("[" + this.getClass().getName() + "]" + e.getMessage(), CmsException.C_SQL_ERROR, e); } catch (Exception e) { throw new CmsException("[" + this.getClass().getName() + "]", e); } finally { if (statement != null) { m_pool.putPreparedStatement(m_cq.C_LANGUAGE_GETALLLANGUAGES_KEY, statement); } } return languages; } /** * Returns all projects, with the overgiven state. * * @param state The state of the projects to read. * * @return a Vector of projects. */ public Vector getAllProjects(int state) throws CmsException { Vector projects = new Vector(); ResultSet res = null; PreparedStatement statement = null; try { // create the statement statement = m_pool.getPreparedStatement(m_cq.C_PROJECTS_READ_BYFLAG_KEY); statement.setInt(1,state); res = statement.executeQuery(); while(res.next()) { projects.addElement( new CmsProject(res.getInt(m_cq.C_PROJECTS_PROJECT_ID), res.getString(m_cq.C_PROJECTS_PROJECT_NAME), res.getString(m_cq.C_PROJECTS_PROJECT_DESCRIPTION), res.getInt(m_cq.C_PROJECTS_TASK_ID), res.getInt(m_cq.C_PROJECTS_USER_ID), res.getInt(m_cq.C_PROJECTS_GROUP_ID), res.getInt(m_cq.C_PROJECTS_MANAGERGROUP_ID), res.getInt(m_cq.C_PROJECTS_PROJECT_FLAGS), SqlHelper.getTimestamp(res,m_cq.C_PROJECTS_PROJECT_CREATEDATE), SqlHelper.getTimestamp(res,m_cq.C_PROJECTS_PROJECT_PUBLISHDATE), res.getInt(m_cq.C_PROJECTS_PROJECT_PUBLISHED_BY), res.getInt(m_cq.C_PROJECTS_PROJECT_TYPE), res.getInt(m_cq.C_PROJECTS_PARENT_ID) ) ); } } catch( SQLException exc ) { throw new CmsException("[" + this.getClass().getName() + ".getAllProjects(int)] " + exc.getMessage(), CmsException.C_SQL_ERROR, exc); } finally { if (res != null) { try { res.close(); } catch (SQLException se) { //cannot do anything. } } if( statement != null) { m_pool.putPreparedStatement(m_cq.C_PROJECTS_READ_BYFLAG_KEY, statement); } } return(projects); } public Vector getAllSites() throws CmsException { Vector sites = new Vector(); PreparedStatement statement = null; CmsSite site = null; try { statement = m_pool.getPreparedStatement(m_cq.C_SITES_GETALLSITES_KEY); ResultSet res = statement.executeQuery(); while (res.next()) { sites.addElement(new CmsSite(res.getInt("SITE_ID"), res.getString("NAME"), res.getString("DESCRIPTION"), res.getInt("CATEGORY_ID"), res.getInt("LANGUAGE_ID"), res.getInt("COUNTRY_ID"), res.getInt("ONLINEPROJECT_ID"))); } res.close(); } catch (SQLException e) { throw new CmsException("[" + this.getClass().getName() + "]" + e.getMessage(), CmsException.C_SQL_ERROR, e); } catch (Exception e) { throw new CmsException("[" + this.getClass().getName() + "]", e); } finally { if (statement != null) { m_pool.putPreparedStatement(m_cq.C_SITES_GETALLSITES_KEY, statement); } } return sites; } public Vector getAllSiteUrls() throws com.opencms.core.CmsException { Vector siteUrls = new Vector(); PreparedStatement statement = null; try { statement = m_pool.getPreparedStatement(m_cq.C_SITEURLS_GETALLSITEURLS_KEY); ResultSet res = statement.executeQuery(); while (res.next()) { siteUrls.addElement(new CmsSiteUrls(res.getInt("URL_ID"), res.getString("URL"), res.getInt("SITE_ID"), res.getInt("PRIMARYURL"))); } res.close(); } catch (SQLException e) { throw new CmsException("[" + this.getClass().getName() + "]" + e.getMessage(), CmsException.C_SQL_ERROR, e); } catch (Exception e) { throw new CmsException("[" + this.getClass().getName() + "]", e); } finally { if (statement != null) { m_pool.putPreparedStatement(m_cq.C_SITEURLS_GETALLSITEURLS_KEY, statement); } } return siteUrls; } /** * Retrieves the onlineproject from the database based on the given project. * * @author Jan Krag * * @return com.opencms.file.CmsProject the onlineproject for the given project. * @param project int the project for which to find the online project. * @exception CmsException Throws CmsException if the resource is not found, or the database communication went wrong. */ public int getBaseProjectId(int project) throws CmsException { PreparedStatement statement = null; int baseproject = project; try { statement = m_pool.getPreparedStatement(m_cq.C_PROJECTS_GETONLINEPROJECT_KEY); statement.setInt(1, project); ResultSet res = statement.executeQuery(); if (res.next()) { baseproject = res.getInt(1); } else { // project not found! throw new CmsException("[" + this.getClass().getName() + "] " + project, CmsException.C_NOT_FOUND); } res.close(); } catch (SQLException e) { throw new CmsException("[" + this.getClass().getName() + "]" + e.getMessage(), CmsException.C_SQL_ERROR, e); } catch (Exception e) { throw new CmsException("[" + this.getClass().getName() + "]", e); } finally { if (statement != null) { m_pool.putPreparedStatement(m_cq.C_PROJECTS_GETONLINEPROJECT_KEY, statement); } } return baseproject; } /** * Returns a CmsCategory object * * @param categoryId the category_id * @return a CmsCategory object according to the categoryId * @exception CmsException Throws CmsException if something goes wrong. */ public CmsCategory getCategory(int categoryId) throws com.opencms.core.CmsException { PreparedStatement statement = null; CmsCategory category = null; ResultSet res = null; try { statement = m_pool.getPreparedStatement(m_cq.C_CATEGORY_GETCATEGORYFROMID_KEY); statement.setInt(1, categoryId); res = statement.executeQuery(); if (res.next()) { category = new CmsCategory(categoryId, res.getString("NAME"), res.getString("DESCRIPTION"), res.getString("SHORTNAME"), res.getInt("PRIORITY")); } else { throw new CmsException("[" + this.getClass().getName() + "] " + categoryId, CmsException.C_NOT_FOUND); } } catch (SQLException e) { throw new CmsException("[" + this.getClass().getName() + "]" + e.getMessage(), CmsException.C_SQL_ERROR, e); } finally { if (res != null) { try { res.close(); } catch (SQLException se) { //cannot do anything. } } if (statement != null) { m_pool.putPreparedStatement(m_cq.C_CATEGORY_GETCATEGORYFROMID_KEY, statement); } } return category; } /** * Returns all child groups of a groups<P/> * * * @param groupname The name of the group. * @return users A Vector of all child groups or null. * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getChild(String groupname) throws CmsException { Vector childs = new Vector(); CmsGroup group; CmsGroup parent; ResultSet res = null; PreparedStatement statement = null; try { // get parent group parent=readGroup(groupname); // parent group exists, so get all childs if (parent != null) { // create statement statement=m_pool.getPreparedStatement(m_cq.C_GROUPS_GETCHILD_KEY); statement.setInt(1,parent.getId()); res = statement.executeQuery(); // create new Cms group objects while ( res.next() ) { group=new CmsGroup(res.getInt(m_cq.C_GROUPS_GROUP_ID), res.getInt(m_cq.C_GROUPS_PARENT_GROUP_ID), res.getString(m_cq.C_GROUPS_GROUP_NAME), res.getString(m_cq.C_GROUPS_GROUP_DESCRIPTION), res.getInt(m_cq.C_GROUPS_GROUP_FLAGS)); childs.addElement(group); } res.close(); } } catch (SQLException e){ throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_GROUPS_GETCHILD_KEY,statement); } } //check if the child vector has no elements, set it to null. if (childs.size() == 0) { childs=null; } return childs; } public CmsCountry getCountry(int countryId) throws com.opencms.core.CmsException { PreparedStatement statement = null; CmsCountry country = null; ResultSet res = null; try { statement = m_pool.getPreparedStatement(m_cq.C_COUNTRY_SELECTCOUNTRY_KEY); statement.setInt(1, countryId); res = statement.executeQuery(); if (res.next()) country = new CmsCountry(countryId, res.getString("NAME"), res.getString("SHORTNAME"), res.getInt("PRIORITY")); else throw new CmsException("[" + this.getClass().getName() + "] " + countryId, CmsException.C_NOT_FOUND); } catch (SQLException e) { throw new CmsException("[" + this.getClass().getName() + "]" + e.getMessage(), CmsException.C_SQL_ERROR, e); } finally { if (res != null) { try { res.close(); } catch (SQLException se) { //cannot do anything. } } if (statement != null) { m_pool.putPreparedStatement(m_cq.C_COUNTRY_SELECTCOUNTRY_KEY, statement); } } return country; } /** * Returns a Vector with all file headers of a folder.<BR/> * * @param parentFolder The folder to be searched. * * @return subfiles A Vector with all file headers of the folder. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getFilesInFolder(CmsFolder parentFolder) throws CmsException { Vector files=new Vector(); CmsResource file=null; ResultSet res =null; PreparedStatement statement = null; try { // get all files in folder statement = m_pool.getPreparedStatement(m_cq.C_RESOURCES_GET_FILESINFOLDER_KEY); statement.setInt(1,parentFolder.getResourceId()); res = statement.executeQuery(); // create new file objects while ( res.next() ) { int resId=res.getInt(m_cq.C_RESOURCES_RESOURCE_ID); int parentId=res.getInt(m_cq.C_RESOURCES_PARENT_ID); String resName=res.getString(m_cq.C_RESOURCES_RESOURCE_NAME); int resType= res.getInt(m_cq.C_RESOURCES_RESOURCE_TYPE); int resFlags=res.getInt(m_cq.C_RESOURCES_RESOURCE_FLAGS); int userId=res.getInt(m_cq.C_RESOURCES_USER_ID); int groupId= res.getInt(m_cq.C_RESOURCES_GROUP_ID); int projectID=res.getInt(m_cq.C_RESOURCES_PROJECT_ID); int fileId=res.getInt(m_cq.C_RESOURCES_FILE_ID); int accessFlags=res.getInt(m_cq.C_RESOURCES_ACCESS_FLAGS); int state= res.getInt(m_cq.C_RESOURCES_STATE); int lockedBy= res.getInt(m_cq.C_RESOURCES_LOCKED_BY); int launcherType= res.getInt(m_cq.C_RESOURCES_LAUNCHER_TYPE); String launcherClass= res.getString(m_cq.C_RESOURCES_LAUNCHER_CLASSNAME); long created=SqlHelper.getTimestamp(res,m_cq.C_RESOURCES_DATE_CREATED).getTime(); long modified=SqlHelper.getTimestamp(res,m_cq.C_RESOURCES_DATE_LASTMODIFIED).getTime(); int resSize= res.getInt(m_cq.C_RESOURCES_SIZE); int modifiedBy=res.getInt(m_cq.C_RESOURCES_LASTMODIFIED_BY); file=new CmsFile(resId,parentId,fileId,resName,resType,resFlags,userId, groupId,projectID,accessFlags,state,lockedBy, launcherType,launcherClass,created,modified,modifiedBy, new byte[0],resSize); files.addElement(file); } } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e); }finally { if (res != null) { try { res.close(); } catch (SQLException se) { //cannot do anything. } } if( statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_GET_FILESINFOLDER_KEY, statement); } } return files; } /** * Returns a Vector with all resource-names that have set the given property to the given value. * * @param projectid, the id of the project to test. * @param propertydef, the name of the propertydefinition to check. * @param property, the value of the property for the resource. * * @return Vector with all names of resources. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getFilesWithProperty(int projectId, String propertyDefinition, String propertyValue) throws CmsException { Vector names = new Vector(); ResultSet res = null; PreparedStatement statement = null; try { statement = m_pool.getPreparedStatement(m_cq.C_RESOURCES_GET_FILES_WITH_PROPERTY_KEY); statement.setInt(1, projectId); statement.setString(2, propertyValue); statement.setString(3, propertyDefinition); res = statement.executeQuery(); // store the result into the vector while (res.next()) { String result = res.getString(1); names.addElement(result); } res.close(); } catch (SQLException e) { throw new CmsException("[" + this.getClass().getName() + "] " + e.getMessage(), CmsException.C_SQL_ERROR, e); } catch (Exception exc) { throw new CmsException("getFilesWithProperty" + exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc); } finally { if (statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_GET_FILES_WITH_PROPERTY_KEY, statement); } } return names; } /** * Returns all groups<P/> * * @return users A Vector of all existing groups. * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getGroups() throws CmsException { Vector groups = new Vector(); CmsGroup group=null; ResultSet res = null; PreparedStatement statement = null; try { // create statement statement=m_pool.getPreparedStatement(m_cq.C_GROUPS_GETGROUPS_KEY); res = statement.executeQuery(); // create new Cms group objects while ( res.next() ) { group=new CmsGroup(res.getInt(m_cq.C_GROUPS_GROUP_ID), res.getInt(m_cq.C_GROUPS_PARENT_GROUP_ID), res.getString(m_cq.C_GROUPS_GROUP_NAME), res.getString(m_cq.C_GROUPS_GROUP_DESCRIPTION), res.getInt(m_cq.C_GROUPS_GROUP_FLAGS)); groups.addElement(group); } res.close(); } catch (SQLException e){ throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_GROUPS_GETGROUPS_KEY,statement); } } return groups; } /** * Returns the parent group of a groups<P/> * * * @param groupname The name of the group. * @return The parent group of the actual group or null; * @exception CmsException Throws CmsException if operation was not succesful. */ /*public CmsGroup getParent(String groupname) throws CmsException { CmsGroup parent = null; // read the actual user group to get access to the parent group id. CmsGroup group= readGroup(groupname); ResultSet res = null; PreparedStatement statement = null; try{ // create statement statement=m_pool.getPreparedStatement(C_GROUPS_GETPARENT_KEY); statement.setInt(1,group.getParentId()); res = statement.executeQuery(); // create new Cms group object if(res.next()) { parent=new CmsGroup(res.getInt(C_GROUPS_GROUP_ID), res.getInt(C_GROUPS_PARENT_GROUP_ID), res.getString(C_GROUPS_GROUP_NAME), res.getString(C_GROUPS_GROUP_DESCRIPTION), res.getInt(C_GROUPS_GROUP_FLAGS)); } res.close(); } catch (SQLException e){ throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_GROUPS_GETPARENT_KEY,statement); } } return parent; }*/ /** * Returns a list of groups of a user.<P/> * * @param name The name of the user. * @return Vector of groups * @exception CmsException Throws CmsException if operation was not succesful */ public Vector getGroupsOfUser(String name) throws CmsException { CmsGroup group; Vector groups=new Vector(); PreparedStatement statement = null; ResultSet res = null; try { // get all all groups of the user statement = m_pool.getPreparedStatement(m_cq.C_GROUPS_GETGROUPSOFUSER_KEY); statement.setString(1,name); res = statement.executeQuery(); while ( res.next() ) { group=new CmsGroup(res.getInt(m_cq.C_GROUPS_GROUP_ID), res.getInt(m_cq.C_GROUPS_PARENT_GROUP_ID), res.getString(m_cq.C_GROUPS_GROUP_NAME), res.getString(m_cq.C_GROUPS_GROUP_DESCRIPTION), res.getInt(m_cq.C_GROUPS_GROUP_FLAGS)); groups.addElement(group); } res.close(); } catch (SQLException e){ throw new CmsException("[" + this.getClass().getName() + "] " + e.getMessage(),CmsException.C_SQL_ERROR, e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_GROUPS_GETGROUPSOFUSER_KEY, statement); } } return groups; } public CmsLanguage getLanguage(int languageId) throws com.opencms.core.CmsException { PreparedStatement statement = null; CmsLanguage language = null; ResultSet res = null; try { statement = m_pool.getPreparedStatement(m_cq.C_LANGUAGE_SELECTLANGUAGE_KEY); statement.setInt(1, languageId); res = statement.executeQuery(); if (res.next()) language = new CmsLanguage(languageId, res.getString("NAME"), res.getString("SHORTNAME"), res.getInt("PRIORITY")); else throw new CmsException("[" + this.getClass().getName() + "] " + languageId, CmsException.C_NOT_FOUND); } catch (SQLException e) { throw new CmsException("[" + this.getClass().getName() + "]" + e.getMessage(), CmsException.C_SQL_ERROR, e); } finally { if (res != null) { try { res.close(); } catch (SQLException se) { //cannot do anything. } } if (statement != null) { m_pool.putPreparedStatement(m_cq.C_LANGUAGE_SELECTLANGUAGE_KEY, statement); } } return language; } /** * Retrieves the onlineproject from the database based on the given project. * * @author Jan Krag * @author Anders Fugmann * @return com.opencms.file.CmsProject the onlineproject for the given project. * @param projectId int the project id for which to find the online project. * @exception CmsException Throws CmsException if the resource is not found, or the database communication went wrong. */ public CmsProject getOnlineProject(int projectId) throws SQLException { CmsProject res = null; res = getProjectIfOnline(projectId); if (res == null) res = getParentProject(projectId); if (res == null) res = readProject(projectId); return res; } public CmsProject getParentProject(int projectId) throws java.sql.SQLException { PreparedStatement statement = null; CmsProject project = null; try { statement = m_pool.getPreparedStatement(m_cq.C_PROJECTS_PARENT_PROJECT_KEY); statement.setInt(1, projectId); ResultSet res = statement.executeQuery(); if (res.next()) //SELECT SITE_ID, NAME, DESCRIPTION,CATEGORY_ID,LANGUAGE_ID, COUNTRY_ID FROM " + C_DATABASE_PREFIX + "SITES, " + C_DATABASE_PREFIX + "SITE_PROJECTS WHERE " + C_DATABASE_PREFIX + "SITE_PROJECTS.BASEPROJECT_ID = ? AND " + C_DATABASE_PREFIX + "SITE_PROJECTS.SITE_ID=" + C_DATABASE_PREFIX + "SITES.SITE_ID"; project = new CmsProject(res,m_cq); res.close(); } finally { //always put the prepared statement back into the pool. if (statement != null) m_pool.putPreparedStatement(m_cq.C_PROJECTS_ONLINE_PROJECT_KEY, statement); } //note that the project can be null. return project; } public CmsProject getProjectIfOnline(int projectId) throws java.sql.SQLException { PreparedStatement statement = null; CmsProject project = null; try { statement = m_pool.getPreparedStatement(m_cq.C_PROJECTS_ONLINE_PROJECT_KEY); statement.setInt(1, projectId); ResultSet res = statement.executeQuery(); if (res.next()) //SELECT SITE_ID, NAME, DESCRIPTION,CATEGORY_ID,LANGUAGE_ID, COUNTRY_ID FROM " + C_DATABASE_PREFIX + "SITES, " + C_DATABASE_PREFIX + "SITE_PROJECTS WHERE " + C_DATABASE_PREFIX + "SITE_PROJECTS.BASEPROJECT_ID = ? AND " + C_DATABASE_PREFIX + "SITE_PROJECTS.SITE_ID=" + C_DATABASE_PREFIX + "SITES.SITE_ID"; project = new CmsProject(res,m_cq); res.close(); } finally { if (statement != null) m_pool.putPreparedStatement(m_cq.C_PROJECTS_ONLINE_PROJECT_KEY, statement); } //note that the project can be null. return project; } /** * retrieve the correct instance of the queries holder. * This method should be overloaded if other query strings should be used. */ protected com.opencms.file.genericSql.CmsQueries getQueries() { return new com.opencms.file.genericSql.CmsQueries(); } public CmsSite getSiteBySiteId(int siteId) throws CmsException { PreparedStatement statement = null; CmsSite site = null; ResultSet res = null; try { statement = m_pool.getPreparedStatement(m_cq.C_SITES_GETSITEFROMSITEID_KEY); statement.setInt(1, siteId); res = statement.executeQuery(); if (res.next()) //SELECT SITE_ID, NAME, DESCRIPTION,CATEGORY_ID,LANGUAGE_ID, COUNTRY_ID FROM " + C_DATABASE_PREFIX + "SITES, " + C_DATABASE_PREFIX + "SITE_PROJECTS WHERE " + C_DATABASE_PREFIX + "SITE_PROJECTS.BASEPROJECT_ID = ? AND " + C_DATABASE_PREFIX + "SITE_PROJECTS.SITE_ID=" + C_DATABASE_PREFIX + "SITES.SITE_ID"; site = new CmsSite(res); else // project not found! throw new CmsException("[" + this.getClass().getName() + "] " , CmsException.C_NOT_FOUND); } catch (SQLException e) { throw new CmsException("[" + this.getClass().getName() + "]" + e.getMessage(), CmsException.C_SQL_ERROR, e); } finally { if (res != null) { try { res.close(); } catch (SQLException se) { //do nothing. } } if (statement != null) { m_pool.putPreparedStatement(m_cq.C_SITES_GETSITEFROMSITEID_KEY, statement); } } return site; } public CmsSite getSiteFromUrl(StringBuffer url) throws CmsException { String host = null; try { java.net.URL siteUrl = new java.net.URL(url.toString()); host = siteUrl.getHost(); } catch (java.net.MalformedURLException mue) { //the StringBuffer was an illigal URL - we should throw an exception. host = "Unknown"; throw new CmsException("[" + this.getClass().getName() + "]", mue); } PreparedStatement statement = null; CmsSite site = null; try { statement = m_pool.getPreparedStatement(m_cq.C_SITES_GETSITEFROMHOST_KEY); statement.setString(1, host); ResultSet res = statement.executeQuery(); if (res.next()) { site = new CmsSite(res.getInt("SITE_ID"), res.getString("NAME"), res.getString("DESCRIPTION"), res.getInt("CATEGORY_ID"), res.getInt("LANGUAGE_ID"), res.getInt("COUNTRY_ID"), res.getInt("ONLINEPROJECT_ID")); } else { //site not found! throw new CmsException("[" + this.getClass().getName() + "] " + host, CmsException.C_NOT_FOUND); } res.close(); } catch (SQLException e) { throw new CmsException("[" + this.getClass().getName() + "]" + e.getMessage(), CmsException.C_SQL_ERROR, e); } catch (Exception e) { throw new CmsException("[" + this.getClass().getName() + "]", e); } finally { if (statement != null) { m_pool.putPreparedStatement(m_cq.C_SITES_GETSITEFROMHOST_KEY, statement); } } return site; } public CmsSite getSite(int projectId) throws CmsException { int baseproject_id = getBaseProjectId(projectId); PreparedStatement statement = null; CmsSite site = null; try { statement = m_pool.getPreparedStatement(m_cq.C_PROJECTS_GETSITEFROMPROJECT_KEY); statement.setInt(1, baseproject_id); ResultSet res = statement.executeQuery(); if (res.next()) { //SELECT SITE_ID, NAME, DESCRIPTION,CATEGORY_ID,LANGUAGE_ID, COUNTRY_ID FROM " + C_DATABASE_PREFIX + "SITES, " + C_DATABASE_PREFIX + "SITE_PROJECTS WHERE " + C_DATABASE_PREFIX + "SITE_PROJECTS.BASEPROJECT_ID = ? AND " + C_DATABASE_PREFIX + "SITE_PROJECTS.SITE_ID=" + C_DATABASE_PREFIX + "SITES.SITE_ID"; site = new CmsSite(res.getInt("SITE_ID"), res.getString("NAME"), res.getString("DESCRIPTION"), res.getInt("CATEGORY_ID"), res.getInt("LANGUAGE_ID"), res.getInt("COUNTRY_ID"), res.getInt("ONLINEPROJECT_ID")); } else { // project not found! throw new CmsException("[" + this.getClass().getName() + "] " + baseproject_id, CmsException.C_NOT_FOUND); } res.close(); } catch (SQLException e) { throw new CmsException("[" + this.getClass().getName() + "]" + e.getMessage(), CmsException.C_SQL_ERROR, e); } catch (Exception e) { throw new CmsException("[" + this.getClass().getName() + "]", e); } finally { if (statement != null) { m_pool.putPreparedStatement(m_cq.C_PROJECTS_GETSITEFROMPROJECT_KEY, statement); } } return site; } public CmsSite getSite(String siteName) throws CmsException { PreparedStatement statement = null; CmsSite site = null; try { statement = m_pool.getPreparedStatement(m_cq.C_PROJECTS_GETSITEFROMNAME_KEY); statement.setString(1, siteName); ResultSet res = statement.executeQuery(); if (res.next()) { site = new CmsSite(res.getInt("SITE_ID"), res.getString("NAME"), res.getString("DESCRIPTION"), res.getInt("CATEGORY_ID"), res.getInt("LANGUAGE_ID"), res.getInt("COUNTRY_ID"), res.getInt("ONLINEPROJECT_ID")); } else { // project not found! throw new CmsException("[" + this.getClass().getName() + "] " + siteName, CmsException.C_NOT_FOUND); } res.close(); } catch (SQLException e) { throw new CmsException("[" + this.getClass().getName() + "]" + e.getMessage(), CmsException.C_SQL_ERROR, e); } catch (Exception e) { throw new CmsException("[" + this.getClass().getName() + "]", e); } finally { if (statement != null) { m_pool.putPreparedStatement(m_cq.C_PROJECTS_GETSITEFROMNAME_KEY, statement); } } return site; } public Vector getSiteMatrixInfo() throws CmsException { Vector siteinfo = new Vector(); String shortname = null; PreparedStatement statement = null; try { statement = m_pool.getPreparedStatement(m_cq.C_GET_SITEMATRIXINFO_KEY); //"SELECT SITE_ID, " + //C_DATABASE_PREFIX + "SITES.CATEGORY_ID, " + //C_DATABASE_PREFIX + "SITES.LANGUAGE_ID, " + //C_DATABASE_PREFIX + "SITES.COUNTRY_ID, " + //C_DATABASE_PREFIX + "LANGUAGE.SHORTNAME AS LANG_NAME, " + //C_DATABASE_PREFIX + "COUNTRY.SHORTNAME AS COUNTRY_NAME //FROM " + C_DATABASE_PREFIX + "SITES," + C_DATABASE_PREFIX + "COUNTRY," + C_DATABASE_PREFIX + "LANGUAGE WHERE " + C_DATABASE_PREFIX + "SITES.LANGUAGE_ID=" + C_DATABASE_PREFIX + "LANGUAGE.LANGUAGE_ID AND " + C_DATABASE_PREFIX + "SITES.COUNTRY_ID=" + C_DATABASE_PREFIX + "COUNTRY.COUNTRY_ID"; ResultSet res = statement.executeQuery(); while (res.next()) { Hashtable a = new Hashtable(); a.put("siteid", new Integer(res.getInt("SITE_ID"))); a.put("sitename", res.getString("SITE_NAME")); a.put("categoryid", new Integer(res.getInt("CATEGORY_ID"))); a.put("langid", new Integer(res.getInt("LANGUAGE_ID"))); a.put("countryid", new Integer(res.getInt("COUNTRY_ID"))); a.put("url", res.getString("URL")); shortname = res.getString("LANG_SNAME"); if (shortname != null) a.put("lang_sname", shortname); a.put("lang_name", res.getString("LANG_NAME")); shortname = res.getString("COUNTRY_SNAME"); if (shortname != null) a.put("country_sname", shortname); a.put("country_name", res.getString("COUNTRY_NAME")); siteinfo.addElement(a); } res.close(); } catch (SQLException e) { throw new CmsException("[" + this.getClass().getName() + "]" + e.getMessage(), CmsException.C_SQL_ERROR, e); } catch (Exception e) { throw new CmsException("[" + this.getClass().getName() + "]", e); } finally { if (statement != null) { m_pool.putPreparedStatement(m_cq.C_GET_SITEMATRIXINFO_KEY, statement); } } return siteinfo; } public Vector getSiteUrls(int siteId) throws com.opencms.core.CmsException { Vector siteUrls = new Vector(); PreparedStatement statement = null; try { statement = m_pool.getPreparedStatement(m_cq.C_SITEURLS_SELECTSITEURLS_KEY); statement.setInt(1, siteId); ResultSet res = statement.executeQuery(); while (res.next()) { siteUrls.addElement(new CmsSiteUrls(res.getInt("URL_ID"), res.getString("URL"), res.getInt("SITE_ID"), res.getInt("PRIMARYURL"))); } res.close(); } catch (SQLException e) { throw new CmsException("[" + this.getClass().getName() + "]" + e.getMessage(), CmsException.C_SQL_ERROR, e); } catch (Exception e) { throw new CmsException("[" + this.getClass().getName() + "]", e); } finally { if (statement != null) { m_pool.putPreparedStatement(m_cq.C_SITEURLS_SELECTSITEURLS_KEY, statement); } } return siteUrls; } /** * Returns a Vector with all subfolders.<BR/> * * @param parentFolder The folder to be searched. * * @return Vector with all subfolders for the given folder. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getSubFolders(CmsFolder parentFolder) throws CmsException { Vector folders=new Vector(); CmsFolder folder=null; ResultSet res =null; PreparedStatement statement = null; try { // get all subfolders statement = m_pool.getPreparedStatement(m_cq.C_RESOURCES_GET_SUBFOLDER_KEY); statement.setInt(1,parentFolder.getResourceId()); res = statement.executeQuery(); // create new folder objects while ( res.next() ) { int resId=res.getInt(m_cq.C_RESOURCES_RESOURCE_ID); int parentId=res.getInt(m_cq.C_RESOURCES_PARENT_ID); String resName=res.getString(m_cq.C_RESOURCES_RESOURCE_NAME); int resType= res.getInt(m_cq.C_RESOURCES_RESOURCE_TYPE); int resFlags=res.getInt(m_cq.C_RESOURCES_RESOURCE_FLAGS); int userId=res.getInt(m_cq.C_RESOURCES_USER_ID); int groupId= res.getInt(m_cq.C_RESOURCES_GROUP_ID); int projectID=res.getInt(m_cq.C_RESOURCES_PROJECT_ID); int fileId=res.getInt(m_cq.C_RESOURCES_FILE_ID); int accessFlags=res.getInt(m_cq.C_RESOURCES_ACCESS_FLAGS); int state= res.getInt(m_cq.C_RESOURCES_STATE); int lockedBy= res.getInt(m_cq.C_RESOURCES_LOCKED_BY); long created=SqlHelper.getTimestamp(res,m_cq.C_RESOURCES_DATE_CREATED).getTime(); long modified=SqlHelper.getTimestamp(res,m_cq.C_RESOURCES_DATE_LASTMODIFIED).getTime(); int modifiedBy=res.getInt(m_cq.C_RESOURCES_LASTMODIFIED_BY); folder = new CmsFolder(resId,parentId,fileId,resName,resType,resFlags,userId, groupId,projectID,accessFlags,state,lockedBy,created, modified,modifiedBy); folders.addElement(folder); } res.close(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e); } catch( Exception exc ) { throw new CmsException("getSubFolders "+exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_GET_SUBFOLDER_KEY, statement); } } return folders; } /** * Get a parameter value for a task. * * @param task The task. * @param parname Name of the parameter. * * @exception CmsException Throws CmsException if something goes wrong. */ public String getTaskPar(int taskId, String parname) throws CmsException { String result = null; ResultSet res = null; PreparedStatement statement = null; try { statement = m_pool.getPreparedStatement(m_cq.C_TASKPAR_GET_KEY); statement.setInt(1, taskId); statement.setString(2, parname); res = statement.executeQuery(); if(res.next()) { result = res.getString(m_cq.C_PAR_VALUE); } res.close(); } catch( SQLException exc ) { throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc); } finally { if(statement != null) { m_pool.putPreparedStatement(m_cq.C_TASKPAR_GET_KEY, statement); } } return result; } protected String getTaskTypeConditon(boolean first, int tasktype) { String result = ""; // handle the tasktype for the SQL String if(!first){ result = result+" AND "; } switch(tasktype) { case C_TASKS_ALL: { result = result + m_cq.C_TASK_ROOT + "<>0"; break; } case C_TASKS_OPEN: { result = result + m_cq.C_TASK_STATE + "=" + C_TASK_STATE_STARTED; break; } case C_TASKS_ACTIVE: { result = result + m_cq.C_TASK_STATE + "=" + C_TASK_STATE_STARTED; break; } case C_TASKS_DONE: { result = result + m_cq.C_TASK_STATE + "=" + C_TASK_STATE_ENDED; break; } case C_TASKS_NEW: { result = result + m_cq.C_TASK_PERCENTAGE + "=0 AND " + m_cq.C_TASK_STATE + "=" + C_TASK_STATE_STARTED; break; } default:{} } return result; } /** * Get the template task id fo a given taskname. * * @param taskName Name of the TAsk * * @return id from the task template * * @exception CmsException Throws CmsException if something goes wrong. */ public int getTaskType(String taskName) throws CmsException { int result = 1; PreparedStatement statement = null; ResultSet res = null; try { statement = m_pool.getPreparedStatement(m_cq.C_TASK_GET_TASKTYPE_KEY); statement.setString(1, taskName); res = statement.executeQuery(); if (res.next()) { result = res.getInt("id"); } res.close(); } catch( SQLException exc ) { throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc); } finally { if(statement != null) { m_pool.putPreparedStatement(m_cq.C_TASK_GET_TASKTYPE_KEY, statement); } } return result; } /** * Gets all resources that are marked as undeleted. * @param resources Vector of resources * @return Returns all resources that are markes as deleted */ protected Vector getUndeletedResources(Vector resources) { Vector undeletedResources=new Vector(); for (int i=0;i<resources.size();i++) { CmsResource res=(CmsResource)resources.elementAt(i); if (res.getState() != C_STATE_DELETED) { undeletedResources.addElement(res); } } return undeletedResources; } /** * Gets all users of a type. * * @param type The type of the user. * @exception thorws CmsException if something goes wrong. */ public Vector getUsers(int type) throws CmsException { Vector users = new Vector(); PreparedStatement statement = null; ResultSet res = null; try { statement = m_pool.getPreparedStatement(m_cq.C_USERS_GETUSERS_KEY); statement.setInt(1,type); res = statement.executeQuery(); // create new Cms user objects while( res.next() ) { // read the additional infos. byte[] value = res.getBytes(m_cq.C_USERS_USER_INFO); // now deserialize the object ByteArrayInputStream bin= new ByteArrayInputStream(value); ObjectInputStream oin = new ObjectInputStream(bin); Hashtable info=(Hashtable)oin.readObject(); CmsUser user = new CmsUser(res.getInt(m_cq.C_USERS_USER_ID), res.getString(m_cq.C_USERS_USER_NAME), res.getString(m_cq.C_USERS_USER_PASSWORD), res.getString(m_cq.C_USERS_USER_RECOVERY_PASSWORD), res.getString(m_cq.C_USERS_USER_DESCRIPTION), res.getString(m_cq.C_USERS_USER_FIRSTNAME), res.getString(m_cq.C_USERS_USER_LASTNAME), res.getString(m_cq.C_USERS_USER_EMAIL), SqlHelper.getTimestamp(res,m_cq.C_USERS_USER_LASTLOGIN).getTime(), SqlHelper.getTimestamp(res,m_cq.C_USERS_USER_LASTUSED).getTime(), res.getInt(m_cq.C_USERS_USER_FLAGS), info, new CmsGroup(res.getInt(m_cq.C_GROUPS_GROUP_ID), res.getInt(m_cq.C_GROUPS_PARENT_GROUP_ID), res.getString(m_cq.C_GROUPS_GROUP_NAME), res.getString(m_cq.C_GROUPS_GROUP_DESCRIPTION), res.getInt(m_cq.C_GROUPS_GROUP_FLAGS)), res.getString(m_cq.C_USERS_USER_ADDRESS), res.getString(m_cq.C_USERS_USER_SECTION), res.getInt(m_cq.C_USERS_USER_TYPE)); users.addElement(user); } res.close(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e); } catch (Exception e) { throw new CmsException("["+this.getClass().getName()+"]", e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_USERS_GETUSERS_KEY, statement); } } return users; } /** * Returns a list of users of a group.<P/> * * @param name The name of the group. * @param type the type of the users to read. * @return Vector of users * @exception CmsException Throws CmsException if operation was not succesful */ public Vector getUsersOfGroup(String name, int type) throws CmsException { CmsGroup group; Vector users = new Vector(); PreparedStatement statement = null; ResultSet res = null; try { statement = m_pool.getPreparedStatement(m_cq.C_GROUPS_GETUSERSOFGROUP_KEY); statement.setString(1,name); statement.setInt(2,type); res = statement.executeQuery(); while( res.next() ) { // read the additional infos. byte[] value = res.getBytes(m_cq.C_USERS_USER_INFO); // now deserialize the object ByteArrayInputStream bin= new ByteArrayInputStream(value); ObjectInputStream oin = new ObjectInputStream(bin); Hashtable info=(Hashtable)oin.readObject(); CmsUser user = new CmsUser(res.getInt(m_cq.C_USERS_USER_ID), res.getString(m_cq.C_USERS_USER_NAME), res.getString(m_cq.C_USERS_USER_PASSWORD), res.getString(m_cq.C_USERS_USER_RECOVERY_PASSWORD), res.getString(m_cq.C_USERS_USER_DESCRIPTION), res.getString(m_cq.C_USERS_USER_FIRSTNAME), res.getString(m_cq.C_USERS_USER_LASTNAME), res.getString(m_cq.C_USERS_USER_EMAIL), SqlHelper.getTimestamp(res,m_cq.C_USERS_USER_LASTLOGIN).getTime(), SqlHelper.getTimestamp(res,m_cq.C_USERS_USER_LASTUSED).getTime(), res.getInt(m_cq.C_USERS_USER_FLAGS), info, new CmsGroup(res.getInt(m_cq.C_USERS_USER_DEFAULT_GROUP_ID), res.getInt(m_cq.C_GROUPS_PARENT_GROUP_ID), res.getString(m_cq.C_GROUPS_GROUP_NAME), res.getString(m_cq.C_GROUPS_GROUP_DESCRIPTION), res.getInt(m_cq.C_GROUPS_GROUP_FLAGS)), res.getString(m_cq.C_USERS_USER_ADDRESS), res.getString(m_cq.C_USERS_USER_SECTION), res.getInt(m_cq.C_USERS_USER_TYPE)); users.addElement(user); } res.close(); } catch (SQLException e){ throw new CmsException("[" + this.getClass().getName() + "] " + e.getMessage(),CmsException.C_SQL_ERROR, e); } catch (Exception e) { throw new CmsException("["+this.getClass().getName()+"]", e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_GROUPS_GETUSERSOFGROUP_KEY, statement); } } return users; } /** * Private method to init all Id statements in the pool. */ protected void initIdStatements() throws com.opencms.core.CmsException { m_pool.initPreparedStatement(m_cq.C_SYSTEMID_INIT_KEY, m_cq.C_SYSTEMID_INIT); m_pool.initPreparedStatement(m_cq.C_SYSTEMID_LOCK_KEY, m_cq.C_SYSTEMID_LOCK); m_pool.initPreparedStatement(m_cq.C_SYSTEMID_READ_KEY, m_cq.C_SYSTEMID_READ); m_pool.initPreparedStatement(m_cq.C_SYSTEMID_WRITE_KEY, m_cq.C_SYSTEMID_WRITE); m_pool.initPreparedStatement(m_cq.C_SYSTEMID_UNLOCK_KEY, m_cq.C_SYSTEMID_UNLOCK); } /** * Private method to init the id-Table of the Database. * * @exception throws CmsException if something goes wrong. */ protected void initId() throws CmsException { PreparedStatement statement = null; try { statement = m_pool.getPreparedStatement(m_cq.C_SYSTEMID_INIT_KEY); for (int i = 0; i <= C_MAX_TABLES; i++){ statement.setInt(1,i); statement.executeUpdate(); statement.clearParameters(); } } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_SYSTEMID_INIT_KEY, statement); } } } /** * Private method to init the max-id of the projects-table. * * @param key the key for the prepared statement to use. * @return the max-id * @exception throws CmsException if something goes wrong. */ protected int initMaxId(Integer key) throws CmsException { int id; PreparedStatement statement = null; try { statement = m_pool.getPreparedStatement(key); ResultSet res = statement.executeQuery(); if (res.next()){ id = res.getInt(1); }else { // no values in Database id = 0; } res.close(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e); } finally { if( statement != null) { m_pool.putPreparedStatement(key, statement); } } return id; } /** * Private method to init the max-id values. * * @exception throws CmsException if something goes wrong. */ protected void initMaxIdValues() throws CmsException { m_maxIds = new int[C_MAX_TABLES]; m_maxIds[C_TABLE_GROUPS] = initMaxId(m_cq.C_GROUPS_MAXID_KEY); m_maxIds[C_TABLE_PROJECTS] = initMaxId(m_cq.C_PROJECTS_MAXID_KEY); m_maxIds[C_TABLE_USERS] = initMaxId(m_cq.C_USERS_MAXID_KEY); m_maxIds[C_TABLE_SYSTEMPROPERTIES] = initMaxId(m_cq.C_SYSTEMPROPERTIES_MAXID_KEY); m_maxIds[C_TABLE_PROPERTYDEF] = initMaxId(m_cq.C_PROPERTYDEF_MAXID_KEY); m_maxIds[C_TABLE_PROPERTIES] = initMaxId(m_cq.C_PROPERTIES_MAXID_KEY); m_maxIds[C_TABLE_RESOURCES] = initMaxId(m_cq.C_RESOURCES_MAXID_KEY); m_maxIds[C_TABLE_FILES] = initMaxId(m_cq.C_FILES_MAXID_KEY); } /** * Inits all mimetypes. * The mimetype-data should be stored in the database. But now this data * is putted directly here. * * @return Returns a hashtable with all mimetypes. */ protected Hashtable initMimetypes() { Hashtable mt=new Hashtable(); mt.put( "ez", "application/andrew-inset" ); mt.put( "hqx", "application/mac-binhex40" ); mt.put( "cpt", "application/mac-compactpro" ); mt.put( "doc", "application/msword" ); mt.put( "bin", "application/octet-stream" ); mt.put( "dms", "application/octet-stream" ); mt.put( "lha", "application/octet-stream" ); mt.put( "lzh", "application/octet-stream" ); mt.put( "exe", "application/octet-stream" ); mt.put( "class", "application/octet-stream" ); mt.put( "oda", "application/oda" ); mt.put( "pdf", "application/pdf" ); mt.put( "ai", "application/postscript" ); mt.put( "eps", "application/postscript" ); mt.put( "ps", "application/postscript" ); mt.put( "rtf", "application/rtf" ); mt.put( "smi", "application/smil" ); mt.put( "smil", "application/smil" ); mt.put( "mif", "application/vnd.mif" ); mt.put( "xls", "application/vnd.ms-excel" ); mt.put( "ppt", "application/vnd.ms-powerpoint" ); mt.put( "bcpio", "application/x-bcpio" ); mt.put( "vcd", "application/x-cdlink" ); mt.put( "pgn", "application/x-chess-pgn" ); mt.put( "cpio", "application/x-cpio" ); mt.put( "csh", "application/x-csh" ); mt.put( "dcr", "application/x-director" ); mt.put( "dir", "application/x-director" ); mt.put( "dxr", "application/x-director" ); mt.put( "dvi", "application/x-dvi" ); mt.put( "spl", "application/x-futuresplash" ); mt.put( "gtar", "application/x-gtar" ); mt.put( "hdf", "application/x-hdf" ); mt.put( "js", "application/x-javascript" ); mt.put( "skp", "application/x-koan" ); mt.put( "skd", "application/x-koan" ); mt.put( "skt", "application/x-koan" ); mt.put( "skm", "application/x-koan" ); mt.put( "latex", "application/x-latex" ); mt.put( "nc", "application/x-netcdf" ); mt.put( "cdf", "application/x-netcdf" ); mt.put( "sh", "application/x-sh" ); mt.put( "shar", "application/x-shar" ); mt.put( "swf", "application/x-shockwave-flash" ); mt.put( "sit", "application/x-stuffit" ); mt.put( "sv4cpio", "application/x-sv4cpio" ); mt.put( "sv4crc", "application/x-sv4crc" ); mt.put( "tar", "application/x-tar" ); mt.put( "tcl", "application/x-tcl" ); mt.put( "tex", "application/x-tex" ); mt.put( "texinfo", "application/x-texinfo" ); mt.put( "texi", "application/x-texinfo" ); mt.put( "t", "application/x-troff" ); mt.put( "tr", "application/x-troff" ); mt.put( "roff", "application/x-troff" ); mt.put( "man", "application/x-troff-man" ); mt.put( "me", "application/x-troff-me" ); mt.put( "ms", "application/x-troff-ms" ); mt.put( "ustar", "application/x-ustar" ); mt.put( "src", "application/x-wais-source" ); mt.put( "zip", "application/zip" ); mt.put( "au", "audio/basic" ); mt.put( "snd", "audio/basic" ); mt.put( "mid", "audio/midi" ); mt.put( "midi", "audio/midi" ); mt.put( "kar", "audio/midi" ); mt.put( "mpga", "audio/mpeg" ); mt.put( "mp2", "audio/mpeg" ); mt.put( "mp3", "audio/mpeg" ); mt.put( "aif", "audio/x-aiff" ); mt.put( "aiff", "audio/x-aiff" ); mt.put( "aifc", "audio/x-aiff" ); mt.put( "ram", "audio/x-pn-realaudio" ); mt.put( "rm", "audio/x-pn-realaudio" ); mt.put( "rpm", "audio/x-pn-realaudio-plugin" ); mt.put( "ra", "audio/x-realaudio" ); mt.put( "wav", "audio/x-wav" ); mt.put( "pdb", "chemical/x-pdb" ); mt.put( "xyz", "chemical/x-pdb" ); mt.put( "bmp", "image/bmp" ); mt.put( "wbmp", "image/vnd.wap.wbmp" ); mt.put( "gif", "image/gif" ); mt.put( "ief", "image/ief" ); mt.put( "jpeg", "image/jpeg" ); mt.put( "jpg", "image/jpeg" ); mt.put( "jpe", "image/jpeg" ); mt.put( "png", "image/png" ); mt.put( "tiff", "image/tiff" ); mt.put( "tif", "image/tiff" ); mt.put( "ras", "image/x-cmu-raster" ); mt.put( "pnm", "image/x-portable-anymap" ); mt.put( "pbm", "image/x-portable-bitmap" ); mt.put( "pgm", "image/x-portable-graymap" ); mt.put( "ppm", "image/x-portable-pixmap" ); mt.put( "rgb", "image/x-rgb" ); mt.put( "xbm", "image/x-xbitmap" ); mt.put( "xpm", "image/x-xpixmap" ); mt.put( "xwd", "image/x-xwindowdump" ); mt.put( "igs", "model/iges" ); mt.put( "iges", "model/iges" ); mt.put( "msh", "model/mesh" ); mt.put( "mesh", "model/mesh" ); mt.put( "silo", "model/mesh" ); mt.put( "wrl", "model/vrml" ); mt.put( "vrml", "model/vrml" ); mt.put( "css", "text/css" ); mt.put( "html", "text/html" ); mt.put( "htm", "text/html" ); mt.put( "asc", "text/plain" ); mt.put( "txt", "text/plain" ); mt.put( "rtx", "text/richtext" ); mt.put( "rtf", "text/rtf" ); mt.put( "sgml", "text/sgml" ); mt.put( "sgm", "text/sgml" ); mt.put( "tsv", "text/tab-separated-values" ); mt.put( "etx", "text/x-setext" ); mt.put( "xml", "text/xml" ); mt.put( "wml", "text/vnd.wap.wml" ); mt.put( "mpeg", "video/mpeg" ); mt.put( "mpg", "video/mpeg" ); mt.put( "mpe", "video/mpeg" ); mt.put( "qt", "video/quicktime" ); mt.put( "mov", "video/quicktime" ); mt.put( "avi", "video/x-msvideo" ); mt.put( "movie", "video/x-sgi-movie" ); mt.put( "ice", "x-conference/x-cooltalk" ); return mt; } /** * Private method to init all statements in the pool. */ protected void initStatements() throws CmsException { // init statements for resources and files m_pool.initPreparedStatement(m_cq.C_RESOURCES_MAXID_KEY,m_cq.C_RESOURCES_MAXID); m_pool.initPreparedStatement(m_cq.C_RESOURCES_REMOVE_KEY,m_cq.C_RESOURCES_REMOVE); m_pool.initPreparedStatement(m_cq.C_FILES_MAXID_KEY,m_cq.C_FILES_MAXID); m_pool.initPreparedStatement(m_cq.C_FILES_UPDATE_KEY,m_cq.C_FILES_UPDATE); m_pool.initPreparedStatement(m_cq.C_RESOURCES_READ_KEY,m_cq.C_RESOURCES_READ); m_pool.initPreparedStatement(m_cq.C_RESOURCES_READBYID_KEY,m_cq.C_RESOURCES_READBYID); m_pool.initPreparedStatement(m_cq.C_RESOURCES_WRITE_KEY,m_cq.C_RESOURCES_WRITE); m_pool.initPreparedStatement(m_cq.C_RESOURCES_GET_SUBFOLDER_KEY,m_cq.C_RESOURCES_GET_SUBFOLDER); m_pool.initPreparedStatement(m_cq.C_RESOURCES_DELETE_KEY,m_cq.C_RESOURCES_DELETE); m_pool.initPreparedStatement(m_cq.C_RESOURCES_ID_DELETE_KEY,m_cq.C_RESOURCES_ID_DELETE); m_pool.initPreparedStatement(m_cq.C_RESOURCES_GET_FILESINFOLDER_KEY,m_cq.C_RESOURCES_GET_FILESINFOLDER); m_pool.initPreparedStatement(m_cq.C_RESOURCES_PUBLISH_PROJECT_READFILE_KEY,m_cq.C_RESOURCES_PUBLISH_PROJECT_READFILE); m_pool.initPreparedStatement(m_cq.C_RESOURCES_PUBLISH_PROJECT_READFOLDER_KEY,m_cq.C_RESOURCES_PUBLISH_PROJECT_READFOLDER); m_pool.initPreparedStatement(m_cq.C_RESOURCES_UPDATE_KEY,m_cq.C_RESOURCES_UPDATE); m_pool.initPreparedStatement(m_cq.C_RESOURCES_UPDATE_FILE_KEY,m_cq.C_RESOURCES_UPDATE_FILE); m_pool.initPreparedStatement(m_cq.C_RESOURCES_GET_LOST_ID_KEY,m_cq.C_RESOURCES_GET_LOST_ID); m_pool.initPreparedStatement(m_cq.C_FILE_DELETE_KEY,m_cq.C_FILE_DELETE); m_pool.initPreparedStatement(m_cq.C_RESOURCES_DELETE_PROJECT_KEY,m_cq.C_RESOURCES_DELETE_PROJECT); m_pool.initPreparedStatement(m_cq.C_FILE_READ_ONLINE_KEY,m_cq.C_FILE_READ_ONLINE); m_pool.initPreparedStatement(m_cq.C_FILE_READ_KEY,m_cq.C_FILE_READ); m_pool.initPreparedStatement(m_cq.C_FILES_WRITE_KEY,m_cq.C_FILES_WRITE); m_pool.initPreparedStatement(m_cq.C_RESOURCES_UNLOCK_KEY,m_cq.C_RESOURCES_UNLOCK); m_pool.initPreparedStatement(m_cq.C_RESOURCES_COUNTLOCKED_KEY,m_cq.C_RESOURCES_COUNTLOCKED); m_pool.initPreparedStatement(m_cq.C_RESOURCES_READBYPROJECT_KEY,m_cq.C_RESOURCES_READBYPROJECT); m_pool.initPreparedStatement(m_cq.C_RESOURCES_READFOLDERSBYPROJECT_KEY,m_cq.C_RESOURCES_READFOLDERSBYPROJECT); m_pool.initPreparedStatement(m_cq.C_RESOURCES_READFILESBYPROJECT_KEY,m_cq.C_RESOURCES_READFILESBYPROJECT); m_pool.initPreparedStatement(m_cq.C_RESOURCES_PUBLISH_MARKED_KEY,m_cq.C_RESOURCES_PUBLISH_MARKED); m_pool.initPreparedStatement(m_cq.C_RESOURCES_DELETEBYID_KEY,m_cq.C_RESOURCES_DELETEBYID); m_pool.initPreparedStatement(m_cq.C_RESOURCES_RENAMERESOURCE_KEY,m_cq.C_RESOURCES_RENAMERESOURCE); m_pool.initPreparedStatement(m_cq.C_RESOURCES_READ_ALL_KEY,m_cq.C_RESOURCES_READ_ALL); m_pool.initPreparedStatement(m_cq.C_RESOURCES_UPDATE_LOCK_KEY,m_cq.C_RESOURCES_UPDATE_LOCK); m_pool.initPreparedStatement(m_cq.C_RESOURCES_GET_FILES_WITH_PROPERTY_KEY ,m_cq.C_RESOURCES_GET_FILES_WITH_PROPERTY); // init statements for groups m_pool.initPreparedStatement(m_cq.C_GROUPS_MAXID_KEY,m_cq.C_GROUPS_MAXID); m_pool.initPreparedStatement(m_cq.C_GROUPS_READGROUP_KEY,m_cq.C_GROUPS_READGROUP); m_pool.initPreparedStatement(m_cq.C_GROUPS_READGROUP2_KEY,m_cq.C_GROUPS_READGROUP2); m_pool.initPreparedStatement(m_cq.C_GROUPS_CREATEGROUP_KEY,m_cq.C_GROUPS_CREATEGROUP); m_pool.initPreparedStatement(m_cq.C_GROUPS_WRITEGROUP_KEY,m_cq.C_GROUPS_WRITEGROUP); m_pool.initPreparedStatement(m_cq.C_GROUPS_DELETEGROUP_KEY,m_cq.C_GROUPS_DELETEGROUP); m_pool.initPreparedStatement(m_cq.C_GROUPS_GETGROUPS_KEY,m_cq.C_GROUPS_GETGROUPS); m_pool.initPreparedStatement(m_cq.C_GROUPS_GETCHILD_KEY,m_cq.C_GROUPS_GETCHILD); m_pool.initPreparedStatement(m_cq.C_GROUPS_GETPARENT_KEY,m_cq.C_GROUPS_GETPARENT); m_pool.initPreparedStatement(m_cq.C_GROUPS_GETGROUPSOFUSER_KEY,m_cq.C_GROUPS_GETGROUPSOFUSER); m_pool.initPreparedStatement(m_cq.C_GROUPS_ADDUSERTOGROUP_KEY,m_cq.C_GROUPS_ADDUSERTOGROUP); m_pool.initPreparedStatement(m_cq.C_GROUPS_USERINGROUP_KEY,m_cq.C_GROUPS_USERINGROUP); m_pool.initPreparedStatement(m_cq.C_GROUPS_GETUSERSOFGROUP_KEY,m_cq.C_GROUPS_GETUSERSOFGROUP); m_pool.initPreparedStatement(m_cq.C_GROUPS_REMOVEUSERFROMGROUP_KEY,m_cq.C_GROUPS_REMOVEUSERFROMGROUP); // init statements for users m_pool.initPreparedStatement(m_cq.C_USERS_MAXID_KEY,m_cq.C_USERS_MAXID); m_pool.initPreparedStatement(m_cq.C_USERS_ADD_KEY,m_cq.C_USERS_ADD); m_pool.initPreparedStatement(m_cq.C_USERS_READ_KEY,m_cq.C_USERS_READ); m_pool.initPreparedStatement(m_cq.C_USERS_READID_KEY,m_cq.C_USERS_READID); m_pool.initPreparedStatement(m_cq.C_USERS_READPW_KEY,m_cq.C_USERS_READPW); m_pool.initPreparedStatement(m_cq.C_USERS_WRITE_KEY,m_cq.C_USERS_WRITE); m_pool.initPreparedStatement(m_cq.C_USERS_DELETE_KEY,m_cq.C_USERS_DELETE); m_pool.initPreparedStatement(m_cq.C_USERS_GETUSERS_KEY,m_cq.C_USERS_GETUSERS); m_pool.initPreparedStatement(m_cq.C_USERS_SETPW_KEY,m_cq.C_USERS_SETPW); m_pool.initPreparedStatement(m_cq.C_USERS_SETRECPW_KEY,m_cq.C_USERS_SETRECPW); m_pool.initPreparedStatement(m_cq.C_USERS_RECOVERPW_KEY,m_cq.C_USERS_RECOVERPW); m_pool.initPreparedStatement(m_cq.C_USERS_DELETEBYID_KEY,m_cq.C_USERS_DELETEBYID); // init statements for projects m_pool.initPreparedStatement(m_cq.C_PROJECTS_MAXID_KEY, m_cq.C_PROJECTS_MAXID); m_pool.initPreparedStatement(m_cq.C_PROJECTS_CREATE_KEY, m_cq.C_PROJECTS_CREATE); m_pool.initPreparedStatement(m_cq.C_PROJECTS_READ_KEY, m_cq.C_PROJECTS_READ); m_pool.initPreparedStatement(m_cq.C_PROJECTS_READ_BYTASK_KEY, m_cq.C_PROJECTS_READ_BYTASK); m_pool.initPreparedStatement(m_cq.C_PROJECTS_READ_BYUSER_KEY, m_cq.C_PROJECTS_READ_BYUSER); m_pool.initPreparedStatement(m_cq.C_PROJECTS_READ_BYGROUP_KEY, m_cq.C_PROJECTS_READ_BYGROUP); m_pool.initPreparedStatement(m_cq.C_PROJECTS_READ_BYFLAG_KEY, m_cq.C_PROJECTS_READ_BYFLAG); m_pool.initPreparedStatement(m_cq.C_PROJECTS_READ_BYMANAGER_KEY, m_cq.C_PROJECTS_READ_BYMANAGER); m_pool.initPreparedStatement(m_cq.C_PROJECTS_DELETE_KEY, m_cq.C_PROJECTS_DELETE); m_pool.initPreparedStatement(m_cq.C_PROJECTS_WRITE_KEY, m_cq.C_PROJECTS_WRITE); m_pool.initPreparedStatement(m_cq.C_PROJECTS_GETONLINEPROJECT_KEY, m_cq.C_PROJECTS_GETONLINEPROJECT); m_pool.initPreparedStatement(m_cq.C_PROJECTS_GETSITEFROMPROJECT_KEY, m_cq.C_PROJECTS_GETSITEFROMPROJECT); m_pool.initPreparedStatement(m_cq.C_SITES_GETSITEFROMSITEID_KEY, m_cq.C_SITES_GETSITEFROMSITEID); m_pool.initPreparedStatement(m_cq.C_PROJECTS_GETSITEFROMNAME_KEY, m_cq.C_PROJECTS_GETSITEFROMNAME); m_pool.initPreparedStatement(m_cq.C_PROJECTS_PARENT_PROJECT_KEY, m_cq.C_PROJECTS_PARENT_PROJECT); m_pool.initPreparedStatement(m_cq.C_PROJECTS_ONLINE_PROJECT_KEY, m_cq.C_PROJECTS_ONLINE_PROJECT); m_pool.initPreparedStatement(m_cq.C_SITES_GETSITEFROMHOST_KEY, m_cq.C_SITES_GETSITEFROMHOST); m_pool.initPreparedStatement(m_cq.C_SITES_GETALLSITES_KEY, m_cq.C_SITES_GETALLSITES); m_pool.initPreparedStatement(m_cq.C_SITES_MAXID_KEY, m_cq.C_SITES_MAXID); m_pool.initPreparedStatement(m_cq.C_SITES_WRITE_KEY, m_cq.C_SITES_WRITE); m_pool.initPreparedStatement(m_cq.C_SITE_URLS_MAXID_KEY, m_cq.C_SITE_URLS_MAXID); m_pool.initPreparedStatement(m_cq.C_SITE_URLS_WRITE_KEY, m_cq.C_SITE_URLS_WRITE); m_pool.initPreparedStatement(m_cq.C_SITE_PROJECTS_WRITE_KEY, m_cq.C_SITE_PROJECTS_WRITE); m_pool.initPreparedStatement(m_cq.C_CATEGORY_GETCATEGORYFROMID_KEY, m_cq.C_CATEGORY_GETCATEGORYFROMID); m_pool.initPreparedStatement(m_cq.C_CATEGORY_GETALLCATEGORIES_KEY, m_cq.C_CATEGORY_GETALLCATEGORIES); m_pool.initPreparedStatement(m_cq.C_GET_SITEMATRIXINFO_KEY, m_cq.C_GET_SITEMATRIXINFO); m_pool.initPreparedStatement(m_cq.C_LANGUAGE_GETALLLANGUAGES_KEY, m_cq.C_LANGUAGE_GETALLLANGUAGES); m_pool.initPreparedStatement(m_cq.C_COUNTRY_GETALLCOUNTRIES_KEY, m_cq.C_COUNTRY_GETALLCOUNTRIES); m_pool.initPreparedStatement(m_cq.C_SITEURLS_GETALLSITEURLS_KEY, m_cq.C_SITEURLS_GETALLSITEURLS); m_pool.initPreparedStatement(m_cq.C_SITE_DELETESITE_KEY, m_cq.C_SITE_DELETESITE); m_pool.initPreparedStatement(m_cq.C_SITE_UPDATESITE_KEY, m_cq.C_SITE_UPDATESITE); m_pool.initPreparedStatement(m_cq.C_SITEURLS_UPDATESITEURLS_KEY, m_cq.C_SITEURLS_UPDATESITEURLS); m_pool.initPreparedStatement(m_cq.C_SITEURLS_SELECTSITEURLS_KEY, m_cq.C_SITEURLS_SELECTSITEURLS); m_pool.initPreparedStatement(m_cq.C_CATEGORY_INSERTCATEGORY_KEY, m_cq.C_CATEGORY_INSERTCATEGORY); m_pool.initPreparedStatement(m_cq.C_LANGUAGE_INSERTLANGUAGE_KEY, m_cq.C_LANGUAGE_INSERTLANGUAGE); m_pool.initPreparedStatement(m_cq.C_COUNTRY_INSERTCOUNTRY_KEY, m_cq.C_COUNTRY_INSERTCOUNTRY); m_pool.initPreparedStatement(m_cq.C_LANGUAGE_SELECTLANGUAGE_KEY, m_cq.C_LANGUAGE_SELECTLANGUAGE); m_pool.initPreparedStatement(m_cq.C_COUNTRY_SELECTCOUNTRY_KEY, m_cq.C_COUNTRY_SELECTCOUNTRY); m_pool.initPreparedStatement(m_cq.C_SITES_CHECKSITE_KEY, m_cq.C_SITES_CHECKSITE); m_pool.initPreparedStatement(m_cq.C_SITESSITEURLS_CHECKSITE_KEY, m_cq.C_SITESSITEURLS_CHECKSITE); // init statements for systemproperties m_pool.initPreparedStatement(m_cq.C_SYSTEMPROPERTIES_MAXID_KEY, m_cq.C_SYSTEMPROPERTIES_MAXID); m_pool.initPreparedStatement(m_cq.C_SYSTEMPROPERTIES_READ_KEY,m_cq.C_SYSTEMPROPERTIES_READ); m_pool.initPreparedStatement(m_cq.C_SYSTEMPROPERTIES_WRITE_KEY,m_cq.C_SYSTEMPROPERTIES_WRITE); m_pool.initPreparedStatement(m_cq.C_SYSTEMPROPERTIES_UPDATE_KEY,m_cq.C_SYSTEMPROPERTIES_UPDATE); m_pool.initPreparedStatement(m_cq.C_SYSTEMPROPERTIES_DELETE_KEY,m_cq.C_SYSTEMPROPERTIES_DELETE); // init statements for propertydef m_pool.initPreparedStatement(m_cq.C_PROPERTYDEF_MAXID_KEY,m_cq.C_PROPERTYDEF_MAXID); m_pool.initPreparedStatement(m_cq.C_PROPERTYDEF_READ_KEY,m_cq.C_PROPERTYDEF_READ); m_pool.initPreparedStatement(m_cq.C_PROPERTYDEF_READALL_A_KEY,m_cq.C_PROPERTYDEF_READALL_A); m_pool.initPreparedStatement(m_cq.C_PROPERTYDEF_READALL_B_KEY,m_cq.C_PROPERTYDEF_READALL_B); m_pool.initPreparedStatement(m_cq.C_PROPERTYDEF_CREATE_KEY,m_cq.C_PROPERTYDEF_CREATE); m_pool.initPreparedStatement(m_cq.C_PROPERTYDEF_DELETE_KEY,m_cq.C_PROPERTYDEF_DELETE); m_pool.initPreparedStatement(m_cq.C_PROPERTYDEF_UPDATE_KEY,m_cq.C_PROPERTYDEF_UPDATE); // init statements for properties m_pool.initPreparedStatement(m_cq.C_PROPERTIES_MAXID_KEY,m_cq.C_PROPERTIES_MAXID); m_pool.initPreparedStatement(m_cq.C_PROPERTIES_READALL_COUNT_KEY,m_cq.C_PROPERTIES_READALL_COUNT); m_pool.initPreparedStatement(m_cq.C_PROPERTIES_READ_KEY,m_cq.C_PROPERTIES_READ); m_pool.initPreparedStatement(m_cq.C_PROPERTIES_UPDATE_KEY,m_cq.C_PROPERTIES_UPDATE); m_pool.initPreparedStatement(m_cq.C_PROPERTIES_CREATE_KEY,m_cq.C_PROPERTIES_CREATE); m_pool.initPreparedStatement(m_cq.C_PROPERTIES_READALL_KEY,m_cq.C_PROPERTIES_READALL); m_pool.initPreparedStatement(m_cq.C_PROPERTIES_DELETEALL_KEY,m_cq.C_PROPERTIES_DELETEALL); m_pool.initPreparedStatement(m_cq.C_PROPERTIES_DELETE_KEY,m_cq.C_PROPERTIES_DELETE); // init statements for tasks m_pool.initPreparedStatement(m_cq.C_TASK_TYPE_COPY_KEY,m_cq.C_TASK_TYPE_COPY); m_pool.initPreparedStatement(m_cq.C_TASK_UPDATE_KEY,m_cq.C_TASK_UPDATE); m_pool.initPreparedStatement(m_cq.C_TASK_READ_KEY,m_cq.C_TASK_READ); m_pool.initPreparedStatement(m_cq.C_TASK_END_KEY,m_cq.C_TASK_END); m_pool.initPreparedStatement(m_cq.C_TASK_FIND_AGENT_KEY,m_cq.C_TASK_FIND_AGENT); m_pool.initPreparedStatement(m_cq.C_TASK_FORWARD_KEY,m_cq.C_TASK_FORWARD); m_pool.initPreparedStatement(m_cq.C_TASK_GET_TASKTYPE_KEY,m_cq.C_TASK_GET_TASKTYPE); // init statements for taskpars m_pool.initPreparedStatement(m_cq.C_TASKPAR_TEST_KEY,m_cq.C_TASKPAR_TEST); m_pool.initPreparedStatement(m_cq.C_TASKPAR_UPDATE_KEY,m_cq.C_TASKPAR_UPDATE); m_pool.initPreparedStatement(m_cq.C_TASKPAR_INSERT_KEY,m_cq.C_TASKPAR_INSERT); m_pool.initPreparedStatement(m_cq.C_TASKPAR_GET_KEY,m_cq.C_TASKPAR_GET); // init statements for tasklogs m_pool.initPreparedStatement(m_cq.C_TASKLOG_WRITE_KEY,m_cq.C_TASKLOG_WRITE); m_pool.initPreparedStatement(m_cq.C_TASKLOG_READ_KEY,m_cq.C_TASKLOG_READ); m_pool.initPreparedStatement(m_cq.C_TASKLOG_READ_LOGS_KEY,m_cq.C_TASKLOG_READ_LOGS); m_pool.initPreparedStatement(m_cq.C_TASKLOG_READ_PPROJECTLOGS_KEY,m_cq.C_TASKLOG_READ_PPROJECTLOGS); // init statements for id // - to be able to override method in other packages initIdStatements(); // init statements for sessions m_pool.initPreparedStatement(m_cq.C_SESSION_CREATE_KEY, m_cq.C_SESSION_CREATE); m_pool.initPreparedStatement(m_cq.C_SESSION_UPDATE_KEY, m_cq.C_SESSION_UPDATE); m_pool.initPreparedStatement(m_cq.C_SESSION_READ_KEY, m_cq.C_SESSION_READ); m_pool.initPreparedStatement(m_cq.C_SESSION_DELETE_KEY, m_cq.C_SESSION_DELETE); } protected int insertTaskPar(int taskId, String parname, String parvalue) throws CmsException { PreparedStatement statement = null; int newId = C_UNKNOWN_ID; try { newId = nextId(C_TABLE_TASKPAR); statement = m_pool.getPreparedStatement(m_cq.C_TASKPAR_INSERT_KEY); statement.setInt(1, newId); statement.setInt(2, taskId); statement.setString(3, parname); statement.setString(4, parvalue); statement.executeUpdate(); } catch( SQLException exc ) { throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc); } finally { if(statement != null) { m_pool.putPreparedStatement(m_cq.C_TASKPAR_INSERT_KEY, statement); } } return newId; } public boolean isSiteLegal(int siteId, String name, String url, int categoryId, int languageId, int countryId) throws CmsException { //public String C_SITES_CHECKSITE = "SELECT NAME FROM " + C_DATABASE_PREFIX + "SITES WHERE NAME <> ? AND CATEGORY_ID = ? LANGUAGE_ID = ? AND COUNTRY_ID = ?"; //public String C_SITESSITEURLS_CHECKSITE = "SELECT NAME FROM " + C_DATABASE_PREFIX + "SITE_URLS, " + C_DATABASE_PREFIX + "SITES WHERE NAME <> ? AND (LOWER(NAME) = ? OR LOWER(URL) = ?)"; boolean isLegal = true; PreparedStatement statement = null; PreparedStatement statement1 = null; try { statement = m_pool.getPreparedStatement(m_cq.C_SITES_CHECKSITE_KEY); statement.setInt(1, siteId); statement.setInt(2, categoryId); statement.setInt(3, languageId); statement.setInt(4, countryId); ResultSet res = statement.executeQuery(); if (res.next()) isLegal = false; res.close(); if (isLegal) { statement1 = m_pool.getPreparedStatement(m_cq.C_SITESSITEURLS_CHECKSITE_KEY); statement1.setInt(1, siteId); statement1.setString(2, name.trim().toLowerCase()); statement1.setString(3, url.trim().toLowerCase()); res = statement1.executeQuery(); if (res.next()) isLegal = false; res.close(); } } catch (SQLException e) { throw new CmsException("[" + this.getClass().getName() + "]" + e.getMessage(), CmsException.C_SQL_ERROR, e); } catch (Exception e) { throw new CmsException("[" + this.getClass().getName() + "]", e); } finally { if (statement != null) m_pool.putPreparedStatement(m_cq.C_SITES_CHECKSITE_KEY, statement); if (statement1 != null) m_pool.putPreparedStatement(m_cq.C_SITESSITEURLS_CHECKSITE_KEY, statement1); } return isLegal; } /** * Instanciates the access-module and sets up all required modules and connections. * @param config The OpenCms configuration. * @exception CmsException Throws CmsException if something goes wrong. */ public CmsDbAccess(Configurations config) throws CmsException { this.m_cq = getQueries(); String rbName = null; String driver = null; String url = null; String user = null; String password = null; String digest = null; String exportpoint = null; String exportpath = null; int sleepTime; boolean fillDefaults = true; int maxConn; if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] init the dbaccess-module."); } // read the name of the rb from the properties rbName = (String)config.getString(C_CONFIGURATION_RESOURCEBROKER); // read the exportpoints m_exportpointStorage = new Hashtable(); int i = 0; while ((exportpoint = config.getString(C_EXPORTPOINT + Integer.toString(i))) != null){ exportpath = config.getString(C_EXPORTPOINT_PATH + Integer.toString(i)); if (exportpath != null){ m_exportpointStorage.put(exportpoint, exportpath); } i++; } // read all needed parameters from the configuration driver = config.getString(C_CONFIGURATION_RESOURCEBROKER + "." + rbName + "." + C_CONFIGURATIONS_DRIVER); if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] read driver from configurations: " + driver); } url = config.getString(C_CONFIGURATION_RESOURCEBROKER + "." + rbName + "." + C_CONFIGURATIONS_URL); if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] read url from configurations: " + url); } user = config.getString(C_CONFIGURATION_RESOURCEBROKER + "." + rbName + "." + C_CONFIGURATIONS_USER); if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] read user from configurations: " + user); } password = config.getString(C_CONFIGURATION_RESOURCEBROKER + "." + rbName + "." + C_CONFIGURATIONS_PASSWORD, ""); maxConn = config.getInteger(C_CONFIGURATION_RESOURCEBROKER + "." + rbName + "." + C_CONFIGURATIONS_MAX_CONN); if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] read maxConn from configurations: " + maxConn); } digest = config.getString(C_CONFIGURATION_RESOURCEBROKER + "." + rbName + "." + C_CONFIGURATIONS_DIGEST, "MD5"); if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] read digest from configurations: " + digest); } sleepTime = config.getInteger(C_CONFIGURATION_RESOURCEBROKER + "." + rbName + "." + C_CONFIGURATIONS_GUARD, 120); if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] read guard-sleeptime from configurations: " + sleepTime); } // create the digest try { m_digest = MessageDigest.getInstance(digest); if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] digest created, using: " + m_digest.toString() ); } } catch (NoSuchAlgorithmException e){ if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] error creating digest - using clear paswords: " + e.getMessage()); } } // create the pool m_pool = createCmsDbPool(driver, url, user, password, maxConn); if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] pool created"); } // now init the statements initStatements(); if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] all statements initialized in the pool"); } // now init the max-ids for key generation initMaxIdValues(); if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] max-ids initialized"); } // have we to fill the default resource like root and guest? if (CmsConstants.USE_MULTISITE) { //in multisite, there has to be a site. getAllSites(); if (getAllSites().size() > 0) fillDefaults = false; } else { try { if (readProject(C_PROJECT_ONLINE_ID) != null); // online-project exists - no need of filling defaults fillDefaults = false; } catch (SQLException se) { throw new CmsException(CmsException.C_SQL_ERROR,se); } } if(fillDefaults) { // YES! if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] fill default resources"); } fillDefaults(); } // start the connection-guard if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] start connection guard"); } m_guard = createCmsConnectionGuard(m_pool, sleepTime); m_guard.start(); } public void newSiteProjectsRecord(int siteID, int projectId) throws CmsException { PreparedStatement statement = null; try { // create statement statement = m_pool.getPreparedStatement(m_cq.C_SITE_PROJECTS_WRITE_KEY); // write new site_url record to the database to the database statement.setInt(1, siteID); statement.setInt(2, projectId); statement.executeUpdate(); } catch (SQLException e) { throw new CmsException("[" + this.getClass().getName() + "] " + e.getMessage(), CmsException.C_SQL_ERROR, e); } finally { if (statement != null) { m_pool.putPreparedStatement(m_cq.C_SITE_PROJECTS_WRITE_KEY, statement); } } } public CmsSite newSiteRecord(String name, String description, int category, int language, int country, int onlineProjectId) throws CmsException { CmsSite newSite = null; PreparedStatement statement = null; try { // create statement statement = m_pool.getPreparedStatement(m_cq.C_SITES_WRITE_KEY); // write new group to the database statement.setInt(1, nextId(C_TABLE_SITES)); statement.setString(2, name); statement.setString(3, checkNull(description)); statement.setInt(4, category); statement.setInt(5, language); statement.setInt(6, country); statement.setInt(7, onlineProjectId); statement.executeUpdate(); // create the site object by reading it from the database. // this is necessary to get the Site id which is generated in the // database. It also provides a basic check of whether the site has been created correctly. newSite = getSite(name); } catch (SQLException e) { throw new CmsException("[" + this.getClass().getName() + "] " + e.getMessage(), CmsException.C_SQL_ERROR, e); } finally { if (statement != null) { m_pool.putPreparedStatement(m_cq.C_SITES_WRITE_KEY, statement); } } return newSite; } public void newSiteUrlRecord(String url, int siteID, String primary_url) throws CmsException { PreparedStatement statement = null; try { int newId = nextId(C_TABLE_SITE_URLS); // create statement statement = m_pool.getPreparedStatement(m_cq.C_SITE_URLS_WRITE_KEY); // write new site_url record to the database to the database statement.setInt(1, newId); statement.setString(2, url); statement.setInt(3, siteID); statement.setInt(4, newId); statement.executeUpdate(); } catch (SQLException e) { throw new CmsException("[" + this.getClass().getName() + "] " + e.getMessage(), CmsException.C_SQL_ERROR, e); } finally { if (statement != null) { m_pool.putPreparedStatement(m_cq.C_SITE_URLS_WRITE_KEY, statement); } } } /** * Private method to get the next id for a table. * This method is synchronized, to generate unique id's. * * @param key A key for the table to get the max-id from. * @return next-id The next possible id for this table. */ protected synchronized int nextId(int key) throws CmsException { com.opencms.file.genericSql.CmsDbPool pool = (com.opencms.file.genericSql.CmsDbPool) m_pool; int newId = C_UNKNOWN_INT; PreparedStatement firstStatement = null; PreparedStatement statement = null; ResultSet res = null; try { firstStatement = pool.getPreparedStatement(m_cq.C_SYSTEMID_LOCK_KEY); firstStatement.executeUpdate(); statement = pool.getNextPreparedStatement(firstStatement, m_cq.C_SYSTEMID_READ_KEY); statement.setInt(1,key); res = statement.executeQuery(); if (res.next()){ newId = res.getInt(m_cq.C_SYSTEMID_ID); res.close(); }else{ res.close(); throw new CmsException("[" + this.getClass().getName() + "] "+" cant read Id! ",CmsException.C_NO_GROUP); } statement = pool.getNextPreparedStatement(firstStatement, m_cq.C_SYSTEMID_WRITE_KEY); statement.setInt(1,newId+1); statement.setInt(2,key); statement.executeUpdate(); statement = pool.getNextPreparedStatement(firstStatement, m_cq.C_SYSTEMID_UNLOCK_KEY); statement.executeUpdate(); m_pool.putPreparedStatement(m_cq.C_SYSTEMID_LOCK_KEY, firstStatement); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e); } return( newId ); } /** * Publishes a specified project to the online project. <br> * * @param project The project to be published. * @param onlineProject The online project of the OpenCms. * @exception CmsException Throws CmsException if operation was not succesful. */ public void publishProject(CmsUser user, int projectId, CmsProject onlineProject) throws CmsException { try //catch SQLException form readFolder, etc. { CmsAccessFilesystem discAccess = new CmsAccessFilesystem(m_exportpointStorage); CmsFolder currentFolder = null; CmsFile currentFile = null; Vector offlineFolders; Vector offlineFiles; Vector deletedFolders = new Vector(); // folderIdIndex: offlinefolderId | onlinefolderId Hashtable folderIdIndex = new Hashtable(); // read all folders in offlineProject offlineFolders = readFolders(projectId); for (int i = 0; i < offlineFolders.size(); i++) { currentFolder = ((CmsFolder) offlineFolders.elementAt(i)); // C_STATE_DELETE if (currentFolder.getState() == C_STATE_DELETED) { deletedFolders.addElement(currentFolder); // C_STATE_NEW } else if (currentFolder.getState() == C_STATE_NEW) { // export to filesystem if necessary String exportKey = checkExport(currentFolder.getAbsolutePath()); if (exportKey != null) { discAccess.createFolder(currentFolder.getAbsolutePath(), exportKey); } // get parentId for onlineFolder either from folderIdIndex or from the database Integer parentId = (Integer) folderIdIndex.get(new Integer(currentFolder.getParentId())); if (parentId == null) { CmsFolder currentOnlineParent = null; currentOnlineParent = readFolder(onlineProject.getId(), currentFolder.getParent()); if (currentOnlineParent == null) throw new CmsException(this.getClass().getName() + ".publishProject: + Folder not found: " + currentFolder.getParent()); parentId = new Integer(currentOnlineParent.getResourceId()); folderIdIndex.put(new Integer(currentFolder.getParentId()), parentId); } // create the new folder and insert its id in the folderindex CmsFolder newFolder = createFolder(user, onlineProject, onlineProject, currentFolder, parentId.intValue(), currentFolder.getAbsolutePath()); newFolder.setState(C_STATE_UNCHANGED); writeFolder(onlineProject, newFolder, false); folderIdIndex.put(new Integer(currentFolder.getResourceId()), new Integer(newFolder.getResourceId())); // copy properties try { Hashtable props = readAllProperties(currentFolder.getResourceId(), currentFolder.getType()); writeProperties(props, newFolder.getResourceId(), newFolder.getType()); } catch (CmsException exc) { if (A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsDbAccess] error publishing, copy properties for " + newFolder.toString() + " Message= " + exc.getMessage()); } } // C_STATE_CHANGED } else if (currentFolder.getState() == C_STATE_CHANGED) { // export to filesystem if necessary String exportKey = checkExport(currentFolder.getAbsolutePath()); if (exportKey != null) { discAccess.createFolder(currentFolder.getAbsolutePath(), exportKey); } CmsFolder onlineFolder = null; onlineFolder = readFolder(onlineProject.getId(), currentFolder.getAbsolutePath()); if (onlineFolder == null) { // if folder does not exist create it // get parentId for onlineFolder either from folderIdIndex or from the database Integer parentId = (Integer) folderIdIndex.get(new Integer(currentFolder.getParentId())); if (parentId == null) { CmsFolder currentOnlineParent = readFolder(onlineProject.getId(), currentFolder.getParent()); if (currentOnlineParent == null) throw new CmsException(this.getClass().getName() + ".publishProject: + Folder not found: " + currentFolder.getParent()); parentId = new Integer(currentOnlineParent.getResourceId()); folderIdIndex.put(new Integer(currentFolder.getParentId()), parentId); } // create the new folder onlineFolder = createFolder(user, onlineProject, onlineProject, currentFolder, parentId.intValue(), currentFolder.getAbsolutePath()); onlineFolder.setState(C_STATE_UNCHANGED); writeFolder(onlineProject, onlineFolder, false); } PreparedStatement statement = null; try { // update the onlineFolder with data from offlineFolder statement = m_pool.getPreparedStatement(m_cq.C_RESOURCES_UPDATE_KEY); statement.setInt(1, currentFolder.getType()); statement.setInt(2, currentFolder.getFlags()); statement.setInt(3, currentFolder.getOwnerId()); statement.setInt(4, currentFolder.getGroupId()); statement.setInt(5, onlineFolder.getProjectId()); statement.setInt(6, currentFolder.getAccessFlags()); statement.setInt(7, C_STATE_UNCHANGED); statement.setInt(8, currentFolder.isLockedBy()); statement.setInt(9, currentFolder.getLauncherType()); statement.setString(10, currentFolder.getLauncherClassname()); statement.setTimestamp(11, new Timestamp(System.currentTimeMillis())); statement.setInt(12, currentFolder.getResourceLastModifiedBy()); statement.setInt(13, 0); statement.setInt(14, currentFolder.getFileId()); statement.setInt(15, onlineFolder.getResourceId()); statement.executeUpdate(); } finally { if (statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_UPDATE_KEY, statement); } } folderIdIndex.put(new Integer(currentFolder.getResourceId()), new Integer(onlineFolder.getResourceId())); // copy properties try { deleteAllProperties(onlineFolder.getResourceId()); Hashtable props = readAllProperties(currentFolder.getResourceId(), currentFolder.getType()); writeProperties(props, onlineFolder.getResourceId(), currentFolder.getType()); } catch (CmsException exc) { if (A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsDbAccess] error publishing, deleting properties for " + onlineFolder.toString() + " Message= " + exc.getMessage()); } } // C_STATE_UNCHANGED } else if (currentFolder.getState() == C_STATE_UNCHANGED) { CmsFolder onlineFolder = null; onlineFolder = readFolder(onlineProject.getId(), currentFolder.getAbsolutePath()); if (onlineFolder == null) { // get parentId for onlineFolder either from folderIdIndex or from the database Integer parentId = (Integer) folderIdIndex.get(new Integer(currentFolder.getParentId())); if (parentId == null) { CmsFolder currentOnlineParent = readFolder(onlineProject.getId(), currentFolder.getParent()); if (currentOnlineParent == null) throw new CmsException(this.getClass().getName() + ".publishProject: + Folder not found: " + currentFolder.getParent()); parentId = new Integer(currentOnlineParent.getResourceId()); folderIdIndex.put(new Integer(currentFolder.getParentId()), parentId); } // create the new folder onlineFolder = createFolder(user, onlineProject, onlineProject, currentFolder, parentId.intValue(), currentFolder.getAbsolutePath()); onlineFolder.setState(C_STATE_UNCHANGED); writeFolder(onlineProject, onlineFolder, false); // copy properties try { Hashtable props = readAllProperties(currentFolder.getResourceId(), currentFolder.getType()); writeProperties(props, onlineFolder.getResourceId(), onlineFolder.getType()); } catch (CmsException exc) { if (A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsDbAccess] error publishing, copy properties for " + onlineFolder.toString() + " Message= " + exc.getMessage()); } } } // end of catch folderIdIndex.put(new Integer(currentFolder.getResourceId()), new Integer(onlineFolder.getResourceId())); } // end of else if } // end of for(... // now read all FILES in offlineProject offlineFiles = readFiles(projectId); for (int i = 0; i < offlineFiles.size(); i++) { currentFile = ((CmsFile) offlineFiles.elementAt(i)); if (currentFile.getName().startsWith(C_TEMP_PREFIX)) { removeFile(projectId, currentFile.getAbsolutePath()); // C_STATE_DELETE } else if (currentFile.getState() == C_STATE_DELETED) { // delete in filesystem if necessary String exportKey = checkExport(currentFile.getAbsolutePath()); if (exportKey != null) { try { discAccess.removeResource(currentFile.getAbsolutePath(), exportKey); } catch (Exception ex) { } } CmsFile currentOnlineFile = readFile(onlineProject.getId(), currentFile.getAbsolutePath()); try { deleteAllProperties(currentOnlineFile.getResourceId()); } catch (CmsException exc) { if (A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsDbAccess] error publishing, deleting properties for " + currentOnlineFile.toString() + " Message= " + exc.getMessage()); } } try { deleteResource(currentOnlineFile.getResourceId()); } catch (CmsException exc) { if (A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsDbAccess] error publishing, deleting resource for " + currentOnlineFile.toString() + " Message= " + exc.getMessage()); } } // C_STATE_CHANGED } else if (currentFile.getState() == C_STATE_CHANGED) { // export to filesystem if necessary String exportKey = checkExport(currentFile.getAbsolutePath()); if (exportKey != null) { discAccess.writeFile(currentFile.getAbsolutePath(), exportKey, readFileContent(currentFile.getFileId())); } CmsFile onlineFile = readFileHeader(onlineProject.getId(), currentFile.getAbsolutePath()); if (onlineFile == null) { // get parentId for onlineFolder either from folderIdIndex or from the database Integer parentId = (Integer) folderIdIndex.get(new Integer(currentFile.getParentId())); if (parentId == null) { CmsFolder currentOnlineParent = readFolder(onlineProject.getId(), currentFolder.getParent()); if (currentOnlineParent == null) throw new CmsException(this.getClass().getName() + ".publishProject: + Folder not found: " + currentFolder.getParent()); parentId = new Integer(currentOnlineParent.getResourceId()); folderIdIndex.put(new Integer(currentFile.getParentId()), parentId); } // create a new File currentFile.setState(C_STATE_UNCHANGED); onlineFile = createFile(onlineProject, onlineProject, currentFile, user.getId(), parentId.intValue(), currentFile.getAbsolutePath(), false); } if (onlineFile.getState() == C_STATE_DELETED) onlineFile = null; PreparedStatement statement = null; try { // update the onlineFile with data from offlineFile statement = m_pool.getPreparedStatement(m_cq.C_RESOURCES_UPDATE_FILE_KEY); statement.setInt(1, currentFile.getType()); statement.setInt(2, currentFile.getFlags()); statement.setInt(3, currentFile.getOwnerId()); statement.setInt(4, currentFile.getGroupId()); statement.setInt(5, onlineFile.getProjectId()); statement.setInt(6, currentFile.getAccessFlags()); statement.setInt(7, C_STATE_UNCHANGED); statement.setInt(8, currentFile.isLockedBy()); statement.setInt(9, currentFile.getLauncherType()); statement.setString(10, currentFile.getLauncherClassname()); statement.setTimestamp(11, new Timestamp(System.currentTimeMillis())); statement.setInt(12, currentFile.getResourceLastModifiedBy()); statement.setInt(13, currentFile.getLength()); statement.setInt(14, currentFile.getFileId()); statement.setInt(15, onlineFile.getResourceId()); statement.executeUpdate(); } finally { if (statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_UPDATE_FILE_KEY, statement); } } // copy properties try { deleteAllProperties(onlineFile.getResourceId()); Hashtable props = readAllProperties(currentFile.getResourceId(), currentFile.getType()); writeProperties(props, onlineFile.getResourceId(), currentFile.getType()); } catch (CmsException exc) { if (A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsDbAccess] error publishing, deleting properties for " + onlineFile.toString() + " Message= " + exc.getMessage()); } } // C_STATE_NEW } else if (currentFile.getState() == C_STATE_NEW) { // export to filesystem if necessary String exportKey = checkExport(currentFile.getAbsolutePath()); if (exportKey != null) { discAccess.writeFile(currentFile.getAbsolutePath(), exportKey, readFileContent(currentFile.getFileId())); } // get parentId for onlineFile either from folderIdIndex or from the database Integer parentId = (Integer) folderIdIndex.get(new Integer(currentFile.getParentId())); if (parentId == null) { CmsFolder currentOnlineParent = readFolder(onlineProject.getId(), currentFile.getParent()); if (currentOnlineParent == null) throw new CmsException(this.getClass().getName() + ".publishProject: + Folder not found: " + currentFolder.getParent()); parentId = new Integer(currentOnlineParent.getResourceId()); folderIdIndex.put(new Integer(currentFile.getParentId()), parentId); } // create the new file CmsFile newFile = createFile(onlineProject, onlineProject, currentFile, user.getId(), parentId.intValue(), currentFile.getAbsolutePath(), false); newFile.setState(C_STATE_UNCHANGED); writeFile(onlineProject, onlineProject, newFile, false); // copy properties try { Hashtable props = readAllProperties(currentFile.getResourceId(), currentFile.getType()); writeProperties(props, newFile.getResourceId(), newFile.getType()); } catch (CmsException exc) { if (A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsDbAccess] error publishing, copy properties for " + newFile.toString() + " Message= " + exc.getMessage()); } } } } // end of for(... // now delete the "deleted" folders for (int i = deletedFolders.size() - 1; i > -1; i { currentFolder = ((CmsFolder) deletedFolders.elementAt(i)); String exportKey = checkExport(currentFolder.getAbsolutePath()); if (exportKey != null) { discAccess.removeResource(currentFolder.getAbsolutePath(), exportKey); } try { deleteAllProperties(currentFolder.getResourceId()); } catch (CmsException exc) { if (A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsDbAccess] error publishing, deleting properties for " + currentFolder.toString() + " Message= " + exc.getMessage()); } } removeFolderForPublish(onlineProject, currentFolder.getAbsolutePath()); } // end of for //clearFilesTable(); } catch (SQLException se) { throw new CmsException(CmsException.C_SQL_ERROR, se); } } /** * Reads all file headers of a file in the OpenCms.<BR> * The reading excludes the filecontent. * * @param filename The name of the file to be read. * * @return Vector of file headers read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful */ public Vector readAllFileHeaders(String filename) throws CmsException { CmsFile file=null; ResultSet res =null; Vector allHeaders = new Vector(); PreparedStatement statement = null; try { statement = m_pool.getPreparedStatement(m_cq.C_RESOURCES_READ_ALL_KEY); // read file header data from database statement.setString(1, filename); res = statement.executeQuery(); // create new file headers while(res.next()) { int resId=res.getInt(m_cq.C_RESOURCES_RESOURCE_ID); int parentId=res.getInt(m_cq.C_RESOURCES_PARENT_ID); String resName=res.getString(m_cq.C_RESOURCES_RESOURCE_NAME); int resType= res.getInt(m_cq.C_RESOURCES_RESOURCE_TYPE); int resFlags=res.getInt(m_cq.C_RESOURCES_RESOURCE_FLAGS); int userId=res.getInt(m_cq.C_RESOURCES_USER_ID); int groupId= res.getInt(m_cq.C_RESOURCES_GROUP_ID); int projectID=res.getInt(m_cq.C_RESOURCES_PROJECT_ID); int fileId=res.getInt(m_cq.C_RESOURCES_FILE_ID); int accessFlags=res.getInt(m_cq.C_RESOURCES_ACCESS_FLAGS); int state= res.getInt(m_cq.C_RESOURCES_STATE); int lockedBy= res.getInt(m_cq.C_RESOURCES_LOCKED_BY); int launcherType= res.getInt(m_cq.C_RESOURCES_LAUNCHER_TYPE); String launcherClass= res.getString(m_cq.C_RESOURCES_LAUNCHER_CLASSNAME); long created=SqlHelper.getTimestamp(res,m_cq.C_RESOURCES_DATE_CREATED).getTime(); long modified=SqlHelper.getTimestamp(res,m_cq.C_RESOURCES_DATE_LASTMODIFIED).getTime(); int resSize= res.getInt(m_cq.C_RESOURCES_SIZE); int modifiedBy=res.getInt(m_cq.C_RESOURCES_LASTMODIFIED_BY); file=new CmsFile(resId,parentId,fileId,resName,resType,resFlags,userId, groupId,projectID,accessFlags,state,lockedBy, launcherType,launcherClass,created,modified,modifiedBy, new byte[0],resSize); allHeaders.addElement(file); } } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e); } catch( Exception exc ) { throw new CmsException("readAllFileHeaders "+exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_READ_ALL_KEY, statement); } } return allHeaders; } /** * Returns a list of all properties of a file or folder. * * @param resourceId The id of the resource. * @param resourceType The Type of the resource. * * @return Vector of properties as Strings. * * @exception CmsException Throws CmsException if operation was not succesful */ public Hashtable readAllProperties(int resourceId, int resourceType) throws CmsException { Hashtable returnValue = new Hashtable(); ResultSet result = null; PreparedStatement statement = null; try { // create project statement = m_pool.getPreparedStatement(m_cq.C_PROPERTIES_READALL_KEY); statement.setInt(1, resourceId); statement.setInt(2, resourceType); result = statement.executeQuery(); while(result.next()) { returnValue.put(result.getString(m_cq.C_PROPERTYDEF_NAME), result.getString(m_cq.C_PROPERTY_VALUE)); } result.close(); } catch( SQLException exc ) { throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(), CmsException.C_SQL_ERROR, exc); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_PROPERTIES_READALL_KEY, statement); } } return(returnValue); } /** * Reads all propertydefinitions for the given resource type. * * @param resourcetype The resource type to read the propertydefinitions for. * @param type The type of the propertydefinition (normal|mandatory|optional). * * @return propertydefinitions A Vector with propertydefefinitions for the resource type. * The Vector is maybe empty. * * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readAllPropertydefinitions(int resourcetype, int type) throws CmsException { Vector metadefs = new Vector(); PreparedStatement statement = null; ResultSet result = null; try { // create statement statement = m_pool.getPreparedStatement(m_cq.C_PROPERTYDEF_READALL_B_KEY); statement.setInt(1,resourcetype); statement.setInt(2,type); result = statement.executeQuery(); while(result.next()) { metadefs.addElement( new CmsPropertydefinition( result.getInt(m_cq.C_PROPERTYDEF_ID), result.getString(m_cq.C_PROPERTYDEF_NAME), result.getInt(m_cq.C_PROPERTYDEF_RESOURCE_TYPE), result.getInt(m_cq.C_PROPERTYDEF_TYPE) ) ); } result.close(); } catch( SQLException exc ) { throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(), CmsException.C_SQL_ERROR, exc); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_PROPERTYDEF_READALL_B_KEY, statement); } } return(metadefs); } /** * Reads all propertydefinitions for the given resource type. * * @param resourcetype The resource type to read the propertydefinitions for. * * @return propertydefinitions A Vector with propertydefefinitions for the resource type. * The Vector is maybe empty. * * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readAllPropertydefinitions(int resourcetype) throws CmsException { Vector metadefs = new Vector(); ResultSet result = null; PreparedStatement statement = null; try { // create statement statement = m_pool.getPreparedStatement(m_cq.C_PROPERTYDEF_READALL_A_KEY); statement.setInt(1,resourcetype); result = statement.executeQuery(); while(result.next()) { metadefs.addElement( new CmsPropertydefinition( result.getInt(m_cq.C_PROPERTYDEF_ID), result.getString(m_cq.C_PROPERTYDEF_NAME), result.getInt(m_cq.C_PROPERTYDEF_RESOURCE_TYPE), result.getInt(m_cq.C_PROPERTYDEF_TYPE) ) ); } result.close(); } catch( SQLException exc ) { throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(), CmsException.C_SQL_ERROR, exc); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_PROPERTYDEF_READALL_A_KEY, statement); } } return(metadefs); } /** * Reads all propertydefinitions for the given resource type. * * @param resourcetype The resource type to read the propertydefinitions for. * @param type The type of the propertydefinition (normal|mandatory|optional). * * @return propertydefinitions A Vector with propertydefefinitions for the resource type. * The Vector is maybe empty. * * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readAllPropertydefinitions(CmsResourceType resourcetype, int type) throws CmsException { return(readAllPropertydefinitions(resourcetype.getResourceType(), type)); } /** * Reads all propertydefinitions for the given resource type. * * @param resourcetype The resource type to read the propertydefinitions for. * * @return propertydefinitions A Vector with propertydefefinitions for the resource type. * The Vector is maybe empty. * * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readAllPropertydefinitions(CmsResourceType resourcetype) throws CmsException { return(readAllPropertydefinitions(resourcetype.getResourceType())); } /** * Private helper method to read the fileContent for publishProject(export). * * @param fileId the fileId. * * @exception CmsException Throws CmsException if operation was not succesful. */ protected byte[] readFileContent(int fileId) throws CmsException { PreparedStatement statement = null; ResultSet res = null; byte[] returnValue = null; try { // read fileContent from database statement = m_pool.getPreparedStatement(m_cq.C_FILE_READ_KEY); statement.setInt(1,fileId); res = statement.executeQuery(); if (res.next()) { returnValue = res.getBytes(m_cq.C_FILE_CONTENT); } else { throw new CmsException("["+this.getClass().getName()+"]"+fileId,CmsException.C_NOT_FOUND); } res.close(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_FILE_READ_KEY, statement); } } return returnValue; } /** * Reads a file header from the Cms.<BR/> * The reading excludes the filecontent. * * @param resourceId The Id of the resource. * * @return file The read file. * * @exception CmsException Throws CmsException if operation was not succesful */ public CmsFile readFileHeader(int resourceId) throws CmsException { CmsFile file=null; ResultSet res =null; PreparedStatement statement = null; try { statement=m_pool.getPreparedStatement(m_cq.C_RESOURCES_READBYID_KEY); // read file data from database statement.setInt(1, resourceId); res = statement.executeQuery(); // create new file if(res.next()) { int resId=res.getInt(m_cq.C_RESOURCES_RESOURCE_ID); int parentId=res.getInt(m_cq.C_RESOURCES_PARENT_ID); String resName=res.getString(m_cq.C_RESOURCES_RESOURCE_NAME); int resType= res.getInt(m_cq.C_RESOURCES_RESOURCE_TYPE); int resFlags=res.getInt(m_cq.C_RESOURCES_RESOURCE_FLAGS); int userId=res.getInt(m_cq.C_RESOURCES_USER_ID); int groupId= res.getInt(m_cq.C_RESOURCES_GROUP_ID); int projectID=res.getInt(m_cq.C_RESOURCES_PROJECT_ID); int fileId=res.getInt(m_cq.C_RESOURCES_FILE_ID); int accessFlags=res.getInt(m_cq.C_RESOURCES_ACCESS_FLAGS); int state= res.getInt(m_cq.C_RESOURCES_STATE); int lockedBy= res.getInt(m_cq.C_RESOURCES_LOCKED_BY); int launcherType= res.getInt(m_cq.C_RESOURCES_LAUNCHER_TYPE); String launcherClass= res.getString(m_cq.C_RESOURCES_LAUNCHER_CLASSNAME); long created=SqlHelper.getTimestamp(res,m_cq.C_RESOURCES_DATE_CREATED).getTime(); long modified=SqlHelper.getTimestamp(res,m_cq.C_RESOURCES_DATE_LASTMODIFIED).getTime(); int resSize= res.getInt(m_cq.C_RESOURCES_SIZE); int modifiedBy=res.getInt(m_cq.C_RESOURCES_LASTMODIFIED_BY); file=new CmsFile(resId,parentId,fileId,resName,resType,resFlags,userId, groupId,projectID,accessFlags,state,lockedBy, launcherType,launcherClass,created,modified,modifiedBy, new byte[0],resSize); res.close(); // check if this resource is marked as deleted if (file.getState() == C_STATE_DELETED) { throw new CmsException("["+this.getClass().getName()+"] "+file.getAbsolutePath(),CmsException.C_RESOURCE_DELETED); } } else { throw new CmsException("["+this.getClass().getName()+"] "+resourceId,CmsException.C_NOT_FOUND); } } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e); } catch (CmsException ex) { throw ex; } catch( Exception exc ) { throw new CmsException("readFile "+exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_READBYID_KEY, statement); } } return file; } /** * Reads a file header from the Cms.<BR/> * The reading excludes the filecontent. * * @param projectId The Id of the project in which the resource will be used. * @param filename The complete name of the new file (including pathinformation). * * @return file The read file, returns null if the resource could not be found. * NOTE: If the reosurce was deleted, it is still returned. * * @exception CmsException Throws CmsException if operation was not succesful */ public CmsFile readFileHeader(int projectId, String filename) throws SQLException { CmsFile file = null; ResultSet res = null; PreparedStatement statement = null; try { statement = m_pool.getPreparedStatement(m_cq.C_RESOURCES_READ_KEY); // read file data from database statement.setString(1, filename); statement.setInt(2, projectId); res = statement.executeQuery(); // create new file if (res.next()) { int resId = res.getInt(m_cq.C_RESOURCES_RESOURCE_ID); int parentId = res.getInt(m_cq.C_RESOURCES_PARENT_ID); String resName = res.getString(m_cq.C_RESOURCES_RESOURCE_NAME); int resType = res.getInt(m_cq.C_RESOURCES_RESOURCE_TYPE); int resFlags = res.getInt(m_cq.C_RESOURCES_RESOURCE_FLAGS); int userId = res.getInt(m_cq.C_RESOURCES_USER_ID); int groupId = res.getInt(m_cq.C_RESOURCES_GROUP_ID); int projectID = res.getInt(m_cq.C_RESOURCES_PROJECT_ID); int fileId = res.getInt(m_cq.C_RESOURCES_FILE_ID); int accessFlags = res.getInt(m_cq.C_RESOURCES_ACCESS_FLAGS); int state = res.getInt(m_cq.C_RESOURCES_STATE); int lockedBy = res.getInt(m_cq.C_RESOURCES_LOCKED_BY); int launcherType = res.getInt(m_cq.C_RESOURCES_LAUNCHER_TYPE); String launcherClass = res.getString(m_cq.C_RESOURCES_LAUNCHER_CLASSNAME); long created = SqlHelper.getTimestamp(res, m_cq.C_RESOURCES_DATE_CREATED).getTime(); long modified = SqlHelper.getTimestamp(res, m_cq.C_RESOURCES_DATE_LASTMODIFIED).getTime(); int resSize = res.getInt(m_cq.C_RESOURCES_SIZE); int modifiedBy = res.getInt(m_cq.C_RESOURCES_LASTMODIFIED_BY); file = new CmsFile(resId, parentId, fileId, resName, resType, resFlags, userId, groupId, projectID, accessFlags, state, lockedBy, launcherType, launcherClass, created, modified, modifiedBy, new byte[0], resSize); } } finally { if (res != null) { try { res.close(); } catch (SQLException se) { } } if (statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_READ_KEY, statement); } } return file; } /** * Reads a file from the Cms.<BR/> * * @param projectId The Id of the project in which the resource will be used. * @param onlineProjectId The online projectId of the OpenCms. * @param filename The complete name of the new file (including pathinformation). * * @return file The read file, or null if the resource could not be found. * Note that if a resource has been deleted, the file is still returned. * * @exception CmsException Throws CmsException if operation was not succesful */ public CmsFile readFile(int projectId, String filename) throws SQLException, CmsException { CmsFile file = null; PreparedStatement statement = null; ResultSet res = null; try { // get the file header file = readFileHeader(projectId, filename); //if the file was not found, or had been deleted - just return it. if ((file == null) || (file.getState() == C_STATE_DELETED)) return file; // read the file content statement = m_pool.getPreparedStatement(m_cq.C_FILE_READ_KEY); statement.setInt(1, file.getFileId()); res = statement.executeQuery(); if (res.next()) file.setContents(res.getBytes(m_cq.C_FILE_CONTENT)); else //if the resource was not deleted - we should be able to read its content. If not this is a serious error. throw new CmsException("[" + this.getClass().getName() + "]" + filename, CmsException.C_NOT_FOUND); } finally { if (res != null) { try { res.close(); } catch (SQLException se) { //do nothing. } } if (statement != null) m_pool.putPreparedStatement(m_cq.C_FILE_READ_KEY, statement); } return file; } /** * Reads all files from the Cms, that are in one project.<BR/> * * @param project The project in which the files are. * * @return A Vecor of files. * * @exception CmsException Throws CmsException if operation was not succesful */ public Vector readFiles(int projectId) throws CmsException { Vector files = new Vector(); CmsFile file; ResultSet res = null; PreparedStatement statement = null; try { // read file data from database statement = m_pool.getPreparedStatement(m_cq.C_RESOURCES_READFILESBYPROJECT_KEY); statement.setInt(1,projectId); res = statement.executeQuery(); // create new file while(res.next()) { int resId=res.getInt(m_cq.C_RESOURCES_RESOURCE_ID); int parentId=res.getInt(m_cq.C_RESOURCES_PARENT_ID); String resName=res.getString(m_cq.C_RESOURCES_RESOURCE_NAME); int resType= res.getInt(m_cq.C_RESOURCES_RESOURCE_TYPE); int resFlags=res.getInt(m_cq.C_RESOURCES_RESOURCE_FLAGS); int userId=res.getInt(m_cq.C_RESOURCES_USER_ID); int groupId= res.getInt(m_cq.C_RESOURCES_GROUP_ID); int projectID=res.getInt(m_cq.C_RESOURCES_PROJECT_ID); int fileId=res.getInt(m_cq.C_RESOURCES_FILE_ID); int accessFlags=res.getInt(m_cq.C_RESOURCES_ACCESS_FLAGS); int state= res.getInt(m_cq.C_RESOURCES_STATE); int lockedBy= res.getInt(m_cq.C_RESOURCES_LOCKED_BY); int launcherType= res.getInt(m_cq.C_RESOURCES_LAUNCHER_TYPE); String launcherClass= res.getString(m_cq.C_RESOURCES_LAUNCHER_CLASSNAME); long created=SqlHelper.getTimestamp(res,m_cq.C_RESOURCES_DATE_CREATED).getTime(); long modified=SqlHelper.getTimestamp(res,m_cq.C_RESOURCES_DATE_LASTMODIFIED).getTime(); int resSize= res.getInt(m_cq.C_RESOURCES_SIZE); int modifiedBy=res.getInt(m_cq.C_RESOURCES_LASTMODIFIED_BY); file=new CmsFile(resId,parentId,fileId,resName,resType,resFlags,userId, groupId,projectID,accessFlags,state,lockedBy, launcherType,launcherClass,created,modified,modifiedBy, new byte[0],resSize); files.addElement(file); } res.close(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e); } catch (Exception ex) { throw new CmsException("["+this.getClass().getName()+"]", ex); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_READFILESBYPROJECT_KEY, statement); } } return files; } /** * Reads a folder from the Cms.<BR/> * * @param project The project in which the resource will be used. * @param foldername The name of the folder to be read. * * @return The read folder, null if not found. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsFolder readFolder(int projectId, String foldername) throws SQLException { CmsFolder folder=null; ResultSet res =null; PreparedStatement statement = null; try { statement=m_pool.getPreparedStatement(m_cq.C_RESOURCES_READ_KEY); statement.setString(1, foldername); statement.setInt(2,projectId); res = statement.executeQuery(); // create new resource if(res.next()) { int resId=res.getInt(m_cq.C_RESOURCES_RESOURCE_ID); int parentId=res.getInt(m_cq.C_RESOURCES_PARENT_ID); String resName=res.getString(m_cq.C_RESOURCES_RESOURCE_NAME); int resType= res.getInt(m_cq.C_RESOURCES_RESOURCE_TYPE); int resFlags=res.getInt(m_cq.C_RESOURCES_RESOURCE_FLAGS); int userId=res.getInt(m_cq.C_RESOURCES_USER_ID); int groupId= res.getInt(m_cq.C_RESOURCES_GROUP_ID); int projectID=res.getInt(m_cq.C_RESOURCES_PROJECT_ID); int fileId=res.getInt(m_cq.C_RESOURCES_FILE_ID); int accessFlags=res.getInt(m_cq.C_RESOURCES_ACCESS_FLAGS); int state= res.getInt(m_cq.C_RESOURCES_STATE); int lockedBy= res.getInt(m_cq.C_RESOURCES_LOCKED_BY); long created=SqlHelper.getTimestamp(res,m_cq.C_RESOURCES_DATE_CREATED).getTime(); long modified=SqlHelper.getTimestamp(res,m_cq.C_RESOURCES_DATE_LASTMODIFIED).getTime(); int modifiedBy=res.getInt(m_cq.C_RESOURCES_LASTMODIFIED_BY); folder = new CmsFolder(resId,parentId,fileId,resName,resType,resFlags,userId, groupId,projectID,accessFlags,state,lockedBy,created, modified,modifiedBy); res.close(); } } finally { if ( res != null) try { res.close(); } catch (SQLException se) {} if( statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_READ_KEY, statement); } } return folder; } /** * Reads all folders from the Cms, that are in one project.<BR/> * * @param project The project in which the folders are. * * @return A Vecor of folders. * * @exception CmsException Throws CmsException if operation was not succesful */ public Vector readFolders(int projectId) throws CmsException { Vector folders = new Vector(); CmsFolder folder; ResultSet res = null; PreparedStatement statement = null; try { // read folder data from database statement = m_pool.getPreparedStatement(m_cq.C_RESOURCES_READFOLDERSBYPROJECT_KEY); statement.setInt(1,projectId); res = statement.executeQuery(); // create new folder while(res.next()) { int resId=res.getInt(m_cq.C_RESOURCES_RESOURCE_ID); int parentId=res.getInt(m_cq.C_RESOURCES_PARENT_ID); String resName=res.getString(m_cq.C_RESOURCES_RESOURCE_NAME); int resType= res.getInt(m_cq.C_RESOURCES_RESOURCE_TYPE); int resFlags=res.getInt(m_cq.C_RESOURCES_RESOURCE_FLAGS); int userId=res.getInt(m_cq.C_RESOURCES_USER_ID); int groupId= res.getInt(m_cq.C_RESOURCES_GROUP_ID); int projectID=res.getInt(m_cq.C_RESOURCES_PROJECT_ID); int fileId=res.getInt(m_cq.C_RESOURCES_FILE_ID); int accessFlags=res.getInt(m_cq.C_RESOURCES_ACCESS_FLAGS); int state= res.getInt(m_cq.C_RESOURCES_STATE); int lockedBy= res.getInt(m_cq.C_RESOURCES_LOCKED_BY); long created=SqlHelper.getTimestamp(res,m_cq.C_RESOURCES_DATE_CREATED).getTime(); long modified=SqlHelper.getTimestamp(res,m_cq.C_RESOURCES_DATE_LASTMODIFIED).getTime(); int modifiedBy=res.getInt(m_cq.C_RESOURCES_LASTMODIFIED_BY); folder = new CmsFolder(resId,parentId,fileId,resName,resType,resFlags,userId, groupId,projectID,accessFlags,state,lockedBy,created, modified,modifiedBy); folders.addElement(folder); } res.close(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e); } catch (Exception ex) { throw new CmsException("["+this.getClass().getName()+"]", ex); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_READFOLDERSBYPROJECT_KEY, statement); } } return folders; } /** * Returns a group object.<P/> * @param groupname The id of the group that is to be read. * @return Group. * @exception CmsException Throws CmsException if operation was not succesful */ public CmsGroup readGroup(int id) throws CmsException { CmsGroup group=null; ResultSet res = null; PreparedStatement statement=null; try{ // read the group from the database statement=m_pool.getPreparedStatement(m_cq.C_GROUPS_READGROUP2_KEY); statement.setInt(1,id); res = statement.executeQuery(); // create new Cms group object if(res.next()) { group=new CmsGroup(res.getInt(m_cq.C_GROUPS_GROUP_ID), res.getInt(m_cq.C_GROUPS_PARENT_GROUP_ID), res.getString(m_cq.C_GROUPS_GROUP_NAME), res.getString(m_cq.C_GROUPS_GROUP_DESCRIPTION), res.getInt(m_cq.C_GROUPS_GROUP_FLAGS)); res.close(); } else { throw new CmsException("[" + this.getClass().getName() + "] "+id,CmsException.C_NO_GROUP); } } catch (SQLException e){ throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_GROUPS_READGROUP2_KEY,statement); } } return group; } /** * Returns a group object.<P/> * @param groupname The name of the group that is to be read. * @return Group. * @exception CmsException Throws CmsException if operation was not succesful */ public CmsGroup readGroup(String groupname) throws CmsException { CmsGroup group=null; ResultSet res = null; PreparedStatement statement=null; try{ // read the group from the database statement=m_pool.getPreparedStatement(m_cq.C_GROUPS_READGROUP_KEY); statement.setString(1,groupname); res = statement.executeQuery(); // create new Cms group object if(res.next()) { group=new CmsGroup(res.getInt(m_cq.C_GROUPS_GROUP_ID), res.getInt(m_cq.C_GROUPS_PARENT_GROUP_ID), res.getString(m_cq.C_GROUPS_GROUP_NAME), res.getString(m_cq.C_GROUPS_GROUP_DESCRIPTION), res.getInt(m_cq.C_GROUPS_GROUP_FLAGS)); res.close(); } else { throw new CmsException("[" + this.getClass().getName() + "] "+groupname,CmsException.C_NO_GROUP); } } catch (SQLException e){ throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_GROUPS_READGROUP_KEY,statement); } } return group; } /** * Reads a project. * * @param id The id of the project. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsProject readProject(int id) throws SQLException { PreparedStatement statement = null; CmsProject project = null; ResultSet res = null; try { statement = m_pool.getPreparedStatement(m_cq.C_PROJECTS_READ_KEY); statement.setInt(1,id); res = statement.executeQuery(); if(res.next()) project = new CmsProject(res,m_cq); } finally { if (res != null) { try { res.close(); } catch (SQLException se) { //ignore. } } if( statement != null) { m_pool.putPreparedStatement(m_cq.C_PROJECTS_READ_KEY, statement); } } return project; } /** * Reads a project by task-id. * * @param task The task to read the project for. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsProject readProject(CmsTask task) throws CmsException { PreparedStatement statement = null; CmsProject project = null; ResultSet res = null; try { statement = m_pool.getPreparedStatement(m_cq.C_PROJECTS_READ_BYTASK_KEY); statement.setInt(1,task.getId()); res = statement.executeQuery(); if(res.next()) project = new CmsProject(res,m_cq); else // project not found! throw new CmsException("[" + this.getClass().getName() + "] " + task, CmsException.C_NOT_FOUND); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e); } finally { if (res != null) { try { res.close(); } catch (SQLException se) { //ignore. } } if( statement != null) m_pool.putPreparedStatement(m_cq.C_PROJECTS_READ_BYTASK_KEY, statement); } return project; } /** * Reads log entries for a project. * * @param project The projec for tasklog to read. * @return A Vector of new TaskLog objects * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readProjectLogs(int projectid) throws CmsException { ResultSet res; CmsTaskLog tasklog = null; Vector logs = new Vector(); PreparedStatement statement = null; String comment = null; String externalusername = null; java.sql.Timestamp starttime = null; int id = C_UNKNOWN_ID; int task = C_UNKNOWN_ID; int user = C_UNKNOWN_ID; int type = C_UNKNOWN_ID; try { statement = m_pool.getPreparedStatement(m_cq.C_TASKLOG_READ_PPROJECTLOGS_KEY); statement.setInt(1, projectid); res = statement.executeQuery(); while(res.next()) { comment = res.getString(m_cq.C_LOG_COMMENT); externalusername = res.getString(m_cq.C_LOG_EXUSERNAME); id = res.getInt(m_cq.C_LOG_ID); starttime = SqlHelper.getTimestamp(res,m_cq.C_LOG_STARTTIME); task = res.getInt(m_cq.C_LOG_TASK); user = res.getInt(m_cq.C_LOG_USER); type = res.getInt(m_cq.C_LOG_TYPE); tasklog = new CmsTaskLog(id, comment, task, user, starttime, type); logs.addElement(tasklog); } res.close(); } catch( SQLException exc ) { throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc); } catch( Exception exc ) { throw new CmsException(exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc); } finally { if(statement != null) { m_pool.putPreparedStatement(m_cq.C_TASKLOG_READ_PPROJECTLOGS_KEY, statement); } } return logs; } /** * Reads a propertydefinition for the given resource type. * * @param name The name of the propertydefinition to read. * @param type The resource type for which the propertydefinition is valid. * * @return propertydefinition The propertydefinition that corresponds to the overgiven * arguments - or null if there is no valid propertydefinition. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsPropertydefinition readPropertydefinition(String name, int type) throws CmsException { CmsPropertydefinition propDef=null; ResultSet res; PreparedStatement statement = null; try { // create statement statement = m_pool.getPreparedStatement(m_cq.C_PROPERTYDEF_READ_KEY); statement.setString(1,name); statement.setInt(2,type); res = statement.executeQuery(); // if resultset exists - return it if(res.next()) { propDef = new CmsPropertydefinition( res.getInt(m_cq.C_PROPERTYDEF_ID), res.getString(m_cq.C_PROPERTYDEF_NAME), res.getInt(m_cq.C_PROPERTYDEF_RESOURCE_TYPE), res.getInt(m_cq.C_PROPERTYDEF_TYPE) ); res.close(); } else { res.close(); // not found! throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_NOT_FOUND); } } catch( SQLException exc ) { throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(), CmsException.C_SQL_ERROR, exc); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_PROPERTYDEF_READ_KEY, statement); } } return propDef; } // methods working with propertydef /** * Reads a propertydefinition for the given resource type. * * @param name The name of the propertydefinition to read. * @param type The resource type for which the propertydefinition is valid. * * @return propertydefinition The propertydefinition that corresponds to the overgiven * arguments - or null if there is no valid propertydefinition. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsPropertydefinition readPropertydefinition(String name, CmsResourceType type) throws CmsException { return( readPropertydefinition(name, type.getResourceType() ) ); } /** * Returns a property of a file or folder. * * @param meta The property-name of which the property has to be read. * @param resourceId The id of the resource. * @param resourceType The Type of the resource. * * @return property The property as string or null if the property not exists. * * @exception CmsException Throws CmsException if operation was not succesful */ public String readProperty(String meta, int resourceId, int resourceType) throws CmsException { ResultSet result; PreparedStatement statement = null; String returnValue = null; try { // create statement statement = m_pool.getPreparedStatement(m_cq.C_PROPERTIES_READ_KEY); statement.setInt(1, resourceId); statement.setString(2, meta); statement.setInt(3, resourceType); result = statement.executeQuery(); // if resultset exists - return it if(result.next()) { returnValue = result.getString(m_cq.C_PROPERTY_VALUE); } } catch( SQLException exc ) { throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(), CmsException.C_SQL_ERROR, exc); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_PROPERTIES_READ_KEY, statement); } } return returnValue; } /** * Reads a resource from the Cms.<BR/> * A resource is either a file header or a folder. * * @param project The project in which the resource will be used. * @param filename The complete name of the new file (including pathinformation). * * @return The resource read. * * @exception CmsException Throws CmsException if operation was not succesful */ protected CmsResource readResource(CmsProject project, String filename) throws CmsException { CmsResource file = null; ResultSet res = null; PreparedStatement statement = null; try { // read resource data from database statement = m_pool.getPreparedStatement(m_cq.C_RESOURCES_READ_KEY); statement.setString(1,filename); statement.setInt(2,project.getId()); res = statement.executeQuery(); // create new resource if(res.next()) { int resId=res.getInt(m_cq.C_RESOURCES_RESOURCE_ID); int parentId=res.getInt(m_cq.C_RESOURCES_PARENT_ID); String resName=res.getString(m_cq.C_RESOURCES_RESOURCE_NAME); int resType= res.getInt(m_cq.C_RESOURCES_RESOURCE_TYPE); int resFlags=res.getInt(m_cq.C_RESOURCES_RESOURCE_FLAGS); int userId=res.getInt(m_cq.C_RESOURCES_USER_ID); int groupId= res.getInt(m_cq.C_RESOURCES_GROUP_ID); int projectId=res.getInt(m_cq.C_RESOURCES_PROJECT_ID); int fileId=res.getInt(m_cq.C_RESOURCES_FILE_ID); int accessFlags=res.getInt(m_cq.C_RESOURCES_ACCESS_FLAGS); int state= res.getInt(m_cq.C_RESOURCES_STATE); int lockedBy= res.getInt(m_cq.C_RESOURCES_LOCKED_BY); int launcherType= res.getInt(m_cq.C_RESOURCES_LAUNCHER_TYPE); String launcherClass= res.getString(m_cq.C_RESOURCES_LAUNCHER_CLASSNAME); long created=SqlHelper.getTimestamp(res,m_cq.C_RESOURCES_DATE_CREATED).getTime(); long modified=SqlHelper.getTimestamp(res,m_cq.C_RESOURCES_DATE_LASTMODIFIED).getTime(); int modifiedBy=res.getInt(m_cq.C_RESOURCES_LASTMODIFIED_BY); int resSize= res.getInt(m_cq.C_RESOURCES_SIZE); file=new CmsResource(resId,parentId,fileId,resName,resType,resFlags, userId,groupId,projectId,accessFlags,state,lockedBy, launcherType,launcherClass,created,modified,modifiedBy, resSize); res.close(); } else { res.close(); throw new CmsException("["+this.getClass().getName()+"] "+filename,CmsException.C_NOT_FOUND); } } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e); } catch( Exception exc ) { throw new CmsException("readResource "+exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_READ_KEY, statement); } } return file; } /** * Reads all resource from the Cms, that are in one project.<BR/> * A resource is either a file header or a folder. * * @param project The project in which the resource will be used. * * @return A Vecor of resources. * * @exception CmsException Throws CmsException if operation was not succesful */ public Vector readResources(CmsProject project) throws CmsException { Vector resources = new Vector(); CmsResource file; ResultSet res = null; PreparedStatement statement = null; try { // read resource data from database statement = m_pool.getPreparedStatement(m_cq.C_RESOURCES_READBYPROJECT_KEY); statement.setInt(1,project.getId()); res = statement.executeQuery(); // create new resource while(res.next()) { int resId=res.getInt(m_cq.C_RESOURCES_RESOURCE_ID); int parentId=res.getInt(m_cq.C_RESOURCES_PARENT_ID); String resName=res.getString(m_cq.C_RESOURCES_RESOURCE_NAME); int resType= res.getInt(m_cq.C_RESOURCES_RESOURCE_TYPE); int resFlags=res.getInt(m_cq.C_RESOURCES_RESOURCE_FLAGS); int userId=res.getInt(m_cq.C_RESOURCES_USER_ID); int groupId= res.getInt(m_cq.C_RESOURCES_GROUP_ID); int projectId=res.getInt(m_cq.C_RESOURCES_PROJECT_ID); int fileId=res.getInt(m_cq.C_RESOURCES_FILE_ID); int accessFlags=res.getInt(m_cq.C_RESOURCES_ACCESS_FLAGS); int state= res.getInt(m_cq.C_RESOURCES_STATE); int lockedBy= res.getInt(m_cq.C_RESOURCES_LOCKED_BY); int launcherType= res.getInt(m_cq.C_RESOURCES_LAUNCHER_TYPE); String launcherClass= res.getString(m_cq.C_RESOURCES_LAUNCHER_CLASSNAME); long created=SqlHelper.getTimestamp(res,m_cq.C_RESOURCES_DATE_CREATED).getTime(); long modified=SqlHelper.getTimestamp(res,m_cq.C_RESOURCES_DATE_LASTMODIFIED).getTime(); int modifiedBy=res.getInt(m_cq.C_RESOURCES_LASTMODIFIED_BY); int resSize= res.getInt(m_cq.C_RESOURCES_SIZE); file=new CmsResource(resId,parentId,fileId,resName,resType,resFlags, userId,groupId,projectId,accessFlags,state,lockedBy, launcherType,launcherClass,created,modified,modifiedBy, resSize); resources.addElement(file); } res.close(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e); } catch (Exception ex) { throw new CmsException("["+this.getClass().getName()+"]", ex); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_READBYPROJECT_KEY, statement); } } return resources; } /** * Reads a session from the database. * * @param sessionId, the id og the session to read. * @return the read session as Hashtable. * @exception thorws CmsException if something goes wrong. */ public Hashtable readSession(String sessionId) throws CmsException { PreparedStatement statement = null; ResultSet res = null; Hashtable session = null; try { statement = m_pool.getPreparedStatement(m_cq.C_SESSION_READ_KEY); statement.setString(1,sessionId); statement.setTimestamp(2,new java.sql.Timestamp(System.currentTimeMillis() - C_SESSION_TIMEOUT )); res = statement.executeQuery(); // create new Cms user object if(res.next()) { // read the additional infos. byte[] value = res.getBytes(1); // now deserialize the object ByteArrayInputStream bin= new ByteArrayInputStream(value); ObjectInputStream oin = new ObjectInputStream(bin); session =(Hashtable)oin.readObject(); } else { deleteSessions(); } res.close(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e); } catch (Exception e) { throw new CmsException("["+this.getClass().getName()+"]", e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_SESSION_READ_KEY, statement); } } return session; } /** * Reads a serializable object from the systempropertys. * * @param name The name of the property. * * @return object The property-object. * * @exception CmsException Throws CmsException if something goes wrong. */ public Serializable readSystemProperty(String name) throws CmsException { Serializable property=null; byte[] value; ResultSet res = null; PreparedStatement statement = null; // create get the property data from the database try { statement=m_pool.getPreparedStatement(m_cq.C_SYSTEMPROPERTIES_READ_KEY); statement.setString(1,name); res = statement.executeQuery(); if(res.next()) { value = res.getBytes(m_cq.C_SYSTEMPROPERTY_VALUE); // now deserialize the object ByteArrayInputStream bin= new ByteArrayInputStream(value); ObjectInputStream oin = new ObjectInputStream(bin); property=(Serializable)oin.readObject(); } res.close(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e); } catch (IOException e){ throw new CmsException("["+this.getClass().getName()+"]"+CmsException. C_SERIALIZATION, e); } catch (ClassNotFoundException e){ throw new CmsException("["+this.getClass().getName()+"]"+CmsException. C_SERIALIZATION, e); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_SYSTEMPROPERTIES_READ_KEY, statement); } } return property; } /** * Reads a task from the Cms. * * @param id The id of the task to read. * * @return a task object or null if the task is not found. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsTask readTask(int id) throws CmsException { ResultSet res; CmsTask task = null; Statement statement = null; try { // At this place I use a statement instead of a prepared statement because for some odd reason // the prepared statement doesn't always work correctly. At the time the beans are spilled we should // switch back to the prepared statement. Mario Stanke statement = m_pool.getStatement(); res = statement.executeQuery(m_cq.C_TASK_READ_STATEMENT+id); if (res.next()) { int autofinish = res.getInt(m_cq.C_TASK_AUTOFINISH); java.sql.Timestamp endtime = SqlHelper.getTimestamp(res, m_cq.C_TASK_ENDTIME); int escalationtype = res.getInt(m_cq.C_TASK_ESCALATIONTYPE); id = res.getInt(m_cq.C_TASK_ID); int initiatoruser = res.getInt(m_cq.C_TASK_INITIATORUSER); int milestone = res.getInt(m_cq.C_TASK_MILESTONE); String name = res.getString(m_cq.C_TASK_NAME); int originaluser = res.getInt(m_cq.C_TASK_ORIGINALUSER); int agentuser = res.getInt(m_cq.C_TASK_AGENTUSER); int parent = res.getInt(m_cq.C_TASK_PARENT); int percentage = res.getInt(m_cq.C_TASK_PERCENTAGE); String permission = res.getString(m_cq.C_TASK_PERMISSION); int priority = res.getInt(m_cq.C_TASK_PRIORITY); int role = res.getInt(m_cq.C_TASK_ROLE); int root = res.getInt(m_cq.C_TASK_ROOT); java.sql.Timestamp starttime = SqlHelper.getTimestamp(res, m_cq.C_TASK_STARTTIME); int state = res.getInt(m_cq.C_TASK_STATE); int tasktype = res.getInt(m_cq.C_TASK_TASKTYPE); java.sql.Timestamp timeout = SqlHelper.getTimestamp(res, m_cq.C_TASK_TIMEOUT); java.sql.Timestamp wakeuptime = SqlHelper.getTimestamp(res, m_cq.C_TASK_WAKEUPTIME); String htmllink = res.getString(m_cq.C_TASK_HTMLLINK); res.close(); task = new CmsTask(id, name, state, tasktype, root, parent, initiatoruser, role, agentuser, originaluser, starttime, wakeuptime, timeout, endtime, percentage, permission, priority, escalationtype, htmllink, milestone, autofinish); } } catch (SQLException exc) { throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc); } catch (Exception exc) { throw new CmsException(exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc); } finally { if (statement != null) { ( (com.opencms.file.genericSql.CmsDbPool)m_pool ).putStatement(statement); } } return task; } /** * Reads a log for a task. * * @param id The id for the tasklog . * @return A new TaskLog object * @exception CmsException Throws CmsException if something goes wrong. */ public CmsTaskLog readTaskLog(int id) throws CmsException { ResultSet res; CmsTaskLog tasklog = null; PreparedStatement statement = null; try { statement = m_pool.getPreparedStatement(m_cq.C_TASKLOG_READ_KEY); statement.setInt(1, id); res = statement.executeQuery(); if(res.next()) { String comment = res.getString(m_cq.C_LOG_COMMENT); String externalusername; id = res.getInt(m_cq.C_LOG_ID); java.sql.Timestamp starttime = SqlHelper.getTimestamp(res,m_cq.C_LOG_STARTTIME); int task = res.getInt(m_cq.C_LOG_TASK); int user = res.getInt(m_cq.C_LOG_USER); int type = res.getInt(m_cq.C_LOG_TYPE); tasklog = new CmsTaskLog(id, comment, task, user, starttime, type); } res.close(); } catch( SQLException exc ) { throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc); } catch( Exception exc ) { throw new CmsException(exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc); } finally { if(statement != null) { m_pool.putPreparedStatement(m_cq.C_TASKLOG_READ_KEY, statement); } } return tasklog; } /** * Reads log entries for a task. * * @param taskid The id of the task for the tasklog to read . * @return A Vector of new TaskLog objects * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readTaskLogs(int taskId) throws CmsException { ResultSet res; CmsTaskLog tasklog = null; Vector logs = new Vector(); PreparedStatement statement = null; String comment = null; String externalusername = null; java.sql.Timestamp starttime = null; int id = C_UNKNOWN_ID; int task = C_UNKNOWN_ID; int user = C_UNKNOWN_ID; int type = C_UNKNOWN_ID; try { statement = m_pool.getPreparedStatement(m_cq.C_TASKLOG_READ_LOGS_KEY); statement.setInt(1, taskId); res = statement.executeQuery(); while(res.next()) { comment = res.getString(m_cq.C_LOG_COMMENT); externalusername = res.getString(m_cq.C_LOG_EXUSERNAME); id = res.getInt(m_cq.C_LOG_ID); starttime = SqlHelper.getTimestamp(res,m_cq.C_LOG_STARTTIME); task = res.getInt(m_cq.C_LOG_TASK); user = res.getInt(m_cq.C_LOG_USER); type = res.getInt(m_cq.C_LOG_TYPE); tasklog = new CmsTaskLog(id, comment, task, user, starttime, type); logs.addElement(tasklog); } res.close(); } catch( SQLException exc ) { throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc); } catch( Exception exc ) { throw new CmsException(exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc); } finally { if(statement != null) { m_pool.putPreparedStatement(m_cq.C_TASKLOG_READ_LOGS_KEY, statement); } } return logs; } /** * Reads all tasks of a user in a project. * @param project The Project in which the tasks are defined. * @param agent The task agent * @param owner The task owner . * @param group The group who has to process the task. * @tasktype C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW * @param orderBy Chooses, how to order the tasks. * @param sort Sort Ascending or Descending (ASC or DESC) * * @return A vector with the tasks * * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readTasks(CmsProject project, CmsUser agent, CmsUser owner, CmsGroup role, int tasktype, String orderBy, String sort) throws CmsException { boolean first = true; Vector tasks = new Vector(); // vector for the return result CmsTask task = null; // tmp task for adding to vector ResultSet recset = null; // create the sql string depending on parameters // handle the project for the SQL String String sqlstr = "SELECT * FROM " + m_cq.C_TABLENAME_TASK+" WHERE "; if(project!=null){ sqlstr = sqlstr + m_cq.C_TASK_ROOT + "=" + project.getTaskId(); first = false; } else { sqlstr = sqlstr + m_cq.C_TASK_ROOT + "<>0 AND " + m_cq.C_TASK_PARENT + "<>0"; first = false; } // handle the agent for the SQL String if(agent!=null){ if(!first){ sqlstr = sqlstr + " AND "; } sqlstr = sqlstr + m_cq.C_TASK_AGENTUSER + "=" + agent.getId(); first = false; } // handle the owner for the SQL String if(owner!=null){ if(!first){ sqlstr = sqlstr + " AND "; } sqlstr = sqlstr + m_cq.C_TASK_INITIATORUSER + "=" + owner.getId(); first = false; } // handle the role for the SQL String if(role!=null){ if(!first){ sqlstr = sqlstr+" AND "; } sqlstr = sqlstr + m_cq.C_TASK_ROLE + "=" + role.getId(); first = false; } sqlstr = sqlstr + getTaskTypeConditon(first, tasktype); // handel the order and sort parameter for the SQL String if(orderBy!=null) { if(!orderBy.equals("")) { sqlstr = sqlstr + " ORDER BY " + orderBy; if(orderBy!=null) { if(!orderBy.equals("")) { sqlstr = sqlstr + " " + sort; } } } } Statement statement = null; try { statement = m_pool.getStatement(); recset = statement.executeQuery(sqlstr); // if resultset exists - return vector of tasks while(recset.next()) { task = new CmsTask(recset.getInt(m_cq.C_TASK_ID), recset.getString(m_cq.C_TASK_NAME), recset.getInt(m_cq.C_TASK_STATE), recset.getInt(m_cq.C_TASK_TASKTYPE), recset.getInt(m_cq.C_TASK_ROOT), recset.getInt(m_cq.C_TASK_PARENT), recset.getInt(m_cq.C_TASK_INITIATORUSER), recset.getInt(m_cq.C_TASK_ROLE), recset.getInt(m_cq.C_TASK_AGENTUSER), recset.getInt(m_cq.C_TASK_ORIGINALUSER), SqlHelper.getTimestamp(recset,m_cq.C_TASK_STARTTIME), SqlHelper.getTimestamp(recset,m_cq.C_TASK_WAKEUPTIME), SqlHelper.getTimestamp(recset,m_cq.C_TASK_TIMEOUT), SqlHelper.getTimestamp(recset,m_cq.C_TASK_ENDTIME), recset.getInt(m_cq.C_TASK_PERCENTAGE), recset.getString(m_cq.C_TASK_PERMISSION), recset.getInt(m_cq.C_TASK_PRIORITY), recset.getInt(m_cq.C_TASK_ESCALATIONTYPE), recset.getString(m_cq.C_TASK_HTMLLINK), recset.getInt(m_cq.C_TASK_MILESTONE), recset.getInt(m_cq.C_TASK_AUTOFINISH)); tasks.addElement(task); } } catch( SQLException exc ) { throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc); } catch( Exception exc ) { throw new CmsException(exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc); } finally { if( statement != null) { ( (com.opencms.file.genericSql.CmsDbPool)m_pool ).putStatement(statement); } } return tasks; } /** * Reads a user from the cms, only if the password is correct. * * @param id the id of the user. * @param type the type of the user. * @return the read user. * @exception thorws CmsException if something goes wrong. */ public CmsUser readUser(int id) throws CmsException { PreparedStatement statement = null; ResultSet res = null; CmsUser user = null; try { statement = m_pool.getPreparedStatement(m_cq.C_USERS_READID_KEY); statement.setInt(1,id); res = statement.executeQuery(); // create new Cms user object if(res.next()) { // read the additional infos. byte[] value = res.getBytes(m_cq.C_USERS_USER_INFO); // now deserialize the object ByteArrayInputStream bin= new ByteArrayInputStream(value); ObjectInputStream oin = new ObjectInputStream(bin); Hashtable info=(Hashtable)oin.readObject(); user = new CmsUser(res.getInt(m_cq.C_USERS_USER_ID), res.getString(m_cq.C_USERS_USER_NAME), res.getString(m_cq.C_USERS_USER_PASSWORD), res.getString(m_cq.C_USERS_USER_RECOVERY_PASSWORD), res.getString(m_cq.C_USERS_USER_DESCRIPTION), res.getString(m_cq.C_USERS_USER_FIRSTNAME), res.getString(m_cq.C_USERS_USER_LASTNAME), res.getString(m_cq.C_USERS_USER_EMAIL), SqlHelper.getTimestamp(res,m_cq.C_USERS_USER_LASTLOGIN).getTime(), SqlHelper.getTimestamp(res,m_cq.C_USERS_USER_LASTUSED).getTime(), res.getInt(m_cq.C_USERS_USER_FLAGS), info, new CmsGroup(res.getInt(m_cq.C_GROUPS_GROUP_ID), res.getInt(m_cq.C_GROUPS_PARENT_GROUP_ID), res.getString(m_cq.C_GROUPS_GROUP_NAME), res.getString(m_cq.C_GROUPS_GROUP_DESCRIPTION), res.getInt(m_cq.C_GROUPS_GROUP_FLAGS)), res.getString(m_cq.C_USERS_USER_ADDRESS), res.getString(m_cq.C_USERS_USER_SECTION), res.getInt(m_cq.C_USERS_USER_TYPE)); } else { res.close(); throw new CmsException("["+this.getClass().getName()+"]"+id,CmsException.C_NO_USER); } res.close(); return user; } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e); } // a.lucas: catch CmsException here and throw it again. // Don't wrap another CmsException around it, since this may cause problems during login. catch (CmsException e) { throw e; } catch (Exception e) { throw new CmsException("["+this.getClass().getName()+"]", e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_USERS_READID_KEY, statement); } } } /** * Reads a user from the cms. * * @param name the name of the user. * @param type the type of the user. * @return the read user. * @exception thorws CmsException if something goes wrong. */ public CmsUser readUser(String name, int type) throws CmsException { PreparedStatement statement = null; ResultSet res = null; CmsUser user = null; try { statement = m_pool.getPreparedStatement(m_cq.C_USERS_READ_KEY); statement.setString(1,name); statement.setInt(2,type); res = statement.executeQuery(); // create new Cms user object if(res.next()) { // read the additional infos. byte[] value = res.getBytes(m_cq.C_USERS_USER_INFO); // now deserialize the object ByteArrayInputStream bin= new ByteArrayInputStream(value); ObjectInputStream oin = new ObjectInputStream(bin); Hashtable info=(Hashtable)oin.readObject(); user = new CmsUser(res.getInt(m_cq.C_USERS_USER_ID), res.getString(m_cq.C_USERS_USER_NAME), res.getString(m_cq.C_USERS_USER_PASSWORD), res.getString(m_cq.C_USERS_USER_RECOVERY_PASSWORD), res.getString(m_cq.C_USERS_USER_DESCRIPTION), res.getString(m_cq.C_USERS_USER_FIRSTNAME), res.getString(m_cq.C_USERS_USER_LASTNAME), res.getString(m_cq.C_USERS_USER_EMAIL), SqlHelper.getTimestamp(res,m_cq.C_USERS_USER_LASTLOGIN).getTime(), SqlHelper.getTimestamp(res,m_cq.C_USERS_USER_LASTUSED).getTime(), res.getInt(m_cq.C_USERS_USER_FLAGS), info, new CmsGroup(res.getInt(m_cq.C_GROUPS_GROUP_ID), res.getInt(m_cq.C_GROUPS_PARENT_GROUP_ID), res.getString(m_cq.C_GROUPS_GROUP_NAME), res.getString(m_cq.C_GROUPS_GROUP_DESCRIPTION), res.getInt(m_cq.C_GROUPS_GROUP_FLAGS)), res.getString(m_cq.C_USERS_USER_ADDRESS), res.getString(m_cq.C_USERS_USER_SECTION), res.getInt(m_cq.C_USERS_USER_TYPE)); } else { res.close(); throw new CmsException("["+this.getClass().getName()+"]"+name,CmsException.C_NO_USER); } res.close(); return user; } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e); } // a.lucas: catch CmsException here and throw it again. // Don't wrap another CmsException around it, since this may cause problems during login. catch (CmsException e) { throw e; } catch (Exception e) { throw new CmsException("["+this.getClass().getName()+"]", e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_USERS_READ_KEY, statement); } } } /** * Reads a user from the cms, only if the password is correct. * * @param name the name of the user. * @param password the password of the user. * @param type the type of the user. * @return the read user. * @exception thorws CmsException if something goes wrong. */ public CmsUser readUser(String name, String password, int type) throws CmsException { PreparedStatement statement = null; ResultSet res = null; CmsUser user = null; try { statement = m_pool.getPreparedStatement(m_cq.C_USERS_READPW_KEY); statement.setString(1,name); statement.setString(2,digest(password)); statement.setInt(3,type); res = statement.executeQuery(); // create new Cms user object if(res.next()) { // read the additional infos. byte[] value = res.getBytes(m_cq.C_USERS_USER_INFO); // now deserialize the object ByteArrayInputStream bin= new ByteArrayInputStream(value); ObjectInputStream oin = new ObjectInputStream(bin); Hashtable info=(Hashtable)oin.readObject(); user = new CmsUser(res.getInt(m_cq.C_USERS_USER_ID), res.getString(m_cq.C_USERS_USER_NAME), res.getString(m_cq.C_USERS_USER_PASSWORD), res.getString(m_cq.C_USERS_USER_RECOVERY_PASSWORD), res.getString(m_cq.C_USERS_USER_DESCRIPTION), res.getString(m_cq.C_USERS_USER_FIRSTNAME), res.getString(m_cq.C_USERS_USER_LASTNAME), res.getString(m_cq.C_USERS_USER_EMAIL), SqlHelper.getTimestamp(res,m_cq.C_USERS_USER_LASTLOGIN).getTime(), SqlHelper.getTimestamp(res,m_cq.C_USERS_USER_LASTUSED).getTime(), res.getInt(m_cq.C_USERS_USER_FLAGS), info, new CmsGroup(res.getInt(m_cq.C_GROUPS_GROUP_ID), res.getInt(m_cq.C_GROUPS_PARENT_GROUP_ID), res.getString(m_cq.C_GROUPS_GROUP_NAME), res.getString(m_cq.C_GROUPS_GROUP_DESCRIPTION), res.getInt(m_cq.C_GROUPS_GROUP_FLAGS)), res.getString(m_cq.C_USERS_USER_ADDRESS), res.getString(m_cq.C_USERS_USER_SECTION), res.getInt(m_cq.C_USERS_USER_TYPE)); } else { res.close(); throw new CmsException("["+this.getClass().getName()+"]"+name,CmsException.C_NO_USER); } res.close(); return user; } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e); } // a.lucas: catch CmsException here and throw it again. // Don't wrap another CmsException around it, since this may cause problems during login. catch (CmsException e) { throw e; } catch (Exception e) { throw new CmsException("["+this.getClass().getName()+"]", e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_USERS_READPW_KEY, statement); } } } /** * Sets the password, only if the user knows the recovery-password. * * @param user the user to set the password for. * @param recoveryPassword the recoveryPassword the user has to know to set the password. * @param password the password to set * @exception thorws CmsException if something goes wrong. */ public void recoverPassword(String user, String recoveryPassword, String password ) throws CmsException { PreparedStatement statement = null; int result; try { statement = m_pool.getPreparedStatement(m_cq.C_USERS_RECOVERPW_KEY); statement.setString(1,digest(password)); statement.setString(2,user); statement.setString(3,digest(recoveryPassword)); result = statement.executeUpdate(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_USERS_RECOVERPW_KEY, statement); } } if(result != 1) { // the update wasn't succesfull -> throw exception throw new CmsException("["+this.getClass().getName()+"] the password couldn't be recovered."); } } /** * Deletes a file in the database. * This method is used to physically remove a file form the database. * * @param project The project in which the resource will be used. * @param filename The complete path of the file. * @exception CmsException Throws CmsException if operation was not succesful */ public void removeFile(int projectId, String filename) throws CmsException{ PreparedStatement statement = null; try { // delete the file header statement = m_pool.getPreparedStatement(m_cq.C_RESOURCES_DELETE_KEY); statement.setString(1, filename); statement.setInt(2,projectId); statement.executeUpdate(); // delete the file content // clearFilesTable(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_DELETE_KEY, statement); } } } /** * Deletes a folder in the database. * This method is used to physically remove a folder form the database. * It is internally used by the publish project method. * * @param project The project in which the resource will be used. * @param foldername The complete path of the folder. * @exception CmsException Throws CmsException if operation was not succesful */ protected void removeFolderForPublish(CmsProject project, String foldername) throws CmsException{ PreparedStatement statement = null; try { // delete the folder statement = m_pool.getPreparedStatement(m_cq.C_RESOURCES_DELETE_KEY); statement.setString(1, foldername); statement.setInt(2,project.getId()); statement.executeUpdate(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_DELETE_KEY, statement); } } } /** * Deletes a folder in the database. * This method is used to physically remove a folder form the database. * * @param folder The folder. * @exception CmsException Throws CmsException if operation was not succesful */ public void removeFolder(CmsFolder folder) throws CmsException{ // the current implementation only deletes empty folders // check if the folder has any files in it Vector files= getFilesInFolder(folder); files=getUndeletedResources(files); if (files.size()==0) { // check if the folder has any folders in it Vector folders= getSubFolders(folder); folders=getUndeletedResources(folders); if (folders.size()==0) { //this folder is empty, delete it PreparedStatement statement = null; try { // delete the folder statement = m_pool.getPreparedStatement(m_cq.C_RESOURCES_ID_DELETE_KEY); statement.setInt(1,folder.getResourceId()); statement.executeUpdate(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_ID_DELETE_KEY, statement); } } } else { throw new CmsException("["+this.getClass().getName()+"] "+folder.getAbsolutePath(),CmsException.C_NOT_EMPTY); } } else { throw new CmsException("["+this.getClass().getName()+"] "+folder.getAbsolutePath(),CmsException.C_NOT_EMPTY); } } /** * Removes a user from a group. * * Only the admin can do this.<P/> * * @param userid The id of the user that is to be added to the group. * @param groupid The id of the group. * @exception CmsException Throws CmsException if operation was not succesful. */ public void removeUserFromGroup(int userid, int groupid) throws CmsException { PreparedStatement statement = null; try { // create statement statement = m_pool.getPreparedStatement(m_cq.C_GROUPS_REMOVEUSERFROMGROUP_KEY); statement.setInt(1,groupid); statement.setInt(2,userid); statement.executeUpdate(); } catch (SQLException e){ throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_GROUPS_REMOVEUSERFROMGROUP_KEY, statement); } } } /** * Renames the file to the new name. * * @param project The project in which the resource will be used. * @param onlineProject The online project of the OpenCms. * @param userId The user id * @param oldfileID The id of the resource which will be renamed. * @param newname The new name of the resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void renameFile(CmsProject project, CmsProject onlineProject, int userId, int oldfileID, String newname) throws CmsException { PreparedStatement statement = null; try{ statement = m_pool.getPreparedStatement(m_cq.C_RESOURCES_RENAMERESOURCE_KEY); statement.setString(1,newname); statement.setInt(2,userId); statement.setInt(3,oldfileID); statement.executeUpdate(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_RENAMERESOURCE_KEY, statement); } } } /** * Sets a new password for a user. * * @param user the user to set the password for. * @param password the password to set * @exception thorws CmsException if something goes wrong. */ public void setPassword(String user, String password) throws CmsException { PreparedStatement statement = null; try { statement = m_pool.getPreparedStatement(m_cq.C_USERS_SETPW_KEY); statement.setString(1,digest(password)); statement.setString(2,user); statement.executeUpdate(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_USERS_SETPW_KEY, statement); } } } /** * Sets a new password for a user. * * @param user the user to set the password for. * @param password the recoveryPassword to set * @exception thorws CmsException if something goes wrong. */ public void setRecoveryPassword(String user, String password) throws CmsException { PreparedStatement statement = null; int result; try { statement = m_pool.getPreparedStatement(m_cq.C_USERS_SETRECPW_KEY); statement.setString(1,digest(password)); statement.setString(2,user); result = statement.executeUpdate(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_USERS_SETRECPW_KEY, statement); } } if(result != 1) { // the update wasn't succesfull -> throw exception throw new CmsException("["+this.getClass().getName()+"] new password couldn't be set."); } } /** * Set a Parameter for a task. * * @param task The task. * @param parname Name of the parameter. * @param parvalue Value if the parameter. * * @return The id of the inserted parameter or 0 if the parameter exists for this task. * * @exception CmsException Throws CmsException if something goes wrong. */ public int setTaskPar(int taskId, String parname, String parvalue) throws CmsException { ResultSet res; int result = 0; PreparedStatement statement = null; try { // test if the parameter already exists for this task statement = m_pool.getPreparedStatement(m_cq.C_TASKPAR_TEST_KEY); statement.setInt(1, taskId); statement.setString(2, parname); res = statement.executeQuery(); if(res.next()) { //Parameter exisits, so make an update updateTaskPar(res.getInt(m_cq.C_PAR_ID), parname, parvalue); } else { //Parameter is not exisiting, so make an insert result = insertTaskPar(taskId, parname, parvalue); } res.close(); } catch( SQLException exc ) { throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc); } finally { if(statement != null) { m_pool.putPreparedStatement(m_cq.C_TASKPAR_TEST_KEY, statement); } } return result; } /** * Sorts a vector of files or folders alphabetically. * This method uses an insertion sort algorithm. * NOT IN USE AT THIS TIME * * @param unsortedList Array of strings containing the list of files or folders. * @return Array of sorted strings. */ protected Vector SortEntrys(Vector list) { int in, out; int nElem = list.size(); long startTime = System.currentTimeMillis(); CmsResource[] unsortedList = new CmsResource[list.size()]; for (int i = 0; i < list.size(); i++) { unsortedList[i] = (CmsResource) list.elementAt(i); } for (out = 1; out < nElem; out++) { CmsResource temp = unsortedList[out]; in = out; while (in > 0 && unsortedList[in - 1].getAbsolutePath().compareTo(temp.getAbsolutePath()) >= 0) { unsortedList[in] = unsortedList[in - 1]; --in; } unsortedList[in] = temp; } Vector sortedList = new Vector(); for (int i = 0; i < list.size(); i++) { sortedList.addElement(unsortedList[i]); } System.err.println("Zeit f?r SortEntrys von " + nElem + " Eintr?gen:" + (System.currentTimeMillis() - startTime)); return sortedList; } /** * Undeletes the file. * * @param project The project in which the resource will be used. * @param filename The complete path of the file. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void undeleteFile(CmsProject project, String filename) throws CmsException { PreparedStatement statement = null; try { statement = m_pool.getPreparedStatement(m_cq.C_RESOURCES_REMOVE_KEY); // mark the file as deleted statement.setInt(1,C_STATE_CHANGED); statement.setInt(2,C_UNKNOWN_ID); statement.setString(3, filename); statement.setInt(4,project.getId()); statement.executeUpdate(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_REMOVE_KEY, statement); } } } /** * Unlocks all resources in this project. * * @param project The project to be unlocked. * * @exception CmsException Throws CmsException if something goes wrong. */ public void unlockProject(CmsProject project) throws CmsException { PreparedStatement statement = null; try { // create the statement statement = m_pool.getPreparedStatement(m_cq.C_RESOURCES_UNLOCK_KEY); statement.setInt(1,project.getId()); statement.executeUpdate(); } catch( Exception exc ) { throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(), CmsException.C_SQL_ERROR, exc); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_UNLOCK_KEY, statement); } } } public void updateLockstate(CmsResource res) throws CmsException { PreparedStatement statement = null; try { statement = m_pool.getPreparedStatement(m_cq.C_RESOURCES_UPDATE_LOCK_KEY); statement.setInt(1, res.isLockedBy()); statement.setInt(2, res.getResourceId()); statement.executeUpdate(); } catch( SQLException exc ) { throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc); } finally { if(statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_UPDATE_LOCK_KEY, statement); } } } /** * This method updates a session in the database. It is used * for sessionfailover. * * @param sessionId the id of the session. * @return data the sessionData. */ public int updateSession(String sessionId, Hashtable data) throws CmsException { byte[] value=null; PreparedStatement statement = null; int retValue; try { // serialize the hashtable ByteArrayOutputStream bout= new ByteArrayOutputStream(); ObjectOutputStream oout=new ObjectOutputStream(bout); oout.writeObject(data); oout.close(); value=bout.toByteArray(); // write data to database statement = m_pool.getPreparedStatement(m_cq.C_SESSION_UPDATE_KEY); statement.setTimestamp(1,new java.sql.Timestamp(System.currentTimeMillis())); statement.setBytes(2,value); statement.setString(3,sessionId); retValue = statement.executeUpdate(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e); } catch (IOException e){ throw new CmsException("["+this.getClass().getName()+"]:"+CmsException.C_SERIALIZATION, e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_SESSION_UPDATE_KEY, statement); } } return retValue; } public void updateSite(int siteId, String name, String description, int categoryId, int languageId, int countryId, String url) throws com.opencms.core.CmsException { PreparedStatement site = null; PreparedStatement siteUrl = null; try { site = m_pool.getPreparedStatement(m_cq.C_SITE_UPDATESITE_KEY); site.setString(1, name); site.setString(2, description); site.setInt(3, categoryId); site.setInt(4, languageId); site.setInt(5, countryId); site.setInt(6, siteId); siteUrl = m_pool.getPreparedStatement(m_cq.C_SITEURLS_UPDATESITEURLS_KEY); siteUrl.setString(1, url); siteUrl.setInt(2, siteId); site.executeUpdate(); siteUrl.executeUpdate(); } catch (SQLException e) { throw new CmsException("[" + this.getClass().getName() + "]" + e.getMessage(), CmsException.C_SQL_ERROR, e); } finally { if (site != null) m_pool.putPreparedStatement(m_cq.C_SITE_UPDATESITE_KEY, site); if (siteUrl != null) m_pool.putPreparedStatement(m_cq.C_SITEURLS_UPDATESITEURLS_KEY, siteUrl); } } protected void updateTaskPar(int parid, String parname, String parvalue) throws CmsException { PreparedStatement statement = null; try { statement = m_pool.getPreparedStatement(m_cq.C_TASKPAR_UPDATE_KEY); statement.setString(1, parvalue); statement.setInt(2, parid); statement.executeUpdate(); } catch( SQLException exc ) { throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc); } finally { if(statement != null) { m_pool.putPreparedStatement(m_cq.C_TASKPAR_UPDATE_KEY, statement); } } } /** * Checks if a user is member of a group.<P/> * * @param nameid The id of the user to check. * @param groupid The id of the group to check. * @return True or False * * @exception CmsException Throws CmsException if operation was not succesful */ public boolean userInGroup(int userid, int groupid) throws CmsException { boolean userInGroup=false; PreparedStatement statement = null; ResultSet res = null; try { // create statement statement = m_pool.getPreparedStatement(m_cq.C_GROUPS_USERINGROUP_KEY); statement.setInt(1,groupid); statement.setInt(2,userid); res = statement.executeQuery(); if (res.next()){ userInGroup=true; } res.close(); } catch (SQLException e){ throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_GROUPS_USERINGROUP_KEY, statement); } } return userInGroup; } /** * Writes the fileheader to the Cms. * * @param project The project in which the resource will be used. * @param onlineProject The online project of the OpenCms. * @param file The new file. * @param changed Flag indicating if the file state must be set to changed. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void writeFileHeader(CmsProject project, CmsFile file,boolean changed) throws CmsException { ResultSet res; ResultSet tmpres; byte[] content; PreparedStatement statementFileRead = null; PreparedStatement statementResourceUpdate = null; try { // check if the file content for this file is already existing in the // offline project. If not, load it from the online project and add it // to the offline project. if ((file.getState() == C_STATE_UNCHANGED) && (changed == true) ) { // read file content form the online project statementFileRead = m_pool.getPreparedStatement(m_cq.C_FILE_READ_KEY); statementFileRead.setInt(1,file.getFileId()); res = statementFileRead.executeQuery(); if (res.next()) { content=res.getBytes(m_cq.C_FILE_CONTENT); } else { throw new CmsException("["+this.getClass().getName()+"]"+file.getAbsolutePath(),CmsException.C_NOT_FOUND); } res.close(); // add the file content to the offline project. PreparedStatement statementFileWrite = null; try { file.setFileId(nextId(C_TABLE_FILES)); statementFileWrite = m_pool.getPreparedStatement(m_cq.C_FILES_WRITE_KEY); statementFileWrite.setInt(1,file.getFileId()); statementFileWrite.setBytes(2,content); statementFileWrite.executeUpdate(); } catch (SQLException se) { if(A_OpenCms.isLogging()) { A_OpenCms.log(C_OPENCMS_CRITICAL, "[CmsAccessFileMySql] " + se.getMessage()); se.printStackTrace(); } }finally { if( statementFileWrite != null) { m_pool.putPreparedStatement(m_cq.C_FILES_WRITE_KEY, statementFileWrite); } } } // update resource in the database statementResourceUpdate = m_pool.getPreparedStatement(m_cq.C_RESOURCES_UPDATE_KEY); statementResourceUpdate.setInt(1,file.getType()); statementResourceUpdate.setInt(2,file.getFlags()); statementResourceUpdate.setInt(3,file.getOwnerId()); statementResourceUpdate.setInt(4,file.getGroupId()); statementResourceUpdate.setInt(5,file.getProjectId()); statementResourceUpdate.setInt(6,file.getAccessFlags()); //STATE int state=file.getState(); if ((state == C_STATE_NEW) || (state == C_STATE_CHANGED)) { statementResourceUpdate.setInt(7,state); } else { if (changed==true) { statementResourceUpdate.setInt(7,C_STATE_CHANGED); } else { statementResourceUpdate.setInt(7,file.getState()); } } statementResourceUpdate.setInt(8,file.isLockedBy()); statementResourceUpdate.setInt(9,file.getLauncherType()); statementResourceUpdate.setString(10,file.getLauncherClassname()); statementResourceUpdate.setTimestamp(11,new Timestamp(System.currentTimeMillis())); statementResourceUpdate.setInt(12,file.getResourceLastModifiedBy()); statementResourceUpdate.setInt(13,file.getLength()); statementResourceUpdate.setInt(14,file.getFileId()); statementResourceUpdate.setInt(15,file.getResourceId()); statementResourceUpdate.executeUpdate(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e); }finally { if( statementFileRead != null) { m_pool.putPreparedStatement(m_cq.C_FILE_READ_KEY, statementFileRead); } if( statementResourceUpdate != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_UPDATE_KEY, statementResourceUpdate); } } } /** * Writes a file to the Cms.<BR/> * * @param project The project in which the resource will be used. * @param onlineProject The online project of the OpenCms. * @param file The new file. * @param changed Flag indicating if the file state must be set to changed. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void writeFile(CmsProject project, CmsProject onlineProject, CmsFile file,boolean changed) throws CmsException { PreparedStatement statement = null; try { // update the file header in the RESOURCE database. writeFileHeader(project,file,changed); // update the file content in the FILES database. statement = m_pool.getPreparedStatement(m_cq.C_FILES_UPDATE_KEY); statement.setBytes(1,file.getContents()); statement.setInt(2,file.getFileId()); statement.executeUpdate(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_FILES_UPDATE_KEY, statement); } } } /** * Writes a folder to the Cms.<BR/> * * @param project The project in which the resource will be used. * @param folder The folder to be written. * @param changed Flag indicating if the file state must be set to changed. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void writeFolder(CmsProject project, CmsFolder folder, boolean changed) throws CmsException { PreparedStatement statement = null; try { // update resource in the database statement = m_pool.getPreparedStatement(m_cq.C_RESOURCES_UPDATE_KEY); statement.setInt(1,folder.getType()); statement.setInt(2,folder.getFlags()); statement.setInt(3,folder.getOwnerId()); statement.setInt(4,folder.getGroupId()); statement.setInt(5,folder.getProjectId()); statement.setInt(6,folder.getAccessFlags()); int state=folder.getState(); if ((state == C_STATE_NEW) || (state == C_STATE_CHANGED)) { statement.setInt(7,state); } else { if (changed==true) { statement.setInt(7,C_STATE_CHANGED); } else { statement.setInt(7,folder.getState()); } } statement.setInt(8,folder.isLockedBy()); statement.setInt(9,folder.getLauncherType()); statement.setString(10,folder.getLauncherClassname()); statement.setTimestamp(11,new Timestamp(System.currentTimeMillis())); statement.setInt(12,folder.getResourceLastModifiedBy()); statement.setInt(13,0); statement.setInt(14,C_UNKNOWN_ID); statement.setInt(15,folder.getResourceId()); statement.executeUpdate(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_RESOURCES_UPDATE_KEY, statement); } } } /** * Writes an already existing group in the Cms.<BR/> * * Only the admin can do this.<P/> * * @param group The group that should be written to the Cms. * @exception CmsException Throws CmsException if operation was not succesfull. */ public void writeGroup(CmsGroup group) throws CmsException { PreparedStatement statement = null; try { if (group != null){ // create statement statement=m_pool.getPreparedStatement(m_cq.C_GROUPS_WRITEGROUP_KEY); statement.setString(1,group.getDescription()); statement.setInt(2,group.getFlags()); statement.setInt(3,group.getParentId()); statement.setInt(4,group.getId()); statement.executeUpdate(); } else { throw new CmsException("[" + this.getClass().getName() + "] ",CmsException.C_NO_GROUP); } } catch (SQLException e){ throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_GROUPS_WRITEGROUP_KEY,statement); } } } /** * Deletes a project from the cms. * Therefore it deletes all files, resources and properties. * * @param project the project to delete. * @exception CmsException Throws CmsException if something goes wrong. */ public void writeProject(CmsProject project) throws CmsException { PreparedStatement statement = null; try { // create the statement statement = m_pool.getPreparedStatement(m_cq.C_PROJECTS_WRITE_KEY); statement.setInt(1,project.getOwnerId()); statement.setInt(2,project.getGroupId()); statement.setInt(3,project.getManagerGroupId()); statement.setInt(4,project.getFlags()); statement.setTimestamp(5,new Timestamp(project.getPublishingDate())); statement.setInt(6,project.getPublishedBy()); statement.setInt(7,project.getId()); statement.executeUpdate(); } catch( Exception exc ) { throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(), CmsException.C_SQL_ERROR, exc); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_PROJECTS_WRITE_KEY, statement); } } } /** * Writes a couple of Properties for a file or folder. * * @param propertyinfos A Hashtable with propertydefinition- property-pairs as strings. * @param resourceId The id of the resource. * @param resourceType The Type of the resource. * * @exception CmsException Throws CmsException if operation was not succesful */ public void writeProperties(Hashtable propertyinfos, int resourceId, int resourceType) throws CmsException { // get all metadefs Enumeration keys = propertyinfos.keys(); // one metainfo-name: String key; while(keys.hasMoreElements()) { key = (String) keys.nextElement(); writeProperty(key, (String) propertyinfos.get(key), resourceId, resourceType); } } /** * Updates the propertydefinition for the resource type.<BR/> * * Only the admin can do this. * * @param metadef The propertydef to be deleted. * * @return The propertydefinition, that was written. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsPropertydefinition writePropertydefinition(CmsPropertydefinition metadef) throws CmsException { PreparedStatement statement = null; CmsPropertydefinition returnValue = null; try { // create statement statement = m_pool.getPreparedStatement(m_cq.C_PROPERTYDEF_UPDATE_KEY); statement.setInt(1, metadef.getPropertydefType() ); statement.setInt(2, metadef.getId() ); statement.executeUpdate(); returnValue = readPropertydefinition(metadef.getName(), metadef.getType()); } catch( SQLException exc ) { throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(), CmsException.C_SQL_ERROR, exc); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_PROPERTYDEF_UPDATE_KEY, statement); } } return returnValue; } /** * Writes a property for a file or folder. * * @param meta The property-name of which the property has to be read. * @param value The value for the property to be set. * @param resourceId The id of the resource. * @param resourceType The Type of the resource. * * @exception CmsException Throws CmsException if operation was not succesful */ public void writeProperty(String meta, String value, int resourceId, int resourceType) throws CmsException { CmsPropertydefinition propdef = readPropertydefinition(meta, resourceType); if( propdef == null) { // there is no propertydefinition for with the overgiven name for the resource throw new CmsException("[" + this.getClass().getName() + "] " + meta, CmsException.C_NOT_FOUND); } else { // write the property into the db PreparedStatement statement = null; boolean newprop=true; try { if( readProperty(propdef.getName(), resourceId, resourceType) != null) { // property exists already - use update. // create statement statement = m_pool.getPreparedStatement(m_cq.C_PROPERTIES_UPDATE_KEY); statement.setString(1, checkNull(value) ); statement.setInt(2, resourceId); statement.setInt(3, propdef.getId()); statement.executeUpdate(); newprop=false; } else { // property dosen't exist - use create. // create statement statement = m_pool.getPreparedStatement(m_cq.C_PROPERTIES_CREATE_KEY); statement.setInt(1, nextId(C_TABLE_PROPERTIES)); statement.setInt(2, propdef.getId()); statement.setInt(3, resourceId); statement.setString(4, checkNull(value)); statement.executeUpdate(); newprop=true; } } catch(SQLException exc) { throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(), CmsException.C_SQL_ERROR, exc); }finally { if( statement != null) { if (newprop) { m_pool.putPreparedStatement(m_cq.C_PROPERTIES_CREATE_KEY, statement); } else { m_pool.putPreparedStatement(m_cq.C_PROPERTIES_UPDATE_KEY, statement); } } } } } /** * Writes a serializable object to the systemproperties. * * @param name The name of the property. * @param object The property-object. * * @return object The property-object. * * @exception CmsException Throws CmsException if something goes wrong. */ public Serializable writeSystemProperty(String name, Serializable object) throws CmsException { byte[] value=null; PreparedStatement statement = null; try { // serialize the object ByteArrayOutputStream bout= new ByteArrayOutputStream(); ObjectOutputStream oout=new ObjectOutputStream(bout); oout.writeObject(object); oout.close(); value=bout.toByteArray(); statement=m_pool.getPreparedStatement(m_cq.C_SYSTEMPROPERTIES_UPDATE_KEY); statement.setBytes(1,value); statement.setString(2,name); statement.executeUpdate(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e); } catch (IOException e){ throw new CmsException("["+this.getClass().getName()+"]"+CmsException. C_SERIALIZATION, e); }finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_SYSTEMPROPERTIES_UPDATE_KEY, statement); } } return readSystemProperty(name); } public void writeSystemTaskLog(int taskid, String comment) throws CmsException { this.writeTaskLog(taskid, C_UNKNOWN_ID, new java.sql.Timestamp(System.currentTimeMillis()), comment, C_TASKLOG_USER); } /** * Updates a task. * * @param task The task that will be written. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsTask writeTask(CmsTask task) throws CmsException { PreparedStatement statement = null; try { statement = m_pool.getPreparedStatement(m_cq.C_TASK_UPDATE_KEY); statement.setString(1,task.getName()); statement.setInt(2,task.getState()); statement.setInt(3,task.getTaskType()); statement.setInt(4,task.getRoot()); statement.setInt(5,task.getParent()); statement.setInt(6,task.getInitiatorUser()); statement.setInt(7,task.getRole()); statement.setInt(8,task.getAgentUser()); statement.setInt(9,task.getOriginalUser()); statement.setTimestamp(10,task.getStartTime()); statement.setTimestamp(11,task.getWakeupTime()); statement.setTimestamp(12,task.getTimeOut()); statement.setTimestamp(13,task.getEndTime()); statement.setInt(14,task.getPercentage()); statement.setString(15,task.getPermission()); statement.setInt(16,task.getPriority()); statement.setInt(17,task.getEscalationType()); statement.setString(18,task.getHtmlLink()); statement.setInt(19,task.getMilestone()); statement.setInt(20,task.getAutoFinish()); statement.setInt(21,task.getId()); statement.executeUpdate(); } catch( SQLException exc ) { throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc); } finally { if(statement != null) { m_pool.putPreparedStatement(m_cq.C_TASK_UPDATE_KEY, statement); } } return(readTask(task.getId())); } /** * Writes new log for a task. * * @param taskid The id of the task. * @param user User who added the Log. * @param starttime Time when the log is created. * @param comment Description for the log. * @param type Type of the log. 0 = Sytem log, 1 = User Log * * @exception CmsException Throws CmsException if something goes wrong. */ public void writeTaskLog(int taskId, int userid, java.sql.Timestamp starttime, String comment, int type) throws CmsException { int newId = C_UNKNOWN_ID; PreparedStatement statement = null; try{ newId = nextId(C_TABLE_TASKLOG); statement = m_pool.getPreparedStatement(m_cq.C_TASKLOG_WRITE_KEY); statement.setInt(1, newId); statement.setInt(2, taskId); if(userid!=C_UNKNOWN_ID){ statement.setInt(3, userid); } else { // no user is specified so set to system user // is only valid for system task log statement.setInt(3, 1); } statement.setTimestamp(4, starttime); statement.setString(5, comment); statement.setInt(6, type); statement.executeUpdate(); } catch( SQLException exc ) { throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc); } finally { if(statement != null) { m_pool.putPreparedStatement(m_cq.C_TASKLOG_WRITE_KEY, statement); } } } /** * Writes a user to the database. * * @param user the user to write * @exception thorws CmsException if something goes wrong. */ public void writeUser(CmsUser user) throws CmsException { byte[] value=null; PreparedStatement statement = null; try { // serialize the hashtable ByteArrayOutputStream bout= new ByteArrayOutputStream(); ObjectOutputStream oout=new ObjectOutputStream(bout); oout.writeObject(user.getAdditionalInfo()); oout.close(); value=bout.toByteArray(); // write data to database statement = m_pool.getPreparedStatement(m_cq.C_USERS_WRITE_KEY); statement.setString(1,checkNull(user.getDescription())); statement.setString(2,checkNull(user.getFirstname())); statement.setString(3,checkNull(user.getLastname())); statement.setString(4,checkNull(user.getEmail())); statement.setTimestamp(5, new Timestamp(user.getLastlogin())); statement.setTimestamp(6, new Timestamp(user.getLastUsed())); statement.setInt(7,user.getFlags()); statement.setBytes(8,value); statement.setInt(9, user.getDefaultGroupId()); statement.setString(10,checkNull(user.getAddress())); statement.setString(11,checkNull(user.getSection())); statement.setInt(12,user.getType()); statement.setInt(13,user.getId()); statement.executeUpdate(); } catch (SQLException e){ throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e); } catch (IOException e){ throw new CmsException("[CmsAccessUserInfoMySql/addUserInformation(id,object)]:"+CmsException. C_SERIALIZATION, e); } finally { if( statement != null) { m_pool.putPreparedStatement(m_cq.C_USERS_WRITE_KEY, statement); } } } }
package com.patr.radix.ui.unlock; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import org.xutils.common.util.LogUtil; import com.felipecsl.gifimageview.library.GifImageView; import com.patr.radix.LockValidateActivity; import com.patr.radix.App; import com.patr.radix.R; import com.patr.radix.adapter.CommunityListAdapter; import com.patr.radix.bean.GetCommunityListResult; import com.patr.radix.bean.GetLockListResult; import com.patr.radix.bean.GetWeatherResult; import com.patr.radix.bean.MDevice; import com.patr.radix.bean.RadixLock; import com.patr.radix.ble.BluetoothLeService; import com.patr.radix.bll.CacheManager; import com.patr.radix.bll.GetCommunityListParser; import com.patr.radix.bll.GetLockListParser; import com.patr.radix.bll.ServiceManager; import com.patr.radix.network.RequestListener; import com.patr.radix.ui.WeatherActivity; import com.patr.radix.ui.view.ListSelectDialog; import com.patr.radix.ui.view.LoadingDialog; import com.patr.radix.ui.view.TitleBarView; import com.patr.radix.utils.Constants; import com.patr.radix.utils.GattAttributes; import com.patr.radix.utils.NetUtils; import com.patr.radix.utils.PrefUtil; import com.patr.radix.utils.ToastUtil; import com.patr.radix.utils.Utils; //import com.yuntongxun.ecdemo.common.CCPAppManager; //import com.yuntongxun.ecdemo.common.utils.FileAccessor; //import com.yuntongxun.ecdemo.core.ClientUser; //import com.yuntongxun.ecdemo.ui.SDKCoreHelper; //import com.yuntongxun.ecsdk.ECInitParams.LoginAuthType; //import com.yuntongxun.ecsdk.ECInitParams.LoginMode; import android.Manifest; import android.annotation.TargetApi; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattService; import android.bluetooth.BluetoothManager; import android.bluetooth.BluetoothAdapter.LeScanCallback; import android.bluetooth.le.BluetoothLeScanner; import android.bluetooth.le.ScanCallback; import android.bluetooth.le.ScanResult; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Resources.NotFoundException; import android.graphics.drawable.GradientDrawable.Orientation; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.os.Vibrator; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; public class UnlockFragment extends Fragment implements OnClickListener, OnItemClickListener, SensorEventListener { private Context context; private TextView areaTv; private ImageView weatherIv; private TextView weatherTv; private TextView tempTv; private ImageButton detailBtn; private ImageButton shakeBtn; private TextView keyTv; private Button sendKeyBtn; private LinearLayout keysLl; private CommunityListAdapter adapter; private LoadingDialog loadingDialog; SensorManager sensorManager = null; Vibrator vibrator = null; private Handler handler; private static BluetoothAdapter mBluetoothAdapter; private final List<MDevice> list = new ArrayList<MDevice>(); private BluetoothLeScanner bleScanner; private boolean mScanning = false; private BluetoothGattCharacteristic notifyCharacteristic; private BluetoothGattCharacteristic writeCharacteristic; private boolean notifyEnable = false; private boolean handShake = false; private String currentDevAddress; private String currentDevName; private boolean isUnlocking = false; private boolean isDisconnectForUnlock = false; private boolean foundDevice = false; private int retryCount = 0; private static final int REQUEST_FINE_LOCATION = 0; @Override public void onAttach(Activity activity) { super.onAttach(activity); context = activity; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_unlock, container, false); areaTv = (TextView) view.findViewById(R.id.area_tv); weatherIv = (ImageView) view.findViewById(R.id.weather_iv); weatherTv = (TextView) view.findViewById(R.id.weather_tv); tempTv = (TextView) view.findViewById(R.id.temp_tv); detailBtn = (ImageButton) view.findViewById(R.id.weather_detail_btn); shakeBtn = (ImageButton) view.findViewById(R.id.shake_btn); keyTv = (TextView) view.findViewById(R.id.key_tv); sendKeyBtn = (Button) view.findViewById(R.id.send_key_btn); keysLl = (LinearLayout) view.findViewById(R.id.key_ll); detailBtn.setOnClickListener(this); shakeBtn.setOnClickListener(this); sendKeyBtn.setOnClickListener(this); loadingDialog = new LoadingDialog(context); init(); loadData(); return view; } private void init() { sensorManager = (SensorManager) context .getSystemService(Context.SENSOR_SERVICE); vibrator = (Vibrator) context .getSystemService(Context.VIBRATOR_SERVICE); adapter = new CommunityListAdapter(context, App.instance.getCommunities()); checkBleSupportAndInitialize(); handler = new Handler(); context.registerReceiver(mGattUpdateReceiver, Utils.makeGattUpdateIntentFilter()); Intent gattServiceIntent = new Intent(context.getApplicationContext(), BluetoothLeService.class); context.startService(gattServiceIntent); } /** * BroadcastReceiver for receiving the GATT communication status */ private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); // Status received when connected to GATT Server if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) { System.out.println(" // statusTv.setText(""); LogUtil.d(""); BluetoothLeService.discoverServices(); } // Services Discovered from GATT Server else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED .equals(action)) { System.out.println(" // statusTv.setText(); LogUtil.d("…"); prepareGattServices( BluetoothLeService.getSupportedGattServices()); doUnlock(); } else if (action .equals(BluetoothLeService.ACTION_GATT_DISCONNECTED)) { System.out.println(" // connect break () // statusTv.setText(""); LogUtil.d(""); if (isDisconnectForUnlock) { BluetoothLeService.close(); isUnlocking = false; } } // There are four basic operations for moving data in BLE: read, // write, notify, // and indicate. The BLE protocol specification requires that the // maximum data // payload size for these operations is 20 bytes, or in the case of // read operations, // 22 bytes. BLE is built for low power consumption, for infrequent // short-burst data transmissions. // Sending lots of data is possible, but usually ends up being less // efficient than classic Bluetooth // when trying to achieve maximum throughput. // googleandroidnotify Bundle extras = intent.getExtras(); if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) { // Data Received if (extras.containsKey(Constants.EXTRA_BYTE_VALUE)) { final byte[] array = intent .getByteArrayExtra(Constants.EXTRA_BYTE_VALUE); LogUtil.d("" + Utils.ByteArraytoHex(array)); if (extras.containsKey(Constants.EXTRA_BYTE_UUID_VALUE)) { handle(array); } } if (extras.containsKey(Constants.EXTRA_DESCRIPTOR_BYTE_VALUE)) { if (extras.containsKey( Constants.EXTRA_DESCRIPTOR_BYTE_VALUE_CHARACTERISTIC_UUID)) { byte[] array = intent.getByteArrayExtra( Constants.EXTRA_DESCRIPTOR_BYTE_VALUE); // updateButtonStatus(array); } } } if (action.equals( BluetoothLeService.ACTION_GATT_DESCRIPTORWRITE_RESULT)) { if (extras .containsKey(Constants.EXTRA_DESCRIPTOR_WRITE_RESULT)) { int status = extras .getInt(Constants.EXTRA_DESCRIPTOR_WRITE_RESULT); if (status != BluetoothGatt.GATT_SUCCESS) { Toast.makeText(context, R.string.option_fail, Toast.LENGTH_LONG).show(); } } } if (action.equals( BluetoothLeService.ACTION_GATT_CHARACTERISTIC_ERROR)) { if (extras.containsKey( Constants.EXTRA_CHARACTERISTIC_ERROR_MESSAGE)) { String errorMessage = extras.getString( Constants.EXTRA_CHARACTERISTIC_ERROR_MESSAGE); System.out.println( "GattDetailActivity + errorMessage); Toast.makeText(context, errorMessage, Toast.LENGTH_LONG) .show(); } } // write characteristics succcess if (action.equals( BluetoothLeService.ACTION_GATT_CHARACTERISTIC_WRITE_SUCCESS)) { LogUtil.d(""); } if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) { // final int state = // intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, // BluetoothDevice.ERROR); // if (state == BluetoothDevice.BOND_BONDING) {} // else if (state == BluetoothDevice.BOND_BONDED) {} // else if (state == BluetoothDevice.BOND_NONE) {} } } }; /** * Getting the GATT Services * * @param gattServices */ private void prepareGattServices(List<BluetoothGattService> gattServices) { prepareData(gattServices); } /** * Prepare GATTServices data. * * @param gattServices */ private void prepareData(List<BluetoothGattService> gattServices) { if (gattServices == null) return; for (BluetoothGattService gattService : gattServices) { String uuid = gattService.getUuid().toString(); if (uuid.equals(GattAttributes.GENERIC_ACCESS_SERVICE) || uuid.equals(GattAttributes.GENERIC_ATTRIBUTE_SERVICE)) continue; if (uuid.equals(GattAttributes.USR_SERVICE)) { initCharacteristics(gattService.getCharacteristics()); notifyOption(); break; } } } private void handle(byte[] array) { int size = array.length; if (size < 6 || array[0] != (byte) 0xAA) { // invalid msg // if (isUnlocking) { // retryCount++; // if (retryCount <= 3) { // doUnlock(); // } else { // ToastUtil.showShort(context, ""); // disconnectDevice(); return; } byte cmd = array[2]; int len; switch (cmd) { case Constants.UNLOCK: len = array[3]; if (size < 6 + len || array[len + 5] != (byte) 0xDD) { // invalid msg if (isUnlocking) { LogUtil.d(""); ToastUtil.showShort(context, ""); disconnectDevice(); } } else { byte check = array[1]; check = (byte) (check ^ cmd ^ array[3]); for (int i = 0; i < len; i++) { check ^= array[i + 4]; } if (check == array[len + 4]) { // check pass if (array[4] == 0x00) { loadingDialog.dismiss(); ToastUtil.showShort(context, ""); disconnectDevice(); } else { if (isUnlocking) { LogUtil.d(""); ToastUtil.showShort(context, ""); disconnectDevice(); } } } else { // check fail if (isUnlocking) { LogUtil.d(""); ToastUtil.showShort(context, ""); disconnectDevice(); } } } break; default: // INVALID REQUEST/RESPONSE. break; // case Constants.HAND_SHAKE: // if (size < 5 || array[4] != (byte) 0xDD) { // // invalidMsg(); // } else { // if ((cmd ^ array[2]) == array[3]) { // if (array[2] == (byte) 0x00) { // handShake = true; // // messageEt.append("\n"); // // messageEt.setSelection(messageEt.getText().length(), // // messageEt.getText().length()); // } else { // // messageEt.append("\n"); // // messageEt.setSelection(messageEt.getText().length(), // // messageEt.getText().length()); // } else { // // checkFailed(); // break; // case Constants.READ_CARD: // if (size < 12 || array[11] != (byte) 0xDD) { // // invalidMsg(); // } else { // for (int i = 2; i < 10; i++) { // if (array[i] != (byte) 0x00) { // // checkFailed(); // writeOption("90 ", "FF 00 00 00 00 00 00 00 00 "); // return; // byte check = cmd; // for (int i = 2; i < 10; i++) { // check ^= array[i]; // if (check == array[10]) { // if (handShake) { // // messageEt.append("\n"); // // messageEt.setSelection(messageEt.getText().length(), // // messageEt.getText().length()); // writeOption("90 ", "00 00 00 00 00 " + // MyApplication.instance.getCardNum()); // } else { // // messageEt.append("\n"); // // messageEt.setSelection(messageEt.getText().length(), // // messageEt.getText().length()); // writeOption("90 ", "FF 00 00 00 00 00 00 00 00 "); // } else { // // checkFailed(); // writeOption("90 ", "FF 00 00 00 00 00 00 00 00 "); // break; // case Constants.WRITE_CARD: // if (size < 12 || array[11] != (byte) 0xDD) { // // invalidMsg(); // } else { // for (int i = 2; i < 6; i++) { // if (array[i] != (byte) 0x00) { // // checkFailed(); // writeOption("91 ", "FF 00 00 00 00 00 00 00 00 "); // return; // byte check = cmd; // for (int i = 2; i < 10; i++) { // check ^= array[i]; // if (check == array[10]) { // if (handShake) { // byte[] cn = new byte[4]; // for (int i = 0; i < 4; i++) { // cn[i] = array[i + 6]; // MyApplication.instance.setCardNum(Utils.ByteArraytoHex(cn)); // MyApplication.instance.setCsn(MyApplication.instance.getCardNum()); // // messageEt.append("" + cardNum + "\n"); // // messageEt.setSelection(messageEt.getText().length(), // // messageEt.getText().length()); // writeOption("91 ", "00 "); // } else { // // messageEt.append("\n"); // // messageEt.setSelection(messageEt.getText().length(), // // messageEt.getText().length()); // writeOption("91 ", "FF "); // } else { // // checkFailed(); // writeOption("91 ", "FF "); // break; // case Constants.DISCONNECT: // if (size < 12 || array[11] != (byte) 0xDD) { // // invalidMsg(); // } else { // for (int i = 2; i < 10; i++) { // if (array[i] != (byte) 0x00) { // // checkFailed(); // writeOption("A0 ", "FF "); // return; // byte check = cmd; // for (int i = 2; i < 10; i++) { // check ^= array[i]; // if (check == array[10]) { // if (handShake) { // // messageEt.append("\n"); // // messageEt.setSelection(messageEt.getText().length(), // // messageEt.getText().length()); // writeOption("A0 ", "00 "); // handShake = false; // } else { // // messageEt.append("\n"); // // messageEt.setSelection(messageEt.getText().length(), // // messageEt.getText().length()); // writeOption("A0 ", "FF "); // } else { // // checkFailed(); // writeOption("A0 ", "FF "); // break; // default: // // messageEt.append("INVALID REQUEST/RESPONSE."); // // messageEt.setSelection(messageEt.getText().length(), // // messageEt.getText().length()); // break; } } private void doUnlock() { writeOption("30 ", "06 00 00 " + App.instance.getUserInfo().getCardNo()); } private void writeOption(String cmd, String data) { writeOption(Utils.getCmdData("00 ", cmd, data)); } private void writeOption(String hexStr) { writeCharacteristic(writeCharacteristic, Utils.getCmdDataByteArray(hexStr)); } private void writeCharacteristic(BluetoothGattCharacteristic characteristic, byte[] bytes) { // Writing the hexValue to the characteristics try { LogUtil.d("write bytes: " + Utils.ByteArraytoHex(bytes)); BluetoothLeService.writeCharacteristicGattDb(characteristic, bytes); } catch (NullPointerException e) { e.printStackTrace(); } } private void initCharacteristics( List<BluetoothGattCharacteristic> characteristics) { for (BluetoothGattCharacteristic c : characteristics) { if (Utils.getPorperties(context, c).equals("Notify")) { notifyCharacteristic = c; continue; } if (Utils.getPorperties(context, c).equals("Write")) { writeCharacteristic = c; continue; } } } private void notifyOption() { if (notifyEnable) { notifyEnable = false; stopBroadcastDataNotify(notifyCharacteristic); } else { notifyEnable = true; prepareBroadcastDataNotify(notifyCharacteristic); } } /** * Preparing Broadcast receiver to broadcast notify characteristics * * @param characteristic */ void prepareBroadcastDataNotify( BluetoothGattCharacteristic characteristic) { final int charaProp = characteristic.getProperties(); if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) { BluetoothLeService.setCharacteristicNotification(characteristic, true); } } /** * Stopping Broadcast receiver to broadcast notify characteristics * * @param characteristic */ void stopBroadcastDataNotify(BluetoothGattCharacteristic characteristic) { final int charaProp = characteristic.getProperties(); if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) { BluetoothLeService.setCharacteristicNotification(characteristic, false); } } private void connectDevice(BluetoothDevice device) { currentDevAddress = device.getAddress(); currentDevName = device.getName(); LogUtil.d("connectDevice: DevName = " + currentDevName + "; DevAddress = " + currentDevAddress); if (BluetoothLeService .getConnectionState() != BluetoothLeService.STATE_DISCONNECTED) { isDisconnectForUnlock = false; BluetoothLeService.disconnect(); } BluetoothLeService.connect(currentDevAddress, currentDevName, context); } private void disconnectDevice() { notifyOption(); if (isUnlocking) { isDisconnectForUnlock = true; } else { isDisconnectForUnlock = false; } BluetoothLeService.disconnect(); } private void loadData() { if (App.instance.getSelectedCommunity() == null) { getCommunityList(); return; } // if (!TextUtils.isEmpty(App.instance.getMyMobile())) { // String appKey = FileAccessor.getAppKey(); // String token = FileAccessor.getAppToken(); // String myMobile = App.instance.getMyMobile(); // String pass = ""; // ClientUser clientUser = new ClientUser(myMobile); // clientUser.setAppKey(appKey); // clientUser.setAppToken(token); // clientUser.setLoginAuthType(LoginAuthType.NORMAL_AUTH); // clientUser.setPassword(pass); // CCPAppManager.setClientUser(clientUser); // SDKCoreHelper.init(App.instance, LoginMode.FORCE_LOGIN); } private void getWeather() { ServiceManager.getWeather(new RequestListener<GetWeatherResult>() { @Override public void onStart() { } @Override public void onSuccess(int stateCode, GetWeatherResult result) { if (result.getErrorCode().equals("0")) { refreshWeather(result); } else { // ToastUtil.showShort(context, result.getReason()); } } @Override public void onFailure(Exception error, String content) { ToastUtil.showShort(context, ""); } }); } private void refreshWeather(GetWeatherResult result) { Field f; try { f = (Field) R.drawable.class .getDeclaredField("ww" + result.getImg()); int id = f.getInt(R.drawable.class); weatherIv.setImageResource(id); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } weatherTv.setText(result.getWeather()); tempTv.setText(result.getTemp() + "℃"); areaTv.setText(result.getCity()); } private void getCommunityList() { switch (NetUtils.getConnectedType(context)) { case NONE: getCommunityListFromCache(); break; case WIFI: case OTHER: getCommunityListFromServer(); break; default: break; } } private void getCommunityListFromCache() { CacheManager.getCacheContent(context, CacheManager.getCommunityListUrl(), new RequestListener<GetCommunityListResult>() { @Override public void onSuccess(int stateCode, GetCommunityListResult result) { if (result != null) { App.instance .setCommunities(result.getCommunities()); adapter.notifyDataSetChanged(); ListSelectDialog.show(context, "", adapter, UnlockFragment.this); } } }, new GetCommunityListParser()); } private void getCommunityListFromServer() { ServiceManager.getCommunityList( new RequestListener<GetCommunityListResult>() { @Override public void onSuccess(int stateCode, GetCommunityListResult result) { if (result != null) { if (result.isSuccesses()) { App.instance.setCommunities( result.getCommunities()); saveCommunityListToDb(result.getResponse()); adapter.notifyDataSetChanged(); ListSelectDialog.show(context, "", adapter, UnlockFragment.this); } else { // ToastUtil.showShort(context, // result.getRetinfo()); getCommunityListFromCache(); } } else { getCommunityListFromCache(); } } @Override public void onFailure(Exception error, String content) { getCommunityListFromCache(); } }); } /** * * * @param content */ protected void saveCommunityListToDb(String content) { CacheManager.saveCacheContent(context, CacheManager.getCommunityListUrl(), content, new RequestListener<Boolean>() { @Override public void onSuccess(Boolean result) { LogUtil.i("save " + CacheManager.getCommunityListUrl() + "=" + result); } }); } private void getLockList() { if (!TextUtils.isEmpty(App.instance.getUserInfo().getToken())) { switch (NetUtils.getConnectedType(context)) { case NONE: getLockListFromCache(); break; case WIFI: case OTHER: getLockListFromServer(); break; default: break; } } else if (App.firstRequest) { ToastUtil.showShort(context, ""); App.firstRequest = false; } } private void getLockListFromCache() { if (App.instance.getSelectedCommunity() != null) { CacheManager.getCacheContent(context, CacheManager.getLockListUrl(), new RequestListener<GetLockListResult>() { @Override public void onSuccess(int stateCode, GetLockListResult result) { if (result != null) { App.instance.setLocks(result.getLocks()); setSelectedKey(); refreshKey(); } } }, new GetLockListParser()); } } private void getLockListFromServer() { if (App.instance.getSelectedCommunity() != null) { ServiceManager .getLockList(new RequestListener<GetLockListResult>() { @Override public void onSuccess(int stateCode, GetLockListResult result) { if (result != null) { if (result.isSuccesses()) { App.instance.setLocks(result.getLocks()); saveLockListToDb(result.getResponse()); setSelectedKey(); refreshKey(); } else { // ToastUtil.showShort(context, // result.getRetinfo()); getLockListFromCache(); } } else { getLockListFromCache(); } } @Override public void onFailure(Exception error, String content) { getLockListFromCache(); } }); } } /** * * * @param content */ protected void saveLockListToDb(String content) { CacheManager.saveCacheContent(context, CacheManager.getLockListUrl(), content, new RequestListener<Boolean>() { @Override public void onSuccess(Boolean result) { LogUtil.i("save " + CacheManager.getLockListUrl() + "=" + result); } }); } private void refreshKey() { RadixLock selectedKey = App.instance.getSelectedLock(); if (selectedKey != null) { keyTv.setText(selectedKey.getName()); } keysLl.removeAllViews(); final List<RadixLock> keys = App.instance.getLocks(); int size = keys.size(); for (int i = 0; i < size; i++) { KeyView keyView; if (keys.get(i).equals(selectedKey)) { keyView = new KeyView(context, keys.get(i), i, true); } else { keyView = new KeyView(context, keys.get(i), i, false); } keyView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { int idx = (int) v.getTag(); if (!keys.get(idx).equals(App.instance.getSelectedLock())) { App.instance.setSelectedLock(keys.get(idx)); refreshKey(); } } }); keysLl.addView(keyView); } } private void setSelectedKey() { String selectedKey = PrefUtil.getString(context, Constants.PREF_SELECTED_KEY); for (RadixLock lock : App.instance.getLocks()) { if (selectedKey.equals(lock.getId())) { App.instance.setSelectedLock(lock); return; } } if (App.instance.getLocks().size() > 0) { App.instance.setSelectedLock(App.instance.getLocks().get(0)); } } @Override public void setArguments(Bundle args) { super.setArguments(args); } @Override public void onResume() { super.onResume(); if (PrefUtil.getBoolean(context, Constants.PREF_SHAKE_SWITCH, true)) { sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); } getWeather(); getLockList(); } @Override public void onPause() { super.onPause(); sensorManager.unregisterListener(this); } @Override public void onDestroy() { super.onDestroy(); context.unregisterReceiver(mGattUpdateReceiver); if (loadingDialog.isShowing()) { loadingDialog.dismiss(); } } /* * (non-Javadoc) * * @see android.view.View.OnClickListener#onClick(android.view.View) */ @Override public void onClick(View v) { switch (v.getId()) { case R.id.weather_detail_btn: case R.id.weather_rl: context.startActivity(new Intent(context, WeatherActivity.class)); break; case R.id.send_key_btn: context.startActivity(new Intent(context, MyKeysActivity.class)); break; case R.id.shake_btn: preUnlock(); break; } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { App.instance.setSelectedCommunity(adapter.getItem(position)); if (!adapter.isSelect(position)) { App.instance.setSelectedLock(null); getLockList(); } adapter.select(position); } @Override public void onSensorChanged(SensorEvent event) { int sensorType = event.sensor.getType(); // values[0]:Xvalues[1]Yvalues[2]Z float[] values = event.values; if (sensorType == Sensor.TYPE_ACCELEROMETER) { if ((Math.abs(values[0]) > 17 || Math.abs(values[1]) > 17 || Math.abs(values[2]) > 17)) { LogUtil.d("============ values[0] = " + values[0]); LogUtil.d("============ values[1] = " + values[1]); LogUtil.d("============ values[2] = " + values[2]); vibrator.vibrate(500); preUnlock(); } } } private void preUnlock() { RadixLock lock = App.instance.getSelectedLock(); LogUtil.d("preUnlock: lock = " + lock.getBleName1()); if (lock != null) { String lockPaternStr = PrefUtil.getString(context, Constants.PREF_LOCK_KEY, null); if (!TextUtils.isEmpty(lockPaternStr)) { LockValidateActivity.startForResult(this, Constants.LOCK_CHECK); } else { unlock(); } } else { ToastUtil.showShort(context, ""); } } private void unlock() { if (mBluetoothAdapter == null) { getBluetoothAdapter(); } if (!mBluetoothAdapter.isEnabled()) { ToastUtil.showLong(context, ""); return; } if (!isUnlocking) { isUnlocking = true; retryCount = 0; RadixLock lock = App.instance.getSelectedLock(); LogUtil.d("unlock: inBleName = " + lock.getBleName1() + ", outBleName = " + lock.getBleName2()); loadingDialog.show("…", true); loadingDialog.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { BluetoothLeService.close(); isUnlocking = false; } }); new Thread() { @Override public void run() { BluetoothLeService.close(); startScan(); } }.start(); } } private void checkBleSupportAndInitialize() { // Use this check to determine whether BLE is supported on the device. if (!context.getPackageManager() .hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { Toast.makeText(context, "BLE", Toast.LENGTH_SHORT).show(); return; } // Initializes a Blue tooth adapter. getBluetoothAdapter(); if (mBluetoothAdapter == null) { // Device does not support Blue tooth Toast.makeText(context, "BLE", Toast.LENGTH_SHORT).show(); return; } if (!mBluetoothAdapter.isEnabled()) { mBluetoothAdapter.enable(); } } private void bleReset() { // Initializes a Blue tooth adapter. getBluetoothAdapter(); if (mBluetoothAdapter == null) { // Device does not support Blue tooth Toast.makeText(context, "BLE", Toast.LENGTH_SHORT).show(); return; } if (mBluetoothAdapter.isDiscovering()) { mBluetoothAdapter.cancelDiscovery(); } if (!mBluetoothAdapter.isEnabled()) { mBluetoothAdapter.enable(); } } private void getBluetoothAdapter() { final BluetoothManager bluetoothManager = (BluetoothManager) context .getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = bluetoothManager.getAdapter(); } /** * Call back for BLE Scan This call back is called when a BLE device is * found near by. */ private LeScanCallback mLeScanCallback = new LeScanCallback() { @Override public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) { MDevice mDev = new MDevice(device, rssi); if (list.contains(mDev)) { return; } list.add(mDev); String name = mDev.getDevice().getName(); LogUtil.d("" + name); if (name == null) { return; } RadixLock lock = App.instance.getSelectedLock(); if (name.equals(lock.getBleName1()) || name.equals(lock.getBleName2())) { if (!foundDevice) { foundDevice = true; LogUtil.d("……"); handler.post(new Runnable() { @Override public void run() { loadingDialog.show("…", true); } }); new Thread() { int time = 0; @Override public void run() { while (isUnlocking) { try { sleep(50); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } time += 50; if (time >= 5000) { break; } } if (isUnlocking) { BluetoothLeService.close(); isUnlocking = false; bleReset(); handler.post(new Runnable() { @Override public void run() { loadingDialog.dismiss(); } }); } } }.start(); connectDevice(device); // if (mBluetoothAdapter != null) { // mBluetoothAdapter.stopLeScan(mLeScanCallback); } } } }; private void startScan() { list.clear(); foundDevice = false; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { scanPrevious21Version(); } else { scanAfter21Version(); } } private void scanPrevious21Version() { handler.postDelayed(new Runnable() { @Override public void run() { if (mBluetoothAdapter != null) { mBluetoothAdapter.stopLeScan(mLeScanCallback); } if (!foundDevice) { // ToastUtil.showShort(context, ""); loadingDialog.dismiss(); isUnlocking = false; } mScanning = false; } }, 2000); if (mBluetoothAdapter == null) { getBluetoothAdapter(); } if (mBluetoothAdapter != null) { mScanning = true; mBluetoothAdapter.startLeScan(mLeScanCallback); } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void scanAfter21Version() { handler.postDelayed(new Runnable() { @Override public void run() { if (bleScanner != null) { bleScanner.stopScan(new ScanCallback() { @Override public void onScanResult(int callbackType, ScanResult result) { super.onScanResult(callbackType, result); } }); } if (!foundDevice) { // ToastUtil.showShort(context, ""); loadingDialog.dismiss(); isUnlocking = false; } mScanning = false; } }, 2000); if (bleScanner == null) { if (mBluetoothAdapter == null) { getBluetoothAdapter(); } bleScanner = mBluetoothAdapter.getBluetoothLeScanner(); } if (bleScanner != null) { mScanning = true; bleScanner.startScan(new ScanCallback() { @Override public void onScanResult(int callbackType, ScanResult result) { super.onScanResult(callbackType, result); final MDevice mDev = new MDevice(result.getDevice(), result.getRssi()); if (list.contains(mDev)) { return; } list.add(mDev); String name = mDev.getDevice().getName(); LogUtil.d("" + name); if (name == null) { return; } RadixLock lock = App.instance.getSelectedLock(); if (name.equals(lock.getBleName1()) || name.equals(lock.getBleName2())) { if (!foundDevice) { foundDevice = true; LogUtil.d("……"); handler.post(new Runnable() { @Override public void run() { loadingDialog.show("…", true); } }); new Thread() { int time = 0; @Override public void run() { while (isUnlocking) { try { sleep(50); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } time += 50; if (time >= 5000) { break; } } if (isUnlocking) { BluetoothLeService.close(); isUnlocking = false; bleReset(); handler.post(new Runnable() { @Override public void run() { loadingDialog.dismiss(); } }); } } }.start(); connectDevice(mDev.getDevice()); // if (bleScanner != null) { // bleScanner.stopScan(new ScanCallback() { // @Override // public void onScanResult(int callbackType, // ScanResult result) { // super.onScanResult(callbackType, // result); } } } }); } } // @TargetApi(Build.VERSION_CODES.M) // private void mayRequestLocation() { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // ToastUtil.showLong(context, "Android 6.0"); // REQUEST_FINE_LOCATION); // return; // } else { // } else { // @Override // switch (requestCode) { // case REQUEST_FINE_LOCATION: // // If request is cancelled, the result arrays are empty. // if (grantResults.length > 0 // if (mScanning == false) { // startScan(); // } else { // break; @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == Constants.LOCK_CHECK) { if (resultCode == Constants.LOCK_CHECK_OK) { unlock(); } else { ToastUtil.showShort(context, ""); } } } }
package com.ss.editor.model.workspace; import static com.ss.editor.util.EditorUtil.getAssetFile; import static com.ss.editor.util.EditorUtil.toAssetPath; import static com.ss.rlib.util.ClassUtils.unsafeCast; import static com.ss.rlib.util.ObjectUtils.notNull; import com.ss.editor.manager.WorkspaceManager; import com.ss.editor.ui.component.editor.EditorDescription; import com.ss.editor.ui.component.editor.FileEditor; import com.ss.editor.ui.component.editor.state.EditorState; import com.ss.editor.util.EditorUtil; import com.ss.rlib.logging.Logger; import com.ss.rlib.logging.LoggerManager; import com.ss.rlib.util.StringUtils; import com.ss.rlib.util.array.Array; import com.ss.rlib.util.array.ArrayFactory; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.io.Serializable; import java.nio.ByteBuffer; import java.nio.channels.SeekableByteChannel; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; /** * The workspace of an editor. * * @author JavaSaBr */ public class Workspace implements Serializable { /** * The constant serialVersionUID. */ public static final long serialVersionUID = 63; @NotNull private static final Logger LOGGER = LoggerManager.getLogger(Workspace.class); /** * The changes counter. */ @NotNull private final AtomicInteger changes; /** * The asset folder of this workspace. */ @Nullable private volatile transient Path assetFolder; /** * The list of expanded folders. */ @Nullable private volatile List<String> expandedFolders; /** * The table of opened files. */ @Nullable private volatile Map<String, String> openedFiles; /** * The table with states of editors. */ @Nullable private volatile Map<String, EditorState> editorStateMap; /** * The current edited file. */ @Nullable private volatile String currentEditedFile; /** * Instantiates a new Workspace. */ public Workspace() { this.changes = new AtomicInteger(); } /** * Notify about finished restoring this workspace. */ public void notifyRestored() { if (openedFiles == null) { openedFiles = new HashMap<>(); } if (editorStateMap == null) { editorStateMap = new HashMap<>(); } else { editorStateMap.forEach((key, editorState) -> editorState.setChangeHandler(this::incrementChanges)); } if (expandedFolders == null) { expandedFolders = new ArrayList<>(); } } /** * Gets current edited file. * * @return the current edited file. */ @Nullable public String getCurrentEditedFile() { return currentEditedFile; } /** * Update a current edited file. * * @param file the current edited file. */ public synchronized void updateCurrentEditedFile(@Nullable final Path file) { if (file == null) { this.currentEditedFile = null; return; } final Path assetFile = getAssetFile(getAssetFolder(), file); this.currentEditedFile = toAssetPath(assetFile); } /** * @return the table with states of editors. */ @NotNull private Map<String, EditorState> getEditorStateMap() { return notNull(editorStateMap); } /** * @return the list of expanded folders. */ @NotNull private List<String> getExpandedFolders() { return notNull(expandedFolders); } /** * Gets expanded absolute folders. * * @return the list of expanded absolute folders. */ @NotNull public synchronized Array<Path> getExpandedAbsoluteFolders() { final Array<Path> result = ArrayFactory.newArray(Path.class); final Path assetFolder = getAssetFolder(); final List<String> expandedFolders = getExpandedFolders(); expandedFolders.forEach(path -> result.add(assetFolder.resolve(path))); return result; } /** * Update a list of expanded folders. * * @param folders the folders */ public synchronized void updateExpandedFolders(@NotNull final Array<Path> folders) { final List<String> expandedFolders = getExpandedFolders(); expandedFolders.clear(); final Path assetFolder = getAssetFolder(); folders.forEach(path -> expandedFolders.add(assetFolder.relativize(path).toString())); incrementChanges(); } /** * Get an editor state for a file. * * @param <T> the type parameter * @param file the edited file. * @param stateFactory the state factory. * @return the state of the editor. */ @NotNull public synchronized <T extends EditorState> T getEditorState(@NotNull final Path file, @NotNull final Supplier<EditorState> stateFactory) { final Path assetFile = getAssetFile(getAssetFolder(), file); final String assetPath = toAssetPath(assetFile); final Map<String, EditorState> editorStateMap = getEditorStateMap(); if (!editorStateMap.containsKey(assetPath)) { final EditorState editorState = stateFactory.get(); editorState.setChangeHandler(this::incrementChanges); editorStateMap.put(assetPath, editorState); incrementChanges(); } return unsafeCast(editorStateMap.get(assetPath)); } /** * Update an editor state of a file. * * @param file the file. * @param editorState the editor state. */ public synchronized void updateEditorState(@NotNull final Path file, @NotNull final EditorState editorState) { final Path assetFile = getAssetFile(getAssetFolder(), file); final String assetPath = toAssetPath(assetFile); final Map<String, EditorState> editorStateMap = getEditorStateMap(); editorStateMap.put(assetPath, editorState); incrementChanges(); } /** * Remove an editor state of a file. * * @param file the file. */ public synchronized void removeEditorState(@NotNull final Path file) { final Path assetFile = getAssetFile(getAssetFolder(), file); final String assetPath = toAssetPath(assetFile); final Map<String, EditorState> editorStateMap = getEditorStateMap(); if (editorStateMap.remove(assetPath) == null) return; incrementChanges(); } /** * Update an editor state for moved/renamed file. * * @param prevFile the previous file. * @param newFile the new file. */ public synchronized void updateEditorState(@NotNull final Path prevFile, @NotNull final Path newFile) { final Path prevAssetFile = getAssetFile(getAssetFolder(), prevFile); final String prevAssetPath = toAssetPath(prevAssetFile); final Map<String, EditorState> editorStateMap = getEditorStateMap(); final EditorState editorState = editorStateMap.remove(prevAssetPath); if (editorState == null) return; final Path newAssetFile = getAssetFile(getAssetFolder(), newFile); final String newAssetPath = toAssetPath(newAssetFile); editorStateMap.put(newAssetPath, editorState); incrementChanges(); } /** * Sets asset folder. * * @param assetFolder the asset folder of this workspace. */ public void setAssetFolder(@NotNull final Path assetFolder) { this.assetFolder = assetFolder; } /** * Gets opened files. * * @return the table of opened files. */ @NotNull public Map<String, String> getOpenedFiles() { return notNull(openedFiles); } /** * Add a new opened file. * * @param file the opened file. * @param fileEditor the editor. */ public synchronized void addOpenedFile(@NotNull final Path file, @NotNull final FileEditor fileEditor) { final Path assetFile = getAssetFile(getAssetFolder(), file); final String assetPath = toAssetPath(assetFile); final EditorDescription description = fileEditor.getDescription(); final Map<String, String> openedFiles = getOpenedFiles(); final String previous = openedFiles.put(assetPath, description.getEditorId()); if (StringUtils.equals(previous, description.getEditorId())) return; incrementChanges(); } /** * Remove an opened file. * * @param file the removed file. */ public synchronized void removeOpenedFile(@NotNull final Path file) { final Path assetFile = getAssetFile(getAssetFolder(), file); final String assetPath = toAssetPath(assetFile); final Map<String, String> openedFiles = getOpenedFiles(); openedFiles.remove(assetPath); incrementChanges(); } /** * Gets asset folder. * * @return the asset folder of this workspace. */ @NotNull public Path getAssetFolder() { return notNull(assetFolder); } /** * Increase a counter of changes. */ private void incrementChanges() { changes.incrementAndGet(); } /** * Clear this workspace. */ public void clear() { getOpenedFiles().clear(); } /** * Save this workspace. * * @param force the force */ public void save(final boolean force) { if (!force && changes.get() == 0) return; final Path assetFolder = getAssetFolder(); if (!Files.exists(assetFolder)) return; final Path workspaceFile = assetFolder.resolve(WorkspaceManager.FOLDER_EDITOR) .resolve(WorkspaceManager.FILE_WORKSPACE); try { if (!Files.exists(workspaceFile)) { Files.createDirectories(workspaceFile.getParent()); Files.createFile(workspaceFile); } } catch (final IOException e) { LOGGER.warning(e); } try { final Boolean hidden = (Boolean) Files.getAttribute(workspaceFile, "dos:hidden", LinkOption.NOFOLLOW_LINKS); if (hidden != null && !hidden) { Files.setAttribute(workspaceFile, "dos:hidden", Boolean.TRUE, LinkOption.NOFOLLOW_LINKS); } } catch (final UnsupportedOperationException | IllegalArgumentException e) { // we can igone that } catch (final IOException e) { LOGGER.warning(e); } changes.set(0); final byte[] serialize = EditorUtil.serialize(this); try (final SeekableByteChannel channel = Files.newByteChannel(workspaceFile, StandardOpenOption.WRITE)) { final ByteBuffer buffer = ByteBuffer.wrap(serialize); buffer.position(serialize.length); buffer.flip(); channel.write(buffer); } catch (final IOException e) { LOGGER.warning(e); } } }
package com.subgraph.orchid.crypto; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.interfaces.RSAPublicKey; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import com.subgraph.orchid.TorException; import com.subgraph.orchid.data.HexDigest; /** * This class wraps the RSA public keys used in the Tor protocol. */ public class TorPublicKey { static public TorPublicKey createFromPEMBuffer(String buffer) throws GeneralSecurityException { final RSAKeyEncoder encoder = new RSAKeyEncoder(); RSAPublicKey pkey = encoder.parsePEMPublicKey(buffer); return new TorPublicKey(pkey); } private final RSAPublicKey key; private HexDigest keyFingerprint = null; public TorPublicKey(RSAPublicKey key) { this.key = key; } public HexDigest getFingerprint() { if(keyFingerprint == null) { final RSAKeyEncoder encoder = new RSAKeyEncoder(); keyFingerprint = HexDigest.createDigestForData(encoder.getPKCS1Encoded(key)); } return keyFingerprint; } public boolean verifySignature(TorSignature signature, HexDigest digest) { return verifySignatureFromDigestBytes(signature, digest.getRawBytes()); } public boolean verifySignature(TorSignature signature, TorMessageDigest digest) { return verifySignatureFromDigestBytes(signature, digest.getDigestBytes()); } public boolean verifySignatureFromDigestBytes(TorSignature signature, byte[] digestBytes) { final Cipher cipher = createCipherInstance(); try { byte[] decrypted = cipher.doFinal(signature.getSignatureBytes()); return constantTimeArrayEquals(decrypted, digestBytes); } catch (IllegalBlockSizeException e) { throw new TorException(e); } catch (BadPaddingException e) { throw new TorException(e); } } private boolean constantTimeArrayEquals(byte[] a1, byte[] a2) { if(a1.length != a2.length) return false; int result = 0; for(int i = 0; i < a1.length; i++) result += (a1[i] & 0xFF) ^ (a2[i] & 0xFF); return result == 0; } private Cipher createCipherInstance() { try { Cipher cipher = getCipherInstance(); cipher.init(Cipher.DECRYPT_MODE, key); return cipher; } catch (InvalidKeyException e) { throw new TorException(e); } } private Cipher getCipherInstance() { try { try { return Cipher.getInstance("RSA/ECB/PKCS1Padding", "SunJCE"); } catch (NoSuchProviderException e) { return Cipher.getInstance("RSA/ECB/PKCS1Padding"); } } catch (NoSuchAlgorithmException e) { throw new TorException(e); } catch (NoSuchPaddingException e) { throw new TorException(e); } } public RSAPublicKey getRSAPublicKey() { return key; } public String toString() { return "Tor Public Key: " + getFingerprint(); } public boolean equals(Object o) { if(!(o instanceof TorPublicKey)) return false; final TorPublicKey other = (TorPublicKey) o; return other.getFingerprint().equals(getFingerprint()); } public int hashCode() { return getFingerprint().hashCode(); } }
package com.swabunga.spell.engine; /** * @author aim4min * */ public abstract class Configuration { /** * used by EditDistance: the cost of having to remove a character */ public static final String COST_REMOVE_CHAR = "EDIT_DEL1"; /** * used by EditDistance: the cost of having to insert a character */ public static final String COST_INSERT_CHAR = "EDIT_DEL2"; /** * used by EditDistance: the cost of having to swap two adjoinging characters * for the swap value to ever be used, it should be smaller than the insert or delete values */ public static final String COST_SWAP_CHARS = "EDIT_SWAP"; /** * used by EditDistance: the cost of having to substitute one character for another * for the sub value to ever be used, it should be smaller than the insert or delete values */ public static final String COST_SUBST_CHARS = "EDIT_SUB"; // public static final String EDIT_SIMILAR = "EDIT_SIMILAR"; //DMV: these does not seem to be used at all // public static final String EDIT_MIN = "EDIT_MIN"; // public static final String EDIT_MAX = "EDIT_MAX"; public static final String SPELL_THRESHOLD = "SPELL_THRESHOLD"; public static final String SPELL_IGNOREUPPERCASE = "SPELL_IGNOREUPPERCASE"; public static final String SPELL_IGNOREMIXEDCASE = "SPELL_IGNOREMIXEDCASE"; public static final String SPELL_IGNOREINTERNETADDRESSES = "SPELL_IGNOREINTERNETADDRESS"; public static final String SPELL_IGNOREDIGITWORDS = "SPELL_IGNOREDIGITWORDS"; public static final String SPELL_IGNOREMULTIPLEWORDS = "SPELL_IGNOREMULTIPLEWORDS"; public static final String SPELL_IGNORESENTENCECAPITALIZATION = "SPELL_IGNORESENTENCECAPTILIZATION"; public abstract int getInteger(String key); public abstract boolean getBoolean(String key); public abstract void setInteger(String key, int value); public abstract void setBoolean(String key, boolean value); public static final Configuration getConfiguration() { return getConfiguration(null); } public static final Configuration getConfiguration(String config) { Configuration result; if (config != null && config.length() > 0) { try { result = (Configuration)Class.forName(config).newInstance(); } catch (InstantiationException e) { result = new PropertyConfiguration(); } catch (IllegalAccessException e) { result = new PropertyConfiguration(); } catch (ClassNotFoundException e) { result = new PropertyConfiguration(); } } else { result = new PropertyConfiguration(); } return result; } }
package com.volumetricpixels.vitals.main; import org.spout.api.command.annotated.AnnotatedCommandRegistrationFactory; import org.spout.api.command.annotated.SimpleInjector; import org.spout.api.plugin.CommonPlugin; import com.volumetricpixels.vitals.main.commands.AdminCommands; import com.volumetricpixels.vitals.main.commands.GeneralCommands; import com.volumetricpixels.vitals.main.commands.ProtectionCommands; import com.volumetricpixels.vitals.main.commands.WorldCommands; import com.volumetricpixels.vitals.main.configuration.VitalsConfiguration; public class Vitals extends CommonPlugin { private VitalsConfiguration config; @Override public void onDisable() { getLogger().info("[Vitals] v" + getDescription().getVersion() + " disabled!"); } @Override public void onEnable() { config = new VitalsConfiguration(getDataFolder()); // Register commands. AnnotatedCommandRegistrationFactory commandRegistration = new AnnotatedCommandRegistrationFactory(new SimpleInjector(this)); getEngine().getRootCommand().addSubCommands(this, AdminCommands.class, commandRegistration); getEngine().getRootCommand().addSubCommands(this, GeneralCommands.class, commandRegistration); getEngine().getRootCommand().addSubCommands(this, ProtectionCommands.class, commandRegistration); getEngine().getRootCommand().addSubCommands(this, WorldCommands.class, commandRegistration); getLogger().info("[Vitals] v" + getDescription().getVersion() + " enabled!"); } public VitalsConfiguration getConfig() { return config; } }
/*/ Mirror Core * wckd Development * Brett Crawford */ package com.wckd_dev.mirror.core; import java.util.Scanner; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Dialog; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.ActivityInfo; import android.content.res.Resources; import android.graphics.Matrix; import android.graphics.PointF; import android.hardware.Camera; import android.hardware.Camera.CameraInfo; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore.Images; import android.provider.Settings; import android.provider.Settings.SettingNotFoundException; import android.util.FloatMath; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.Window; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.Toast; public class MirrorActivity extends Activity implements OnTouchListener { private final String TAG = "wckd"; /* Intent variables */ protected final static String MIRROR_MESSAGE = "com.wckd_dev.mirror.core.MESSAGE"; private String intentMessage; private String store; protected String version; protected String dialogAppInfoText; /* Constants for Calling Dialogs */ protected static final int WELCOME_DIALOG = 1; protected static final int SNAPSHOT_DIALOG = 2; protected static final int SNAPSHOT_SIZE = 3; protected static final int PHOTOSTRIP_DIALOG = 4; protected static final int FRAME_STYLE_DIALOG = 5; protected static final int ZOOM_DIALOG = 6; protected static final int EXPOSURE_DIALOG = 7; protected static final int THEME_DIALOG = 8; protected static final int APP_INFO_DIALOG = 9; protected static final int HELP_DIALOG = 10; protected static final int FRONT_CAMERA_NOT_FOUND = 11; protected static final int CAMERA_NOT_FOUND = 12; protected static final int UPGRADE = 13; protected static final int RATE = 14; protected static final int PAUSE_DIALOG = 15; protected static final int WELCOME_ONE_DIALOG = 16; protected static final int WELCOME_TWO_DIALOG = 17; /** Change between 1 and 2 to display one time messages to users after upgrades */ private final int INFO_DIALOGS = 2; // v2.4 set to 2 for release /* Preferences Strings*/ protected static final String APP_PREFERENCES = "AppPrefs"; protected static final String APP_PREFERENCES_ORIENTATION = "Orientation"; protected static final String APP_PREFERENCES_REVERSE = "Reverse"; protected static final String APP_PREFERENCES_FLIP = "Flip"; protected static final String APP_PREFERENCES_FRAME = "Frame"; protected static final String APP_PREFERENCES_FRAME_CHANGED = "FrameChanged"; protected static final String APP_PREFERENCES_INITIAL_LOAD_ONE = "InitialLoadOne"; protected static final String APP_PREFERENCES_INITIAL_LOAD_TWO = "InitialLoadTwo"; protected static final String APP_PREFERENCES_INITIAL_PAUSE = "InitialPause"; protected static final String APP_PREFERENCES_INITIAL_SNAPSHOT = "InitialSnapshot"; protected static final String APP_PREFERENCES_INITIAL_PHOTOBOOTH = "InitialPhotoBooth"; protected static final String APP_PREFERENCES_THEME = "Theme"; protected static final String APP_PREFERENCES_EXPOSURE = "Exposure"; protected static final String APP_PREFERENCES_WHITE_BALANCE = "WhiteBalance"; protected static final String APP_PREFERENCES_ZOOM = "Zoom"; protected static final String APP_PREFERENCES_HAS_RATED = "HasRated"; protected static final String APP_PREFERENCES_USE_COUNT = "UseCount"; protected static final String APP_PREFERENCES_SNAPSHOT_SIZE = "SnapshotSize"; protected static final String APP_PREFERENCES_BRIGHTNESS = "Brightness"; protected static final String APP_PREFERENCES_BRIGHTNESS_MODE = "BrightnessMode"; protected static final String APP_PREFERENCES_BRIGHTNESS_LEVEL = "BrightnessLevel"; /* Preferences */ private int reversePref; private int flipPref; private int orientationPref; private int frameModePref; private int framePacksPref; private int initialLoadOnePref; private int initialLoadTwoPref; private int initialPausePref; private int initialSnapshotPref; private int initialPhotoBoothPref; protected int themePref; private String themeColor; private int exposurePref; private int whiteBalancePref; private float zoomPrefF; protected int hasRatedPref; private int useCountPref; private int snapshotSizePref; private int brightnessPref; private int brightnessModePref; private int brightnessLevelPref; /* Camera */ private int numberOfCameras; private int currentCameraId; private int backCameraId; private int frontCameraId; private int photoBoothCount = 0; // Paid Only /* Flags */ private boolean isPaused = false; private boolean isPreviewStopped = false; private boolean isBackCameraFound = false; private boolean isFrontCameraFound = false; private boolean isUsingFrontCamera = false; protected boolean isZoomSupported = false; protected boolean isExposureSupported = false; private boolean isWhiteBalanceSupported = false; private boolean isFullscreen = true; private boolean isMirrorMode = true; private boolean isPortrait; private boolean isPauseButtonVisible = false; private boolean isSnapshotButtonVisible = false; private boolean isPhotoBoothButtonVisible = false; private boolean isBrightness = false; /* Objects */ private Camera camera = null; private MirrorView mirrorView; protected SharedPreferences appSettings; protected Dialog dialog; private MenuItem menuItemWhiteBalance; private MenuItem menuItemMirrorModeOn; private MenuItem menuItemMirrorModeOff; private Animation slideUp, slideDown; private Animation rightSlideIn, rightSlideOut; private Animation leftSlideIn, leftSlideOut; private ImageButton pause, takeSnapshot, takePhotoBooth; protected FrameManager frameMgr; private Snapshot snapshot; // Paid/Ads Only protected Snapshot.ImageSize imageSize = Snapshot.ImageSize.LARGE; // Paid/Ads Only private PhotoBooth booth; // Paid/Ads Only /* Touch */ private Matrix matrix; private Matrix savedMatrix; private static final int NONE = 0; private static final int PRESS = 1; private static final int DRAG = 2; private static final int ZOOM = 3; private int touchState = NONE; private PointF start = new PointF(); private PointF mid = new PointF(); private float startDist = 1f; private float lastDist = 0f; private float minDist = 10f; private float zoomRate = 0f; /* Brightness */ private ContentResolver conRes; /* Store Links */ protected static String rateLink; protected static String upgradeAdsLink; protected static String upgradePaidLink; protected static String frameLink; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initIntentInfo(); initPrefs(); initTheme(); initWindowFeatures(); initContentView(); initMirrorView(); initFrameManager(); initCamera(); initPauseButton(); initSnapshotButton(); initPhotoBoothButton(); initOnTouchListener(); initBrightnessSettings(); showWelcomeOneDialog(); } @Override protected void onStart() { super.onStart(); } @Override protected void onResume() { super.onResume(); loadCamera(); } @Override protected void onPause() { super.onPause(); unloadCamera(); restoreBrightnessSettings(false); // Save preferences Editor editor = appSettings.edit(); editor.putString(APP_PREFERENCES_REVERSE, Integer.toString(reversePref)); editor.putString(APP_PREFERENCES_FLIP, Integer.toString(flipPref)); editor.putString(APP_PREFERENCES_ORIENTATION, Integer.toString(orientationPref)); editor.putString(APP_PREFERENCES_FRAME, Integer.toString(frameModePref)); editor.putString(APP_PREFERENCES_FRAME_CHANGED, Integer.toString(framePacksPref)); editor.putString(APP_PREFERENCES_EXPOSURE, Integer.toString(exposurePref)); editor.putString(APP_PREFERENCES_WHITE_BALANCE, Integer.toString(whiteBalancePref)); editor.putString(APP_PREFERENCES_ZOOM, Integer.toString(Math.round(zoomPrefF))); editor.putString(APP_PREFERENCES_HAS_RATED, Integer.toString(hasRatedPref)); editor.putString(APP_PREFERENCES_USE_COUNT, Integer.toString(useCountPref)); editor.putString(APP_PREFERENCES_SNAPSHOT_SIZE, Integer.toString(snapshotSizePref)); editor.putString(APP_PREFERENCES_BRIGHTNESS, Integer.toString(brightnessPref)); editor.putString(APP_PREFERENCES_BRIGHTNESS_MODE, Integer.toString(brightnessModePref)); editor.putString(APP_PREFERENCES_BRIGHTNESS_LEVEL, Integer.toString(brightnessLevelPref)); editor.commit(); } @Override protected void onStop() { super.onStop(); } @Override protected void onDestroy() { super.onDestroy(); } @Override public void onBackPressed() { if(version.compareTo("paid") != 0 && hasRatedPref == 0 && useCountPref > 6) displayDialog(RATE); else { useCountPref++; MirrorActivity.this.finish(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); if(reversePref == 0) { mirrorView.mirrorMode(false); isMirrorMode = false; } if(flipPref == 0) { (menu.findItem(R.id.menu_options_flip_mode_off)).setChecked(true); } else { (menu.findItem(R.id.menu_options_flip_mode_on)).setChecked(true); mirrorView.flipMode(true); } if(Math.round(zoomPrefF) > 0) setZoom(Math.round(zoomPrefF)); // Set the zoom preference if(brightnessPref == 0) { (menu.findItem(R.id.menu_options_brightness_off)).setChecked(true); } else { (menu.findItem(R.id.menu_options_brightness_on)).setChecked(true); } if(exposurePref != -999) { // If exposure pref is valid try { setExposure(exposurePref); // Set the exposure preference } catch(RuntimeException e) { // No action taken. Exposure settings will not be used. } } menuItemWhiteBalance = menu.findItem(R.id.menu_options_white_balance); if(whiteBalancePref != 0) setWhiteBalance(whiteBalancePref); // Set the white balance preference if(numberOfCameras > 1) { (menu.findItem(R.id.menu_options_switch_camera)).setEnabled(true); (menu.findItem(R.id.menu_options_switch_camera)).setVisible(true); } if(isPortrait) { (menu.findItem(R.id.menu_options_screen_rotation_portrait)).setChecked(true); } else { (menu.findItem(R.id.menu_options_screen_rotation_landscape)).setChecked(true); } if(version.compareTo("free") != 0) { if(snapshotSizePref == 2) { (menu.findItem(R.id.menu_options_snapshot_size_small)).setChecked(true); } else if(snapshotSizePref == 1) { (menu.findItem(R.id.menu_options_snapshot_size_medium)).setChecked(true); } else { (menu.findItem(R.id.menu_options_snapshot_size_large)).setChecked(true); } } else { (menu.findItem(R.id.menu_options_snapshot_size)).setEnabled(false); (menu.findItem(R.id.menu_options_snapshot_size)).setVisible(false); } return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { menuItemWhiteBalance = menu.findItem(R.id.menu_options_white_balance); menuItemMirrorModeOn = menu.findItem(R.id.menu_options_mirror_mode_on); menuItemMirrorModeOff = menu.findItem(R.id.menu_options_mirror_mode_off); //menuItemFlipModeOn = menu.findItem(R.id.menu_options_flip_mode_on); //menuItemFlipModeOff = menu.findItem(R.id.menu_options_flip_mode_off); if(reversePref == 0) { menuItemMirrorModeOff.setChecked(true); } //if(flipPref == 0) { // menuItemFlipModeOff.setChecked(true); if(snapshotSizePref == 2) { (menu.findItem(R.id.menu_options_snapshot_size_small)).setChecked(true); } else if(snapshotSizePref == 1) { (menu.findItem(R.id.menu_options_snapshot_size_medium)).setChecked(true); } else { (menu.findItem(R.id.menu_options_snapshot_size_large)).setChecked(true); } return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { boolean result = false; int id = item.getItemId(); /* Snapshot */ if(id == R.id.menu_snapshot_snapshot) { if(isSnapshotButtonVisible) { // Hide snapshot button takeSnapshot.startAnimation(rightSlideOut); takeSnapshot.setVisibility(View.INVISIBLE); isSnapshotButtonVisible = false; } else { // Show snapshot button if(isPhotoBoothButtonVisible) { takePhotoBooth.startAnimation(leftSlideOut); takePhotoBooth.setVisibility(View.INVISIBLE); isPhotoBoothButtonVisible = false; booth = null; // Paid Only photoBoothCount = 0; // Paid Only } if(isPauseButtonVisible) { pause.startAnimation(slideDown); pause.setVisibility(View.INVISIBLE); isPauseButtonVisible = false; } takeSnapshot.startAnimation(rightSlideIn); takeSnapshot.setVisibility(View.VISIBLE); isSnapshotButtonVisible = true; showSnapshotDialog(); } result = true; } /* Photobooth */ else if(id == R.id.menu_snapshot_photobooth) { showPhotoBoothDialog(); if(isPhotoBoothButtonVisible) { takePhotoBooth.startAnimation(leftSlideOut); takePhotoBooth.setVisibility(View.INVISIBLE); isPhotoBoothButtonVisible = false; booth = null; // Paid Only photoBoothCount = 0; // Paid Only } else { if(isSnapshotButtonVisible) { takeSnapshot.startAnimation(rightSlideOut); takeSnapshot.setVisibility(View.INVISIBLE); isSnapshotButtonVisible = false; } if(isPauseButtonVisible) { pause.startAnimation(slideDown); pause.setVisibility(View.INVISIBLE); isPauseButtonVisible = false; } takePhotoBooth.startAnimation(leftSlideIn); takePhotoBooth.setVisibility(View.VISIBLE); isPhotoBoothButtonVisible = true; } result = true; } /* Pause */ else if(id == R.id.menu_pause) { showPauseDialog(); if(isPauseButtonVisible) { pause.startAnimation(slideDown); pause.setVisibility(View.INVISIBLE); isPauseButtonVisible = false; } else { if(isPhotoBoothButtonVisible) { takePhotoBooth.startAnimation(leftSlideOut); takePhotoBooth.setVisibility(View.INVISIBLE); isPhotoBoothButtonVisible = false; booth = null; // Paid Only photoBoothCount = 0; // Paid Only } if(isSnapshotButtonVisible) { takeSnapshot.startAnimation(rightSlideOut); takeSnapshot.setVisibility(View.INVISIBLE); isSnapshotButtonVisible = false; } pause.startAnimation(slideUp); pause.setVisibility(View.VISIBLE); isPauseButtonVisible = true; } result = true; } /* Frames */ else if(id == R.id.menu_frame) { displayDialog(FRAME_STYLE_DIALOG); result = true; } /* Zoom */ else if(id == R.id.menu_options_zoom) { displayDialog(ZOOM_DIALOG); result = true; } /* Brightness On */ else if(id == R.id.menu_options_brightness_on) { if(!isBrightness) { isBrightness = true; brightnessPref = 1; item.setChecked(true); initBrightnessSettings(); } result = true; } /* Brightness Off */ else if(id == R.id.menu_options_brightness_off) { if(isBrightness) { isBrightness = false; brightnessPref = 0; item.setChecked(true); restoreBrightnessSettings(true); } result = true; } /* Exposure */ else if(id == R.id.menu_options_exposure) { displayDialog(EXPOSURE_DIALOG); result = true; } /* White Balance Auto */ else if(id == R.id.menu_options_white_balance_auto) { if(isWhiteBalanceSupported) setWhiteBalance(0); else Toast.makeText(getApplicationContext(), R.string.toast_no_white_balance, Toast.LENGTH_SHORT).show(); result = true; } /* White Balance Daylight */ else if(id == R.id.menu_options_white_balance_daylight) { if(isWhiteBalanceSupported) setWhiteBalance(1); else Toast.makeText(getApplicationContext(), R.string.toast_no_white_balance, Toast.LENGTH_SHORT).show(); result = true; } /* White Balance Incandescent */ else if(id == R.id.menu_options_white_balance_incandescent) { if(isWhiteBalanceSupported) setWhiteBalance(2); else Toast.makeText(getApplicationContext(), R.string.toast_no_white_balance, Toast.LENGTH_SHORT).show(); result = true; } /* White Balance Fluorescent */ else if(id == R.id.menu_options_white_balance_fluorescent) { if(isWhiteBalanceSupported) setWhiteBalance(3); else Toast.makeText(getApplicationContext(), R.string.toast_no_white_balance, Toast.LENGTH_SHORT).show(); result = true; } /* Mirror Mode On */ else if(id == R.id.menu_options_mirror_mode_on) { if(!isMirrorMode) { mirrorView.mirrorMode(true); isMirrorMode = true; reversePref = 1; item.setChecked(true); } result = true; } /* Mirror Mode Off */ else if(id == R.id.menu_options_mirror_mode_off) { if(isMirrorMode) { mirrorView.mirrorMode(false); isMirrorMode = false; reversePref = 0; item.setChecked(true); } result = true; } /* Flip Mode On */ else if(id == R.id.menu_options_flip_mode_on) { flipPref = 1; item.setChecked(true); mirrorView.flipMode(true); } /* Flip Mode Off */ else if(id == R.id.menu_options_flip_mode_off) { flipPref = 0; item.setChecked(true); mirrorView.flipMode(false); } /* Switch Camera */ else if(id == R. id.menu_options_switch_camera) { unloadCamera(); if(isUsingFrontCamera) { currentCameraId = backCameraId; isUsingFrontCamera = false; } else { currentCameraId = frontCameraId; isUsingFrontCamera = true; } loadCamera(); result = true; } /* Screen Rotation Portrait */ else if(id == R.id.menu_options_screen_rotation_portrait) { if(!isPortrait) { isMirrorMode = true; reversePref = 1; mirrorView.mirrorMode(true); menuItemMirrorModeOn.setChecked(true); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); mirrorView.isPortrait = isPortrait = true; camera.setDisplayOrientation(90); setFrame(0); orientationPref = 0; item.setChecked(true); } result = true; } /* Screen Rotation Landscape */ else if(id == R.id.menu_options_screen_rotation_landscape) { if(isPortrait) { isMirrorMode = true; reversePref = 1; mirrorView.mirrorMode(true); menuItemMirrorModeOn.setChecked(true); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); mirrorView.isPortrait = isPortrait = false; camera.setDisplayOrientation(0); setFrame(0); orientationPref = 1; item.setChecked(true); } result = true; } /* Dark Theme */ else if(id == R.id.menu_options_theme_dark) { themePref = 1; displayDialog(THEME_DIALOG); result = true; } /* Light Theme */ else if(id == R.id.menu_options_theme_light) { themePref = 2; displayDialog(THEME_DIALOG); result = true; } /* RedTheme */ else if(id == R.id.menu_options_theme_red) { if(version.compareTo("free") != 0) { themePref = 3; displayDialog(THEME_DIALOG); } else displayDialog(UPGRADE); result = true; } /* Orange Theme */ else if(id == R.id.menu_options_theme_orange) { if(version.compareTo("free") != 0) { themePref = 4; displayDialog(THEME_DIALOG); } else displayDialog(UPGRADE); result = true; } /* Green Theme */ else if(id == R.id.menu_options_theme_green) { if(version.compareTo("free") != 0) { themePref = 5; displayDialog(THEME_DIALOG); } else displayDialog(UPGRADE); result = true; } /* Purple Theme */ else if(id == R.id.menu_options_theme_purple) { if(version.compareTo("free") != 0) { themePref = 6; displayDialog(THEME_DIALOG); } else displayDialog(UPGRADE); result = true; } /* Blue Theme */ else if(id == R.id.menu_options_theme_blue) { if(version.compareTo("free") != 0) { themePref = 7; displayDialog(THEME_DIALOG); } else displayDialog(UPGRADE); result = true; } /* Snapshot Size Large */ else if(id == R.id.menu_options_snapshot_size_large) { snapshotSizePref = 0; item.setChecked(true); } /* Snapshot Size Medium */ else if(id == R.id.menu_options_snapshot_size_medium) { snapshotSizePref = 1; item.setChecked(true); } /* Snapshot Size Small */ else if(id == R.id.menu_options_snapshot_size_small) { snapshotSizePref = 2; item.setChecked(true); } /* App Info */ else if(id == R.id.menu_options_app_info) { displayDialog(APP_INFO_DIALOG); result = true; } /* Help */ else if(id == R.id.menu_options_help) { displayDialog(HELP_DIALOG); result = true; } /* Exit */ else if(id == R.id.menu_exit) { if(version.compareTo("paid") != 0 && hasRatedPref == 0 && useCountPref > 6) displayDialog(RATE); else { useCountPref++; MirrorActivity.this.finish(); } } else result = super.onOptionsItemSelected(item); return result; } private void initIntentInfo() { // Get information from the intent intentMessage = getIntent().getStringExtra(MIRROR_MESSAGE); Scanner message = new Scanner(intentMessage); store = message.next(); version = message.next(); rateLink = message.next(); upgradePaidLink = message.next(); frameLink = message.next(); message.useDelimiter("&"); dialogAppInfoText = message.next(); } private void initPrefs() { appSettings = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE); reversePref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_REVERSE, "1")); flipPref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_FLIP, "0")); orientationPref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_ORIENTATION, "0")); frameModePref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_FRAME, "0")); framePacksPref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_FRAME_CHANGED, "0")); initialLoadOnePref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_INITIAL_LOAD_ONE, "0")); initialLoadTwoPref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_INITIAL_LOAD_TWO, "0")); initialPausePref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_INITIAL_PAUSE, "0")); initialSnapshotPref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_INITIAL_SNAPSHOT, "0")); initialPhotoBoothPref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_INITIAL_PHOTOBOOTH, "0")); themePref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_THEME, "2")); exposurePref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_EXPOSURE, "-999")); whiteBalancePref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_WHITE_BALANCE, "0")); zoomPrefF = Integer.parseInt(appSettings.getString(APP_PREFERENCES_ZOOM, "0")); hasRatedPref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_HAS_RATED, "0")); useCountPref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_USE_COUNT, "0")); snapshotSizePref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_SNAPSHOT_SIZE, "0")); brightnessPref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_BRIGHTNESS, "0")); brightnessModePref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_BRIGHTNESS_MODE, "1")); brightnessLevelPref = Integer.parseInt(appSettings.getString(APP_PREFERENCES_BRIGHTNESS_LEVEL, "255")); } private void initTheme() { switch(themePref) { case 1: setTheme(R.style.HoloDark); themeColor = "#33B5E5"; break; case 2: setTheme(R.style.HoloLight); themeColor = "#0099CC"; break; case 3: setTheme(R.style.HoloRed); themeColor = "#CC0000"; break; case 4: setTheme(R.style.HoloOrange); themeColor = "#FF8800"; break; case 5: setTheme(R.style.HoloGreen); themeColor = "#669900"; break; case 6: setTheme(R.style.HoloPurple); themeColor = "#9933CC"; break; case 7: setTheme(R.style.HoloBlue); themeColor = "#0099CC"; break; } } private void initWindowFeatures() { if(orientationPref == 0) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); isPortrait = true; } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); isPortrait = false; } if(brightnessPref == 0) { isBrightness = false; } else { isBrightness = true; } getWindow().requestFeature(Window.FEATURE_ACTION_BAR); getActionBar().hide(); getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN); getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE); } private void initContentView() { setContentView(R.layout.main); } private void initMirrorView() { mirrorView = (MirrorView) findViewById(R.id.mirror_view_view); mirrorView.isFullscreen = true; // App starts in fullscreen mode if(isPortrait) { mirrorView.isPortrait = true; } else { mirrorView.isPortrait = false; } } private void initFrameManager() { int numberOfPacks = 0; frameMgr = new FrameManager(getPackageManager()); Resources res = getResources(); if(version.compareTo("free") == 0) { frameMgr.addFrame(res.getIdentifier("com.wckd_dev.mirror:drawable/frame_thumb0", null, null), res.getIdentifier("com.wckd_dev.mirror:drawable/frame0", null, null), res.getString(res.getIdentifier("com.wckd_dev.mirror:string/frame_no_frame", null, null)), res); frameMgr.addFrame(res.getIdentifier("com.wckd_dev.mirror:drawable/frame_thumb1", null, null), res.getIdentifier("com.wckd_dev.mirror:drawable/frame1", null, null), res.getString(res.getIdentifier("com.wckd_dev.mirror:string/frame_low_light", null, null)), res); frameMgr.addFrame(res.getIdentifier("com.wckd_dev.mirror:drawable/frame_thumb2", null, null), res.getIdentifier("com.wckd_dev.mirror:drawable/frame2", null, null), res.getString(res.getIdentifier("com.wckd_dev.mirror:string/frame_soft_gold", null, null)), res); frameMgr.addFrame(res.getIdentifier("com.wckd_dev.mirror:drawable/frame_thumb3", null, null), res.getIdentifier("com.wckd_dev.mirror:drawable/frame3", null, null), res.getString(res.getIdentifier("com.wckd_dev.mirror:string/frame_brushed", null, null)), res); } else if(version.compareTo("paid") == 0) { frameMgr.addFrame(res.getIdentifier("com.wckd_dev.mirror_paid:drawable/frame_thumb0", null, null), res.getIdentifier("com.wckd_dev.mirror_paid:drawable/frame0", null, null), res.getString(res.getIdentifier("com.wckd_dev.mirror_paid:string/frame_no_frame", null, null)), res); frameMgr.addFrame(res.getIdentifier("com.wckd_dev.mirror_paid:drawable/frame_thumb1", null, null), res.getIdentifier("com.wckd_dev.mirror_paid:drawable/frame1", null, null), res.getString(res.getIdentifier("com.wckd_dev.mirror_paid:string/frame_low_light", null, null)), res); frameMgr.addFrame(res.getIdentifier("com.wckd_dev.mirror_paid:drawable/frame_thumb2", null, null), res.getIdentifier("com.wckd_dev.mirror_paid:drawable/frame2", null, null), res.getString(res.getIdentifier("com.wckd_dev.mirror_paid:string/frame_soft_gold", null, null)), res); frameMgr.addFrame(res.getIdentifier("com.wckd_dev.mirror_paid:drawable/frame_thumb3", null, null), res.getIdentifier("com.wckd_dev.mirror_paid:drawable/frame3", null, null), res.getString(res.getIdentifier("com.wckd_dev.mirror_paid:string/frame_brushed", null, null)), res); } else if(version.compareTo("ads") == 0) { frameMgr.addFrame(res.getIdentifier("com.wckd_dev.mirror_ads:drawable/frame_thumb0", null, null), res.getIdentifier("com.wckd_dev.mirror_ads:drawable/frame0", null, null), res.getString(res.getIdentifier("com.wckd_dev.mirror_ads:string/frame_no_frame", null, null)), res); frameMgr.addFrame(res.getIdentifier("com.wckd_dev.mirror_ads:drawable/frame_thumb1", null, null), res.getIdentifier("com.wckd_dev.mirror_ads:drawable/frame1", null, null), res.getString(res.getIdentifier("com.wckd_dev.mirror_ads:string/frame_low_light", null, null)), res); frameMgr.addFrame(res.getIdentifier("com.wckd_dev.mirror_ads:drawable/frame_thumb2", null, null), res.getIdentifier("com.wckd_dev.mirror_ads:drawable/frame2", null, null), res.getString(res.getIdentifier("com.wckd_dev.mirror_ads:string/frame_soft_gold", null, null)), res); frameMgr.addFrame(res.getIdentifier("com.wckd_dev.mirror_ads:drawable/frame_thumb3", null, null), res.getIdentifier("com.wckd_dev.mirror_ads:drawable/frame3", null, null), res.getString(res.getIdentifier("com.wckd_dev.mirror_ads:string/frame_brushed", null, null)), res); } if(frameMgr.hasCFP1()) numberOfPacks++; if(frameMgr.hasCFP2()) numberOfPacks++; if(frameMgr.hasFFP1()) numberOfPacks++; if(frameMgr.hasFFP2()) numberOfPacks++; if(frameMgr.hasNFP1()) numberOfPacks++; if(frameMgr.hasNFP2()) numberOfPacks++; if(frameMgr.hasVFP()) numberOfPacks++; if(numberOfPacks == framePacksPref) // No new frame packs setFrame(frameModePref); // Restore saved preference else { // Packs have been installed/removed setFrame(0); // Default frame used framePacksPref = numberOfPacks; // Record number of packs installed } } private void initCamera() { // Try to find the ID of the front camera numberOfCameras = Camera.getNumberOfCameras(); CameraInfo cameraInfo = new CameraInfo(); for(int i = 0; i < numberOfCameras && !isFrontCameraFound; i++) { Camera.getCameraInfo(i, cameraInfo); if(cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) { backCameraId = i; isBackCameraFound = true; } else if(cameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT) { frontCameraId = i; isFrontCameraFound = true; } } if(isFrontCameraFound) { // If front camera is found, use front camera currentCameraId = frontCameraId; isUsingFrontCamera = true; } else if(!isFrontCameraFound && isBackCameraFound) { // If no front camera and back is found, use back camera currentCameraId = backCameraId; isUsingFrontCamera = false; displayDialog(FRONT_CAMERA_NOT_FOUND); } else if(!isBackCameraFound && !isFrontCameraFound) {// No cameras found displayDialog(CAMERA_NOT_FOUND); } } private void initPauseButton() { // Prepare pause button pause = (ImageButton) findViewById(R.id.pause_button); slideUp = AnimationUtils.loadAnimation(this, R.anim.slide_up); slideDown = AnimationUtils.loadAnimation(this, R.anim.slide_down); pause.startAnimation(slideDown); pause.setVisibility(View.INVISIBLE); pause.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(isPaused) { mirrorView.startPreview(); isPaused = false; } else { mirrorView.stopPreview(); isPaused = true; } } }); } private void initSnapshotButton() { // Prepare snapshot button takeSnapshot = (ImageButton) findViewById(R.id.snapshot_button); rightSlideIn = AnimationUtils.loadAnimation(this, R.anim.right_slide_in); rightSlideOut = AnimationUtils.loadAnimation(this, R.anim.right_slide_out); takeSnapshot.startAnimation(rightSlideOut); takeSnapshot.setVisibility(View.INVISIBLE); takeSnapshot.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(version.compareTo("free") == 0) { displayDialog(UPGRADE); } else { snapshot = new Snapshot(mirrorView, findViewById(R.id.frame_overlay), getApplicationContext()); if(snapshotSizePref == 2) { imageSize = Snapshot.ImageSize.SMALL; } else if(snapshotSizePref == 1) { imageSize = Snapshot.ImageSize.MEDIUM; } else { imageSize = Snapshot.ImageSize.LARGE; } snapshot.takePhoto(imageSize); try { ContentValues values = snapshot.savePhoto(); MirrorActivity.this.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values); } catch(Exception e) { e.printStackTrace(); } snapshot = null; } } }); } private void initPhotoBoothButton() { // Prepare photobooth button takePhotoBooth = (ImageButton) findViewById(R.id.photobooth_button); leftSlideIn = AnimationUtils.loadAnimation(this, R.anim.left_slide_in); leftSlideOut = AnimationUtils.loadAnimation(this, R.anim.left_slide_out); takePhotoBooth.startAnimation(leftSlideOut); takePhotoBooth.setVisibility(View.INVISIBLE); takePhotoBooth.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(version.compareTo("free") == 0) { displayDialog(UPGRADE); } else { try { photoBoothCount++; switch(photoBoothCount) { case 1: booth = new PhotoBooth(mirrorView, findViewById(R.id.frame_overlay), getResources(), getApplicationContext()); booth.takePhotoOne(); break; case 2: booth.takePhotoTwo(); break; case 3: booth.takePhotoThree(); break; case 4: booth.takePhotoFour(); booth.createPhotoStrip(); try { ContentValues values = booth.savePhotoStrip(); MirrorActivity.this.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values); } catch(Exception e) { e.printStackTrace(); throw e; } booth = null; photoBoothCount = 0; break; default: } } catch (Exception e) { e.printStackTrace(); } } } }); } private void initOnTouchListener() { // Initialize onTouchListener ImageView view = (ImageView) findViewById(R.id.invis_button); view.setOnTouchListener(this); matrix = new Matrix(); savedMatrix = new Matrix(); } private void initBrightnessSettings() { conRes = getContentResolver(); if(isBrightness) { try { brightnessModePref = Settings.System.getInt(conRes, Settings.System.SCREEN_BRIGHTNESS_MODE); if(brightnessModePref == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) { Settings.System.putInt(conRes, Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL); } else { brightnessLevelPref = Settings.System.getInt(conRes, Settings.System.SCREEN_BRIGHTNESS); } Settings.System.putInt(conRes, Settings.System.SCREEN_BRIGHTNESS, 255); } catch(SettingNotFoundException e) { Log.e(TAG, "Cannot access system brightness settings."); e.printStackTrace(); } } } private void restoreBrightnessSettings(boolean force) { if(isBrightness || force) { if(brightnessModePref == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) { Settings.System.putInt(conRes, Settings.System.SCREEN_BRIGHTNESS_MODE, brightnessModePref); } else { Settings.System.putInt(conRes, Settings.System.SCREEN_BRIGHTNESS, brightnessLevelPref); } } } protected void initExpSeekBar(SeekBar expSeek) { switch(themePref) { case 1: setTheme(R.style.HoloDark); expSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_dark)); expSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_dark)); break; case 2: setTheme(R.style.HoloLight); expSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_light)); expSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_light)); break; case 3: setTheme(R.style.HoloRed); expSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_red)); expSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_red)); break; case 4: setTheme(R.style.HoloOrange); expSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_orange)); expSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_orange)); break; case 5: setTheme(R.style.HoloGreen); expSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_green)); expSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_green)); break; case 6: setTheme(R.style.HoloPurple); expSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_purple)); expSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_purple)); break; case 7: setTheme(R.style.HoloBlue); expSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_blue)); expSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_blue)); break; } int[] range = mirrorView.getExposureRange(); expSeek.setMax(range[1] - range[0]); expSeek.setProgress(exposurePref == -999 ? (range[1] - range[0]) / 2 : exposurePref); expSeek.setPadding(50, 20, 50, 20); expSeek.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { try { setExposure(seekBar.getProgress()); } catch(RuntimeException e) { } } public void onStartTrackingTouch(SeekBar seekBar) { } public void onStopTrackingTouch(SeekBar seekBar) { try { setExposure(seekBar.getProgress()); } catch(RuntimeException e) { Toast.makeText(getApplicationContext(), R.string.toast_no_exposure, Toast.LENGTH_SHORT).show(); } } }); } protected void initZoomSeekBar(SeekBar zoomSeek) { switch(themePref) { case 1: setTheme(R.style.HoloDark); zoomSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_dark)); zoomSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_dark)); break; case 2: setTheme(R.style.HoloLight); zoomSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_light)); zoomSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_light)); break; case 3: setTheme(R.style.HoloRed); zoomSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_red)); zoomSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_red)); break; case 4: setTheme(R.style.HoloOrange); zoomSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_orange)); zoomSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_orange)); break; case 5: setTheme(R.style.HoloGreen); zoomSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_green)); zoomSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_green)); break; case 6: setTheme(R.style.HoloPurple); zoomSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_purple)); zoomSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_purple)); break; case 7: setTheme(R.style.HoloBlue); zoomSeek.setProgressDrawable(getResources().getDrawable(R.drawable.seekbar_progress_blue)); zoomSeek.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb_blue)); break; } zoomSeek.setMax(mirrorView.getZoomMax()); zoomSeek.setProgress(Math.round(zoomPrefF) == -1 ? 0 : Math.round(zoomPrefF)); zoomSeek.setPadding(50, 20, 50, 20); zoomSeek.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { zoomPrefF = seekBar.getProgress(); setZoom(Math.round(zoomPrefF)); } public void onStartTrackingTouch(SeekBar seekBar) { } public void onStopTrackingTouch(SeekBar seekBar) { zoomPrefF = seekBar.getProgress(); setZoom(Math.round(zoomPrefF)); } }); } // TODO - These show<action>Dialog methods could be condensed into one method // or they could be removed in favor of something else private void showWelcomeOneDialog() { // If first load, first click, display instruction dialog if(initialLoadOnePref != INFO_DIALOGS) { initialLoadOnePref = INFO_DIALOGS; // Set app preferences initial load to false Editor editor = appSettings.edit(); editor.putString(APP_PREFERENCES_INITIAL_LOAD_ONE, Integer.toString(initialLoadOnePref)); editor.commit(); displayCustomDialog(WELCOME_ONE_DIALOG); } } private void showWelcomeTwoDialog() { // If first load, second click, display instruction dialog if(initialLoadOnePref == INFO_DIALOGS && initialLoadTwoPref != INFO_DIALOGS) { initialLoadTwoPref = INFO_DIALOGS; // Set app preferences initial load to false Editor editor = appSettings.edit(); editor.putString(APP_PREFERENCES_INITIAL_LOAD_TWO, Integer.toString(initialLoadTwoPref)); editor.commit(); displayCustomDialog(WELCOME_TWO_DIALOG); } } private void showSnapshotDialog() { // If first button press, display instruction dialog if(initialSnapshotPref != INFO_DIALOGS) { initialSnapshotPref = INFO_DIALOGS; // Set app preferences initial load to false Editor editor = appSettings.edit(); editor.putString(APP_PREFERENCES_INITIAL_SNAPSHOT, Integer.toString(initialSnapshotPref)); editor.commit(); displayCustomDialog(SNAPSHOT_DIALOG); } } private void showPhotoBoothDialog() { // If first button press, display instruction dialog if(initialPhotoBoothPref != INFO_DIALOGS) { initialPhotoBoothPref = INFO_DIALOGS; // Set app preferences initial load to false Editor editor = appSettings.edit(); editor.putString(APP_PREFERENCES_INITIAL_PHOTOBOOTH, Integer.toString(initialPhotoBoothPref)); editor.commit(); displayCustomDialog(PHOTOSTRIP_DIALOG); } } private void showPauseDialog() { // If first button press, display instruction dialog if(initialPausePref != INFO_DIALOGS) { initialPausePref = INFO_DIALOGS; // Set app preferences initial load to false Editor editor = appSettings.edit(); editor.putString(APP_PREFERENCES_INITIAL_PAUSE, Integer.toString(initialPausePref)); editor.commit(); displayCustomDialog(PAUSE_DIALOG); } } private void loadCamera() { if(camera == null) { try { camera = Camera.open(currentCameraId); if(isPortrait) camera.setDisplayOrientation(90); else camera.setDisplayOrientation(0); mirrorView.setCamera(camera); Camera.Parameters parameters = camera.getParameters(); isZoomSupported = parameters.isZoomSupported(); if(parameters.getMinExposureCompensation() != 0 || parameters.getMaxExposureCompensation() != 0 ) isExposureSupported = true; if(parameters.getWhiteBalance() != null) isWhiteBalanceSupported = true; } catch(RuntimeException e) { displayDialog(CAMERA_NOT_FOUND); e.printStackTrace(); } if(isPreviewStopped) { mirrorView.startPreview(); isPreviewStopped = false; } } } private void unloadCamera() { if (camera != null) { try { mirrorView.setCamera(null); } catch(RuntimeException e) { Toast.makeText(this, "Error Unloading Camera", Toast.LENGTH_SHORT).show(); } camera.stopPreview(); isPreviewStopped = true; camera.release(); camera = null; } } private void displayDialog(int id) { QustomDialogBuilder builder = new QustomDialogBuilder(this); builder .setTitleColor(themeColor) .setDividerColor(themeColor); DialogManager.buildQustomDialog(this, id, builder); } private void displayCustomDialog(int id) { dialog = new Dialog(this); DialogManager.buildDialog(this, id); } protected void sendBugReport(String subject) { Intent emailIntent = new Intent(android.content.Intent.ACTION_VIEW); emailIntent.setData(Uri.parse("mailto:wckd.dev@gmail.com")); emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject); emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "" + getResources().getString(R.string.bug_report) + "\n\nStore: " + store + "\nVersion: " + version + "\nBrand: " + android.os.Build.BRAND + "\nManufacturer: " + android.os.Build.MANUFACTURER + "\nModel: " + android.os.Build.MODEL + "\nDevice: " + android.os.Build.DEVICE + "\nCameras: " + numberOfCameras + "\nBack ID: " + backCameraId + "\nFront ID: " + frontCameraId + "\nCurrent ID: " + currentCameraId + "\n" + mirrorView.getDisplayInfo()); startActivity(Intent.createChooser(emailIntent, getResources().getString(R.string.bug_report_send))); MirrorActivity.this.finish(); } protected void setFrame(int position) { ImageView frame = (ImageView) findViewById(R.id.frame_overlay); frame.setImageDrawable(frameMgr.getFrameResId(position)); frameModePref = position; } private void setZoom(int level){ if(isZoomSupported) { mirrorView.zoom(level); } else { Toast.makeText(getApplicationContext(), R.string.toast_no_zoom, Toast.LENGTH_SHORT).show(); } } private void setExposure(int level) throws RuntimeException { try { mirrorView.exposure(level); exposurePref = level; } catch(RuntimeException e) { exposurePref = -999; throw e; } } private void setWhiteBalance(int level) { try { mirrorView.whiteBalance(level); whiteBalancePref = level; // TODO - Why won't this work? App crashes during menu load after icon change // Requesting resource failed because it is too complex /* switch(level) { case 0: menuItemWB.setIcon(R.attr.wbAutoIcon); // drawable.menu_options_white_balance_auto_holo_dark); break; case 1: menuItemWB.setIcon(R.attr.wbDaylightIcon); // drawable.menu_options_white_balance_daylight_holo_dark); break; case 2: menuItemWB.setIcon(R.attr.wbIncanIcon); // drawable.menu_options_white_balance_incandescent_holo_dark); break; case 3: menuItemWB.setIcon(R.attr.wbFluorIcon); // drawable.menu_options_white_balance_fluorescent_holo_dark); break; } */ switch(level) { case 0: if(themePref == 2 || themePref == 4 || themePref == 5 || themePref == 7) menuItemWhiteBalance.setIcon(R.drawable.menu_options_white_balance_auto_holo_light); else menuItemWhiteBalance.setIcon(R.drawable.menu_options_white_balance_auto_holo_dark); break; case 1: if(themePref == 2 || themePref == 4 || themePref == 5 || themePref == 7) menuItemWhiteBalance.setIcon(R.drawable.menu_options_white_balance_daylight_holo_light); else menuItemWhiteBalance.setIcon(R.drawable.menu_options_white_balance_daylight_holo_dark); break; case 2: if(themePref == 2 || themePref == 4 || themePref == 5 || themePref == 7) menuItemWhiteBalance.setIcon(R.drawable.menu_options_white_balance_incandescent_holo_light); else menuItemWhiteBalance.setIcon(R.drawable.menu_options_white_balance_incandescent_holo_dark); break; case 3: if(themePref == 2 || themePref == 4 || themePref == 5 || themePref == 7) menuItemWhiteBalance.setIcon(R.drawable.menu_options_white_balance_fluorescent_holo_light); else menuItemWhiteBalance.setIcon(R.drawable.menu_options_white_balance_fluorescent_holo_dark); break; } } catch(RuntimeException e) { Toast.makeText(getApplicationContext(), R.string.toast_no_white_balance, Toast.LENGTH_SHORT).show(); whiteBalancePref = 0; } } @Override public boolean onTouch(View v, MotionEvent event) { switch(event.getAction() & MotionEvent.ACTION_MASK){ case MotionEvent.ACTION_DOWN: savedMatrix.set(matrix); start.set(event.getX(), event.getY()); touchState = PRESS; break; case MotionEvent.ACTION_POINTER_DOWN: startDist = spacing(event); if (startDist > minDist) { savedMatrix.set(matrix); midPoint(mid, event); touchState = ZOOM; } break; case MotionEvent.ACTION_UP: if(touchState == PRESS) { float moveDist = spacing(event, start); if(moveDist < minDist) { fullScreenClick(); } } break; case MotionEvent.ACTION_POINTER_UP: if(touchState == ZOOM) { touchState = NONE; } break; case MotionEvent.ACTION_MOVE: if ( (touchState == PRESS && spacing(event, start) > minDist) || touchState == DRAG) { matrix.set(savedMatrix); matrix.postTranslate(event.getX() - start.x, event.getY() - start.y); touchState = DRAG; } else if (touchState == ZOOM) { float nowDist = spacing(event); if (nowDist > minDist) { matrix.set(savedMatrix); float scale = nowDist / startDist; matrix.postScale(scale, scale, mid.x, mid.y); if(nowDist > lastDist) zoomIn(); else zoomOut(); } lastDist = nowDist; } break; } return true; } /** Determine the space between a finger and a saved point */ @SuppressLint("FloatMath") private float spacing(MotionEvent event, PointF point) { float x = event.getX() - point.x; float y = event.getY() - point.y; return FloatMath.sqrt(x * x + y * y); } /** Determine the space between the first two fingers */ @SuppressLint("FloatMath") private float spacing(MotionEvent event) { float x = event.getX(0) - event.getX(1); float y = event.getY(0) - event.getY(1); return FloatMath.sqrt(x * x + y * y); } /** Calculate the mid point of the first two fingers */ private void midPoint(PointF point, MotionEvent event) { float x = event.getX(0) + event.getX(1); float y = event.getY(0) + event.getY(1); point.set(x / 2, y / 2); } private void fullScreenClick() { showWelcomeTwoDialog(); // Exit fullscreen mode if(isFullscreen) { // Show navigation and notification bar getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE); getActionBar().show(); // Show action bar isFullscreen = false; mirrorView.isFullscreen = false; } // Enter fullscreen mode else { // Hide notification bar and set navigation bar to low profile getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LOW_PROFILE); getActionBar().hide(); // Hide action bar isFullscreen = true; mirrorView.isFullscreen = true; } } private void zoomIn() { if(zoomRate == 0f) zoomRate = mirrorView.getZoomMax() * 0.02f; if(zoomPrefF < (mirrorView.getZoomMax() - zoomRate)) { zoomPrefF += zoomRate; setZoom(Math.round(zoomPrefF)); } } private void zoomOut() { if(zoomRate == 0f) zoomRate = mirrorView.getZoomMax() * 0.02f; if(zoomPrefF > (0 + zoomRate)) { zoomPrefF -= zoomRate; setZoom(Math.round(zoomPrefF)); } } }
package com.yidejia.app.mall.initview; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.graphics.Bitmap; import android.os.Bundle; import android.util.Log; import android.util.TypedValue; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.assist.ImageLoadingListener; import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener; import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer; import com.yidejia.app.mall.GoodsInfoActivity; import com.yidejia.app.mall.MyApplication; import com.yidejia.app.mall.R; import com.yidejia.app.mall.datamanage.CartsDataManage; import com.yidejia.app.mall.datamanage.FavoriteDataManage; import com.yidejia.app.mall.model.BaseProduct; import com.yidejia.app.mall.model.Cart; import com.yidejia.app.mall.model.MainProduct; import com.yidejia.app.mall.model.ProductBaseInfo; import com.yidejia.app.mall.util.Consts; import com.yidejia.app.mall.view.GoCartActivity; import com.yidejia.app.mall.view.LoginActivity; import com.yidejia.app.mall.view.PayActivity; public class GoodsView { private View view; private int width; private CartsDataManage manage; private int cart_num = 0; private Activity activity; private String productId; private String userid; private boolean isLogin; private AlertDialog builder; public GoodsView(Activity activity, View view, int width) { this.view = view; this.width = width; this.activity = activity; initDisplayImageOption(); Log.i("width", this.width + ""); MyApplication myApplication = new MyApplication(); userid = myApplication.getUserId(); isLogin = myApplication.getIsLogin(); } public void initGoodsView(ProductBaseInfo info) { try { if (info == null) return; manage = new CartsDataManage(); cart_num = manage.getCartAmount(); final Cart cart = new Cart(); cart.setSalledAmmount(1); productId = info.getUId(); cart.setUId(productId); cart.setImgUrl(info.getImgUrl()); TextView base_info_content_text = (TextView) view .findViewById(R.id.base_info_content_text); String name = info.getName(); base_info_content_text.setText(name); cart.setProductText(name); TextView price = (TextView) view.findViewById(R.id.price); final String priceString = info.getPrice(); try { float priceNum = Float.parseFloat(priceString); cart.setPrice(priceNum); price.setText(priceString + "Ԫ"); } catch (Exception e) { // TODO: handle exception Toast.makeText(activity, "۸ϵǵĿͷ޸ģ", Toast.LENGTH_SHORT) .show(); price.setText(""); } ImageView buy_now = (ImageView) view.findViewById(R.id.buy_now); ImageView add_to_cart = (ImageView) view.findViewById(R.id.add_to_cart); TextView selled_num_text = (TextView) view .findViewById(R.id.selled_num_text); selled_num_text.setText(info.getSalledAmmount()); TextView emulate_num_text = (TextView) view .findViewById(R.id.emulate_num_text); emulate_num_text.setText(info.getCommentAmount()); TextView show_num_text = (TextView) view .findViewById(R.id.show_num_text); show_num_text.setText(info.getShowListAmount()); TextView brand_name_text = (TextView) view .findViewById(R.id.brand_name_text); brand_name_text.setText(info.getBrands()); TextView product_id_num_text = (TextView) view .findViewById(R.id.product_id_num_text); if(info.getProductNumber()==null||"".equals(info.getProductNumber())){ product_id_num_text.setText(""); }else{ product_id_num_text.setText(info.getProductNumber()); } TextView standard_content_text = (TextView) view .findViewById(R.id.standard_content_text); standard_content_text.setText(info.getProductSpecifications()); bannerArray = info.getBannerArray(); addBaseImage(view, bannerArray); recommendArray = info.getRecommendArray(); addMatchImage(view, recommendArray); shopping_cart_button = (Button) view .findViewById(R.id.shopping_cart_button); // CartsDataManage cartsDataManage = new CartsDataManage(); cart_num = manage.getCartAmount(); if (cart_num == 0) { shopping_cart_button.setVisibility(View.GONE); } else { setCartNum(cart_num); } add_to_cart.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub cart_num++; setCartNum(cart_num); Intent intent = new Intent(Consts.UPDATE_CHANGE); activity.sendBroadcast(intent); if(cart.getPrice()>0){ boolean istrue = manage.addCart(cart); }else{ Toast.makeText(activity, "Ʒܹ", Toast.LENGTH_LONG).show(); } // Log.i("info", istrue+" cart_num"); // if (istrue) { // builder.show(); } }); buy_now.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(activity, PayActivity.class); try{ float sum = Float.parseFloat(priceString); if(sum <= 0) return; Bundle bundle = new Bundle(); bundle.putSerializable("Cart", cart); bundle.putString("price", priceString); intent.putExtras(bundle); activity.startActivity(intent); // activity.finish(); } catch (NumberFormatException e){ } } }); RelativeLayout shopping_cart_in_goodsinfo = (RelativeLayout) view .findViewById(R.id.shopping_cart_in_goodsinfo); shopping_cart_in_goodsinfo.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(activity, GoCartActivity.class); // Bundle bundle = new Bundle(); // intent.putExtras(bundle); activity.startActivity(intent); // activity.finish(); } }); add_favorites = (ImageView) view.findViewById(R.id.add_favorites); add_favorites.setOnClickListener(addFavoriteListener); FavoriteDataManage favoriteManage = new FavoriteDataManage(activity); if (isLogin && !"".equals(userid)) { if (favoriteManage.checkExists(userid, productId)) { add_favorites.setImageResource(R.drawable.add_favorites2); // Toast.makeText(activity, "yes", Toast.LENGTH_LONG).show(); } else { add_favorites.setImageResource(R.drawable.add_favorites1); // Toast.makeText(activity, "no", Toast.LENGTH_LONG).show(); } } else { add_favorites.setImageResource(R.drawable.add_favorites1); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); Toast.makeText(activity,"", Toast.LENGTH_LONG); } } private ImageView add_favorites; private Button shopping_cart_button; private void setCartNum(int crat_num) { shopping_cart_button.setVisibility(view.VISIBLE); shopping_cart_button.setText("" + cart_num); } private LinearLayout baseInfoImageLayout; private LinearLayout matchGoodsImageLayout; private ArrayList<BaseProduct> bannerArray; private ArrayList<MainProduct> recommendArray; private void addBaseImage(View view, ArrayList<BaseProduct> bannerArray) { try { baseInfoImageLayout = (LinearLayout) view .findViewById(R.id.base_info_image_linear_layout); int lenght = bannerArray.size(); // child.setId(BASE_IMAGE_ID); // Log.e(TAG, TAG+child.getId()); // Log.e(TAG, TAG+baseInfoImageLayout.getId()); Resources r = activity.getResources(); float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 150, r.getDisplayMetrics()); for (int i = 0; i < lenght; i++) { // ImageView matchchild = (ImageView) // getSherlockActivity().getLayoutInflater().inflate(R.layout.item_base_image, // null); // ImageView child = (ImageView) // getSherlockActivity().getLayoutInflater().inflate(R.layout.item_base_image, // null); // ImageView child = new ImageView(); // ImageView matchchild = new ImageView(getSherlockActivity()); // int base_px = // getResources().getDimensionPixelSize(R.dimen.base_info_image); // int imageDimen = (int) // getResources().getDimension(R.dimen.base_info_image); // lp_base.setMargins(imageDimen, imageDimen, imageDimen, // imageDimen); // LinearLayout.LayoutParams lp_match = new // LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, // LayoutParams.MATCH_PARENT, 1); // int matchDimen = (int) // getResources().getDimension(R.dimen.base_info_match); // lp_match.setMargins(matchDimen, matchDimen, matchDimen, // matchDimen); // child.setLayoutParams(lp_base); // child.setImageResource(R.drawable.product_photo1); // matchchild.setLayoutParams(lp_match); // matchchild.setImageResource(R.drawable.product_photo2); // baseInfoImageLayout.addView(child, lp_base);// // matchGoodsImageLayout.addView(matchchild, lp_match);// LinearLayout.LayoutParams lp_base = new LinearLayout.LayoutParams( (new Float(px)).intValue(), LayoutParams.WRAP_CONTENT); // View imageViewLayout = LayoutInflater.from(view.getContext()) // .inflate(R.layout.goods_banner_imageview, null); // ImageView bannerImageView = (ImageView) imageViewLayout // .findViewById(R.id.banner_imageview); ImageView bannerImageView = new ImageView(activity); bannerImageView.setLayoutParams(lp_base); imageLoader.displayImage(bannerArray.get(i).getImgUrl(), bannerImageView, options, animateFirstListener); baseInfoImageLayout.setPadding(10, 0, 10, 0); // imageViewLayout.setPadding(10, 0, 10, 0); bannerImageView.setPadding(10, 0, 10, 0); baseInfoImageLayout.addView(bannerImageView, lp_base); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); Toast.makeText(activity, "", Toast.LENGTH_LONG).show(); } } private void addMatchImage(View view, final ArrayList<MainProduct> bannerArray) { try { matchGoodsImageLayout = (LinearLayout) view .findViewById(R.id.match_goods_image); int lenght = bannerArray.size(); Resources r = activity.getResources(); float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 90, r.getDisplayMetrics()); for (int i = 0; i < lenght; i++) { LinearLayout.LayoutParams lp_base = new LinearLayout.LayoutParams( (new Float(px)).intValue(), LayoutParams.WRAP_CONTENT); // View imageViewLayout = // LayoutInflater.from(view.getContext()).inflate(R.layout.goods_banner_imageview, // null); // ImageView bannerImageView = (ImageView) // imageViewLayout.findViewById(R.id.banner_imageview); ImageView bannerImageView = new ImageView(activity); bannerImageView.setLayoutParams(lp_base); imageLoader.displayImage(bannerArray.get(i).getImgUrl(), bannerImageView, options, animateFirstListener); matchGoodsImageLayout.setPadding(80, 0, 80, 0); // imageViewLayout.setPadding(10, 0, 10, 0); bannerImageView.setPadding(10, 0, 10, 0); final int index = i; bannerImageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(activity, GoodsInfoActivity.class); Bundle bundle = new Bundle(); bundle.putString("goodsId", bannerArray.get(index).getUId()); intent.putExtras(bundle); activity.startActivity(intent); activity.finish(); } }); // TextView nameTextView = (TextView) // imageViewLayout.findViewById(R.id.banner_name); // nameTextView.setText(bannerArray.get(i).getTitle()); // TextView priceTextView = (TextView) // imageViewLayout.findViewById(R.id.banner_price); // priceTextView.setText(bannerArray.get(i).getPrice()); matchGoodsImageLayout.addView(bannerImageView, lp_base); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); Toast.makeText(activity, "", Toast.LENGTH_LONG).show(); } } static final List<String> displayedImages = Collections .synchronizedList(new LinkedList<String>()); private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener { @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { if (loadedImage != null) { ImageView imageView = (ImageView) view; boolean firstDisplay = !displayedImages.contains(imageUri); if (firstDisplay) { FadeInBitmapDisplayer.animate(imageView, 500); displayedImages.add(imageUri); } } } } private DisplayImageOptions options; protected ImageLoader imageLoader = ImageLoader.getInstance(); private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener(); private void initDisplayImageOption() { builder = new AlertDialog.Builder(activity) .setTitle("½") .setMessage("Ƿȥ½") .setPositiveButton("ȥ½", new android.content.DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub Intent intent = new Intent(activity,LoginActivity.class); activity.startActivity(intent); } }).setNegativeButton("", null).create(); options = new DisplayImageOptions.Builder() .showStubImage(R.drawable.hot_sell_right_top_image) .showImageOnFail(R.drawable.hot_sell_right_top_image) .showImageForEmptyUri(R.drawable.hot_sell_right_top_image) .cacheInMemory(true).cacheOnDisc(true).build(); } private boolean flag = false; private OnClickListener addFavoriteListener = new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub FavoriteDataManage manage = new FavoriteDataManage(activity); if(!isLogin){ builder.show(); } else if (isLogin && !"".equals(userid)) { if (!manage.checkExists(userid, productId)) { if (manage.addFavourite(userid, productId)) { Toast.makeText(activity, "ղسɹ!", Toast.LENGTH_SHORT) .show(); add_favorites .setImageResource(R.drawable.add_favorites2); } else { Toast.makeText(activity, "Ǹղʧܡ", Toast.LENGTH_SHORT).show(); add_favorites .setImageResource(R.drawable.add_favorites1); } } else { if (manage.deleteFavourite(userid, productId)) { add_favorites .setImageResource(R.drawable.add_favorites1); } else { add_favorites .setImageResource(R.drawable.add_favorites2); } } } else { flag = !flag; changeFravoriteBg(); } } }; private void changeFravoriteBg() { if (flag) { add_favorites.setImageResource(R.drawable.add_favorites2); } else { add_favorites.setImageResource(R.drawable.add_favorites1); } } }
package lombok.eclipse; import static lombok.eclipse.handlers.EclipseHandlerUtil.error; import java.lang.reflect.Field; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.parser.Parser; import lombok.core.debug.DebugSnapshotStore; import lombok.core.debug.HistogramTracker; import lombok.patcher.Symbols; /** * Entry point for the Eclipse Parser patch that lets lombok modify the Abstract Syntax Tree as generated by * Eclipse's parser implementations. This class is injected into the appropriate OSGi ClassLoader and can thus * use any classes that belong to org.eclipse.jdt.(apt.)core. * * Note that, for any Method body, if Bit24 is set, the Eclipse parser has been patched to never attempt to * (re)parse it. You should set Bit24 on any MethodDeclaration object you inject into the AST: * * {@code methodDeclaration.bits |= ASTNode.Bit24; //0x800000} * * @author rzwitserloot * @author rspilker */ public class TransformEclipseAST { private final EclipseAST ast; //The patcher hacks this field onto CUD. It's public. private static final Field astCacheField; private static final HandlerLibrary handlers; public static boolean disableLombok = false; private static final HistogramTracker lombokTracker; static { String v = System.getProperty("lombok.histogram"); if (v == null) lombokTracker = null; else if (v.toLowerCase().equals("sysout")) lombokTracker = new HistogramTracker("lombok.histogram", System.out); else lombokTracker = new HistogramTracker("lombok.histogram"); } static { Field f = null; HandlerLibrary h = null; if (System.getProperty("lombok.disable") != null) { disableLombok = true; astCacheField = null; handlers = null; } else { try { h = HandlerLibrary.load(); } catch (Throwable t) { try { error(null, "Problem initializing lombok", t); } catch (Throwable t2) { System.err.println("Problem initializing lombok"); t.printStackTrace(); } disableLombok = true; } try { f = CompilationUnitDeclaration.class.getDeclaredField("$lombokAST"); } catch (Throwable t) { //I guess we're in an ecj environment; we'll just not cache stuff then. } astCacheField = f; handlers = h; } } public static void transform_swapped(CompilationUnitDeclaration ast, Parser parser) { transform(parser, ast); } public static EclipseAST getAST(CompilationUnitDeclaration ast, boolean forceRebuild) { EclipseAST existing = null; if (astCacheField != null) { try { existing = (EclipseAST) astCacheField.get(ast); } catch (Exception e) { // existing remains null } } if (existing == null) { existing = new EclipseAST(ast); if (astCacheField != null) try { astCacheField.set(ast, existing); } catch (Exception ignore) { } } else { existing.rebuild(forceRebuild); } return existing; } /** * This method is called immediately after Eclipse finishes building a CompilationUnitDeclaration, which is * the top-level AST node when Eclipse parses a source file. The signature is 'magic' - you should not * change it! * * Eclipse's parsers often operate in diet mode, which means many parts of the AST have been left blank. * Be ready to deal with just about anything being null, such as the Statement[] arrays of the Method AST nodes. * * @param parser The Eclipse parser object that generated the AST. Not actually used; mostly there to satisfy parameter rules for lombok.patcher scripts. * @param ast The AST node belonging to the compilation unit (java speak for a single source file). */ public static void transform(Parser parser, CompilationUnitDeclaration ast) { if (disableLombok) return; if (Symbols.hasSymbol("lombok.disable")) return; String disabled = System.getProperty("ol.lombok.disabled"); if (disabled != null && Boolean.valueOf(disabled)) { return; } // Do NOT abort if (ast.bits & ASTNode.HasAllMethodBodies) != 0 - that doesn't work. try { DebugSnapshotStore.INSTANCE.snapshot(ast, "transform entry"); long histoToken = lombokTracker == null ? 0L : lombokTracker.start(); EclipseAST existing = getAST(ast, false); new TransformEclipseAST(existing).go(); if (lombokTracker != null) lombokTracker.end(histoToken); DebugSnapshotStore.INSTANCE.snapshot(ast, "transform exit"); } catch (Throwable t) { DebugSnapshotStore.INSTANCE.snapshot(ast, "transform error: %s", t.getClass().getSimpleName()); try { String message = "Lombok can't parse this source: " + t.toString(); EclipseAST.addProblemToCompilationResult(ast.getFileName(), ast.compilationResult, false, message, 0, 0); t.printStackTrace(); } catch (Throwable t2) { try { error(ast, "Can't create an error in the problems dialog while adding: " + t.toString(), t2); } catch (Throwable t3) { //This seems risky to just silently turn off lombok, but if we get this far, something pretty //drastic went wrong. For example, the eclipse help system's JSP compiler will trigger a lombok call, //but due to class loader shenanigans we'll actually get here due to a cascade of //ClassNotFoundErrors. This is the right action for the help system (no lombok needed for that JSP compiler, //of course). 'disableLombok' is static, but each context classloader (e.g. each eclipse OSGi plugin) has //it's own edition of this class, so this won't turn off lombok everywhere. disableLombok = true; } } } } public TransformEclipseAST(EclipseAST ast) { this.ast = ast; } /** * First handles all lombok annotations except PrintAST, then calls all non-annotation based handlers. * then handles any PrintASTs. */ public void go() { for (Long d : handlers.getPriorities()) { ast.traverse(new AnnotationVisitor(d)); handlers.callASTVisitors(ast, d, ast.isCompleteParse()); } } private static class AnnotationVisitor extends EclipseASTAdapter { private final long priority; public AnnotationVisitor(long priority) { this.priority = priority; } @Override public void visitAnnotationOnField(FieldDeclaration field, EclipseNode annotationNode, Annotation annotation) { CompilationUnitDeclaration top = (CompilationUnitDeclaration) annotationNode.top().get(); handlers.handleAnnotation(top, annotationNode, annotation, priority); } @Override public void visitAnnotationOnMethodArgument(Argument arg, AbstractMethodDeclaration method, EclipseNode annotationNode, Annotation annotation) { CompilationUnitDeclaration top = (CompilationUnitDeclaration) annotationNode.top().get(); handlers.handleAnnotation(top, annotationNode, annotation, priority); } @Override public void visitAnnotationOnLocal(LocalDeclaration local, EclipseNode annotationNode, Annotation annotation) { CompilationUnitDeclaration top = (CompilationUnitDeclaration) annotationNode.top().get(); handlers.handleAnnotation(top, annotationNode, annotation, priority); } @Override public void visitAnnotationOnMethod(AbstractMethodDeclaration method, EclipseNode annotationNode, Annotation annotation) { CompilationUnitDeclaration top = (CompilationUnitDeclaration) annotationNode.top().get(); handlers.handleAnnotation(top, annotationNode, annotation, priority); } @Override public void visitAnnotationOnType(TypeDeclaration type, EclipseNode annotationNode, Annotation annotation) { CompilationUnitDeclaration top = (CompilationUnitDeclaration) annotationNode.top().get(); handlers.handleAnnotation(top, annotationNode, annotation, priority); } } }
package org.springframework.roo.addon.finder; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import org.springframework.roo.addon.beaninfo.BeanInfoMetadata; import org.springframework.roo.addon.entity.EntityMetadata; import org.springframework.roo.addon.entity.RooEntity; import org.springframework.roo.classpath.PhysicalTypeIdentifierNamingUtils; import org.springframework.roo.classpath.PhysicalTypeMetadata; import org.springframework.roo.classpath.details.DefaultMethodMetadata; import org.springframework.roo.classpath.details.MethodMetadata; import org.springframework.roo.classpath.details.annotations.AnnotatedJavaType; import org.springframework.roo.classpath.details.annotations.AnnotationMetadata; import org.springframework.roo.classpath.itd.AbstractItdTypeDetailsProvidingMetadataItem; import org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder; import org.springframework.roo.metadata.MetadataIdentificationUtils; import org.springframework.roo.model.JavaSymbolName; import org.springframework.roo.model.JavaType; import org.springframework.roo.project.Path; import org.springframework.roo.support.style.ToStringCreator; import org.springframework.roo.support.util.Assert; /** * Metadata for {@link RooEntity}. * * <p> * Any getter produced by this metadata is automatically included in the {@link BeanInfoMetadata}. * * @author Stefan Schmidt * @author Ben Alex * @since 1.0 * */ public class FinderMetadata extends AbstractItdTypeDetailsProvidingMetadataItem { private static final String PROVIDES_TYPE_STRING = FinderMetadata.class.getName(); private static final String PROVIDES_TYPE = MetadataIdentificationUtils.create(PROVIDES_TYPE_STRING); private BeanInfoMetadata beanInfoMetadata; private EntityMetadata entityMetadata; public FinderMetadata(String identifier, JavaType aspectName, PhysicalTypeMetadata governorPhysicalTypeMetadata, BeanInfoMetadata beanInfoMetadata, EntityMetadata entityMetadata) { super(identifier, aspectName, governorPhysicalTypeMetadata); Assert.isTrue(isValid(identifier), "Metadata identification string '" + identifier + "' does not appear to be a valid"); Assert.notNull(beanInfoMetadata, "Bean info metadata required"); Assert.notNull(entityMetadata, "Entity metadata required"); if (!isValid()) { return; } this.beanInfoMetadata = beanInfoMetadata; this.entityMetadata = entityMetadata; for (String method : entityMetadata.getDynamicFinders()) { builder.addMethod(getDynamicFinderMethod(method)); } // Create a representation of the desired output ITD itdTypeDetails = builder.build(); } /** * Locates a dynamic finder method of the specified name, or creates one on demand if not present. * * <p> * It is required that the requested name was defined in the {@link RooEntity#finders()}. If it is not * present, an exception is thrown. * * @return the user-defined method, or an ITD-generated method (never returns null) */ public MethodMetadata getDynamicFinderMethod(String dynamicFinderMethodName) { Assert.hasText(dynamicFinderMethodName, "Dynamic finder method name is required"); Assert.isTrue(entityMetadata.getDynamicFinders().contains(dynamicFinderMethodName), "Undefined method name '" + dynamicFinderMethodName + "'"); JavaSymbolName methodName = new JavaSymbolName(dynamicFinderMethodName); // We have no access to method parameter information, so we scan by name alone and treat any match as authoritative // We do not scan the superclass, as the caller is expected to know we'll only scan the current class for (MethodMetadata method : governorTypeDetails.getDeclaredMethods()) { if (method.getMethodName().equals(methodName)) { // Found a method of the expected name; we won't check method parameters though return method; } } // To get this far we need to create the method... DynamicFinderServices dynamicFinderServices = new DynamicFinderServicesImpl(); String jpaQuery = dynamicFinderServices.getJpaQueryFor(methodName, entityMetadata.getPlural(), beanInfoMetadata); List<JavaSymbolName> paramNames = dynamicFinderServices.getParameterNames(methodName, entityMetadata.getPlural(), beanInfoMetadata); List<JavaType> paramTypes = dynamicFinderServices.getParameterTypes(methodName, entityMetadata.getPlural(), beanInfoMetadata); // We declared the field in this ITD, so produce a public accessor for it InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); for (int i = 0; i < paramTypes.size(); i++) { String name = paramNames.get(i).getSymbolName(); StringBuilder length = new StringBuilder(); if (paramTypes.get(i).equals(new JavaType("java.lang.String"))) { length.append(" || ").append(paramNames.get(i)).append(".length() == 0"); } if (!paramTypes.get(i).isPrimitive()) { bodyBuilder.appendFormalLine("if (" + name + " == null" + length.toString() + ") throw new IllegalArgumentException(\"The " + name + " argument is required\");"); } if (length.length() > 0 && dynamicFinderMethodName.substring(dynamicFinderMethodName.indexOf(paramNames.get(i).getSymbolNameCapitalisedFirstLetter()) + name.length()).startsWith("Like")){ bodyBuilder.appendFormalLine(name + " = " + name + ".replace('*', '%');"); bodyBuilder.appendFormalLine("if (" + name + ".charAt(0) != '%') {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(name + " = \"%\" + " + name + ";"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.appendFormalLine("if (" + name + ".charAt(" + name + ".length() -1) != '%') {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine(name + " = " + name + " + \"%\";"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } } // Get the entityManager() method (as per ROO-216) MethodMetadata entityManagerMethod = entityMetadata.getEntityManagerMethod(); Assert.notNull(entityManagerMethod, "Entity manager method incorrectly returned null"); bodyBuilder.appendFormalLine("javax.persistence.EntityManager em = " + governorTypeDetails.getName().getSimpleTypeName() + "." + entityManagerMethod.getMethodName().getSymbolName() + "();"); bodyBuilder.appendFormalLine("javax.persistence.Query q = em.createQuery(\"" + jpaQuery + "\");"); for (JavaSymbolName name : paramNames) { bodyBuilder.appendFormalLine("q.setParameter(\"" + name + "\", " + name + ");"); } bodyBuilder.appendFormalLine("return q;"); int modifier = Modifier.PUBLIC; modifier = modifier |= Modifier.STATIC; return new DefaultMethodMetadata(getId(), modifier, methodName, new JavaType("javax.persistence.Query"), AnnotatedJavaType.convertFromJavaTypes(paramTypes), paramNames, new ArrayList<AnnotationMetadata>(), bodyBuilder.getOutput()); } public String toString() { ToStringCreator tsc = new ToStringCreator(this); tsc.append("identifier", getId()); tsc.append("valid", valid); tsc.append("aspectName", aspectName); tsc.append("destinationType", destination); tsc.append("governor", governorPhysicalTypeMetadata.getId()); tsc.append("itdTypeDetails", itdTypeDetails); return tsc.toString(); } public static final String getMetadataIdentiferType() { return PROVIDES_TYPE; } public static final String createIdentifier(JavaType javaType, Path path) { return PhysicalTypeIdentifierNamingUtils.createIdentifier(PROVIDES_TYPE_STRING, javaType, path); } public static final JavaType getJavaType(String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.getJavaType(PROVIDES_TYPE_STRING, metadataIdentificationString); } public static final Path getPath(String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.getPath(PROVIDES_TYPE_STRING, metadataIdentificationString); } public static boolean isValid(String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.isValid(PROVIDES_TYPE_STRING, metadataIdentificationString); } }
package ca.cmput301f13t03.adventure_datetime.model; import android.content.Context; import android.graphics.BitmapFactory; import android.util.Log; import ca.cmput301f13t03.adventure_datetime.R; import ca.cmput301f13t03.adventure_datetime.model.Interfaces.*; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.UUID; public final class StoryManager implements IStoryModelPresenter, IStoryModelDirector { private static final String TAG = "StoryManager"; private StoryDB m_db = null; private Context m_context = null; // Current focus private Story m_currentStory = null; private StoryFragment m_currentFragment = null; private Collection<Story> m_storyList = null; private Collection<Bookmark> m_bookmarkList = null; // Listeners private Set<ICurrentFragmentListener> m_fragmentListeners = new HashSet<ICurrentFragmentListener>(); private Set<ICurrentStoryListener> m_storyListeners = new HashSet<ICurrentStoryListener>(); private Set<IStoryListListener> m_storyListListeners = new HashSet<IStoryListListener>(); private Set<IBookmarkListListener> m_bookmarkListListeners = new HashSet<IBookmarkListListener>(); public StoryManager(Context context) { m_context = context; m_db = new StoryDB(context); m_bookmarkList = m_db.getAllBookmarks(); PublishBookmarkListChange(); Log.v("StoryManager", "There are this many Bookmarks: " + m_bookmarkList.size()); } // IStoryModelPresenter // The design is such that a publish will to the subscriber will // occur immediately if data is available. If not the data will // be supplied later once it is available. public void Subscribe(ICurrentFragmentListener fragmentListener) { m_fragmentListeners.add(fragmentListener); if (m_currentFragment != null) { fragmentListener.OnCurrentFragmentChange(m_currentFragment); } } public void Subscribe(ICurrentStoryListener storyListener) { m_storyListeners.add(storyListener); if (m_currentStory != null) { storyListener.OnCurrentStoryChange(m_currentStory); } } public void Subscribe(IStoryListListener storyListListener) { m_storyListListeners.add(storyListListener); if (m_storyList != null) { storyListListener.OnCurrentStoryListChange(m_storyList); } else { m_storyList = new ArrayList<Story>(); m_storyList.addAll(m_db.getStories()); PublishStoryListChange(); } } public void Subscribe(IBookmarkListListener bookmarkListListener) { m_bookmarkListListeners.add(bookmarkListListener); if (m_bookmarkList != null) { bookmarkListListener.OnBookmarkListChange(m_bookmarkList); } else { m_bookmarkList = new ArrayList<Bookmark>(); m_bookmarkList.addAll(m_db.getAllBookmarks()); PublishBookmarkListChange(); } } public void Unsubscribe(ICurrentFragmentListener fragmentListener) { m_fragmentListeners.remove(fragmentListener); } public void Unsubscribe(ICurrentStoryListener storyListener) { m_storyListeners.remove(storyListener); } public void Unsubscribe(IStoryListListener storyListListener) { m_storyListListeners.remove(storyListListener); } public void Unsubscribe(IBookmarkListListener bookmarkListListener) { m_bookmarkListListeners.remove(bookmarkListListener); } // Publish private void PublishCurrentStoryChange() { for (ICurrentStoryListener storyListener : m_storyListeners) { storyListener.OnCurrentStoryChange(m_currentStory); } } private void PublishCurrentFragmentChange() { for (ICurrentFragmentListener fragmentListener : m_fragmentListeners) { fragmentListener.OnCurrentFragmentChange(m_currentFragment); } } private void PublishStoryListChange() { for (IStoryListListener listListener : m_storyListListeners) { listListener.OnCurrentStoryListChange(m_storyList); } } private void PublishBookmarkListChange() { for (IBookmarkListListener bookmarkListener : m_bookmarkListListeners) { bookmarkListener.OnBookmarkListChange(m_bookmarkList); } } // IStoryModelDirector public void selectStory(String storyId) { m_currentStory = getStory(storyId); PublishCurrentStoryChange(); } public void selectFragment(String fragmentId) { m_currentFragment = getFragment(fragmentId); PublishCurrentFragmentChange(); } public boolean putStory(Story story) { // Set default image if needed if (story.getThumbnail() == null) story.setThumbnail(BitmapFactory.decodeResource( m_context.getResources(), R.drawable.logo)); return m_db.setStory(story); } public void deleteStory(String storyId) { // TODO Needs to be implemented in database. } public Story getStory(String storyId) { return m_db.getStory(storyId); } public boolean putFragment(StoryFragment fragment) { return m_db.setStoryFragment(fragment); } public void deleteFragment(UUID fragmentId) { // TODO Needs to be implemented in database. } public StoryFragment getFragment(String fragmentId) { return m_db.getStoryFragment(fragmentId); } public ArrayList<Story> getStoriesAuthoredBy(String author) { return m_db.getStoriesAuthoredBy(author); } public Bookmark getBookmark(String id) { return m_db.getBookmark(id); } public void setBookmark(Bookmark bookmark) { m_db.setBookmark(bookmark); } }
/** * EditorWindow * <p> * The window for the Airport editor * * @author Serjoscha Bassauer */ package de.bwv_aachen.dijkstra.gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Arrays; import java.util.Map; import java.util.NoSuchElementException; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.WindowConstants; import javax.swing.border.BevelBorder; import javax.swing.border.Border; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.joda.time.Duration; import de.bwv_aachen.dijkstra.controller.Controller; import de.bwv_aachen.dijkstra.helpers.DateHelper; import de.bwv_aachen.dijkstra.model.Airport; import de.bwv_aachen.dijkstra.model.Connection; @SuppressWarnings("serial") public class EditorWindow extends View implements ActionListener, ListSelectionListener { // Beans JPanel connectionsContainer; JList<Airport> locationJList; JButton lAdd; JButton lRem; JButton rAdd; // Helper Window(s) EditorWindow_AirportSelector airportSel; // Model(s) DefaultListModel<Airport> lm = new DefaultListModel<>(); public EditorWindow(Controller c) { super("EditorWindow",c); // generate Airport List Model for(Airport ca: controller.getModel().getAirportList().values()) { // assign every location to the jList Model this.lm.addElement(ca); } } public void draw() { Container cp = super.getContentPane(); cp.removeAll(); // making this function being able to repaint the mainwindow super.setTitle("Bearbeiten"); super.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); super.setResizable(false); cp.setLayout(new BoxLayout(cp, BoxLayout.PAGE_AXIS)); ((JComponent)cp).setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)); // Build the UI Elems locationJList = new JList<Airport>(lm); locationJList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); //Only one airport can be selected locationJList.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)); connectionsContainer = new JPanel(); connectionsContainer.setLayout(new BoxLayout(connectionsContainer, BoxLayout.PAGE_AXIS)); // Some Look and feel helper captions JLabel formTitle = new JLabel("Daten bearbeiten"); formTitle.setFont(new Font("Arial", Font.CENTER_BASELINE, 20)); JLabel leftAreaCaption = new JLabel("Flughäfen"); JLabel rightAreaCaption = new JLabel("Verbindungen"); // Panels for the captions JPanel headArea = new JPanel(); headArea.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)); headArea.setLayout(new BorderLayout()); headArea.add(formTitle, BorderLayout.CENTER); JPanel subHeaderArea = new JPanel(); subHeaderArea.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)); subHeaderArea.setLayout(new BorderLayout()); subHeaderArea.add(leftAreaCaption, BorderLayout.WEST); subHeaderArea.add(rightAreaCaption, BorderLayout.EAST); // Add caption cp.add(headArea); cp.add(subHeaderArea); // Container for the left and the right side JPanel dataArea = new JPanel(); // this panel contains all date elems (list and select boxes) dataArea.setLayout(new BoxLayout(dataArea, BoxLayout.LINE_AXIS)); JPanel leftContainer = new JPanel(); leftContainer.setLayout(new BorderLayout()); leftContainer.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); JPanel rightContainer = new JPanel(); rightContainer.setLayout(new BorderLayout()); //rightContainer.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)); rightContainer.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); // Buttons this.lAdd = new JButton("+"); this.lAdd.setActionCommand("lAdd"); this.lRem = new JButton("-"); this.lRem.setEnabled(false); this.lRem.setActionCommand("lRem"); this.rAdd = new JButton("+"); this.rAdd.setActionCommand("rAdd"); this.rAdd.setEnabled(false); // Container for the buttons JPanel lButtons = new JPanel(); lButtons.setLayout(new FlowLayout()); JPanel rButtons = new JPanel(); rButtons.setLayout(new FlowLayout()); // Add buttons to container lButtons.add(lAdd); lButtons.add(lRem); rButtons.add(rAdd); // Add ActionListening locationJList.addListSelectionListener(this); this.lAdd.addActionListener(this); this.rAdd.addActionListener(this); this.lRem.addActionListener(this); if(locationJList.getSelectedIndex()==-1) // initially start with selecting the first elem in list locationJList.setSelectedIndex(0); // Add lists and buttons to the correct jpanel leftContainer.add(locationJList, BorderLayout.CENTER); leftContainer.add(lButtons, BorderLayout.SOUTH); rightContainer.add(connectionsContainer, BorderLayout.NORTH); rightContainer.add(rButtons, BorderLayout.SOUTH); // Add elems (panels) to frame dataArea.add(leftContainer); dataArea.add(rightContainer); cp.add(dataArea); // Do the rest for displaying the window super.pack(); super.setLocationRelativeTo(null); // center the frame // Show the window super.setVisible(true); } public void actionPerformed(ActionEvent e) { //JButton button = (JButton)e.getSource(); switch(e.getActionCommand()){ case "lAdd": // add FROM/source airport String input = JOptionPane.showInputDialog("Name des Flughafens:"); if(input != null) { // prevents some nullpointer exceptions (which would not take any effect for the program, but disturbed me) if(!input.equals("")) { DefaultListModel<Airport> lm = (DefaultListModel<Airport>)this.locationJList.getModel(); Long id = 0L; try { id = lm.lastElement().getId()+1; } //Last element not found, so create a new airport with ID 1 catch (NoSuchElementException | NullPointerException ex) { id = 1L; } Airport nAp = new Airport(id, input); // create an temp airport that will later be assigned as connection lm.addElement(nAp); // add the String as given Airport to the JList Model //Put the new airport to the real data model controller.getModel().getAirportList().put(id, nAp); //refresh the list this.repaint(); } } break; case "lRem": Airport oldAirport = lm.remove(this.locationJList.getSelectedIndex()); controller.getModel().getAirportList().remove(oldAirport.getId()); break; case "rAdd": // Show our self made selection box modal this.airportSel = new EditorWindow_AirportSelector(controller, this); this.airportSel.draw(); break; case "approveAPselection": int elem = this.lm.indexOf(locationJList.getSelectedValue()); Airport ap = this.lm.get(elem); ap.getConnections().put(airportSel.getSelection(), new Connection(Duration.ZERO)); this.airportSel.dispose(); break; } int selection = this.locationJList.getSelectedIndex(); // repainting makes the form lose its selection so lets manually save and restore them this.draw(); // repaint this.locationJList.setSelectedIndex(selection); } /** * Triggered as soon as the list selection changes in any way */ public void valueChanged(ListSelectionEvent e) { // first enable the action buttons this.lRem.setEnabled(true); this.rAdd.setEnabled(true); // Render Form connectionsContainer.removeAll(); //Index points to a deleted Airport if (locationJList.getSelectedIndex() == -1) { return; } Airport ap = this.lm.elementAt(locationJList.getSelectedIndex()); if (ap == null) { return; } //connectionsContainer.setLayout(new GridLayout(ap.getConnections().size(), 4)); for (Map.Entry<Airport, Connection> entry : ap.getConnections().entrySet()) { // Create a flowing panel for each row JPanel row = new JPanel(); row.setLayout(new GridLayout(1, 4)); // create beans JTextField textDuration = new JTextField(); JButton deleteButton = new JButton("Löschen"); deleteButton.addActionListener(new ActionListener() { private Airport ap; private Map.Entry<Airport, Connection> entry; public void actionPerformed(ActionEvent ev) { ap.getConnections().remove(entry.getKey()); connectionsContainer.repaint(); } public ActionListener fakeConstructor(Airport ap, Map.Entry<Airport, Connection> entry) { this.ap = ap; this.entry = entry; return this; } }.fakeConstructor(ap,entry)); deleteButton.setActionCommand("removeConnection"); deleteButton.addActionListener(this); // TODO this needs to be deleted later for its obsolete row.add(new JLabel(entry.getKey().toString())); row.add(textDuration); row.add(new ConnectionChangeButton(entry.getValue(),textDuration)); row.add(deleteButton); connectionsContainer.add(row); } pack(); setLocationRelativeTo(null); connectionsContainer.repaint(); } }
package com.andela.voluminotesapp.activities; import android.support.design.internal.NavigationMenuItemView; import android.support.design.widget.NavigationView; import android.support.test.InstrumentationRegistry; import android.support.test.espresso.UiController; import android.support.test.espresso.ViewAction; import android.support.test.espresso.assertion.ViewAssertions; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.test.ActivityInstrumentationTestCase2; import android.view.MenuItem; import android.view.View; import com.andela.voluminotesapp.R; import org.hamcrest.Matcher; import org.junit.Test; import static android.support.test.espresso.Espresso.onData; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.swipeLeft; import static android.support.test.espresso.action.ViewActions.swipeRight; import static android.support.test.espresso.action.ViewActions.typeText; import static android.support.test.espresso.core.deps.guava.base.CharMatcher.is; import static android.support.test.espresso.core.deps.guava.base.Predicates.instanceOf; import static android.support.test.espresso.matcher.ViewMatchers.isAssignableFrom; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withClassName; import static android.support.test.espresso.matcher.ViewMatchers.withContentDescription; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static java.util.EnumSet.allOf; public class MainActivityTest extends ActivityInstrumentationTestCase2 { public MainActivityTest() { super(MainActivity.class); } @Override public void setUp() throws Exception { super.setUp(); getActivity(); } @Override public void tearDown() throws Exception { testOnDeleteAllNote(); } private void takeANote() { onView(withText("Take a note")).perform(click()); onView(withId(R.id.noteTitle)).perform(typeText("01 This is a simple title")); onView(withId(R.id.noteArea)).perform(typeText("This is a simple content and you're gonna love it. peace!")); onView(withContentDescription("Navigate up")).perform(click()); } @Test public void testOnDeleteAllNote() { MyApplication.getNoteManager(getActivity()).deleteAll(); onView(withId(R.id.toolbar_title)).check(ViewAssertions.matches(isDisplayed())); } @Test public void testOnCreateNote() throws Exception { takeANote(); } @Test public void testOnReadNote() throws Exception { takeANote(); onView(withId(R.id.text)).perform(click()); } @Test public void testOnEditNote() throws Exception { takeANote(); onView(withId(R.id.text)).perform(click()); onView(withId(R.id.noteTitle)).perform(typeText("02 This is an expensive title")); onView(withId(R.id.noteArea)).perform(typeText("This is an expensive content and you're gonna buy it. harmony!")); onView(withContentDescription("Navigate up")).perform(click()); } @Test public void testOnDelete() throws Exception { takeANote(); onView(withId(R.id.list_icon)).perform(click()); onView(withId(R.id.text)).perform(swipeLeft()); } @Test public void testOpenTrash() throws Exception { takeANote(); onView(withId(R.id.list_icon)).perform(click()); onView(withId(R.id.text)).perform(swipeLeft()); onView(withId(R.id.drawer_layout)).perform(actionOpenDrawer()); } private static ViewAction actionOpenDrawer() { return new ViewAction() { @Override public Matcher<View> getConstraints() { return isAssignableFrom(DrawerLayout.class); } @Override public String getDescription() { return "open drawer"; } @Override public void perform(UiController uiController, View view) { ((DrawerLayout) view).openDrawer(GravityCompat.START); } }; } private static ViewAction actionCloseDrawer() { return new ViewAction() { @Override public Matcher<View> getConstraints() { return isAssignableFrom(DrawerLayout.class); } @Override public String getDescription() { return "close drawer"; } @Override public void perform(UiController uiController, View view) { ((DrawerLayout) view).closeDrawer(GravityCompat.START); } }; } }
package dr.app.beauti.options; import dr.app.beauti.types.FixRateType; import dr.app.beauti.types.OperatorType; import dr.app.beauti.types.RelativeRatesType; import dr.evolution.datatype.DataType; import dr.evolution.datatype.Microsatellite; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evolution.tree.UPGMATree; import dr.evolution.util.Taxa; import dr.math.MathUtils; import dr.stats.DiscreteStatistics; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.Vector; /** * @author Alexei Drummond * @author Andrew Rambaut * @author Walter Xie * @version $Id$ */ public class ClockModelOptions extends ModelOptions { // Instance variables private final BeautiOptions options; // private FixRateType rateOptionClockModel = FixRateType.RELATIVE_TO; // private double meanRelativeRate = 1.0; // public List<ClockModelGroup> clockModelGroupList = new ArrayList<ClockModelGroup>(); public ClockModelOptions(BeautiOptions options) { this.options = options; initGlobalClockModelParaAndOpers(); // fixRateOfFirstClockPartition(); } private void initGlobalClockModelParaAndOpers() { // createParameter("allClockRates", "All the relative rates regarding clock models"); // createOperator("deltaAllClockRates", RelativeRatesType.CLOCK_RELATIVE_RATES.toString(), // "Delta exchange operator for all the relative rates regarding clock models", "allClockRates", // OperatorType.DELTA_EXCHANGE, 0.75, rateWeights); // // only available for *BEAST and EBSP // createUpDownAllOperator("upDownAllRatesHeights", "Up down all rates and heights", // "Scales all rates inversely to node heights of the tree", // demoTuning, branchWeights); } /** * return a list of parameters that are required */ public void selectParameters() { for (ClockModelGroup clockModelGroup : getClockModelGroups()) { createParameter(clockModelGroup.getName(), // used in BeastGenerator (Branch Rates Model) part "All relative rates regarding clock models in group " + clockModelGroup.getName()); } } /** * return a list of operators that are required * * @param ops the operator list */ public void selectOperators(List<Operator> ops) { for (ClockModelGroup clockModelGroup : getClockModelGroups()) { if (clockModelGroup.getRateTypeOption() == FixRateType.FIX_MEAN) { createOperator("delta_" + clockModelGroup.getName(), RelativeRatesType.CLOCK_RELATIVE_RATES.toString() + " in " + clockModelGroup.getName(), "Delta exchange operator for all relative rates regarding clock models", clockModelGroup.getName(), OperatorType.DELTA_EXCHANGE, 0.75, rateWeights); Operator deltaOperator = getOperator("delta_" + clockModelGroup.getName()); // update delta clock operator weight deltaOperator.weight = options.getPartitionClockModels(clockModelGroup).size(); ops.add(deltaOperator); } //up down all rates and trees operator only available for *BEAST and EBSP if (clockModelGroup.getRateTypeOption() == FixRateType.RELATIVE_TO && //TODO what about Calibration? (options.useStarBEAST || options.isEBSPSharingSamePrior())) { // only available for *BEAST and EBSP createUpDownAllOperator("upDownAllRatesHeights_" + clockModelGroup.getName(), "Up down all rates and heights in " + clockModelGroup.getName(), "Scales all rates inversely to node heights of the tree", demoTuning, branchWeights); Operator op = getOperator("upDownAllRatesHeights_" + clockModelGroup.getName()); op.setClockModelGroup(clockModelGroup); ops.add(op); } } } //+++++++++++++++++++++++ Clock Model Group ++++++++++++++++++++++++++++++++ public void initClockModelGroup() { // only used in BeautiImporter for (PartitionClockModel model : options.getPartitionClockModels()) { addClockModelGroup(model); } for (ClockModelGroup clockModelGroup : getClockModelGroups()) { if (clockModelGroup.contain(Microsatellite.INSTANCE, options)) { if (options.getPartitionClockModels(clockModelGroup).size() == 1) { fixRateOfFirstClockPartition(clockModelGroup); options.getPartitionClockModels(clockModelGroup).get(0).setEstimatedRate(true); } else { fixMeanRate(clockModelGroup); } } else if (!(clockModelGroup.getRateTypeOption() == FixRateType.TIP_CALIBRATED || clockModelGroup.getRateTypeOption() == FixRateType.NODE_CALIBRATED || clockModelGroup.getRateTypeOption() == FixRateType.RATE_CALIBRATED)) { //TODO correct? fixRateOfFirstClockPartition(clockModelGroup); } } } public void addClockModelGroup(PartitionClockModel model) { if (model.getClockModelGroup() == null) { String groupName = model.getDataType().getDescription().toLowerCase() + "_group"; List<ClockModelGroup> groupsList = getClockModelGroups(); ClockModelGroup clockModelGroup; if (containsGroup(groupName, groupsList)) { clockModelGroup = getGroup(groupName, groupsList); } else { clockModelGroup = new ClockModelGroup(groupName); } model.setClockModelGroup(clockModelGroup); } } public List<ClockModelGroup> getClockModelGroups(DataType dataType) { List<ClockModelGroup> activeClockModelGroups = new ArrayList<ClockModelGroup>(); for (PartitionClockModel model : options.getPartitionClockModels(dataType)) { ClockModelGroup group = model.getClockModelGroup(); if (group != null && (!activeClockModelGroups.contains(group))) { activeClockModelGroups.add(group); } } return activeClockModelGroups; } public List<ClockModelGroup> getClockModelGroups(List<? extends AbstractPartitionData> givenDataPartitions) { List<ClockModelGroup> activeClockModelGroups = new ArrayList<ClockModelGroup>(); for (PartitionClockModel model : options.getPartitionClockModels(givenDataPartitions)) { ClockModelGroup group = model.getClockModelGroup(); if (group != null && (!activeClockModelGroups.contains(group))) { activeClockModelGroups.add(group); } } return activeClockModelGroups; } public List<ClockModelGroup> getClockModelGroups() { return getClockModelGroups(options.dataPartitions); } public Vector<String> getClockModelGroupNames(List<ClockModelGroup> group) { Vector<String> activeClockModelGroups = new Vector<String>(); for (ClockModelGroup clockModelGroup : group) { String name = clockModelGroup.getName(); if (name != null && (!activeClockModelGroups.contains(name))) { activeClockModelGroups.add(name); } } return activeClockModelGroups; } public boolean containsGroup(String groupName, List<ClockModelGroup> groupsList) { for (ClockModelGroup clockModelGroup : groupsList) { if (clockModelGroup.getName().equalsIgnoreCase(groupName)) return true; } return false; } public ClockModelGroup getGroup(String groupName, List<ClockModelGroup> groupsList) { for (ClockModelGroup clockModelGroup : groupsList) { if (clockModelGroup.getName().equalsIgnoreCase(groupName)) return clockModelGroup; } return null; } public void fixRateOfFirstClockPartition(ClockModelGroup group) { group.setRateTypeOption(FixRateType.RELATIVE_TO); // fix rate of 1st partition int i = 0; for (PartitionClockModel model : options.getPartitionClockModels(group)) { if (i < 1) { model.setEstimatedRate(false); } else { model.setEstimatedRate(true); } i = i + 1; } } public void fixMeanRate(ClockModelGroup group) { group.setRateTypeOption(FixRateType.FIX_MEAN); for (PartitionClockModel model : options.getPartitionClockModels(group)) { model.setEstimatedRate(true); // all set to NOT fixed, because detla exchange model.setRate(group.getFixMeanRate(), false); } } public void tipTimeCalibration(ClockModelGroup group) { group.setRateTypeOption(FixRateType.TIP_CALIBRATED); for (PartitionClockModel model : options.getPartitionClockModels(group)) { model.setEstimatedRate(true); } } public void nodeCalibration(ClockModelGroup group) { group.setRateTypeOption(FixRateType.NODE_CALIBRATED); for (PartitionClockModel model : options.getPartitionClockModels(group)) { model.setEstimatedRate(true); } } public void rateCalibration(ClockModelGroup group) { group.setRateTypeOption(FixRateType.RATE_CALIBRATED); for (PartitionClockModel model : options.getPartitionClockModels(group)) { model.setEstimatedRate(true); } } public String statusMessageClockModel(ClockModelGroup group) { String t; if (group.getRateTypeOption() == FixRateType.RELATIVE_TO) { if (options.getPartitionClockModels(group).size() == 1) { // single partition clock if (options.getPartitionClockModels(group).get(0).isEstimatedRate()) { t = "Estimate clock rate"; } else { t = "Fix clock rate to " + options.getPartitionClockModels(group).get(0).getRate(); } } else { // todo is the following code excuted? t = group.getRateTypeOption().toString() + " "; int c = 0; for (PartitionClockModel model : options.getPartitionClockModels(group)) { if (!model.isEstimatedRate()) { if (c > 0) t = t + ", "; c = c + 1; t = t + model.getName(); } } if (c == 0) t = "Estimate all clock rates"; if (c == options.getPartitionClockModels(group).size()) t = "Fix all clock rates"; } } else { t = group.getRateTypeOption().toString(); } return t + " in " + group.getName(); } public String statusMessageClockModel() { String t = ""; for (ClockModelGroup clockModelGroup : getClockModelGroups()) { t += statusMessageClockModel(clockModelGroup) + "; "; } return t; } // public FixRateType getRateOptionClockModel() { // return rateOptionClockModel; // public void setRateOptionClockModel(FixRateType rateOptionClockModel) { // this.rateOptionClockModel = rateOptionClockModel; // public void setMeanRelativeRate(double meanRelativeRate) { // this.meanRelativeRate = meanRelativeRate; // public double calculateAvgBranchLength(List<AbstractPartitionData> partitions) { // todo // double avgBranchLength = 1; // for (PartitionTreeModel tree : options.getPartitionTreeModels(partitions)) { // return MathUtils.round(avgBranchLength, 2); public double[] calculateInitialRootHeightAndRate(List<AbstractPartitionData> partitions) { double avgInitialRootHeight = 1; double avgInitialRate = 1; double avgMeanDistance = 1; // List<AbstractPartitionData> partitions = options.getDataPartitions(clockModelGroup); if (partitions.size() > 0) { avgMeanDistance = options.getAveWeightedMeanDistance(partitions); } if (options.getPartitionClockModels(partitions).size() > 0) { avgInitialRate = options.clockModelOptions.getSelectedRate(partitions); // all clock models //todo multi-group? ClockModelGroup clockModelGroup = options.getPartitionClockModels(partitions).get(0).getClockModelGroup(); switch (clockModelGroup.getRateTypeOption()) { case FIX_MEAN: case RELATIVE_TO: if (partitions.size() > 0) { avgInitialRootHeight = avgMeanDistance / avgInitialRate; } break; case TIP_CALIBRATED: avgInitialRootHeight = options.maximumTipHeight * 10.0;//TODO avgInitialRate = avgMeanDistance / avgInitialRootHeight;//TODO break; case NODE_CALIBRATED: avgInitialRootHeight = getCalibrationEstimateOfRootTime(partitions); if (avgInitialRootHeight < 0) avgInitialRootHeight = 1; // no leaf nodes avgInitialRate = avgMeanDistance / avgInitialRootHeight;//TODO break; case RATE_CALIBRATED: break; default: throw new IllegalArgumentException("Unknown fix rate type"); } } avgInitialRootHeight = MathUtils.round(avgInitialRootHeight, 2); avgInitialRate = MathUtils.round(avgInitialRate, 2); return new double[]{avgInitialRootHeight, avgInitialRate}; } public double getSelectedRate(List<AbstractPartitionData> partitions) { double selectedRate = 1; double avgInitialRootHeight; double avgMeanDistance = 1; // calibration: all isEstimatedRate = true // List<AbstractPartitionData> partitions = options.getDataPartitions(clockModelGroup); if (partitions.size() > 0 && options.getPartitionClockModels(partitions).size() > 0) { //todo multi-group? ClockModelGroup clockModelGroup = options.getPartitionClockModels(partitions).get(0).getClockModelGroup(); switch (clockModelGroup.getRateTypeOption()) { case FIX_MEAN: selectedRate = clockModelGroup.getFixMeanRate(); break; case RELATIVE_TO: List<PartitionClockModel> models = options.getPartitionClockModels(partitions); // fix ?th partition if (models.size() == 1) { selectedRate = models.get(0).getRate(); } else { selectedRate = getAverageRate(models); } break; case TIP_CALIBRATED: if (partitions.size() > 0) { avgMeanDistance = options.getAveWeightedMeanDistance(partitions); } avgInitialRootHeight = options.maximumTipHeight * 10.0;//TODO selectedRate = avgMeanDistance / avgInitialRootHeight;//TODO break; case NODE_CALIBRATED: if (partitions.size() > 0) { avgMeanDistance = options.getAveWeightedMeanDistance(partitions); } avgInitialRootHeight = getCalibrationEstimateOfRootTime(partitions); if (avgInitialRootHeight < 0) avgInitialRootHeight = 1; // no leaf nodes selectedRate = avgMeanDistance / avgInitialRootHeight;//TODO break; case RATE_CALIBRATED: //TODO break; default: throw new IllegalArgumentException("Unknown fix rate type"); } } return selectedRate; } // private List<AbstractPartitionData> getAllPartitionDataGivenClockModels(List<PartitionClockModel> models) { // List<AbstractPartitionData> allData = new ArrayList<AbstractPartitionData>(); // for (PartitionClockModel model : models) { // for (AbstractPartitionData partition : model.getDataPartitions()) { // if (partition != null && (!allData.contains(partition))) { // allData.add(partition); // return allData; private double getCalibrationEstimateOfRootTime(List<AbstractPartitionData> partitions) { // TODO - shouldn't this method be in the PartitionTreeModel?? List<Taxa> taxonSets = options.taxonSets; if (taxonSets != null && taxonSets.size() > 0) { // tmrca statistic // estimated root times based on each of the taxon sets double[] rootTimes = new double[taxonSets.size()]; for (int i = 0; i < taxonSets.size(); i++) { Taxa taxa = taxonSets.get(i); Parameter tmrcaStatistic = options.getStatistic(taxa); double taxonSetCalibrationTime = tmrcaStatistic.getPriorExpectationMean(); // the calibration distance is the patristic genetic distance back to the common ancestor of // the set of taxa. double calibrationDistance = 0; // the root distance is the patristic genetic distance back to the root of the tree. double rootDistance = 0; int siteCount = 0; for (AbstractPartitionData partition : partitions) { Tree tree = new UPGMATree(partition.getDistances()); Set<String> leafNodes = Taxa.Utils.getTaxonListIdSet(taxa); if (leafNodes.size() < 1) { return -1; } NodeRef node = Tree.Utils.getCommonAncestorNode(tree, leafNodes); calibrationDistance += tree.getNodeHeight(node); rootDistance += tree.getNodeHeight(tree.getRoot()); siteCount += partition.getSiteCount(); } rootDistance /= partitions.size(); calibrationDistance /= partitions.size(); if (calibrationDistance == 0.0) { calibrationDistance = 0.25 / siteCount; } if (rootDistance == 0) { rootDistance = 0.25 / siteCount; } rootTimes[i] += (rootDistance / calibrationDistance) * taxonSetCalibrationTime; } // return the mean estimate of the root time for this set of partitions return DiscreteStatistics.mean(rootTimes); } else { // prior on treeModel.rootHight double avgInitialRootHeight = 0; double count = 0; for (PartitionTreeModel tree : options.getPartitionTreeModels(partitions)) { avgInitialRootHeight = avgInitialRootHeight + tree.getInitialRootHeight(); count = count + 1; } if (count != 0) avgInitialRootHeight = avgInitialRootHeight / count; return avgInitialRootHeight; } } // FixRateType.FIX_MEAN // public double getMeanRelativeRate() { // return meanRelativeRate; // FixRateType.ESTIMATE public double getAverageRate(List<PartitionClockModel> models) { //TODO average per tree, but how to control the estimate clock => tree? double averageRate = 0; double count = 0; for (PartitionClockModel model : models) { if (!model.isEstimatedRate()) { averageRate = averageRate + model.getRate(); count = count + 1; } } if (count > 0) { averageRate = averageRate / count; } else { averageRate = 1; //TODO how to calculate rate when estimate all } return averageRate; } // Calibration Series Data public double getAverageRateForCalibrationSeriesData() { //TODO return (double) 0; } // Calibration TMRCA public double getAverageRateForCalibrationTMRCA() { //TODO return (double) 0; } public boolean isTipCalibrated() { return options.maximumTipHeight > 0; } public boolean isRateCalibrated() { return false;//TODO } public int[] getPartitionClockWeights(ClockModelGroup group) { int[] weights = new int[options.getPartitionClockModels().size()]; // use List? int k = 0; for (PartitionClockModel model : options.getPartitionClockModels()) { for (AbstractPartitionData partition : options.getDataPartitions(model)) { int n = partition.getSiteCount(); weights[k] += n; } k += 1; } assert (k == weights.length); return weights; } // public void fixRateOfFirstClockPartition() { // this.rateOptionClockModel = FixRateType.RELATIVE_TO; // // fix rate of 1st partition // int i = 0; // for (PartitionClockModel model : options.getPartitionClockModels()) { // if (i < 1) { // model.setEstimatedRate(false); // } else { // model.setEstimatedRate(true); // i = i + 1; // public void fixMeanRate() { // this.rateOptionClockModel = FixRateType.FIX_MEAN; // for (PartitionClockModel model : options.getPartitionClockModels()) { // model.setEstimatedRate(true); // all set to NOT fixed, because detla exchange // public void tipTimeCalibration() { // this.rateOptionClockModel = FixRateType.TIP_CALIBRATED; // for (PartitionClockModel model : options.getPartitionClockModels()) { // model.setEstimatedRate(true); // public void nodeCalibration() { // this.rateOptionClockModel = FixRateType.NODE_CALIBRATED; // for (PartitionClockModel model : options.getPartitionClockModels()) { // model.setEstimatedRate(true); // public void rateCalibration() { // this.rateOptionClockModel = FixRateType.RATE_CALIBRATED; // for (PartitionClockModel model : options.getPartitionClockModels()) { // model.setEstimatedRate(true); // public String statusMessageClockModel() { // if (rateOptionClockModel == FixRateType.RELATIVE_TO) { // if (options.getPartitionClockModels().size() == 1) { // single partition clock // if (options.getPartitionClockModels().get(0).isEstimatedRate()) { // return "Estimate clock rate"; // } else { // return "Fix clock rate to " + options.getPartitionClockModels().get(0).getRate(); // } else { // String t = rateOptionClockModel.toString() + " "; // int c = 0; // for (PartitionClockModel model : options.getPartitionClockModels()) { // if (!model.isEstimatedRate()) { // if (c > 0) t = t + ", "; // c = c + 1; // t = t + model.getName(); // if (c == 0) t = "Estimate all clock rates"; // if (c == options.getPartitionClockModels().size()) t = "Fix all clock rates"; // return t; // } else { // return rateOptionClockModel.toString(); //+++++++++++++++++++++++ Validation ++++++++++++++++++++++++++++++++ // true => valid, false => warning message // public boolean validateFixMeanRate(boolean fixedMeanRateCheck) { // return !(fixedMeanRateCheck && options.getPartitionClockModels().size() < 2); // public boolean validateRelativeTo() { // for (PartitionClockModel model : options.getPartitionClockModels()) { // if (!model.isEstimatedRate()) { // fixed // return true; // return false; }
package dr.app.tools; import dr.app.util.Arguments; import dr.geo.math.SphericalPolarCoordinates; import dr.stats.DiscreteStatistics; import org.jdom.Element; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class DiscreteRatePriorGenerator { public static final String HELP = "help"; public static final String COORDINATES = "coordinates"; public static final String DENSITIES = "densities"; public static final String GENERICS = "generics"; public static final String FORMAT = "format"; public static final String MODEL = "model"; public DiscreteRatePriorGenerator(String[] locations, Double[] latitudes, Double[] longitudes, Double[] densities) { if (locations == null) { //System.out.println(locations[0]); System.err.println("no locations specified!"); } else { this.locations = locations; } this.latitudes = latitudes; this.longitudes = longitudes; this.densities = densities; if ((latitudes == null)||(longitudes == null)) { progressStream.println("no latitudes or longitudes specified!"); } else { distances = getUpperTriangleDistanceMatrix(latitudes,longitudes); } if (densities != null) { densityDonorMatrix = getDensityMatrix(densities, true); densityRecipientMatrix = getDensityMatrix(densities, false); } } // for the time being, locations, latitudes and longitudes are not required private String[] locations; private Double[] latitudes; private Double[] longitudes; private final Double[] densities; private double[] distances; private double[] densityDonorMatrix; private double[] densityRecipientMatrix; private double[] getUpperTriangleDistanceMatrix(Double[] latitudes, Double[] longitudes) { double[] distances = new double[(latitudes.length * (latitudes.length - 1))/2]; int distanceCounter = 0; int pairwiseCounter1 = 0; for (int c = 0; c < latitudes.length; c++) { pairwiseCounter1 ++; for (int d = pairwiseCounter1; d < latitudes.length; d++) { distances[distanceCounter] = getKilometerGreatCircleDistance(latitudes[c],longitudes[c],latitudes[d],longitudes[d]); distanceCounter++; } } return distances; } private double[] getFullDistanceMatrix(Double[] latitudes, Double[] longitudes) { double[] distances = new double[latitudes.length * latitudes.length]; int distanceCounter = 0; for (int a = 0; a < latitudes.length; a++) { //resultsStream.print(locations[a]+"\t"); for (int b = 0; b < latitudes.length; b++) { distances[distanceCounter] = getKilometerGreatCircleDistance(latitudes[a],longitudes[a],latitudes[b],longitudes[b]); distanceCounter++; } } return distances; } private double[] getFullCoordDiffMatrix(Double[] coordinates, boolean positive, boolean negative) { double[] differences = new double[coordinates.length * coordinates.length]; int differenceCounter = 0; for (int a = 0; a < coordinates.length; a++) { for (int b = 0; b < coordinates.length; b++) { double difference = coordinates[b]-coordinates[a]; if (difference > 0 && positive) { differences[differenceCounter] = difference; } else if (difference < 0 && negative) { differences[differenceCounter] = difference; } else { differences[differenceCounter] = 0; } differenceCounter++; } } return differences; } private static double getKilometerGreatCircleDistance(double lat1, double long1, double lat2, double long2) { SphericalPolarCoordinates coord1 = new SphericalPolarCoordinates(lat1, long1); SphericalPolarCoordinates coord2 = new SphericalPolarCoordinates(lat2, long2); return (coord1.distance(coord2)); } private double[] getDensityMatrix(Double[] densities, boolean donor) { double[] returnMatrix = new double[densities.length * (densities.length - 1)]; int distanceCounter = 0; int matrixEntry; for (int c = 0; c < densities.length; c++) { for (int d = 0; d < densities.length; d++) { if (c == d) { continue; } if (donor) { matrixEntry = c; } else { matrixEntry = d; } returnMatrix[distanceCounter] = densities[matrixEntry]; distanceCounter++; } } return returnMatrix; } private void printLocations(String[] locs, boolean upper) { int pairwiseCounter1 = 0; for (int c = 0; c < locs.length; c++) { pairwiseCounter1 ++; for (int d = pairwiseCounter1; d < locs.length; d++) { if (upper) { System.out.println(locs[c]+"\t"+locs[d]); } else { System.out.println(locs[d]+"\t"+locs[c]); } } } } private void printLocationsDensitiesDistances (String[] locs, boolean upper) { double[] firstDensity = getSingleElementFromFullMatrix(densities,false); double[] secondDensity = getSingleElementFromFullMatrix(densities,true); System.out.println("location1\tlocation2\tdistance\tdensity1\tdensity2"); int pairwiseCounter1 = 0; int arrayCounter = 0; for (int c = 0; c < locs.length; c++) { pairwiseCounter1 ++; for (int d = pairwiseCounter1; d < locs.length; d++) { if (upper) { System.out.println(locs[c]+"\t"+locs[d]+"\t"+distances[arrayCounter]+"\t"+firstDensity[arrayCounter]+"\t"+secondDensity[arrayCounter]); arrayCounter ++; } else { System.out.println(locs[d]+"\t"+locs[c]+"\t"+distances[arrayCounter]+"\t"+firstDensity[(firstDensity.length/2)+arrayCounter]+"\t"+secondDensity[(secondDensity.length/2)+arrayCounter]); arrayCounter ++; } } } } private void printFullDistanceMatrix(String name, boolean locationNames) { try { PrintWriter outFile = new PrintWriter(new FileWriter(name), true); outFile.print("location"); for (int a = 0; a < locations.length; a++) { outFile.print(locations[a]+"\t"); for (int b = 0; b < locations.length; b++) { double lat1 = latitudes[a]; double lat2 = latitudes[b]; double long1 = longitudes[a]; double long2 = longitudes[b]; double distance = getKilometerGreatCircleDistance(lat1,long1,lat2,long2); outFile.print(distance+"\t"); } outFile.print("\r"); } outFile.close(); } catch(IOException io) { System.err.print("Error writing to file: " + name); } } enum OutputFormat { TAB, SPACE, XML } enum Model { PRIOR, GLM, JUMP } public void output(String outputFileName, OutputFormat outputFormat, Model model) { //printLocations(locations,false); //printLocationsDensitiesDistances(locations,true); //printLocationsDensitiesDistances(locations,false); //printFullDistanceMatrix("test.txt", false); resultsStream = System.out; if (outputFileName != null) { try { resultsStream = new PrintStream(new File(outputFileName)); } catch (IOException e) { System.err.println("Error opening file: "+outputFileName); System.exit(1); } } if (model == model.PRIOR) { int predictor = 0; if (distances != null) { outputStringLine("reversible priors: distances",outputFormat); resultsStream.print("\r"); outputArray(distances, outputFormat, model, predictor, false); resultsStream.print("\r"); outputStringLine("reversible priors: normalized inverse distances",outputFormat); resultsStream.print("\r"); outputArray(transform(distances,true, true, false, false), outputFormat, model, predictor, false); resultsStream.print("\r"); outputStringLine("reversible priors: normalized inverse log distances",outputFormat); resultsStream.print("\r"); outputArray(transform(distances,true, true, false, true), outputFormat, model, predictor, false); resultsStream.print("\r"); } if (densities != null) { outputStringLine("reversible priors: densities",outputFormat); resultsStream.print("\r"); outputArray(transform(getUpperTrianglePairwiseProductMatrix(densities),false,false,false,false), outputFormat, model, predictor, false); resultsStream.print("\r"); outputStringLine("reversible priors: normalized densities",outputFormat); resultsStream.print("\r"); outputArray(transform(getUpperTrianglePairwiseProductMatrix(densities),false,true,false,false), outputFormat, model, predictor, false); resultsStream.print("\r"); outputStringLine("reversible priors: normalized log densities",outputFormat); resultsStream.print("\r"); outputArray(transform(getUpperTrianglePairwiseProductMatrix(densities),false,true,false,true), outputFormat, model, predictor, false); resultsStream.print("\r"); if (distances != null) { outputStringLine("reversible priors: product of normalized densities divided by normalized distances",outputFormat); resultsStream.print("\r"); outputArray(productOfArrays(transform(getUpperTrianglePairwiseProductMatrix(densities),false,true,false,false),transform(distances,false, true,false,false),true), outputFormat, model, predictor, false); resultsStream.print("\r"); outputStringLine("reversible priors: normalized product of densities divided by distances",outputFormat); resultsStream.print("\r"); outputArray(transform(productOfArrays(getUpperTrianglePairwiseProductMatrix(densities),distances, true),false,true,false,false), outputFormat, model, predictor, false); resultsStream.print("\r"); outputStringLine("reversible priors: normalized log product of densities divided by distances",outputFormat); resultsStream.print("\r"); outputArray(transform(productOfArrays(getUpperTrianglePairwiseProductMatrix(densities),distances, true),false,true,false,true), outputFormat, model, predictor, false); resultsStream.print("\r"); } } if (distances != null) { outputStringLine("nonreversible priors: distances",outputFormat); resultsStream.print("\r"); outputArray(distances, outputFormat, model, predictor, true); resultsStream.print("\r"); outputStringLine("nonreversible priors: normalized inverse distances",outputFormat); resultsStream.print("\r"); outputArray(transform(distances,true, true, false, false), outputFormat, model, predictor, true); resultsStream.print("\r"); outputStringLine("nonreversible priors: normalized inverse log distances",outputFormat); resultsStream.print("\r"); outputArray(transform(distances,true, true, false, true), outputFormat, model,predictor, true); resultsStream.print("\r"); } if (densities != null) { outputStringLine("nonreversible priors: densities",outputFormat); resultsStream.print("\r"); outputArray(transform(getUpperTrianglePairwiseProductMatrix(densities),false,false,false,false), outputFormat, model, predictor, true); resultsStream.print("\r"); outputStringLine("nonreversible priors: normalized densities",outputFormat); resultsStream.print("\r"); outputArray(transform(getUpperTrianglePairwiseProductMatrix(densities),false,true,false,false), outputFormat, model, predictor, true); resultsStream.print("\r"); outputStringLine("nonreversible priors: normalized log densities",outputFormat); resultsStream.print("\r"); outputArray(transform(getUpperTrianglePairwiseProductMatrix(densities),false,true,false,true), outputFormat, model, predictor, true); resultsStream.print("\r"); if (distances != null) { outputStringLine("nonreversible priors: product of normalized densities divided by normalized distances",outputFormat); resultsStream.print("\r"); outputArray(productOfArrays(transform(getUpperTrianglePairwiseProductMatrix(densities),false,true,false,false),transform(distances,false, true, false, false),true), outputFormat, model, predictor, true); resultsStream.print("\r"); outputStringLine("nonreversible priors: normalized product of densities divided by distances",outputFormat); resultsStream.print("\r"); outputArray(transform(productOfArrays(getUpperTrianglePairwiseProductMatrix(densities),distances, true),false,true,false,false), outputFormat, model, predictor, true); resultsStream.print("\r"); outputStringLine("nonreversible priors: normalized log product of densities divided by distances",outputFormat); resultsStream.print("\r"); outputArray(transform(productOfArrays(getUpperTrianglePairwiseProductMatrix(densities),distances, true),false,true,false,true), outputFormat, model, predictor, true); resultsStream.print("\r"); } } } else if (model == model.GLM) { int predictor = 1; //TODO: fully implement glm output if (distances != null) { //printLocations(locations, true); //printLocations(locations, false); outputStringLine("predictor: distances",outputFormat); resultsStream.print("\r"); outputArray(transform(distances,false, false, true, false), outputFormat, model, predictor, true); predictor++; outputStringLine("predictor: standardized log distances",outputFormat); resultsStream.print("\r"); outputArray(transform(distances,false, false, true, true), outputFormat, model, predictor, true); } if (densities != null) { predictor++; outputStringLine("predictor: standardized donor densities",outputFormat); resultsStream.print("\r"); outputArray(transform(getSingleElementFromFullMatrix(densities, false),false,false,true,true), outputFormat, model, predictor, false); predictor++; outputStringLine("predictor: standardized recipient densities",outputFormat); resultsStream.print("\r"); outputArray(transform(getSingleElementFromFullMatrix(densities, true),false,false,true,true), outputFormat, model, predictor, false); // products not necessary, and shouldn't be normalized but standardized, also log // outputStringLine("predictor: normalized product of densities divided by distances",outputFormat); // resultsStream.print("\r"); // outputArray(transform(productOfArrays(getUpperTrianglePairwiseProductMatrix(densities),distances, true),false,true,false,false), outputFormat, predictor, true); // resultsStream.print("\r"); // predictor++; // outputStringLine("predictor: normalized log product of densities divided by distances",outputFormat); // resultsStream.print("\r"); // outputArray(transform(productOfArrays(getUpperTrianglePairwiseProductMatrix(densities),distances, true),false,true,false,true), outputFormat, predictor, true); // resultsStream.print("\r"); } } else if (model == model.JUMP) { int predictor = 0; outputStringLine("great circle distance jump matrix",outputFormat); resultsStream.print("\r"); outputArray(transform(getFullDistanceMatrix(latitudes, longitudes),false,false,false,false), outputFormat, model, predictor, false); resultsStream.print("\r"); predictor ++; outputStringLine("latitude jump matrix",outputFormat); resultsStream.print("\r"); outputArray(transform(getFullCoordDiffMatrix(latitudes, true, true),false,false,false,false), outputFormat, model, predictor, false); resultsStream.print("\r"); predictor ++; outputStringLine("longitude jump matrix",outputFormat); resultsStream.print("\r"); outputArray(transform(getFullCoordDiffMatrix(longitudes, true, true),false,false,false,false), outputFormat, model, predictor, false); resultsStream.print("\r"); predictor ++; outputStringLine("westward jump matrix",outputFormat); resultsStream.print("\r"); outputArray(transform(getFullCoordDiffMatrix(longitudes, false, true),false,false,false,false), outputFormat, model, predictor, false); resultsStream.print("\r"); predictor ++; outputStringLine("eastward jump matrix",outputFormat); resultsStream.print("\r"); outputArray(transform(getFullCoordDiffMatrix(longitudes, true, false),false,false,false,false), outputFormat, model, predictor, false); resultsStream.print("\r"); predictor ++; outputStringLine("northward jump matrix",outputFormat); resultsStream.print("\r"); outputArray(transform(getFullCoordDiffMatrix(latitudes, true, false),false,false,false,false), outputFormat, model, predictor, false); resultsStream.print("\r"); predictor ++; outputStringLine("southward jump matrix",outputFormat); resultsStream.print("\r"); outputArray(transform(getFullCoordDiffMatrix(latitudes, false, true),false,false,false,false), outputFormat, model, predictor, false); resultsStream.print("\r"); predictor ++; // outputStringLine("latitude reward parameter",outputFormat); // resultsStream.print("\r"); // outputArray(transform(objectToPrimitiveArray(latitudes),false,false,false,false), outputFormat, model, predictor, false); // resultsStream.print("\r"); // predictor ++; // outputStringLine("longitude reward parameter",outputFormat); // resultsStream.print("\r"); // outputArray(transform(objectToPrimitiveArray(longitudes),false,false,false,false), outputFormat, model, predictor, false); // resultsStream.print("\r"); // predictor ++; for (int i = 0; i < locations.length; i++) { double[] locationReward = getLocationReward(i,locations.length); outputStringLine(locations[i]+" reward parameter",outputFormat); resultsStream.print("\r"); outputArray(transform(locationReward,false,false,false,false), outputFormat, model, predictor, false); resultsStream.print("\r"); predictor ++; } } } private double[] getUpperTrianglePairwiseProductMatrix(Double[] matrixValues) { double[] pairwiseProducts = new double[(matrixValues.length * (matrixValues.length - 1))/2]; int counter = 0; int pairwiseCounter1 = 0; for(Double matrixValue : matrixValues) { pairwiseCounter1++; for(int d = pairwiseCounter1; d < matrixValues.length; d++) { pairwiseProducts[counter] = matrixValue * matrixValues[d]; counter++; } } return pairwiseProducts; } private double[] getSingleElementFromFullMatrix(Double[] matrixValues, boolean secondElement) { double[] singleElements = new double[(matrixValues.length * (matrixValues.length - 1))]; //System.out.println("matrixsize "+(matrixValues.length * (matrixValues.length - 1))); //get upper matrix int counter = 0; int pairwiseCounter1 = 0; for(Double matrixValue : matrixValues) { pairwiseCounter1++; for(int d = pairwiseCounter1; d < matrixValues.length; d++) { if (secondElement) { singleElements[counter] = matrixValues[d]; } else { singleElements[counter] = matrixValue; } counter++; } } //get lower matrix int pairwiseCounter2 = 0; for(Double matrixValue : matrixValues) { pairwiseCounter2++; for(int d = pairwiseCounter2; d < matrixValues.length; d++) { if (secondElement) { singleElements[counter] = matrixValue; } else { singleElements[counter] = matrixValues[d]; } counter++; } } //System.out.println("counter "+counter); return singleElements; } private double[] productOfArrays(double[] inputArray1, double[] inputArray2, boolean devision) { if (inputArray1.length != inputArray2.length) { System.err.println("trying to get a product of arrays of unequals size!"); System.exit(1); } double[] productOfArray = new double[inputArray1.length]; for (int i = 0; i < inputArray1.length; i++) { if (devision) { productOfArray[i] = inputArray1[i]/inputArray2[i]; } else { } productOfArray[i] = inputArray1[i]*inputArray2[i]; } return productOfArray; } // normalize is really rescaling the vector to have a mean = 1 here, standardize is rescaling it to have mean = 0 and variance =1 private double[] transform(double[] inputArray, boolean inverse, boolean normalize, boolean standardize, boolean log) { double[] transformedDistances = new double[inputArray.length]; for(int u=0; u<inputArray.length; u++) { double distance = inputArray[u]; if (log) { distance = Math.log(distance); } if (inverse) { distance = 1/distance; } transformedDistances[u] = distance; } double meanDistance = 1; double stdev = 0; if (normalize || standardize) { meanDistance = DiscreteStatistics.mean(transformedDistances); } if (standardize) { stdev = Math.sqrt(DiscreteStatistics.variance(transformedDistances)); } for(int v=0; v<inputArray.length; v++) { if (normalize) { transformedDistances[v] = (transformedDistances[v]/meanDistance); } else if (standardize) { transformedDistances[v] = ((transformedDistances[v] - meanDistance)/stdev); } } return transformedDistances; } private void outputArray(double[] array, OutputFormat outputFormat, Model model, int predictor, boolean nonreversible) { StringBuilder sb1 = new StringBuilder(); StringBuilder sb2 = new StringBuilder(); String sep; if (outputFormat == OutputFormat.TAB ) { sep = "\t"; } else { sep = " "; } //String newLine = "\n"; //here we break up the jump parameter output in a lenght*by*length matrix // int entryCounter = 1; // double length = Math.sqrt(array.length); // System.out.println(length); // for(double anArray : array) { // if (model == model.JUMP) { // if ( (entryCounter % length) > 0 ) { // sb1.append(anArray + sep); // sb2.append(1 + sep); // entryCounter ++; // } else { // System.out.println("return"); // sb1.append(newLine+anArray + sep); // sb2.append(newLine+1 + sep); // entryCounter ++; // } else { // sb1.append(anArray + sep); // sb2.append(1 + sep); for(double anArray : array) { sb1.append(anArray + sep); sb2.append(1 + sep); } if (outputFormat == OutputFormat.XML ) { if (model == model.GLM) { Element parameter = new Element("parameter"); parameter.setAttribute("id","predictor"+predictor); if (nonreversible) { parameter.setAttribute("value",(sb1.toString()+sb1.toString())); } else { parameter.setAttribute("value",sb1.toString()); } XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat().setTextMode(Format.TextMode.PRESERVE)); try { xmlOutputter.output(parameter,resultsStream); } catch (IOException e) { System.err.println("IO Exception encountered: "+e.getMessage()); System.exit(-1); } resultsStream.print("\r"); } else if (model == model.PRIOR) { Element priorElement = new Element("multivariateGammaPrior"); Element data = new Element("data"); Element parameter1 = new Element("parameter"); parameter1.setAttribute("idref","rates"); data.addContent(parameter1); Element meanParameter = new Element("meanParameter"); Element parameter2 = new Element("parameter"); if (nonreversible) { parameter2.setAttribute("value",(sb1.toString()+sb1.toString())); } else { parameter2.setAttribute("value",sb1.toString()); } meanParameter.addContent(parameter2); Element coefficientOfVariation = new Element("coefficientOfVariation"); Element parameter3 = new Element("parameter"); if (nonreversible) { parameter3.setAttribute("value",sb2.toString()+sb2.toString()); } else { parameter3.setAttribute("value",sb2.toString()); } coefficientOfVariation.addContent(parameter3); priorElement.addContent(data); priorElement.addContent(meanParameter); priorElement.addContent(coefficientOfVariation); XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat().setTextMode(Format.TextMode.PRESERVE)); try { xmlOutputter.output(priorElement,resultsStream); } catch (IOException e) { System.err.println("IO Exception encountered: "+e.getMessage()); System.exit(-1); } resultsStream.print("\r"); } else if (model == model.JUMP) { Element parameter = new Element("parameter"); parameter.setAttribute("id","jump"+predictor); parameter.setAttribute("value",sb1.toString()); XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat().setTextMode(Format.TextMode.PRESERVE)); try { xmlOutputter.output(parameter,resultsStream); } catch (IOException e) { System.err.println("IO Exception encountered: "+e.getMessage()); System.exit(-1); } resultsStream.print("\r"); } } else { if (nonreversible) { resultsStream.print(sb1.toString()+sb1.toString()+"\r"); } else { resultsStream.print(sb1+"\r"); } } } private void outputStringLine(String outputString, OutputFormat outputFormat) { if (outputFormat == OutputFormat.XML ) { resultsStream.print("<! } resultsStream.print(outputString); if (outputFormat == OutputFormat.XML ) { resultsStream.print(" } else { resultsStream.print("\r"); } } private double[] objectToPrimitiveArray(Double[] array) { double[] returnArray = new double[array.length]; int counter = 0; for(Double anArray : array) { returnArray[counter] = anArray.doubleValue(); counter ++; } return returnArray; } private double[] getLocationReward(int indicator, int length) { double[] returnArray = new double[length]; for (int i = 0; i < length; i++) { if (i == indicator) { returnArray[i] = 1.0; } else { returnArray[i] = 0.0; } } return returnArray; } // Messages to stderr, output to stdout private static final PrintStream progressStream = System.err; private PrintStream resultsStream; private static final String commandName = "discreteRatePriorGenerator"; public static void printUsage(Arguments arguments) { arguments.printUsage(commandName, "[<output-file-name>]"); progressStream.println(); progressStream.println(" Example: " + commandName + " coordinates.txt ratePriors.txt"); progressStream.println(); } private static ArrayList parseCoordinatesFile(String inputFile, String[] locations, Double[] latitudes, Double[] longitudes) { ArrayList<Object[]> returnList = new ArrayList<Object[]>(); List<String> countList = new ArrayList<String>(); try{ BufferedReader reader = new BufferedReader(new FileReader(inputFile)); String line = reader.readLine(); while (line != null && !line.equals("")) { countList.add(line); line = reader.readLine(); } } catch (IOException e) { System.err.println("Error reading " + inputFile); System.exit(1); } if (countList.size()>0) { locations = new String[countList.size()]; latitudes = new Double[countList.size()]; longitudes = new Double[countList.size()]; for(int i=0; i<countList.size(); i++) { StringTokenizer tokens = new StringTokenizer(countList.get(i)); locations[i] = tokens.nextToken("\t"); latitudes[i] = Double.parseDouble(tokens.nextToken("\t")); longitudes[i] = Double.parseDouble(tokens.nextToken("\t")); //System.out.println(locations[i]+"\t"+latitudes[i]+"\t"+longitudes[i]); } } returnList.add(locations); returnList.add(latitudes); returnList.add(longitudes); return returnList; } private static ArrayList parseSingleMeasureFile(String inputFile, String[] locations, Double[] densities) { ArrayList<Object[]> returnList = new ArrayList<Object[]>(); boolean locationsSpecified = true; if (locations == null) { locationsSpecified = false; } List<String> countList = new ArrayList<String>(); try{ BufferedReader reader = new BufferedReader(new FileReader(inputFile)); String line = reader.readLine(); while (line != null && !line.equals("")) { countList.add(line); line = reader.readLine(); } } catch (IOException e) { System.err.println("Error reading " + inputFile); System.exit(1); } if (countList.size()>0) { if (!locationsSpecified) { locations = new String[countList.size()]; } densities = new Double[countList.size()]; for(int i=0; i<countList.size(); i++) { StringTokenizer tokens = new StringTokenizer(countList.get(i)); String location = tokens.nextToken("\t"); if (!locationsSpecified) { locations[i] = location; } else { if (!(locations[i].equals(location))) { System.err.println("Error in location specification in different files: " + locations[i] + "is not = " + location); } } densities[i] = Double.parseDouble(tokens.nextToken("\t")); } } returnList.add(locations); returnList.add(densities); return returnList; } public static void main(String[] args) throws IOException { String outputFileName = null; String[] locations = null; Double[] latitudes = null; Double[] longitudes = null; Double[] densities = null; OutputFormat outputFormat = OutputFormat.XML; Model model = Model.PRIOR; Arguments arguments = new Arguments( new Arguments.Option[]{ new Arguments.StringOption(COORDINATES, "coordinate file", "specifies a tab-delimited file with coordinates for the locations"), new Arguments.StringOption(DENSITIES, "density file", "specifies a tab-delimited file with densities for the locations"), new Arguments.StringOption(GENERICS, "generics file", "specifies a tab-delimited file-list to use as measures for the locations"), new Arguments.StringOption(FORMAT, TimeSlicer.enumNamesToStringArray(OutputFormat.values()),false, "prior output format [default = XML]"), new Arguments.StringOption(MODEL, TimeSlicer.enumNamesToStringArray(Model.values()),false, "model output [default = rate priors]"), //example: new Arguments.RealOption(MRSD,"specifies the most recent sampling data in fractional years to rescale time [default=0]"), new Arguments.Option(HELP, "option to print this message"), }); try { arguments.parseArguments(args); } catch (Arguments.ArgumentException ae) { progressStream.println(ae); printUsage(arguments); System.exit(1); } if (arguments.hasOption(HELP)) { printUsage(arguments); System.exit(0); } String coordinatesFileString = arguments.getStringOption(COORDINATES); if (coordinatesFileString != null) { ArrayList LocsLatsLongs = parseCoordinatesFile(coordinatesFileString,locations,latitudes,longitudes); locations = (String[]) LocsLatsLongs.get(0); latitudes = (Double[]) LocsLatsLongs.get(1); longitudes = (Double[]) LocsLatsLongs.get(2); } String densitiesFileString = arguments.getStringOption(DENSITIES); if (densitiesFileString != null) { ArrayList LocsDens = parseSingleMeasureFile(densitiesFileString,locations,densities); locations = (String[]) LocsDens.get(0); densities = (Double[]) LocsDens.get(1); } //TODO: support reading any measure (GENERICS) String summaryFormat = arguments.getStringOption(FORMAT); if (summaryFormat != null) { outputFormat = OutputFormat.valueOf(summaryFormat.toUpperCase()); } String modelComponent = arguments.getStringOption(MODEL); if (modelComponent != null) { model = Model.valueOf(modelComponent.toUpperCase()); } final String[] args2 = arguments.getLeftoverArguments(); switch (args2.length) { case 0: printUsage(arguments); System.exit(1); case 1: outputFileName = args2[0]; break; default: { System.err.println("Unknown option: " + args2[1]); System.err.println(); printUsage(arguments); System.exit(1); } } DiscreteRatePriorGenerator rates = new DiscreteRatePriorGenerator(locations, latitudes, longitudes, densities); rates.output(outputFileName, outputFormat, model); System.exit(0); } private static void printArray(Double[] array, String name) { try { PrintWriter outFile = new PrintWriter(new FileWriter(name), true); for(Double anArray : array) { outFile.print(anArray + "\t"); } outFile.close(); } catch(IOException io) { System.err.print("Error writing to file: " + name); } } private static void printArray(String[] array, String name) { try { PrintWriter outFile = new PrintWriter(new FileWriter(name), true); for(String anArray : array) { outFile.print(anArray + "\t"); } outFile.close(); } catch(IOException io) { System.err.print("Error writing to file: " + name); } } }
package com.blogspot.sontx.bottle.presenter; import android.support.annotation.Nullable; import com.blogspot.sontx.bottle.App; import com.blogspot.sontx.bottle.model.bean.PublicProfile; import com.blogspot.sontx.bottle.model.bean.chat.Channel; import com.blogspot.sontx.bottle.model.bean.chat.ChannelDetail; import com.blogspot.sontx.bottle.model.bean.chat.ChannelMember; import com.blogspot.sontx.bottle.model.dummy.DummyAnimals; import com.blogspot.sontx.bottle.model.service.Callback; import com.blogspot.sontx.bottle.model.service.FirebaseServicePool; import com.blogspot.sontx.bottle.model.service.interfaces.ChannelService; import com.blogspot.sontx.bottle.model.service.interfaces.ChatService; import com.blogspot.sontx.bottle.model.service.interfaces.PublicProfileService; import com.blogspot.sontx.bottle.presenter.interfaces.ListChannelPresenter; import com.blogspot.sontx.bottle.system.event.ChatChannelAddedEvent; import com.blogspot.sontx.bottle.system.event.ChatChannelChangedEvent; import com.blogspot.sontx.bottle.system.event.ChatChannelRemovedEvent; import com.blogspot.sontx.bottle.view.interfaces.ListChannelView; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.List; public class ListChannelPresenterImpl extends PresenterBase implements ListChannelPresenter { private final ListChannelView listChannelView; private final ChannelService channelService; private final PublicProfileService publicProfileService; private List<Channel> channels; private boolean isUpdatedChannels = false; public ListChannelPresenterImpl(ListChannelView ListChannelView) { this.listChannelView = ListChannelView; this.channelService = FirebaseServicePool.getInstance().getChannelService(); this.publicProfileService = FirebaseServicePool.getInstance().getPublicProfileService(); } @Override public void updateChannelsIfNecessary() { if (isUpdatedChannels && channels != null) return; if (!App.getInstance().getBottleContext().isLogged()) return; listChannelView.clearChannels(); channelService.getCurrentChannelsAsync(new Callback<List<Channel>>() { @Override public void onSuccess(List<Channel> result) { channels = result; if (channelService.isCachedChannels()) { for (Channel channel : channels) { DummyAnimals.mix(channel.getAnotherGuy().getPublicProfile()); } listChannelView.showChannels(channels); } else if (!channels.isEmpty()) { for (Channel channel : channels) { getChannelDetailAsync(channel); getChannelMembersAsync(channel); } } ChatService chatService = FirebaseServicePool.getInstance().getChatService(); for (Channel channel : channels) { chatService.registerChannel(channel); } isUpdatedChannels = true; } @Override public void onError(Throwable what) { listChannelView.showErrorMessage(what); } }); } @Override public void registerEvents() { EventBus.getDefault().register(this); } @Override public void unregisterEvents() { EventBus.getDefault().unregister(this); } @Override public void createChannelAsync(final String anotherMemberId) { final Channel channel = channelService.createChannel(anotherMemberId); List<ChannelMember> memberList = channel.getMemberList(); if (memberList.get(0).getId().equals(anotherMemberId)) { getPublicProfileAsync(memberList.get(0), channel); getPublicProfileAsync(memberList.get(1), null); } else { getPublicProfileAsync(memberList.get(0), null); getPublicProfileAsync(memberList.get(1), channel); } } @Subscribe(threadMode = ThreadMode.MAIN) public void onChatChannelAddedEvent(ChatChannelAddedEvent chatChannelAddedEvent) { Channel channel = chatChannelAddedEvent.getChannel(); ChatService chatService = FirebaseServicePool.getInstance().getChatService(); chatService.registerChannel(channel); DummyAnimals.mix(channel.getAnotherGuy().getPublicProfile()); listChannelView.showChannel(channel); } @Subscribe(threadMode = ThreadMode.MAIN) public void onChatChannelRemovedEvent(ChatChannelRemovedEvent chatChannelRemovedEvent) { String channelId = chatChannelRemovedEvent.getChannelId(); ChatService chatService = FirebaseServicePool.getInstance().getChatService(); chatService.unregisterChannel(channelId); listChannelView.removeChannel(channelId); } @Subscribe(threadMode = ThreadMode.MAIN) public void onChatChannelChangedEvent(ChatChannelChangedEvent chatChannelChangedEvent) { listChannelView.showChannel(chatChannelChangedEvent.getChannel()); } private void getPublicProfileAsync(final ChannelMember channelMember, @Nullable final Channel channel) { publicProfileService.getPublicProfileAsync(channelMember.getId(), new Callback<PublicProfile>() { @Override public void onSuccess(PublicProfile result) { DummyAnimals.mix(result); channelMember.setPublicProfile(result); if (channel != null) { listChannelView.showChannel(channel); } } @Override public void onError(Throwable what) { listChannelView.showErrorMessage(what); } }); } private void getChannelMembersAsync(final Channel channel) { channelService.getChannelMembersAsync(channel.getId(), new Callback<List<ChannelMember>>() { @Override public void onSuccess(List<ChannelMember> result) { channel.setMemberList(result); for (ChannelMember member : result) { getPublicProfileAsync(member, channel); } } @Override public void onError(Throwable what) { listChannelView.showErrorMessage(what); } }); } private void getChannelDetailAsync(final Channel channel) { channelService.getChannelDetailAsync(channel.getId(), new Callback<ChannelDetail>() { @Override public void onSuccess(ChannelDetail result) { channel.setDetail(result); listChannelView.showChannel(channel); } @Override public void onError(Throwable what) { listChannelView.showErrorMessage(what); } }); } }
package xal.app.pasta; import java.awt.*; import java.util.*; import javax.swing.table.*; import java.text.*; import java.io.*; import xal.smf.*; import xal.smf.impl.*; import xal.smf.impl.qualify.*; import xal.tools.apputils.*; import xal.extension.fit.spline.*; import xal.tools.dispatch.DispatchQueue; import xal.extension.widgets.plot.*; import xal.tools.beam.*; import xal.tools.math.TrigStuff; import xal.extension.scan.*; import xal.model.xml.*; import xal.model.probe.*; import xal.model.probe.traj.*; import xal.model.alg.ParticleTracker; import xal.sim.scenario.Scenario; import xal.tools.xml.XmlDataAdaptor; import xal.extension.fit.spline.*; import xal.extension.solver.*; import xal.extension.solver.algorithm.*; import xal.sim.scenario.ProbeFactory; import xal.sim.scenario.AlgorithmFactory; /** * This class contains the components internal to the Scanning procedure. * @author jdg */ public class AnalysisStuff { /** containers for fits of measured data */ private HashMap<Integer, CubicSpline> splineFitsBPMDiff, splineFitsBPMAmp, splineFitsWOut; /** containers for the model predicted arrays */ protected HashMap<Integer, Vector<Double>> phasesCavModelScaledV, phaseDiffsBPMModelV, WOutsV; protected HashMap<Integer, BasicGraphData> WOutModelMap = new HashMap<Integer, BasicGraphData>(); /** containers for measured data */ protected HashMap<Integer, Vector<Double>> phasesCavMeasured, phaseDiffsBPMMeasured; /** container for cavity phase points to evaluate BPM phases at */ private Vector<Double> calcPointsV = new Vector<Double>(); /** container for the parametric amplitude values of the measurement */ private Vector<Double> paramMeasuredVals = new Vector<Double>(); /** The index value (starting at 0) of the parametic curve to vary the * cavity amplitude for. The other amplitude values in ampValueV * are scaled from this indexed value, using paramMeasuredVals values */ protected int amplitudeVariableIndex = 1; /** the setpoint to uise for the cavity phase (deg) */ protected double cavPhaseSetpoint; /** the setpoint to use for the cavity amplitude (AU)*/ protected double cavAmpSetpoint; // Stuff to save with the document: /** the minimum phase to start model scan from */ protected double phaseModelMin=-90; /** the maximum phase to start model scan to */ protected double phaseModelMax = 30; /** the number of model points to use per scan */ protected int nCalcPoints = 20; /** the minimum BPM amplitude for points to consider in the scanning (mA) */ protected double minBPMAmp = 5.; /** a multiplier used to get evaluation points more dense near the scan edges */ private double stepMultiplier = 1.1; private double rad2deg = 180./Math.PI; /** defines the phase quadrant to work in */ private double BPMPhaseMin = -180.; /** the number of parametric values for amplitude settings */ protected int nParamAmpVals = 0; /** the minimum BPM amplitude, below which data is not parsed in * it may be further filtered for analysis purposes later */ private double minBPMAmpRead= 1.; // Stuff used in the analysis calculations. /** the phase offset to apply to the model to line up the BPM phase with measurements (deg) */ protected double cavPhaseOffset = 0.; /** the input energy of the beam (MeV) */ protected double WIn = 2.5; /** the calculated output energy (MeV) */ protected double WOutCalc; /** the nominal cavity voltage (MV/m) */ protected double cavityVoltage = 1.; /** Container for the amplitude scaling factors */ protected Vector<Double> ampValueV = new Vector<Double>(); // stuff for 1 vs 2 BPM analysis /** flag indicating whether to use a single BPM */ protected boolean useOneBPM = false; /** calculated BPM phases with the cavity off */ protected double BPM1TimeCavOff, BPM2TimeCavOff; /** the BPMs to use in thge analysis for calculating phase differences */ protected BPM firstBPM, secondBPM; /** the total error for the match * = sqrt(sum squares of [measure-model])*/ protected double errorTotal = 0.; // analysis table stuff protected AnalysisTableModel analysisTableModel; // solver control stuff /** the time to try and solve (sec) */ protected double timeoutPeriod = 100.; /** collection to hold the solver variables */ protected Hashtable<String, Variable> variableList = new Hashtable<String, Variable>(); /** Id for the type algorithm to use */ protected String algorithmId = RANDOM_ALG; /** the solver algorithm */ protected SearchAlgorithm algorithm; /** The solver */ protected Solver solver;// = new Solver(); /** the scorer object */ private PastaScorer theScorer = new PastaScorer(); // model stuff /** the probe to use for the model */ protected Probe theProbe; /** the default file for the probe file */ protected File probeFile; /** the default filename for the probe file */ protected String probeFileName; /** the model scenario */ protected Scenario theModel; /** the default input energy for the cavity - just use the initial probe value */ protected double defaultEnergy = 0.; // ready flags: /** flag if model is ready to run */ protected boolean modelReady = false; /** flag that the scan data is imported */ protected boolean analysisDataReady = false; /** flag the the solver variables are properly initialized */ protected boolean solverReady = false; /** flag indicatingf whether data is aquired yet */ protected boolean haveData = false; /** flag indicating whether to do analysis using the cavity-off information or not */ protected boolean useCavOffData; /** Array to hold Booleans for variable use */ protected ArrayList<Object> variableActiveFlags = new ArrayList<Object>(); // Application stuff /** the document this belongs to */ protected PastaDocument theDoc; //gr labels: static String RANDOM_ALG = "Random"; static String SIMPLEX_ALG = "Simplex"; static String POWELL_ALG = "Powell"; static String Combo_ALG = "Combo"; static String WIN_VAR_NAME = "WIn"; static String PHASE_VAR_NAME = "CavPhaseOffset"; static String AMP_VAR_NAME = "CavAmplitude"; static String FF_VAR_NAME = "FudgeOffset"; /** Create an object */ public AnalysisStuff(PastaDocument doc) { theDoc = doc; for (int i = 0; i<3; i++) variableActiveFlags.add(new Boolean(true)); variableActiveFlags.add(new Boolean(false)); analysisTableModel = new AnalysisTableModel(this); splineFitsBPMDiff = new HashMap<Integer, CubicSpline>(); splineFitsBPMAmp = new HashMap<Integer, CubicSpline>(); splineFitsWOut = new HashMap<Integer, CubicSpline>(); phasesCavModelScaledV = new HashMap<Integer, Vector<Double>>(); phaseDiffsBPMModelV = new HashMap<Integer, Vector<Double>>(); WOutsV = new HashMap<Integer, Vector<Double>>(); phaseDiffsBPMMeasured = new HashMap<Integer, Vector<Double>>(); phasesCavMeasured = new HashMap<Integer, Vector<Double>>(); makeCalcPoints(); } /** initialize the analysis stuff, after the setup + scan stuff is done */ protected void init() { useCavOffData = theDoc.scanStuff.haveCavOffData() && (theDoc.myWindow()).useCavOffBox.isSelected(); if(!useCavOffData && (!theDoc.myWindow().useBPM1Box.isSelected() || !theDoc.myWindow().useBPM2Box.isSelected() ) ) { Toolkit.getDefaultToolkit().beep(); String errText = "Cavity Off data must exist to use only 1 BPM"; theDoc.myWindow().errorText.setText(errText); System.err.println(errText); return; } updateAnalysisData(); theDoc.myWindow().updateScanNumberSelector(); theDoc.myWindow().updateScanUseSelector(); theDoc.myWindow().plotMeasuredData(); updateAmpFactors(); analysisTableModel.fireTableDataChanged(); analysisDataReady = true; theDoc.setHasChanges(true); } /** initialize the cavity voltages by scaling from the measured parametric values * Note - one of the amplitude settings is set from the user/solver. * this is specified by amplitudeVariableIndex. The others are scaled. */ protected void updateAmpFactors() { if(amplitudeVariableIndex < 0) { Toolkit.getDefaultToolkit().beep(); String errText = "Please pick a scan number for the voltage variable to correspond to."; theDoc.myWindow().errorText.setText(errText); System.err.println(errText); return; } // check for sanity: if(amplitudeVariableIndex > nParamAmpVals-1) amplitudeVariableIndex = nParamAmpVals-1; ampValueV.clear(); double nominalField = avgFieldRB(amplitudeVariableIndex); for (int i=0; i< nParamAmpVals; i++) { // if a guess for the cavity voltage is not given, prescribe "one" if(i == amplitudeVariableIndex) ampValueV.add(new Double(cavityVoltage)); else { double ratio = 0.; double field1 = avgFieldRB(i); if(nominalField != 0) ratio = field1/nominalField; //System.out.println("i = " + i + " field1 = " + field1 + " nomfield = " + nominalField); if (ratio == 0.) { // backward compatibility case, before measured E-field were taken: ratio = ( paramMeasuredVals.get(i)).doubleValue()/ (paramMeasuredVals.get(amplitudeVariableIndex)).doubleValue(); } double val2 = ratio * cavityVoltage; ampValueV.add(new Double(val2)); } } } /** gets the average value of the field readback, for a requeseted scan index */ double avgFieldRB(int index) { if(theDoc.scanStuff.cavAmpRBMV == null) { Toolkit.getDefaultToolkit().beep(); String errText = "Requested cav field container does not exist yet"; theDoc.myWindow().errorText.setText(errText); System.err.println(errText); return 0.; } if(theDoc.scanStuff.cavAmpRBMV.getNumberOfDataContainers() < index) { Toolkit.getDefaultToolkit().beep(); String errText = "Requested cav field info for a scan number that does not exist? index = " + (new Integer(index)).toString(); theDoc.myWindow().errorText.setText(errText); System.err.println(errText); return 0.; } if( theDoc.scanStuff.cavAmpRBMV.getDataContainer(index) == null) { Toolkit.getDefaultToolkit().beep(); String errText = "Requested field readback info does not exist, index = " + (new Integer(index)).toString(); theDoc.myWindow().errorText.setText(errText); System.err.println(errText); return 0.; } BasicGraphData cavFieldBGD = theDoc.scanStuff.cavAmpRBMV.getDataContainer(index); double sum = 0.; for (int i=0; i < cavFieldBGD.getNumbOfPoints(); i++) sum += cavFieldBGD.getY(i); return sum/((double) cavFieldBGD.getNumbOfPoints()); } /** this method takes raw data from the scan Stuff and puts it into the analysis * containers. Some filtering is done here, to restrict data to above some critical * BPM amplitude. */ protected void updateAnalysisData() { clearData(); nParamAmpVals = theDoc.scanStuff.BPM1PhaseMV.getNumberOfDataContainers(); if( theDoc.scanStuff.BPM2PhaseMV.getNumberOfDataContainers() != nParamAmpVals || theDoc.scanStuff.BPM1AmpMV.getNumberOfDataContainers() != nParamAmpVals || theDoc.scanStuff.BPM2AmpMV.getNumberOfDataContainers() != nParamAmpVals) { Toolkit.getDefaultToolkit().beep(); String errText = "Opps, The number of parametric scans is different for the some of the BPM amp. and phases\nDid the scan complete?"; theDoc.myWindow().errorText.setText(errText); System.err.println(errText); return; } double cavPhase, amp1, amp2, theAmp, phase1, phase2; // get the data from the scan stuff and store it in our own containers. for (int i=0; i<nParamAmpVals; i++) { BasicGraphData bgdBPMAmp1 = theDoc.scanStuff.BPM1AmpMV.getDataContainer(i); BasicGraphData bgdBPMAmp2 = theDoc.scanStuff.BPM2AmpMV.getDataContainer(i); BasicGraphData bgdBPMPhase1 = theDoc.scanStuff.BPM1PhaseMV.getDataContainer(i); BasicGraphData bgdBPMPhase2 = theDoc.scanStuff.BPM2PhaseMV.getDataContainer(i); Double paramValue = (Double) bgdBPMAmp1.getGraphProperty("PARAMETER_VALUE_RB"); paramMeasuredVals.add(paramValue); // check for equal number of points per parametic scan for all amplitude and phase curves if(bgdBPMAmp1.getNumbOfPoints() != bgdBPMAmp2.getNumbOfPoints() || bgdBPMAmp1.getNumbOfPoints() != bgdBPMPhase1.getNumbOfPoints() || bgdBPMAmp1.getNumbOfPoints() != bgdBPMPhase2.getNumbOfPoints() ) { Toolkit.getDefaultToolkit().beep(); String errText = "The number of points a parametric scan is not the same for BPM amp. and phases\nDid the scan complete?"; theDoc.myWindow().errorText.setText(errText); System.err.println(errText); return; } int np = bgdBPMAmp1.getNumbOfPoints(); Vector<Double> cavPhaseV = new Vector<Double>(); Vector<Double> BPMPhaseDiffV = new Vector<Double>(); Vector<Double> BPMAmpV = new Vector<Double>(); minBPMAmpRead = minBPMAmp; // filter using the same value as for analysis later int index; for (int j=0; j< np; j++) { cavPhase = bgdBPMAmp1.getX(j); double diff; double cavPhaseScaled = cavPhase + theDoc.DTLPhaseOffset; double delta = cavPhaseScaled - 180.; if(delta > 0.) cavPhaseScaled = -180. + delta; if(delta < -360.) cavPhaseScaled = 540. + delta; amp1 = bgdBPMAmp1.getValueY(cavPhase); amp2 = bgdBPMAmp2.getValueY(cavPhase); theAmp = amp2; if(!theDoc.myWindow().useBPM1Box.isSelected()) theAmp = amp2; if(!theDoc.myWindow().useBPM2Box.isSelected()) theAmp = amp1; if(theDoc.myWindow().useBPM1Box.isSelected() && theDoc.myWindow().useBPM2Box.isSelected()) theAmp = Math.min(amp1, amp2); // filter if the beam intensity is too small if(theAmp> minBPMAmpRead) { phase1 = bgdBPMPhase1.getValueY(cavPhase); phase2 = bgdBPMPhase2.getValueY(cavPhase); if(useOneBPM) { if(theDoc.myWindow().useBPM1Box.isSelected()) diff = phase1 - theDoc.scanStuff.BPM1CavOffPhase(cavPhase); else diff = phase2 - theDoc.scanStuff.BPM2CavOffPhase(cavPhase); } else { diff = phase2 - phase1; if(useCavOffData) { diff -= (theDoc.scanStuff.BPM2CavOffPhase(cavPhase) - theDoc.scanStuff.BPM1CavOffPhase(cavPhase)); } } diff += theDoc.BPMPhaseDiffOffset; // wrap to a 2-pi interval: if(diff < BPMPhaseMin) diff += 360.; if( diff > BPMPhaseMin+360.) diff -= 360.; index = findInsertPoint(cavPhaseV, cavPhaseScaled); if(index < 0) { cavPhaseV.add(new Double(cavPhaseScaled)); BPMPhaseDiffV.add(new Double(diff)); BPMAmpV.add(new Double(theAmp)); } else { cavPhaseV.insertElementAt(new Double(cavPhaseScaled), index); BPMPhaseDiffV.insertElementAt(new Double(diff), index); BPMAmpV.insertElementAt(new Double(theAmp), index); } } } // make fits of the measured BPM diff andf amplitude to use later // stash them if(cavPhaseV.size() < 5) { Toolkit.getDefaultToolkit().beep(); String errText = "Hmm - there do not appear to be enough good points to analyzel"; theDoc.myWindow().errorText.setText(errText); System.err.println(errText); return; } if(theDoc.myWindow().useWrappingButton.isSelected() && (BPMPhaseDiffV.size() > 0)) { // unwrap data option here: double previousVal = ( BPMPhaseDiffV.get(0)).doubleValue(); for (int k = 1; k < BPMPhaseDiffV.size(); k++) { double oldVal = ( BPMPhaseDiffV.get(k)).doubleValue(); double newVal = TrigStuff.unwrap(oldVal, previousVal); BPMPhaseDiffV.setElementAt(new Double(newVal), k); previousVal = newVal; } } phasesCavMeasured.put(new Integer(i), cavPhaseV); phaseDiffsBPMMeasured.put(new Integer(i), BPMPhaseDiffV); CubicSpline splineFitBPMDiff = new CubicSpline(toDouble(cavPhaseV), toDouble(BPMPhaseDiffV)); CubicSpline splineFitBPMAmp = new CubicSpline(toDouble(cavPhaseV), toDouble(BPMAmpV)); splineFitsBPMAmp.put(new Integer(i), splineFitBPMAmp); splineFitsBPMDiff.put(new Integer(i), splineFitBPMDiff); theDoc.useScanInMatch.add(new Boolean(true)); } } /** clear the containers of data */ private void clearData() { splineFitsBPMDiff.clear(); splineFitsBPMAmp.clear(); splineFitsWOut.clear(); phasesCavModelScaledV.clear(); phaseDiffsBPMModelV.clear(); WOutsV.clear(); phasesCavMeasured.clear(); phaseDiffsBPMMeasured.clear(); paramMeasuredVals.clear(); theDoc.useScanInMatch.clear(); haveData = false; // check for 1 vs. 2 BPMs if(!theDoc.myWindow().useBPM1Box.isSelected() && !theDoc.myWindow().useBPM2Box.isSelected()) { Toolkit.getDefaultToolkit().beep(); String errText = "Hey dude - you gotta select at least 1 BPM to analyze"; theDoc.myWindow().errorText.setText(errText); System.err.println(errText); return; } if(theDoc.myWindow().useBPM1Box.isSelected() && theDoc.myWindow().useBPM2Box.isSelected()) { useOneBPM = false; } else useOneBPM = true; } /** refresh both measured and model plot data */ protected void plotUpdate() { theDoc.myWindow().plotMeasuredData();; theDoc.myWindow().plotModelData(); } /** this method returns the phase of a node in a trajectory, relative to the first point in the model run for this state. */ private double getPhase( ProbeState state, BPM bpm) { double freq = bpm.getBPMBucket().getFrequency() * 1.e6; // correction time for electrode being offset from the BPM center: double gamma = 1. + state.getKineticEnergy()/state.getSpeciesRestEnergy(); double beta = Math.sqrt(1. - 1./(gamma*gamma)); double dt = ( bpm.getBPMBucket().getOrientation() * bpm.getBPMBucket().getLength()) / (2*IConstants.LightSpeed * beta); double phase = (state.getTime() + dt) * 2. * Math.PI * freq; phase = (phase % (2. * Math.PI)) * rad2deg; return phase; } private double getPhaseAbs(double time, BPM bpm) { double freq = bpm.getBPMBucket().getFrequency() * 1.e6; double phase = (time) * 2. * Math.PI * freq; phase *= rad2deg; return phase; } private double getPhase(double time, BPM bpm) { double freq = bpm.getBPMBucket().getFrequency() * 1.e6; double phase = (time) * 2. * Math.PI * freq; phase = (phase % (2. * Math.PI)) * rad2deg; return phase; } private double getTime(ProbeState state, BPM bpm) { // correction time for electrode being offset from the BPM center: double gamma = 1. + state.getKineticEnergy()/state.getSpeciesRestEnergy(); double beta = Math.sqrt(1. - 1./(gamma*gamma)); double dt = ( bpm.getBPMBucket().getOrientation() * bpm.getBPMBucket().getLength()) / (IConstants.LightSpeed * beta); return (state.getTime() + dt); } /** calculate the BPM phases when the cavity is off */ private void cavOffCalc() { // some model stuff Trajectory traj; //EnvelopeProbeState state0, state1, state2; ProbeState state0, state1, state2; ProbeState[] states; double time0; theDoc.theCavity.updateDesignAmp(0.); // turn off the cavity theDoc.theCavity.updateDesignPhase(0.);// cavity phase setting does not matter try{ theModel.resync(); } catch (Exception exc) { System.out.println("Trouble resyncing probe with cavity off " + "\n" + exc.getMessage()); } // set the probe to the solver's guess theProbe.reset(); theProbe.setKineticEnergy(WIn * 1.e6); // OK let's run the model: try{ theModel.run(); traj = theModel.getProbe().getTrajectory(); ArrayList<RfGap> al = new ArrayList<RfGap>(theDoc.theCavity.getGaps()); RfGap gap0 = al.get(0); states = traj.statesForElement(gap0.getId()); //state0 = (EnvelopeProbeState) states[0]; state0 = states[0]; //System.out.println("time0 = " + state0.getElementId() + " " + state0.getTime()); time0 = state0.getTime(); states = traj.statesForElement(theDoc.BPM1.getId()); //state1 = (EnvelopeProbeState) states[0]; state1 = states[0]; states = traj.statesForElement(theDoc.BPM2.getId()); //state2 = (EnvelopeProbeState) states[0]; state2 = states[0]; BPM1TimeCavOff = getTime(state1, theDoc.BPM1) - time0; BPM2TimeCavOff = getTime(state2, theDoc.BPM2) - time0; } catch(Exception exc) { System.out.println("Model evaluation failed at cavity off calc" + exc.getMessage()); } //System.out.println("off calcs: " + BPM1TimeCavOff + "\t" + BPM2TimeCavOff + "\t" + WIn); } /* run the model for a given phae, amplitude and beam input energy */ private void runModel(double amp, double phase, double energy) { theDoc.theCavity.updateDesignAmp(amp); theDoc.theCavity.updateDesignPhase(phase); try{ theModel.resync(); } catch (Exception exc) { System.out.println("Trouble resyncing probe with phase = " + phase + "\n" + exc.getMessage()); } // set the probe to the solver's guess theProbe.reset(); theProbe.setKineticEnergy(energy); // OK let's run the model: try{ //System.out.println("Phase = " + cavPhaseScaled + " bpmAmp = " + bpmAmp); theModel.run(); } catch (Exception exc) { System.out.println("Troubler unning modelwith phase = " + phase + " amp = " + amp + " energy = " + energy + "\n" + exc.getMessage()); } } /** do a single model pass - scan through the phases for the prescibed * amplitude factor. The amp factor is specified though the argument i * to this method. This method should not be called directly. It is meant * to be called by the doCalc method which loops though all amp factors. */ private void singlePass(int i) { // calculate phasesCavModelScaledV and phaseDiffsBPMModelV here boolean firstPass = true; double time0, time1, time2, deltaPhi, deltaPhi0, diff0; double cavPhase, cavPhaseScaled, betaZ1, betaZ2, phase1, phase2, diff; double sigmaz1, sigmaz2, WOut; // range of phases that have BPM amplitude readings above minimum for parsing: double cavPhaseScaledMin, cavPhaseScaledMax; Vector<Double> phaseCavMeasured = phasesCavMeasured.get(new Integer(i)); cavPhaseScaledMin = (phaseCavMeasured.get(0)).doubleValue(); cavPhaseScaledMax = (phaseCavMeasured.get(phaseCavMeasured.size()-1)).doubleValue(); // some model stuff Trajectory traj; //EnvelopeProbeState state0, state1, state2; ProbeState state0, state1, state2; ProbeState[] states; Twiss[] twiss1, twiss2; double ampModel = (ampValueV.get(i)).doubleValue(); CubicSpline splineFitBPMAmp = splineFitsBPMAmp.get(new Integer(i)); CubicSpline splineFitPhaseDiff = splineFitsBPMDiff.get(new Integer(i)); theDoc.theCavity.updateDesignAmp(ampModel); double[] phases = toDouble(calcPointsV); double measuredDiff0 = splineFitPhaseDiff. evaluateAt(phases[0]); Vector<Double> phaseCavModel = new Vector<Double>(); Vector<Double> phaseDiffBPMModel = new Vector<Double>(); Vector<Double> WOutV = new Vector<Double>(); deltaPhi0 = 0.; diff0= 0.; for (int j = 0; j < phases.length; j++) { //jdg 10/11/04: use scaled phase to work with - much easier for user //cavPhase = phases[j]; //cavPhaseScaled = cavPhase + cavPhaseOffset; cavPhaseScaled = phases[j]; cavPhase = cavPhaseScaled - cavPhaseOffset; double bpmAmp = splineFitBPMAmp.evaluateAt(cavPhaseScaled); // is the measurement worth comparing the model to?: // spline fit is only valid for // cavPhaseScaledMin < phaseScaled < cavPhaseScaledMax //if(bpmAmp > minBPMAmp) { if(cavPhaseScaled > cavPhaseScaledMin && cavPhaseScaled < cavPhaseScaledMax && bpmAmp > minBPMAmp) { try { runModel(ampModel, cavPhase, WIn*1.e6); traj = theModel.getProbe().getTrajectory(); ArrayList<RfGap> al = new ArrayList<RfGap>(theDoc.theCavity.getGaps()); RfGap gap0 = al.get(0); states = traj.statesForElement(gap0.getId()); //state0 = (EnvelopeProbeState) states[0]; state0 = states[0]; //System.out.println("time0 = " + state0.getElementId() + " " + state0.getTime()); time0 = state0.getTime(); states =traj.statesForElement(firstBPM.getId()); //traj.statesForElement(theDoc.BPM1.getId()); //state1 = (EnvelopeProbeState) states[0]; state1 = states[0]; //twiss1 = state1.phaseCorrelation().twissParameters(); //betaZ1 = twiss1[2].getBeta(); states = traj.statesForElement(secondBPM.getId()); //traj.statesForElement(theDoc.BPM2.getId()); //state2 = (EnvelopeProbeState) states[0]; state2 = states[0]; //twiss2 = state2.phaseCorrelation().twissParameters(); //betaZ2 = twiss2[2].getBeta(); WOut = state1.getKineticEnergy()/1.e6; //sigmaz1 = twiss1[2].getEnvelopeRadius(); //sigmaz2 = twiss2[2].getEnvelopeRadius(); //System.out.println(betaZ1 + "\t" + betaZ2 + "\t" + sigmaz1 + "\t" + sigmaz2); //check that the beam is not blown up too much longitudinally //if( Math.abs(betaZ1) < 1.e5 && Math.abs(betaZ2) < 1.e5) { if(true) { //System.out.println("phase = " + cavPhase + " betaz = " + betaZ + " bpmamp = " + bpmAmp); time1 = getTime(state1, firstBPM) - time0; phase1 = getPhase(time1, firstBPM); time2 = getTime(state2, secondBPM) - time0; phase2 = getPhase(time2, secondBPM); if (useOneBPM) { if(theDoc.myWindow().useBPM1Box.isSelected()) { time1 = BPM1TimeCavOff; } else { time1 = BPM2TimeCavOff; } phase1 = getPhase(time1, firstBPM); phase2 = getPhase(time2, secondBPM); diff = phase2 - phase1; } else { diff = phase2 - phase1; if(useCavOffData) { double p20 = getPhase(BPM2TimeCavOff, secondBPM); double p10 = getPhase(BPM1TimeCavOff, firstBPM); diff -= (p20 - p10); //System.out.println("Off phases = " + p10 + "\t" + p20); //System.out.println("Off times = " + BPM1TimeCavOff + "\t" + BPM2TimeCavOff); } } diff += theDoc.BPMPhaseDiffOffset + theDoc.fudgePhaseOffset; if(theDoc.myWindow().useWrappingButton.isSelected() ){ if (firstPass) { firstPass = false; deltaPhi0 = getPhaseAbs(time2, secondBPM) - getPhaseAbs(time1, firstBPM); // stick the starting calculated diff in the closest 2pi period to the measured diff diff = TrigStuff.unwrap(diff, measuredDiff0); /* if(diff < BPMPhaseMin) diff += 360.; if(diff > (BPMPhaseMin + 360.)) diff -= 360.; */ diff0 = diff; } else { deltaPhi = getPhaseAbs(time2,secondBPM) - getPhaseAbs(time1, firstBPM); diff = diff0 + deltaPhi - deltaPhi0; } } else { if(diff < BPMPhaseMin) diff += 360.; if(diff > (BPMPhaseMin + 360.)) diff -= 360.; } phaseCavModel.add(new Double(cavPhaseScaled)); phaseDiffBPMModel.add( new Double(diff)); WOutV.add(new Double(WOut)); //System.out.println(phase1 + "\t" + phase2 + "\t" + diff); } } catch(Exception exc) { System.out.println("Model evaluation failed at Phase = " + cavPhase + " amp = " + ampModel + " " + exc.getMessage()); } } } phasesCavModelScaledV.put(new Integer (i), phaseCavModel); phaseDiffsBPMModelV.put(new Integer (i), phaseDiffBPMModel); WOutsV.put(new Integer (i), WOutV); } /** loop through all amplitude setings and scan the phase for each with the model * Also calculate the total error between the model and measurements */ // make another method that the solver calls to set WIn, cavPhaseOffset + ampValueV values first, and then calls this protected double doCalc() { // run the model through the cav phase scan for all amplitude factors: phasesCavModelScaledV.clear(); phaseDiffsBPMModelV.clear(); WOutsV.clear(); errorTotal = 0.; if(useOneBPM) { //cavOffCalc(); // if using only 1 BPM - do the cavity off calc if (theDoc.myWindow().useBPM1Box.isSelected() ) { firstBPM = theDoc.BPM1; secondBPM = theDoc.BPM1; } else { firstBPM = theDoc.BPM2; secondBPM = theDoc.BPM2; } } else { firstBPM = theDoc.BPM1; secondBPM = theDoc.BPM2; } if(!modelReady) { if (!calcInit()) return 0.; } if(useCavOffData) cavOffCalc(); for (int i=0; i< ampValueV.size(); i++) { if( (theDoc.useScanInMatch.get(i)).booleanValue() ) { singlePass(i); // do the scan at this amplitude // stash results: Vector<Double> phaseDiffBPMModelV = phaseDiffsBPMModelV.get(new Integer(i) ); Vector<Double> phaseCavModelScaledV = phasesCavModelScaledV.get(new Integer(i)); CubicSpline splineFit = splineFitsBPMDiff.get(new Integer(i)); double error = 0.; //calculate error for this amplitude factor for( int j=0; j< phaseCavModelScaledV.size(); j++) { double phase = (phaseCavModelScaledV.get(j)).doubleValue(); double diff = (phaseDiffBPMModelV.get(j)).doubleValue() - splineFit.evaluateAt(phase); error += Math.pow(diff, 2.); } error /= (double) phaseCavModelScaledV.size(); errorTotal += error; } } System.out.println(errorTotal); haveData = true; theDoc.myWindow().errorField.setText(theDoc.myWindow().prettyString(errorTotal)); return errorTotal; } /** start the solver * the error from the solver is returned * i.e. sqrt(sum residuals)*/ protected void solve() { variableList.clear(); if( ((Boolean) variableActiveFlags.get(1)).booleanValue()) { Variable varWIn = new Variable(WIN_VAR_NAME, WIn, WIn*0.975, WIn*1.025); variableList.put("WIn",varWIn); } if( ((Boolean) variableActiveFlags.get(0)).booleanValue()) { Variable varCavPhaseOffset = new Variable(PHASE_VAR_NAME, cavPhaseOffset, cavPhaseOffset-20.,cavPhaseOffset+20.); variableList.put("PhaseOffset", varCavPhaseOffset); } if( ((Boolean) variableActiveFlags.get(2)).booleanValue()) { double val = cavityVoltage; //String name = "Amp fac " +(new Integer(i+1)).toString(); Variable pp = new Variable(AMP_VAR_NAME, val, val*0.85, val*1.15); variableList.put("AmpFac", pp); } if( ((Boolean) variableActiveFlags.get(3)).booleanValue()) { Variable varFF = new Variable(FF_VAR_NAME, theDoc.fudgePhaseOffset, -180, 180); variableList.put("Fudge", varFF); } Problem problem = ProblemFactory.getInverseSquareMinimizerProblem( new ArrayList<Variable>( variableList.values()), theScorer, 0.001 ); solver = new Solver(SolveStopperFactory.minMaxTimeSatisfactionStopper(0, timeoutPeriod, SatisfactionCurve.inverseSquareSatisfaction( 0.001, 0.1 ))); //solver.setStopper(SolveStopperFactory.targetStopperWithMaxTime(.1, timeoutPeriod)); solverReady = true; solver.solve( problem ); System.out.println("Done solving"); showSolution(); } /** display the variable values on the main window */ protected void showSolution() { Variable pp; ScoreBoard sb = solver.getScoreBoard(); System.out.println(sb.toString()); //errorTotal = sb.getBestScore(); Map<Variable, Number> solutionMap = sb.getBestSolution().getTrialPoint().getValueMap(); if(variableList.get("WIn") != null) { pp = variableList.get("WIn"); WIn = ((Double) solutionMap.get(pp)).doubleValue(); } if(variableList.get("PhaseOffset") != null) { pp = variableList.get("PhaseOffset"); cavPhaseOffset = ((Double) solutionMap.get(pp)).doubleValue(); } if(variableList.get("AmpFac") != null) { pp = variableList.get("AmpFac"); Double val = (Double) solutionMap.get(pp); cavityVoltage = val.doubleValue(); updateAmpFactors(); } // run model through final point again so plot shows final solution. doCalc(); analysisTableModel.fireTableDataChanged(); theDoc.myWindow().errorField.setText(theDoc.myWindow().prettyString(errorTotal)); plotUpdate(); } /** Model initialization and checks */ private boolean calcInit() { Collection<RfCavity> cavs2; // any data to compare to ? if(!analysisDataReady) { Toolkit.getDefaultToolkit().beep(); String errText = "Whoa there - please import measured data before running model"; theDoc.myWindow().errorText.setText(errText); System.err.println(errText); return false; } // probe set yet ? probeInit(); // model latice constructed yet ? if(theModel == null) { Toolkit.getDefaultToolkit().beep(); String errText = "Whoa there - the model is not defined - is a sequence even selected?"; theDoc.myWindow().errorText.setText(errText); System.err.println(errText); return false; } // turn off all downstream cavities in the model if ((theDoc.theSequence.getClass()).equals(AcceleratorSeqCombo.class)) { OrTypeQualifier kq = (new OrTypeQualifier()).or("rfcavity").or(SCLCavity.s_strType); cavs2 = (theDoc.theSequence).getAllInclusiveNodesWithQualifier(kq); Iterator<RfCavity> itr = cavs2.iterator(); while (itr.hasNext()) { AcceleratorSeq seq = (AcceleratorSeq) itr.next(); if(!seq.getId().equals(theDoc.theCavity.getId()) ) { ((RfCavity) seq) .updateDesignAmp(0.); System.out.println("deactivating cav " + seq.getId()); } } } //make sure that RF phase is calculated theProbe.getAlgorithm().setRfGapPhaseCalculation(true); // turn charge off - does not affect longitudinal dynamics: //((BeamProbe)theProbe).setBeamCharge(0.); //((BeamProbe)theProbe).setBeamCurrent(0.); theModel.setProbe(theProbe); theModel.setSynchronizationMode(Scenario.SYNC_MODE_DESIGN); // run only through part of sequence of interest: theProbe.getAlgorithm().setStopElementId(theDoc.theCavity.getId()); theProbe.getAlgorithm().setStopElementId(secondBPM.getId()); modelReady = true; return true; } protected boolean probeInit() { if(theProbe == null) { // try reading in the probe file first if there is one if(probeFileName != null) { try{ probeFile = new File(probeFileName); if (!setProbe(probeFile)) return false; } catch (Exception exc) { String errText = "Damn!, I can't read the probe file you requested: " + probeFileName; Toolkit.getDefaultToolkit().beep(); theDoc.myWindow().errorText.setText(errText); System.err.println(errText); return false; } } else{ // force the default probe for this sequence: /* Toolkit.getDefaultToolkit().beep(); String errText = "Whoa there - please pick a probe file before running the model"; theDoc.myWindow().errorText.setText(errText); System.err.println(errText); return false; */ ParticleTracker pt = null; try { pt= AlgorithmFactory.createParticleTracker(theDoc.theSequence); } catch (InstantiationException e) { System.err.println( "Instantiation exception creating tracker." ); e.printStackTrace(); } pt.setRfGapPhaseCalculation(true); System.out.println("cav = " + theDoc.theCavity.getId()); try { if(theDoc.theSequence.getId().equals("MEBT")) { theProbe = ProbeFactory.createParticleProbe(theDoc.theSequence, AlgorithmFactory.createParticleTracker(theDoc.theSequence)); } else { theProbe = ProbeFactory.getParticleProbe(theDoc.theCavity.getId(), theDoc.theSequence, AlgorithmFactory.createParticleTracker(theDoc.theSequence)); } } catch (InstantiationException e) { System.err.println( "Instantiation exception creating probe." ); e.printStackTrace(); } } } defaultEnergy = theProbe.getKineticEnergy()/1.e6; return true; } /** make the CAV Phase points to evaluate the model at for the scan */ protected void makeCalcPoints() { calcPointsV.clear(); double delta = (phaseModelMax - phaseModelMin)/((double)(nCalcPoints-1)); double pos; for (int i=0; i< nCalcPoints; i++) { pos = phaseModelMin + ((double) i) * delta; calcPointsV.add(new Double(pos)); } } /** method to refresf table */ protected void refreshTable() { analysisTableModel.fireTableDataChanged(); System.out.println("Table refresh"); } /** sets the probe from a filename */ protected boolean setProbe(File file) { XmlDataAdaptor probeXmlDataAdaptor; try { probeXmlDataAdaptor =XmlDataAdaptor.adaptorForFile(file, false); theProbe = ProbeXmlParser.parseDataAdaptor(probeXmlDataAdaptor); } catch(Exception ex) { Toolkit.getDefaultToolkit().beep(); String errText = "Darn, I can't pasre the file :" + file.getPath(); if(theDoc.myWindow() != null) theDoc.myWindow().errorText.setText(errText); System.err.println(errText); return false; } System.out.println("Probe " + probeFile.getPath() + " parsed OK "); // to speed up the calculation turn off space charge. This does not affect // motion of sync. particle //((BeamProbe) theProbe).setBeamCharge(0.); modelReady = false; return true; } /** method to estimate the phase and amplitude settings from present state of analysis */ protected void updateSetpoints() { double WOutModel0, WOutModel1; if ( theDoc.BPM1 == null || paramMeasuredVals.size() < 1 || ampValueV.size() < 1) { Toolkit.getDefaultToolkit().beep(); String errText = "Whoa buddy - I don't see any scan data yet"; if(theDoc.myWindow() != null) theDoc.myWindow().errorText.setText(errText); System.err.println(errText); return; } double [] pvs = toDouble(paramMeasuredVals); double [] svs = toDouble(ampValueV); cavPhaseSetpoint = theDoc.theDesignPhase + cavPhaseOffset - theDoc.DTLPhaseOffset; if(svs.length < 2) { // only one parametric point - no interpolation cavAmpSetpoint = pvs[0] * theDoc.theDesignAmp/svs[0]; BasicGraphData WOutModel = WOutModelMap.get(new Integer(0)); WOutCalc = WOutModel.getValueY(cavPhaseSetpoint); return; } // find the index close to where we ant to set the amplitude int ind = 0; while(theDoc.theDesignAmp <= svs[ind] && ind < svs.length-1) { ind++; } if(ind > (pvs.length -2)) ind = pvs.length -2; double slope = (pvs[ind+1] - pvs[ind])/(svs[ind+1]-svs[ind]); cavAmpSetpoint = pvs[ind] + (theDoc.theDesignAmp - svs[ind])*slope; runModel(cavityVoltage, theDoc.theDesignPhase, WIn*1.e6); Trajectory traj = theModel.getProbe().getTrajectory(); ProbeState[] states =traj.statesForElement(firstBPM.getId()); ProbeState state = states[0]; WOutCalc = state.getKineticEnergy()/1.e6; /* if(!((Boolean) theDoc.useScanInMatch.get(ind)).booleanValue()) { WOutCalc = ((BasicGraphData) WOutModelMap.get(new Integer(ind+1))).getValueY(cavPhaseSetpoint); return; } if(!((Boolean) theDoc.useScanInMatch.get(ind+1)).booleanValue()) { WOutCalc = ((BasicGraphData) WOutModelMap.get(new Integer(ind))).getValueY(cavPhaseSetpoint); return; } WOutModel0 = ((BasicGraphData) WOutModelMap.get(new Integer(ind))).getValueY(cavPhaseSetpoint + theDoc.DTLPhaseOffset); WOutModel1 = ((BasicGraphData) WOutModelMap.get(new Integer(ind+1))).getValueY(cavPhaseSetpoint + theDoc.DTLPhaseOffset); double slope2 = (WOutModel1 - WOutModel0)/(svs[ind+1]-svs[ind]); WOutCalc = WOutModel0 + (theDoc.theDesignAmp - svs[ind])*slope2; */ } /** send the new setpoints to the control system */ protected void sendNewSetpoints() { if(cavPhaseSetpoint == 0. || cavAmpSetpoint < 0.05) { Toolkit.getDefaultToolkit().beep(); String errText = "Calculate setpoints first!"; theDoc.myWindow().errorText.setText(errText); System.err.println(errText); return; } try { theDoc.theCavity.setCavPhase(cavPhaseSetpoint); theDoc.theCavity.setCavAmp(cavAmpSetpoint); } catch (Exception ex) { Toolkit.getDefaultToolkit().beep(); String errText = "Error trying to send new setpoints to EPICS"; theDoc.myWindow().errorText.setText(errText); System.err.println(errText); } } /** helper method to dump contents of a Vector to a primitive double array */ protected double[] toDouble(Vector<Double> vec) { double [] da = new double [vec.size()]; Object za [] = vec.toArray(); for (int i=0; i< za.length; i++) da[i] = ((Double) za[i]).doubleValue(); return da; } /** find the first occurance of a Vector of Doubles with a value > an input * return the index of this object * if none are > that the inpuit, return 0 */ private int findInsertPoint(Vector<Double> vec, double value) { for (int i= 0; i< vec.size(); i++) { double valTest = (vec.get(i)).doubleValue(); if(valTest > value) return i; } return -1; } /** class to do solver function evaluation */ private class PastaScorer implements Scorer { public PastaScorer() {} public double score( final Trial trial, final java.util.List<Variable> variables ) { final TrialPoint trialPoint = trial.getTrialPoint(); // set the quantities used in function evaluation // to the solver guesses: if(variableList.get("WIn") != null) WIn = trialPoint.getValue( variableList.get("WIn") ); if(variableList.get("PhaseOffset") != null) cavPhaseOffset = trialPoint.getValue( variableList.get("PhaseOffset") ); if(variableList.get("AmpFac") != null) { Variable pp = variableList.get("AmpFac"); cavityVoltage = trialPoint.getValue( pp ); updateAmpFactors(); } if(variableList.get("Fudge") != null) { theDoc.fudgePhaseOffset = trialPoint.getValue( variableList.get("Fudge") ); } // calculate error term for these settings: System.out.print("scan at " + WIn + " " + cavPhaseOffset + " " + cavityVoltage + " " + theDoc.fudgePhaseOffset + " "); final double score = doCalc(); // System.out.println( "" ); // for ( final Variable variable : variables ) { // System.out.println( variable.getName() + ": " + trialPoint.getValue( variable ) ); // System.out.println( "Score: " + score ); return score; } } /** method to come up with an initial guess for cavity offset, amplitude, and input beam energy */ protected void initialGuess() { double minPhase, maxPhase, avgPhase, dPhase; BasicGraphData someMeasuredData = null; // start with beam energy - set it to design: WIn = defaultEnergy; // same with amplitude: cavityVoltage = theDoc.theDesignAmp; //assume the cavity phase setpoint is in the center of the scan range: if(theDoc.myWindow().useBPM1Box.isSelected()) someMeasuredData = theDoc.scanStuff.BPM1AmpMV.getDataContainer(0); if(theDoc.myWindow().useBPM2Box.isSelected()) someMeasuredData = theDoc.scanStuff.BPM2AmpMV.getDataContainer(0); if(someMeasuredData == null) { String errText = "Hey - give me some measured data first!!!: "; Toolkit.getDefaultToolkit().beep(); theDoc.myWindow().errorText.setText(errText); System.err.println(errText); return; } Vector<Double> phaseCavMeasured = phasesCavMeasured.get(new Integer(0)); minPhase = (phaseCavMeasured.get(0)).doubleValue(); maxPhase = (phaseCavMeasured.get(phaseCavMeasured.size()-1)).doubleValue(); //minPhase = someMeasuredData.getX(0); //int np = someMeasuredData.getNumbOfPoints(); //maxPhase = someMeasuredData.getX(np-1); avgPhase = (minPhase + maxPhase)/2.; dPhase = maxPhase - minPhase; System.out.println("Phases " + minPhase + " " + maxPhase); cavPhaseOffset = avgPhase - theDoc.theDesignPhase + theDoc.DTLPhaseOffset; // give some margin away from the scan endpoints for analysis range: theDoc.analysisStuff.phaseModelMax = maxPhase - 0.1 * dPhase; theDoc.myWindow().maxScanPhaseField.setValue(phaseModelMax); theDoc.analysisStuff.phaseModelMin = minPhase + 0.1 * dPhase; theDoc.myWindow().minScanPhaseField.setValue(phaseModelMin); theDoc.analysisStuff.makeCalcPoints(); analysisTableModel.fireTableDataChanged(); } }
package dr.evomodel.speciation; import dr.evolution.coalescent.DemographicFunction; import dr.evolution.coalescent.ConstantPopulation; import dr.evolution.tree.*; import dr.evolution.util.MutableTaxonListListener; import dr.evolution.util.Taxon; import dr.evolution.io.NewickImporter; import dr.evomodel.coalescent.VDdemographicFunction; import dr.evomodel.operators.TreeNodeSlide; import dr.evomodel.tree.TreeLogger; import dr.inference.model.*; import dr.inference.operators.Scalable; import dr.inference.operators.OperatorFailedException; import dr.util.Attributable; import dr.util.HeapSort; import dr.xml.*; import jebl.util.FixedBitSet; import java.util.*; public class SpeciesTreeModel extends AbstractModel implements MutableTree, NodeAttributeProvider, TreeLogger.LogUpon, Scalable { public static final String SPECIES_TREE = "speciesTree"; public static final String SPP_SPLIT_POPULATIONS = "sppSplitPopulations"; public static final String COALESCENT_POINTS_POPULATIONS = "coalescentPointsPopulations"; public static final String COALESCENT_POINTS_INDICATORS = "coalescentPointsIndicators"; public static final String BMPRIOR = "bmPrior"; public static final String CONST_ROOT_POPULATION = "constantRoot"; public static final String CONSTANT_POPULATION = "constantPopulation"; private final SimpleTree spTree; private final SpeciesBindings species; private final Map<NodeRef, NodeProperties> props = new HashMap<NodeRef, NodeProperties>(); public final Parameter sppSplitPopulations; private int[] singleStartPoints; private int[] pairStartPoints; private final Parameter coalPointsPops; private final Parameter coalPointsIndicator; private boolean nodePropsReady; private final NodeRef[] children; private final double[] heights; // any change of underlying parameters / models private boolean anyChange; // Tree has been edited in this cycle private boolean treeChanged; private final String spIndexAttrName = "spi"; private final boolean bmp; private final boolean nonConstRootPopulation; private final boolean constantPopulation; private class NodeProperties { final int speciesIndex; public VDdemographicFunction demogf; FixedBitSet spSet; public NodeProperties(int n) { speciesIndex = n; demogf = null; spSet = new FixedBitSet(species.nSpecies()); } } SpeciesTreeModel(SpeciesBindings species, Parameter sppSplitPopulations, Parameter coalPointsPops, Parameter coalPointsIndicator, Tree startTree, boolean bmp, boolean nonConstRootPopulation, boolean constantPopulation) { super(SPECIES_TREE); this.species = species; this.sppSplitPopulations = sppSplitPopulations; this.coalPointsPops = coalPointsPops; this.coalPointsIndicator = coalPointsIndicator; this.bmp = bmp; this.nonConstRootPopulation = nonConstRootPopulation; this.constantPopulation = constantPopulation; addVariable(sppSplitPopulations); addModel(species); if( coalPointsPops != null ) { assert coalPointsIndicator != null; assert !constantPopulation; addVariable(coalPointsPops); addVariable(coalPointsIndicator); final double[][] pts = species.getPopTimesSingle(); int start = 0; singleStartPoints = new int[pts.length]; for(int i = 0; i < pts.length; i++) { singleStartPoints[i] = start; start += pts[i].length; } if( ! bmp ) { final double[][] ptp = species.getPopTimesPair(); pairStartPoints = new int[ptp.length]; for(int i = 0; i < ptp.length; i++) { pairStartPoints[i] = start; start += ptp[i].length; } } } // build an initial noninformative tree spTree = compatibleUninformedSpeciesTree(startTree); // some of the code is generic but some parts assume a binary tree. assert Tree.Utils.isBinary(spTree); final int nNodes = spTree.getNodeCount(); heights = new double[nNodes]; children = new NodeRef[2 * nNodes + 1]; // fixed properties for(int k = 0; k < getExternalNodeCount(); ++k) { final NodeRef nodeRef = getExternalNode(k); final int n = (Integer) getNodeAttribute(nodeRef, spIndexAttrName); final NodeProperties np = new NodeProperties(n); props.put(nodeRef, np); np.spSet.set(n); } for(int k = 0; k < getInternalNodeCount(); ++k) { final NodeRef nodeRef = getInternalNode(k); props.put(nodeRef, new NodeProperties(-1)); } nodePropsReady = false; // crappy way to pass a result back from compatibleUninformedSpeciesTree. // check is using isCompatible(), which requires completion of construction. boolean check = spTree.getAttribute("check") != null; spTree.setAttribute("check", null); while( check ) { // Start tree had branch info, keep it when compatible, decrease height by 1% until // compatible otherwise. check = false; for( SpeciesBindings.GeneTreeInfo t : species.getGeneTrees() ) { if( ! isCompatible(t) ) { SimpleTree.Utils.scaleNodeHeights(spTree, 0.99); check = true; break; } } } } public boolean constPopulation() { return constantPopulation; } // Is gene tree compatible with species tree public boolean isCompatible(SpeciesBindings.GeneTreeInfo geneTreeInfo) { // can't set demographics if a tree is not compatible, but we need spSets. if (!nodePropsReady) { setSPsets(getRoot()); } return isCompatible(getRoot(), geneTreeInfo.getCoalInfo(), 0) >= 0; } // Not very efficient, should do something better, based on traversing the cList once private int isCompatible(NodeRef node, SpeciesBindings.CoalInfo[] cList, int loc) { if( !isExternal(node) ) { int l = -1; for(int nc = 0; nc < getChildCount(node); ++nc) { int l1 = isCompatible(getChild(node, nc), cList, loc); if( l1 < 0 ) { return -1; } assert l == -1 || l1 == l; l = l1; } loc = l; assert cList[loc].ctime >= getNodeHeight(node); } if( node == getRoot() ) { return cList.length; } // spSet guaranteed to be ready by caller final FixedBitSet nodeSps = props.get(node).spSet; final double limit = getNodeHeight(getParent(node)); while( loc < cList.length ) { final SpeciesBindings.CoalInfo ci = cList[loc]; if( ci.ctime >= limit ) { break; } boolean allIn = true, noneIn = true; for(int i = 0; i < 2; ++i) { final FixedBitSet s = ci.sinfo[i]; final int in1 = s.intersectCardinality(nodeSps); if( in1 > 0 ) { noneIn = false; } if( s.cardinality() != in1 ) { allIn = false; } } if( !(allIn || noneIn) ) { return -1; } ++loc; } return loc; } private static double fp(double val, double low, double[][] tt, int[] ii) { for (int k = 0; k < ii.length; ++k) { int ip = ii[k]; if (ip == tt[k].length || val <= tt[k][ip]) { --ip; while (ip >= 0 && val <= tt[k][ip]) { --ip; } assert ((ip < 0) || (tt[k][ip] < val)) && ((ip + 1 == tt[k].length) || (val <= tt[k][ip + 1])); if (ip >= 0) { low = Math.max(low, tt[k][ip]); } } else { ++ip; while (ip < tt[k].length && val > tt[k][ip]) { ++ip; } assert tt[k][ip - 1] < val && ((ip == tt[k].length) || (val <= tt[k][ip])); low = Math.max(low, tt[k][ip - 1]); } } return low; } private interface SimpleDemographicFunction { double population(double t); double upperBound(); } private class PLSD implements SimpleDemographicFunction { private final double[] pops; private final double[] times; public PLSD(double[] pops, double[] times) { assert pops.length == times.length + 1; this.pops = pops; this.times = times; } public double population(double t) { if( t >= upperBound() ) { return pops[pops.length-1]; } int k = 0; while( t > times[k] ) { t -= times[k]; ++k; } double a = t / (times[k] - (k > 0 ? times[k-1] : 0)); return a * pops[k] + (1-a) * pops[k+1]; } public double upperBound() { return times[times.length-1]; } } // Pass arguments of recursive functions in a compact format. private class Args { final double[][] cps = species.getPopTimesSingle(); final double[][] cpp; // = species.getPopTimesPair(); final int[] iSingle = new int[cps.length]; final int[] iPair; // = new int[cpp.length]; final double[] indicators = ((Parameter.Default) coalPointsIndicator).inspectParameterValues(); final double[] pops = ((Parameter.Default) coalPointsPops).inspectParameterValues(); final SimpleDemographicFunction[] dms; Args(Boolean bmp) { if( ! bmp ) { cpp = species.getPopTimesPair(); iPair = new int[cpp.length]; dms = null; } else { cpp = null; iPair = null; int nsps = cps.length; dms = new SimpleDemographicFunction[nsps]; for(int nsp = 0; nsp < nsps; ++nsp) { final int start = singleStartPoints[nsp]; final int stop = nsp < nsps - 1 ? singleStartPoints[nsp+1] : pops.length; double[] pop = new double[1 + stop - start] ; pop[0] = sppSplitPopulations.getParameterValue(nsp); // pops[nsp]; for(int k = 0; k < stop-start; ++k) { pop[k+1] = pops[start + k]; } dms[nsp] = new PLSD(pop, cps[nsp]); } } } private double findPrev(double val, double low) { low = fp(val, low, cps, iSingle); low = fp(val, low, cpp, iPair); return low; } } class RawPopulationHelper { final int[] preOrderIndices = new int[getNodeCount()]; final double[] pops = ((Parameter.Default) sppSplitPopulations).inspectParameterValues(); final int nsp = species.nSpecies(); final Args args = coalPointsPops != null ? new Args(bmp) : null; RawPopulationHelper() { setPreorderIndices(preOrderIndices); } public void getPopulations(NodeRef n, int nc, double[] p) { p[1] = pops[nsp + 2 * preOrderIndices[n.getNumber()] + nc]; final NodeRef child = getChild(n, nc); if( isExternal(child) ) { p[0] = pops[props.get(child).speciesIndex]; } else { int k = nsp + 2 * preOrderIndices[child.getNumber()]; p[0] = pops[k] + pops[k+1]; } } public double tipPopulation(NodeRef tip) { return pops[props.get(tip).speciesIndex]; } public int nSpecies() { return species.nSpecies(); } public boolean perSpeciesPopulation() { return args != null; } public double[] getTimes(int ns) { return ((PLSD)args.dms[ns]).times; } public double[] getPops(int ns) { return ((PLSD)args.dms[ns]).pops; } public void getRootPopulations(double[] p) { int k = nsp + 2 * preOrderIndices[getRoot().getNumber()]; p[0] = pops[k] + pops[k+1]; p[1] = nonConstRootPopulation ? pops[pops.length - 1] : p[0]; } public double geneTreesRootHeight() { //getNodeDemographic(getRoot()). double h = -1; for(SpeciesBindings.GeneTreeInfo t : species.getGeneTrees()) { h = Math.max(h, t.tree.getNodeHeight(t.tree.getRoot())); } return h; } } RawPopulationHelper getPopulationHelper() { return new RawPopulationHelper(); } static private class Points implements Comparable<Points> { final double time; double population; final boolean use; Points(double t, double p) { time = t; population = p; use = true; } Points(double t, boolean u) { time = t; population = 0; use = u; } public int compareTo(Points points) { return time < points.time ? -1 : (time > points.time ? 1 : 0); } } private NodeProperties setSPsets(NodeRef nodeID) { final NodeProperties nprop = props.get(nodeID); if( !isExternal(nodeID) ) { nprop.spSet = new FixedBitSet(species.nSpecies()); for(int nc = 0; nc < getChildCount(nodeID); ++nc) { NodeProperties p = setSPsets(getChild(nodeID, nc)); nprop.spSet.union(p.spSet); } } return nprop; } private int ti2f(int i,int j) { return (i==0) ? j : 2*i + j + 1; } private VDdemographicFunction bestLinearFit(double[] xs, double[] ys, boolean[] use) { assert (xs.length+1) == ys.length; assert ys.length == use.length + 2 || ys.length == use.length + 1; int N = ys.length; if( N == 2 ) { // cheaper return new VDdemographicFunction(xs, ys, getUnits()); } List<Integer> iv = new ArrayList<Integer>(2); iv.add(0); for(int k = 0; k < N-2; ++k) { if( use[k] ) { iv.add(k+1); } } iv.add(N-1); double[] ati = new double[xs.length + 1]; ati[0] = 0.0; System.arraycopy(xs, 0, ati, 1, xs.length); int n = iv.size(); double[] a = new double[3*n]; double[] v = new double[n]; for(int k = 0; k < n-1; ++k) { int i0 = iv.get(k); int i1 = iv.get(k+1); double u0 = ati[i0]; double u1 = ati[i1] - ati[i0]; // on last interval add data for last point if( i1 == N-1 ) { i1 += 1; } final int l = ti2f(k,k); final int l1 = ti2f(k+1,k); for(int j = i0; j < i1; ++j) { double t = ati[j]; double y = ys[j]; double z = (t - u0)/u1; v[k] += y * (1-z); a[l] += (1-z)*(1-z); a[l+1] += z * (1-z); a[l1] += z * (1-z); a[l1+1] += z*z; v[k+1] += y * z; } } for(int k = 0; k < n-1; ++k) { final double r = a[ti2f(k+1, k)] / a[ti2f(k,k)]; for(int j = k; j < k+3; ++j) { a[ti2f((k+1) , j)] -= a[ti2f(k, j)] * r; } v[k+1] -= v[k] * r; } double[] z = new double[n]; for(int k = n-1; k > 0; --k) { z[k] = v[k]/a[ti2f(k, k)]; v[k-1] -= a[ti2f((k-1) , k)] * z[k]; } z[0] = v[0]/a[ti2f(0,0)]; double[] t = new double[iv.size()-1]; for(int j = 0; j < t.length; ++j) { t[j] = ati[iv.get(j+1)]; } return new VDdemographicFunction(t, z, getUnits()); } // Assign positions in 'pointsList' for the sub-tree rooted at the ancestor of // nodeID. // pointsList is indexed by node-id. Every element is a list of internal // population points for the branch between nodeID and it's ancestor private NodeProperties getDemographicPoints(final NodeRef nodeID, Args args, Points[][] pointsList) { final NodeProperties nprop = props.get(nodeID); final int nSpecies = species.nSpecies(); // Species assignment from the tips never changes if( ! isExternal(nodeID) ) { nprop.spSet = new FixedBitSet(nSpecies); for(int nc = 0; nc < getChildCount(nodeID); ++nc) { final NodeProperties p = getDemographicPoints(getChild(nodeID, nc), args, pointsList); nprop.spSet.union(p.spSet); } } if( args == null ) { return nprop; } // parent height final double cHeight = nodeID != getRoot() ? getNodeHeight(getParent(nodeID)) : Double.MAX_VALUE; // points along branch // not sure what a good default size is? List<Points> allPoints = new ArrayList<Points>(5); if( bmp ) { for(int isp = nprop.spSet.nextOnBit(0); isp >= 0; isp = nprop.spSet.nextOnBit(isp + 1)) { final double[] cp = args.cps[isp]; final int upi = singleStartPoints[isp]; int i = args.iSingle[isp]; for(; i < cp.length && cp[i] < cHeight; ++i) { allPoints.add(new Points(cp[i], args.indicators[upi + i] > 0)); } args.iSingle[isp] = i; } } else { for(int isp = nprop.spSet.nextOnBit(0); isp >= 0; isp = nprop.spSet.nextOnBit(isp + 1)) { final double nodeHeight = spTree.getNodeHeight(nodeID); { double[] cp = args.cps[isp]; final int upi = singleStartPoints[isp]; int i = args.iSingle[isp]; while( i < cp.length && cp[i] < cHeight ) { if( args.indicators[upi + i] > 0 ) { //System.out.println(" popbit s"); args.iSingle[isp] = i; double prev = args.findPrev(cp[i], nodeHeight); double mid = (prev + cp[i]) / 2.0; assert nodeHeight < mid; allPoints.add(new Points(mid, args.pops[upi + i])); } ++i; } args.iSingle[isp] = i; } final int kx = (isp * (2 * nSpecies - isp - 3)) / 2 - 1; for(int y = nprop.spSet.nextOnBit(isp + 1); y >= 0; y = nprop.spSet.nextOnBit(y + 1)) { assert isp < y; int k = kx + y; double[] cp = args.cpp[k]; int i = args.iPair[k]; final int upi = pairStartPoints[k]; while( i < cp.length && cp[i] < cHeight ) { if( args.indicators[upi + i] > 0 ) { //System.out.println(" popbit p"); args.iPair[k] = i; final double prev = args.findPrev(cp[i], nodeHeight); double mid = (prev + cp[i]) / 2.0; assert nodeHeight < mid; allPoints.add(new Points(mid, args.pops[upi + i])); } ++i; } args.iPair[k] = i; } } } Points[] all = null; if( allPoints.size() > 0 ) { all = allPoints.toArray(new Points[allPoints.size()]); if( all.length > 1 ) { HeapSort.sort(all); } int len = all.length; if( bmp ) { int k = 0; while( k + 1 < len ) { final double t = all[k].time; if( t == all[k + 1].time ) { int j = k + 2; boolean use = all[k].use || all[k + 1].use; while( j < len && t == all[j].time ) { use = use || all[j].use; j += 1; } int removed = (j - k - 1); all[k] = new Points(t, use); for(int i = k + 1; i < len - removed; ++i) { all[i] = all[i + removed]; } len -= removed; } ++k; } } else { // duplications int k = 0; while( k + 1 < len ) { double t = all[k].time; if( t == all[k + 1].time ) { int j = k + 2; double v = all[k].population + all[k + 1].population; while( j < len && t == all[j].time ) { v += all[j].population; j += 1; } int removed = (j - k - 1); all[k] = new Points(t, v / (removed + 1)); for(int i = k + 1; i < len - removed; ++i) { all[i] = all[i + removed]; } //System.arraycopy(all, j, all, k + 1, all.length - j + 1); len -= removed; } ++k; } } if( len != all.length ) { Points[] a = new Points[len]; System.arraycopy(all, 0, a, 0, len); all = a; } if( bmp ) { for( Points p : all ) { double t = p.time; assert p.population == 0; for(int isp = nprop.spSet.nextOnBit(0); isp >= 0; isp = nprop.spSet.nextOnBit(isp + 1)) { SimpleDemographicFunction d = args.dms[isp]; if( t <= d.upperBound() ) { p.population += d.population(t); } } } } } pointsList[nodeID.getNumber()] = all; return nprop; } private int setDemographics(NodeRef nodeID, int pStart, int side, double[] pops, Points[][] pointsList) { final int nSpecies = species.nSpecies(); final NodeProperties nprop = props.get(nodeID); int pEnd; double p0; if( isExternal(nodeID) ) { final int sps = nprop.speciesIndex; p0 = pops[sps]; pEnd = pStart; } else { assert getChildCount(nodeID) == 2; final int iHere = setDemographics(getChild(nodeID, 0), pStart, 0, pops, pointsList); pEnd = setDemographics(getChild(nodeID, 1), iHere + 1, 1, pops, pointsList); if( constantPopulation ) { final int i = nSpecies + iHere; p0 = pops[i]; } else { final int i = nSpecies + iHere * 2; p0 = pops[i] + pops[i + 1]; } } if( constantPopulation ) { double[] xs = {}; double[] ys = {p0}; nprop.demogf = new VDdemographicFunction(xs, ys, getUnits()); // new ConstantPopulation(p0, getUnits()); } else { final double t0 = getNodeHeight(nodeID); Points[] p = pointsList != null ? pointsList[nodeID.getNumber()] : null; final int plen = p == null ? 0 : p.length; final boolean isRoot = nodeID == getRoot(); // double[] xs = new double[plen + (isRoot ? 1 : 1)]; // double[] ys = new double[plen + (isRoot ? 2 : 2)]; final boolean useBMP = bmp && pointsList != null; // internal nodes add one population point for the branch end. // on the root (with bmp) there is no such point. final int len = plen + (useBMP ? (!isRoot ? 1 : 0) : 1); double[] xs = new double[len]; double[] ys = new double[len+1]; boolean[] use = new boolean[len]; ys[0] = p0; for(int i = 0; i < plen; ++i) { xs[i] = p[i].time - t0; ys[i + 1] = p[i].population; use[i] = p[i].use; } if( !isRoot ) { final int anccIndex = (side == 0) ? pEnd : pStart - 1; final double pe = pops[nSpecies + anccIndex * 2 + side]; final double b = getBranchLength(nodeID); xs[xs.length - 1] = b; ys[ys.length - 1] = pe; } if( useBMP ) { nprop.demogf = bestLinearFit(xs, ys, use); } else { if( isRoot ) { // extend the last point to most ancient coalescent point. Has no effect on the demographic // per se but for use when analyzing the results. double h = -1; for(SpeciesBindings.GeneTreeInfo t : species.getGeneTrees()) { h = Math.max(h, t.tree.getNodeHeight(t.tree.getRoot())); } final double rh = h - t0; xs[xs.length - 1] = rh; //getNodeHeight(nodeID); //spTree.setBranchLength(nodeID, rh); // last value is for root branch end point ys[ys.length - 1] = pointsList != null ? ys[ys.length - 2] : (nonConstRootPopulation ? pops[pops.length - 1] : ys[ys.length - 2]); } nprop.demogf = new VDdemographicFunction(xs, ys, getUnits()); } } return pEnd; } private void setNodeProperties() { Points[][] perBranchPoints = null; if( coalPointsPops != null ) { final Args args = new Args(bmp); perBranchPoints = new Points[getNodeCount()][]; getDemographicPoints(getRoot(), args, perBranchPoints); } else { // sets species info getDemographicPoints(getRoot(), null, null); } setDemographics(getRoot(), 0, -1, ((Parameter.Default) sppSplitPopulations).inspectParameterValues(), perBranchPoints); } private Map<NodeRef, NodeProperties> getProps() { if (!nodePropsReady) { setNodeProperties(); nodePropsReady = true; } return props; } public DemographicFunction getNodeDemographic(NodeRef node) { return getProps().get(node).demogf; } public FixedBitSet spSet(NodeRef node) { return getProps().get(node).spSet; } public int speciesIndex(NodeRef tip) { assert isExternal(tip); // always ready even if props is dirty return props.get(tip).speciesIndex; } private Double setInitialSplitPopulations(FlexibleTree startTree, NodeRef node, int pos[]) { if( ! startTree.isExternal(node) ) { int loc=-1; for(int nc = 0; nc < startTree.getChildCount(node); ++nc ) { Double p = setInitialSplitPopulations(startTree, startTree.getChild(node, nc), pos ); if( nc == 0 ) { loc = pos[0]; pos[0] += 1; } if( p != null ) { sppSplitPopulations.setParameterValueQuietly(species.nSpecies() + 2*loc + nc, p); } } } final String comment = (String)startTree.getNodeAttribute(node, NewickImporter.COMMENT); Double p0 = null; if( comment != null ) { StringTokenizer st = new StringTokenizer(comment); p0 = Double.parseDouble(st.nextToken()); if( startTree.isExternal(node) ) { int ns = (Integer)startTree.getNodeAttribute(node, spIndexAttrName); sppSplitPopulations.setParameterValueQuietly(ns, p0); } // if just one value const if( st.hasMoreTokens() ) { p0 = Double.parseDouble(st.nextToken()); } } return p0; } private SimpleTree compatibleUninformedSpeciesTree(Tree startTree) { double rootHeight = Double.MAX_VALUE; for( SpeciesBindings.GeneTreeInfo t : species.getGeneTrees() ) { rootHeight = Math.min(rootHeight, t.getCoalInfo()[0].ctime); } final SpeciesBindings.SPinfo[] spp = species.species; if( startTree != null ) { // Allow start tree to be very basic basic - may be only partially resolved and no // branch lengths if( startTree.getExternalNodeCount() != spp.length ) { throw new Error("Start tree error - different number of tips"); } final FlexibleTree tree = new FlexibleTree(startTree, true); tree.resolveTree(); final double treeHeight = tree.getRootHeight(); if( treeHeight <= 0 ) { tree.setRootHeight(1.0); Utils.correctHeightsForTips(tree); SimpleTree.Utils.scaleNodeHeights(tree, rootHeight / tree.getRootHeight()); } SimpleTree sTree = new SimpleTree(tree); for(int ns = 0; ns < spp.length; ns++) { SpeciesBindings.SPinfo sp = spp[ns]; final int i = sTree.getTaxonIndex(sp.name); if( i < 0 ) { throw new Error(sp.name + " is not present in the start tree"); } final SimpleNode node = sTree.getExternalNode(i); node.setAttribute(spIndexAttrName, ns); // set for possible pops tree.setNodeAttribute( tree.getNode(tree.getTaxonIndex(sp.name)), spIndexAttrName, ns); } if( treeHeight > 0 ) { sTree.setAttribute("check", new Double(rootHeight)); } { assert ! constantPopulation; // not implemented yet int[] pos = {0}; setInitialSplitPopulations(tree, tree.getRoot(), pos); } return sTree; } final double delta = rootHeight / (spp.length + 1); double cTime = delta; List<SimpleNode> subs = new ArrayList<SimpleNode>(spp.length); for(int ns = 0; ns < spp.length; ns++) { SpeciesBindings.SPinfo sp = spp[ns]; final SimpleNode node = new SimpleNode(); node.setTaxon(new Taxon(sp.name)); subs.add(node); node.setAttribute(spIndexAttrName, ns); } while( subs.size() > 1 ) { final SimpleNode node = new SimpleNode(); int i = 0, j = 1; node.addChild(subs.get(i)); node.addChild(subs.get(j)); node.setHeight(cTime); cTime += delta; subs.set(j, node); subs.remove(i); } return new SimpleTree(subs.get(0)); } public void setPreorderIndices(int[] indices) { setPreorderIndices(getRoot(), 0, indices); } private int setPreorderIndices(NodeRef node, int loc, int[] indices) { if( ! isExternal(node) ) { int l = setPreorderIndices(getChild(node, 0), loc, indices); indices[node.getNumber()] = l; loc = setPreorderIndices(getChild(node, 1), l+1, indices); } return loc; } public String getName() { return getModelName(); } static private TreeNodeSlide internalTreeOP = null; public int scale(double scaleFactor, int nDims) throws OperatorFailedException { assert scaleFactor > 0; if( nDims <= 0 ) { storeState(); // just checks assert really beginTreeEdit(); final int count = getInternalNodeCount(); for(int i = 0; i < count; ++i) { final NodeRef n = getInternalNode(i); setNodeHeight(n, getNodeHeight(n) * scaleFactor); } endTreeEdit(); fireModelChanged(this, 1); return count; } else { if (nDims != 1) { throw new OperatorFailedException("not implemented for count != 1"); } if( internalTreeOP == null ) { internalTreeOP = new TreeNodeSlide(this, species, 1); } internalTreeOP.operateOneNode(scaleFactor); fireModelChanged(this, 1); return nDims; } } private final boolean verbose = false; protected void handleModelChangedEvent(Model model, Object object, int index) { if (verbose) System.out.println(" SPtree: model changed " + model.getId()); nodePropsReady = false; anyChange = true; // this should happen by default, no? fireModelChanged(); } protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { if (verbose) System.out.println(" SPtree: parameter changed " + variable.getId()); nodePropsReady = false; anyChange = true; } protected void storeState() { assert !treeChanged; assert !anyChange; } protected void restoreState() { if( verbose ) System.out.println(" SPtree: restore (" + treeChanged + "," + anyChange + ")"); if( treeChanged ) { spTree.beginTreeEdit(); for(int k = 0; k < getInternalNodeCount(); ++k) { final NodeRef node = getInternalNode(k); final int index = node.getNumber(); final double h = heights[index]; if( getNodeHeight(node) != h ) { setNodeHeight(node, h); } for(int nc = 0; nc < 2; ++nc) { final NodeRef child = getChild(node, nc); final NodeRef child1 = children[2 * index + nc]; if( child != child1 ) { replaceChild(node, child, child1); } assert getParent(child1) == node; } } setRoot(children[children.length - 1]); if( verbose ) System.out.println(" restored to: " + spTree); spTree.endTreeEdit(); } if( treeChanged || anyChange ) { setNodeProperties(); } treeChanged = false; anyChange = false; } protected void acceptState() { if (verbose) System.out.println(" SPtree: accept"); treeChanged = false; anyChange = false; } String previousTopology = null; public boolean logNow(int state) { final String curTop = Tree.Utils.uniqueNewick(spTree, spTree.getRoot()); if( state == 0 || !curTop.equals(previousTopology) ) { previousTopology = curTop; return true; } return false; } public String[] getNodeAttributeLabel() { // keep short, repeated endlessly in tree log return new String[]{"dmf"}; } public String[] getAttributeForNode(Tree tree, NodeRef node) { assert tree == this; //final VDdemographicFunction df = getProps().get(node).demogf; final DemographicFunction df = getNodeDemographic(node); return new String[]{"{" + df.toString() + "}"}; } // boring delegation public SimpleTree getSimpleTree() { return spTree; } public Tree getCopy() { return spTree.getCopy(); } public Type getUnits() { return spTree.getUnits(); } public void setUnits(Type units) { spTree.setUnits(units); } public int getNodeCount() { return spTree.getNodeCount(); } public boolean hasNodeHeights() { return spTree.hasNodeHeights(); } public double getNodeHeight(NodeRef node) { return spTree.getNodeHeight(node); } public double getNodeRate(NodeRef node) { return spTree.getNodeRate(node); } public Taxon getNodeTaxon(NodeRef node) { return spTree.getNodeTaxon(node); } public int getChildCount(NodeRef node) { return spTree.getChildCount(node); } public boolean isExternal(NodeRef node) { return spTree.isExternal(node); } public boolean isRoot(NodeRef node) { return spTree.isRoot(node); } public NodeRef getChild(NodeRef node, int i) { return spTree.getChild(node, i); } public NodeRef getParent(NodeRef node) { return spTree.getParent(node); } public boolean hasBranchLengths() { return spTree.hasBranchLengths(); } public double getBranchLength(NodeRef node) { return spTree.getBranchLength(node); } public void setBranchLength(NodeRef node, double length) { spTree.setBranchLength(node, length); } public NodeRef getExternalNode(int i) { return spTree.getExternalNode(i); } public NodeRef getInternalNode(int i) { return spTree.getInternalNode(i); } public NodeRef getNode(int i) { return spTree.getNode(i); } public int getExternalNodeCount() { return spTree.getExternalNodeCount(); } public int getInternalNodeCount() { return spTree.getInternalNodeCount(); } public NodeRef getRoot() { return spTree.getRoot(); } public void setRoot(NodeRef r) { spTree.setRoot(r); } public void addChild(NodeRef p, NodeRef c) { spTree.addChild(p, c); } public void removeChild(NodeRef p, NodeRef c) { spTree.removeChild(p, c); } public void replaceChild(NodeRef node, NodeRef child, NodeRef newChild) { spTree.replaceChild(node, child, newChild); } public boolean beginTreeEdit() { boolean beingEdited = spTree.beginTreeEdit(); if (!beingEdited) { // save tree for restore for (int n = 0; n < getInternalNodeCount(); ++n) { final NodeRef node = getInternalNode(n); final int k = node.getNumber(); children[2 * k] = getChild(node, 0); children[2 * k + 1] = getChild(node, 1); heights[k] = getNodeHeight(node); } children[children.length - 1] = getRoot(); treeChanged = true; nodePropsReady = false; //anyChange = true; } return beingEdited; } public void endTreeEdit() { spTree.endTreeEdit(); fireModelChanged(); } public void setNodeHeight(NodeRef n, double height) { spTree.setNodeHeight(n, height); } public void setNodeRate(NodeRef n, double rate) { spTree.setNodeRate(n, rate); } public void setNodeAttribute(NodeRef node, String name, Object value) { spTree.setNodeAttribute(node, name, value); } public Object getNodeAttribute(NodeRef node, String name) { return spTree.getNodeAttribute(node, name); } public Iterator getNodeAttributeNames(NodeRef node) { return spTree.getNodeAttributeNames(node); } public int getTaxonCount() { return spTree.getTaxonCount(); } public Taxon getTaxon(int taxonIndex) { return spTree.getTaxon(taxonIndex); } public String getTaxonId(int taxonIndex) { return spTree.getTaxonId(taxonIndex); } public int getTaxonIndex(String id) { return spTree.getTaxonIndex(id); } public int getTaxonIndex(Taxon taxon) { return spTree.getTaxonIndex(taxon); } public List<Taxon> asList() { return spTree.asList(); } public Iterator<Taxon> iterator() { return spTree.iterator(); } public Object getTaxonAttribute(int taxonIndex, String name) { return spTree.getTaxonAttribute(taxonIndex, name); } public int addTaxon(Taxon taxon) { return spTree.addTaxon(taxon); } public boolean removeTaxon(Taxon taxon) { return spTree.removeTaxon(taxon); } public void setTaxonId(int taxonIndex, String id) { spTree.setTaxonId(taxonIndex, id); } public void setTaxonAttribute(int taxonIndex, String name, Object value) { spTree.setTaxonAttribute(taxonIndex, name, value); } public String getId() { return spTree.getId(); } public void setId(String id) { spTree.setId(id); } public void setAttribute(String name, Object value) { spTree.setAttribute(name, value); } public Object getAttribute(String name) { return spTree.getAttribute(name); } public Iterator getAttributeNames() { return spTree.getAttributeNames(); } public void addMutableTreeListener(MutableTreeListener listener) { spTree.addMutableTreeListener(listener); } public void addMutableTaxonListListener(MutableTaxonListListener listener) { spTree.addMutableTaxonListListener(listener); } private static Parameter createCoalPointsPopParameter(SpeciesBindings spb, Double value, Boolean bmp) { int dim = 0; for( double[] d : spb.getPopTimesSingle() ) { dim += d.length; } if( ! bmp ) { for( double[] d : spb.getPopTimesPair() ) { dim += d.length; } } return new Parameter.Default(dim, value); } private static Parameter createSplitPopulationsParameter(SpeciesBindings spb, double value, boolean root, boolean constPop) { int dim ; if( constPop ) { // one per node dim = 2 * spb.nSpecies() - 1; } else { // one per species leaf (ns) + 2 per internal node (2*(ns-1)) + optionally one for the root dim = 3 * spb.nSpecies() - 2 + (root ? 1 : 0); } return new Parameter.Default(dim, value); } public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public Object parseXMLObject(XMLObject xo) throws XMLParseException { SpeciesBindings spb = (SpeciesBindings) xo.getChild(SpeciesBindings.class); Parameter coalPointsPops = null; Parameter coalPointsIndicators = null; final Boolean cr = xo.getAttribute(CONST_ROOT_POPULATION, false); final Boolean cp = xo.getAttribute(CONSTANT_POPULATION, false); final Boolean bmp = xo.getAttribute(BMPRIOR, false); { XMLObject cxo = xo.getChild(COALESCENT_POINTS_POPULATIONS); if( cxo != null ) { final double value = cxo.getAttribute(Attributable.VALUE, 1.0); coalPointsPops = createCoalPointsPopParameter(spb, cxo.getAttribute(Attributable.VALUE, value), bmp); ParameterParser.replaceParameter(cxo, coalPointsPops); coalPointsPops.addBounds( new Parameter.DefaultBounds(Double.MAX_VALUE, 0, coalPointsPops.getDimension())); cxo = xo.getChild(COALESCENT_POINTS_INDICATORS); if( cxo == null ) { throw new XMLParseException("Must have indicators"); } coalPointsIndicators = new Parameter.Default(coalPointsPops.getDimension(), 0); ParameterParser.replaceParameter(cxo, coalPointsIndicators); } else { // assert ! bmp; } } final XMLObject cxo = xo.getChild(SPP_SPLIT_POPULATIONS); final double value = cxo.getAttribute(Attributable.VALUE, 1.0); final boolean nonConstRootPopulation = coalPointsPops == null && !cr; final Parameter sppSplitPopulations = createSplitPopulationsParameter(spb, value, nonConstRootPopulation, cp); ParameterParser.replaceParameter(cxo, sppSplitPopulations); final Parameter.DefaultBounds bounds = new Parameter.DefaultBounds(Double.MAX_VALUE, 0, sppSplitPopulations.getDimension()); sppSplitPopulations.addBounds(bounds); final Tree startTree = (Tree) xo.getChild(Tree.class); return new SpeciesTreeModel(spb, sppSplitPopulations, coalPointsPops, coalPointsIndicators, startTree, bmp, nonConstRootPopulation, cp); } public XMLSyntaxRule[] getSyntaxRules() { return new XMLSyntaxRule[]{ AttributeRule.newBooleanRule(BMPRIOR, true), AttributeRule.newBooleanRule(CONST_ROOT_POPULATION, true), AttributeRule.newBooleanRule(CONSTANT_POPULATION, true), new ElementRule(SpeciesBindings.class), // A starting tree. Can be very minimal, i.e. no branch lengths and not resolved new ElementRule(Tree.class, true), new ElementRule(SPP_SPLIT_POPULATIONS, new XMLSyntaxRule[]{ AttributeRule.newDoubleRule(Attributable.VALUE, true), new ElementRule(Parameter.class)}), new ElementRule(COALESCENT_POINTS_POPULATIONS, new XMLSyntaxRule[]{ AttributeRule.newDoubleRule(Attributable.VALUE, true), new ElementRule(Parameter.class)}, true), new ElementRule(COALESCENT_POINTS_INDICATORS, new XMLSyntaxRule[]{ new ElementRule(Parameter.class)}, true), }; } public String getParserDescription() { return "Species tree which includes demographic function per branch."; } public Class getReturnType() { return SpeciesTreeModel.class; } public String getParserName() { return SPECIES_TREE; } }; }
package com.erakk.lnreader.ui.fragment; import android.annotation.SuppressLint; import android.app.Activity; import android.content.DialogInterface; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AlertDialog; import android.support.v7.widget.SearchView; import android.util.Log; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.erakk.lnreader.AlternativeLanguageInfo; import com.erakk.lnreader.Constants; import com.erakk.lnreader.LNReaderApplication; import com.erakk.lnreader.R; import com.erakk.lnreader.UIHelper; import com.erakk.lnreader.adapter.PageModelAdapter; import com.erakk.lnreader.callback.CallbackEventData; import com.erakk.lnreader.callback.DownloadCallbackEventData; import com.erakk.lnreader.callback.ICallbackEventData; import com.erakk.lnreader.callback.IExtendedCallbackNotifier; import com.erakk.lnreader.dao.NovelsDao; import com.erakk.lnreader.model.NovelCollectionModel; import com.erakk.lnreader.model.PageModel; import com.erakk.lnreader.task.AddNovelTask; import com.erakk.lnreader.task.AsyncTaskResult; import com.erakk.lnreader.task.DownloadNovelDetailsTask; import com.erakk.lnreader.task.LoadAlternativeTask; import com.erakk.lnreader.task.LoadNovelsTask; import org.jsoup.HttpStatusException; import java.util.ArrayList; public class DisplayLightNovelListFragment extends ListFragment implements IExtendedCallbackNotifier<AsyncTaskResult<?>>, INovelListHelper { private static final String TAG = DisplayLightNovelListFragment.class.toString(); private final ArrayList<PageModel> listItems = new ArrayList<PageModel>(); private PageModelAdapter adapter; private LoadNovelsTask task = null; private LoadAlternativeTask altTask = null; private DownloadNovelDetailsTask downloadTask = null; private AddNovelTask addTask = null; private boolean onlyWatched = false; private String touchedForDownload; private String mode; private String lang; private TextView loadingText; private ProgressBar loadingBar; private IFragmentListener mFragListener; @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mFragListener = (IFragmentListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement FragListener"); } mode = getArguments().getString(Constants.EXTRA_NOVEL_LIST_MODE); if(mode == null) mode = Constants.EXTRA_NOVEL_LIST_MODE_MAIN; onlyWatched = getArguments().getBoolean(Constants.EXTRA_ONLY_WATCHED, false); lang = getArguments().getString(Constants.EXTRA_NOVEL_LANG); Log.i(TAG, "IsWatched: " + onlyWatched + " Mode: " + mode + " lang: " + lang); String page = getArguments().getString(Constants.EXTRA_PAGE); String pageTitleHint = getArguments().getString(Constants.EXTRA_TITLE); if (page != null) loadNovel(page, pageTitleHint); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.fragment_display_light_novel_list, container, false); if (onlyWatched) { getActivity().setTitle("Watched Novels"); } else if (lang != null) { getActivity().setTitle("Alt. Novels"); } else { getActivity().setTitle("Light Novels"); } loadingText = (TextView) view.findViewById(R.id.emptyList); loadingBar = (ProgressBar) getActivity().findViewById(R.id.empttListProgress); return view; } @Override public void onStart() { super.onStart(); registerForContextMenu(getListView()); // Encapsulated in updateContent updateContent(false, onlyWatched); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.fragment_display_novel_watched, menu); MenuItem searchItem = menu.findItem(R.id.search_item); if(searchItem != null) { SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); if (searchView != null) { searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { Log.d("SEARCH", "Search: + " + query); performSearch(query); return false; } @Override public boolean onQueryTextChange(String query) { performSearch(query); return false; } }); searchView.setOnCloseListener(new SearchView.OnCloseListener() { @Override public boolean onClose() { performSearch(null); return false; } }); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) { searchView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() { @Override public void onViewAttachedToWindow(View v) { } @Override public void onViewDetachedFromWindow(View v) { performSearch(null); } }); } } } } private void performSearch(String query) { if(adapter != null) { adapter.filterData(query); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_download_all_info: this.downloadAllNovelInfo(); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); // Get the item that was clicked PageModel o = adapter.getItem(position); String novel = o.toString(); // Create a bundle containing information about the novel that is clicked Bundle bundle = new Bundle(); bundle.putString(Constants.EXTRA_NOVEL, novel); bundle.putString(Constants.EXTRA_PAGE, o.getPage()); bundle.putString(Constants.EXTRA_TITLE, o.getTitle()); bundle.putBoolean(Constants.EXTRA_ONLY_WATCHED, onlyWatched); mFragListener.changeNextFragment(bundle); Log.d(TAG, o.getPage() + " (" + o.getTitle() + ")"); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getActivity().getMenuInflater(); inflater.inflate(R.menu.context_menu_novel_item, menu); } @Override public boolean onContextItemSelected(android.view.MenuItem item) { if (!(item.getMenuInfo() instanceof AdapterView.AdapterContextMenuInfo)) return super.onContextItemSelected(item); Log.d(TAG, "Context menu called"); AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); switch (item.getItemId()) { case R.id.add_to_watch: /* * Implement code to toggle watch of this novel */ if (info.position > -1) { PageModel novel = listItems.get(info.position); if (novel.isWatched()) { novel.setWatched(false); Toast.makeText(getActivity(), "Removed from watch list: " + novel.getTitle(), Toast.LENGTH_SHORT).show(); } else { novel.setWatched(true); Toast.makeText(getActivity(), "Added to watch list: " + novel.getTitle(), Toast.LENGTH_SHORT).show(); } NovelsDao.getInstance().updatePageModel(novel); adapter.notifyDataSetChanged(); } return true; case R.id.download_novel: /* * Implement code to download novel synopsis */ if (info.position > -1) { PageModel novel = listItems.get(info.position); ArrayList<PageModel> novels = new ArrayList<PageModel>(); novels.add(novel); touchedForDownload = novel.getTitle() + "'s information"; executeDownloadTask(novels); } return true; case R.id.delete_novel: if (info.position > -1) { toggleProgressBar(true); PageModel novel = listItems.get(info.position); int result = NovelsDao.getInstance().deleteNovel(novel); if (result > 0) { listItems.remove(novel); adapter.notifyDataSetChanged(); } toggleProgressBar(false); } return true; default: return super.onContextItemSelected(item); } } // region private methods private void updateContent(boolean isRefresh, boolean onlyWatched) { // use the cached items. if (!isRefresh && listItems != null && listItems.size() > 0) return; try { // Check size int resourceId = R.layout.item_novel; if (UIHelper.isSmallScreen(getActivity())) { resourceId = R.layout.item_novel_small; } if (adapter != null) { adapter.setResourceId(resourceId); } else { adapter = new PageModelAdapter(getActivity(), resourceId, listItems); } boolean alphOrder = UIHelper.isAlphabeticalOrder(getActivity()); if (lang == null) executeTask(isRefresh, onlyWatched, alphOrder); else { executeAltTask(isRefresh, alphOrder, lang); } setListAdapter(adapter); } catch (Exception e) { Log.e(TAG, e.getMessage(), e); Toast.makeText(getActivity(), "Error when updating: " + e.getMessage(), Toast.LENGTH_LONG).show(); } } @SuppressLint("NewApi") private void executeTask(boolean isRefresh, boolean onlyWatched, boolean alphOrder) { task = new LoadNovelsTask(this, isRefresh, onlyWatched, alphOrder, mode); String key = null; if (mode.equalsIgnoreCase(Constants.EXTRA_NOVEL_LIST_MODE_MAIN)) { key = TAG + ":LoadNovelsTask:" + Constants.ROOT_NOVEL_ENGLISH; } else if (mode.equalsIgnoreCase(Constants.EXTRA_NOVEL_LIST_MODE_TEASER)) { key = TAG + ":LoadNovelsTask:" + Constants.ROOT_TEASER; } else if (mode.equalsIgnoreCase(Constants.EXTRA_NOVEL_LIST_MODE_ORIGINAL)) { key = TAG + ":LoadNovelsTask:" + Constants.ROOT_ORIGINAL; } else if (mode.equalsIgnoreCase(Constants.EXTRA_NOVEL_LIST_MODE_WEB)) { key = TAG + ":LoadNovelsTask:" + Constants.ROOT_WEB; } boolean isAdded = LNReaderApplication.getInstance().addTask(key, task); if (isAdded) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else task.execute(); } else { Log.i(TAG, "Continue execute task: " + key); LoadNovelsTask tempTask = (LoadNovelsTask) LNReaderApplication.getInstance().getTask(key); if (tempTask != null) { task = tempTask; task.owner = this; } } toggleProgressBar(true); } private void executeAltTask(boolean isRefresh, boolean alphOrder, String lang) { altTask = new LoadAlternativeTask(this, isRefresh, alphOrder, lang); String key = null; if (lang != null) key = TAG + ":LoadAlternativeTask:" + AlternativeLanguageInfo.getAlternativeLanguageInfo().get(lang).getCategoryInfo(); boolean isAdded = LNReaderApplication.getInstance().addTask(key, altTask); if (isAdded) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) altTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else altTask.execute(); } else { Log.i(TAG, "Continue execute task: " + key); LoadAlternativeTask tempTask = (LoadAlternativeTask) LNReaderApplication.getInstance().getTask(key); if (tempTask != null) { altTask = tempTask; altTask.owner = this; } } toggleProgressBar(true); } @SuppressLint("NewApi") private void executeDownloadTask(ArrayList<PageModel> novels) { downloadTask = new DownloadNovelDetailsTask(this); if (novels == null || novels.size() == 0) return; String key = DisplayLightNovelDetailsFragment.TAG + ":" + novels.get(0).getPage(); if (novels.size() > 1) { if (mode.equalsIgnoreCase(Constants.EXTRA_NOVEL_LIST_MODE_MAIN)) { key = DisplayLightNovelDetailsFragment.TAG + ":All_Novels"; } else if (mode.equalsIgnoreCase(Constants.EXTRA_NOVEL_LIST_MODE_TEASER)) { key = DisplayLightNovelDetailsFragment.TAG + ":All_Teasers"; } else if (mode.equalsIgnoreCase(Constants.EXTRA_NOVEL_LIST_MODE_ORIGINAL)) { key = DisplayLightNovelDetailsFragment.TAG + ":All_Original"; } } boolean isAdded = LNReaderApplication.getInstance().addTask(key, downloadTask); if (isAdded) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) downloadTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, novels.toArray(new PageModel[novels.size()])); else downloadTask.execute(novels.toArray(new PageModel[novels.size()])); } else { Log.i(TAG, "Continue download task: " + key); DownloadNovelDetailsTask tempTask = (DownloadNovelDetailsTask) LNReaderApplication.getInstance().getTask(key); if (tempTask != null) { downloadTask = tempTask; downloadTask.owner = this; } toggleProgressBar(true); } } @SuppressLint("NewApi") private void executeAddTask(PageModel novel) { String key = DisplayLightNovelDetailsFragment.TAG + ":Add:" + novel.getPage(); addTask = new AddNovelTask(this, key); boolean isAdded = LNReaderApplication.getInstance().addTask(key, addTask); if (isAdded) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) addTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, novel); else addTask.execute(novel); } else { Log.i(TAG, "Continue Add task: " + key); AddNovelTask tempTask = (AddNovelTask) LNReaderApplication.getInstance().getTask(key); if (tempTask != null) { addTask = tempTask; addTask.owner = this; } } toggleProgressBar(true); } private void loadNovel(String page, String novelTitleHint) { Bundle bundle = new Bundle(); bundle.putString(Constants.EXTRA_PAGE, page); bundle.putString(Constants.EXTRA_TITLE, novelTitleHint); mFragListener.changeNextFragment(bundle); } @Override public void refreshList() { boolean onlyWatched = getActivity().getIntent().getBooleanExtra(Constants.EXTRA_ONLY_WATCHED, false); updateContent(true, onlyWatched); Toast.makeText(getActivity(), "Refreshing " + mode + " Novel...", Toast.LENGTH_SHORT).show(); } @Override public void downloadAllNovelInfo() { if (onlyWatched) { touchedForDownload = "Watched Light Novels information"; } else if (mode == null || mode.equalsIgnoreCase(Constants.EXTRA_NOVEL_LIST_MODE_MAIN)) { touchedForDownload = "All Main Light Novels information"; } else if (mode.equalsIgnoreCase(Constants.EXTRA_NOVEL_LIST_MODE_TEASER)) { touchedForDownload = "All Teaser Light Novels information"; } else if (mode.equalsIgnoreCase(Constants.EXTRA_NOVEL_LIST_MODE_ORIGINAL)) { touchedForDownload = "All Original Light Novels information"; } executeDownloadTask(listItems); } @Override public void manualAdd() { AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); alert.setTitle(getString(R.string.add_novel_main, mode)); LayoutInflater factory = LayoutInflater.from(getActivity()); View inputView = factory.inflate(R.layout.dialog_add_new_novel, null); final EditText inputName = (EditText) inputView.findViewById(R.id.page); final EditText inputTitle = (EditText) inputView.findViewById(R.id.title); alert.setView(inputView); alert.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { if (whichButton == DialogInterface.BUTTON_POSITIVE) { handleOK(inputName, inputTitle); } } }); alert.setNegativeButton("Cancel", null); alert.show(); } private void handleOK(EditText input, EditText inputTitle) { String novel = input.getText().toString(); String title = inputTitle.getText().toString(); if (novel != null && novel.length() > 0 && inputTitle != null && inputTitle.length() > 0) { PageModel temp = new PageModel(); temp.setPage(novel); temp.setTitle(title); temp.setType(PageModel.TYPE_NOVEL); temp.setParent(Constants.ROOT_NOVEL_ENGLISH); if (mode.equalsIgnoreCase(Constants.EXTRA_NOVEL_LIST_MODE_MAIN)) { temp.setParent(Constants.ROOT_NOVEL_ENGLISH); } else if (mode.equalsIgnoreCase(Constants.EXTRA_NOVEL_LIST_MODE_TEASER)) { temp.setParent(Constants.ROOT_TEASER); temp.setStatus(Constants.STATUS_TEASER); } else if (mode.equalsIgnoreCase(Constants.EXTRA_NOVEL_LIST_MODE_ORIGINAL)) { temp.setParent(Constants.ROOT_ORIGINAL); temp.setStatus(Constants.STATUS_ORIGINAL); } executeAddTask(temp); } else { Toast.makeText(getActivity(), "Empty Input", Toast.LENGTH_LONG).show(); } } private void toggleProgressBar(boolean show) { View root = getView(); if (root != null) { ListView listView = getListView(); if (listView == null || loadingText == null || loadingBar == null) return; if (show) { loadingText.setText("Loading List, please wait..."); loadingText.setVisibility(TextView.VISIBLE); loadingBar.setVisibility(ProgressBar.VISIBLE); listView.setVisibility(ListView.GONE); } else { loadingText.setVisibility(TextView.GONE); loadingBar.setVisibility(ProgressBar.GONE); listView.setVisibility(ListView.VISIBLE); } } } // endregion // region IExtendedCallbackNotifier<AsyncTaskResult<?>> implementation @Override public void onCompleteCallback(ICallbackEventData message, AsyncTaskResult<?> result) { if (!isAdded()) return; Exception e = result.getError(); if (e == null) { Class t = result.getResultType(); // from LoadNovelsTask if (t == PageModel[].class) { PageModel[] list = (PageModel[]) result.getResult(); Log.d(TAG, "LoadNovelsTask result ok"); if (list != null && list.length > 0) { adapter.clear(); adapter.addAll(list); toggleProgressBar(false); if (loadingText != null) { loadingText.setVisibility(TextView.GONE); } } else { toggleProgressBar(false); if (loadingText != null) { loadingText.setVisibility(TextView.VISIBLE); loadingText.setText(getResources().getString(R.string.list_empty)); } Log.w(TAG, "Empty ArrayList!"); } } // from DownloadNovelDetailsTask else if (t == NovelCollectionModel[].class) { onProgressCallback(new CallbackEventData("Download complete.", "DownloadNovelDetailsTask")); NovelCollectionModel[] list = (NovelCollectionModel[]) result.getResult(); for (NovelCollectionModel novelCol : list) { try { PageModel page = novelCol.getPageModel(); boolean found = false; for (PageModel temp : adapter.data) { if (temp.getPage().equalsIgnoreCase(page.getPage())) { found = true; break; } } if (!found) { adapter.data.add(page); } } catch (Exception e1) { Log.e(TAG, e1.getClass().toString() + ": " + e1.getMessage(), e1); } } adapter.notifyDataSetChanged(); toggleProgressBar(false); } else { Log.e(TAG, "Unknown ResultType: " + t.getName()); } } else { String msg = e.getMessage(); Log.e(TAG, e.getClass().toString() + ": " + message, e); if (e.getClass() == HttpStatusException.class) { HttpStatusException hes = (HttpStatusException) e; msg += ". Status=" + hes.getStatusCode(); } Toast.makeText(getActivity(), e.getClass().toString() + ": " + msg, Toast.LENGTH_LONG).show(); } toggleProgressBar(false); } @Override public void onProgressCallback(ICallbackEventData message) { if (loadingText != null && loadingText.getVisibility() == TextView.VISIBLE) loadingText.setText(message.getMessage()); if (message instanceof DownloadCallbackEventData) { DownloadCallbackEventData downloadData = (DownloadCallbackEventData) message; LNReaderApplication.getInstance().updateDownload(message.getSource(), downloadData.getPercentage(), message.getMessage()); if (loadingBar != null && loadingBar.getVisibility() == View.VISIBLE) { loadingBar.setIndeterminate(false); loadingBar.setMax(100); loadingBar.setProgress(downloadData.getPercentage()); loadingBar.setProgress(0); loadingBar.setProgress(downloadData.getPercentage()); loadingBar.setMax(100); } } } /** * @param id task id * @param toastText toast text * @param type 0=Add Download 1=Show progress 2=Remove Download * @param hasError has error? * @return */ @Override public boolean downloadListSetup(String id, String toastText, int type, boolean hasError) { if (!this.isAdded() || this.isDetached()) return false; boolean exists = false; if (type == 0) { if (LNReaderApplication.getInstance().isDownloadExists(id)) { exists = true; Toast.makeText(getActivity(), "Download already on queue.", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getActivity(), "Downloading " + touchedForDownload + ".", Toast.LENGTH_SHORT).show(); LNReaderApplication.getInstance().addDownload(id, touchedForDownload); } } else if (type == 1) { Toast.makeText(getActivity(), toastText, Toast.LENGTH_SHORT).show(); } else if (type == 2) { String name = LNReaderApplication.getInstance().getDownloadName(id); if (name != null) { String message = String.format("%s's download finished!", name); if (hasError) message = String.format("%s's download finished with error(s)!", name); Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show(); LNReaderApplication.getInstance().removeDownload(id); } } return exists; } // endregion }
package com.sem4ikt.uni.recipefinderchatbot.presenter; import android.support.annotation.VisibleForTesting; import com.sem4ikt.uni.recipefinderchatbot.activity.LoginActivity; import com.sem4ikt.uni.recipefinderchatbot.database.Authentication; import com.sem4ikt.uni.recipefinderchatbot.database.Interface.IFirebaseAuth; import com.sem4ikt.uni.recipefinderchatbot.model.LoginUserModel; import com.sem4ikt.uni.recipefinderchatbot.model.interfaces.ILoginUserModel; import com.sem4ikt.uni.recipefinderchatbot.presenter.interfaces.ILoginCallback; import com.sem4ikt.uni.recipefinderchatbot.presenter.interfaces.ILoginPresenter; import com.sem4ikt.uni.recipefinderchatbot.view.ILoginView; public class LoginPresenter extends BasePresenter<ILoginView> implements ILoginPresenter<ILoginView>, ILoginCallback { private ILoginUserModel user; private IFirebaseAuth auth; public LoginPresenter(ILoginView view){ super(view); // Create login user model user = new LoginUserModel(); // Create model auth = new Authentication(); } @VisibleForTesting LoginPresenter(ILoginView view, IFirebaseAuth auth, ILoginUserModel userModel ){ super(view); user = new LoginUserModel(); // Create model this.auth = auth; this.user = userModel; } @Override public void clear() { view.onClearText(); } @Override public void doLogin(String email, String password){ user.setPassword(password); user.setEmail(email); setProgressBarVisiblity(true); if (user.checkUserValidity()) { auth.signIn(email, password, this); } else { view.onShowToast("Incorrect password or email"); setProgressBarVisiblity(false); } } @Override public void doCreateUser(String email, String password, String confirm_password) { user.setPassword(password); user.setConfirmPassword(confirm_password); user.setEmail(email); setProgressBarVisiblity(true); if (user.checkUserValidity()) if (user.checkPasswordsMatches()) { auth.createUserWithEmailAndPassword(email, password, this); } else { view.onShowToast("Password and Confirm Password must be identical."); setProgressBarVisiblity(false); } else { view.onShowToast("Password and Confirm Password must be identical and email must be vaild."); setProgressBarVisiblity(false); } } @Override public void doForgotPassword(String email) { setProgressBarVisiblity(true); auth.sendResetEmailVerification(email, this); } @Override public void showLayout(LoginActivity.LoginView v) { view.onPresentView(v); } @Override public void doBack(LoginActivity.LoginView state) { switch (state) { case LOGIN: view.onFinish(); break; case SIGN_UP: case FORGOT_PASSWORD: default: view.onPresentView(LoginActivity.LoginView.LOGIN); break; } clear(); } @Override public void onAuthenticationFinished(AUTH auth, String reason) { setProgressBarVisiblity(false); switch (auth){ case SIGN_IN_SUCCESS: view.onLogin(true); break; case SIGN_IN_FAILED: view.onLogin(false); break; case CREATE_SUCCESS: view.onRegister(true); view.onPresentView(LoginActivity.LoginView.LOGIN); break; case CREATE_FAILED: view.onRegister(false); break; case FORGOT_PASSWORD_SUCCESS: view.onPassForgot(true); view.onPresentView(LoginActivity.LoginView.LOGIN); break; case FORGOT_PASSWORD_FAILED: view.onPassForgot(false); break; case UPDATE_PASSWORD_SUCCESS: break; case UPDATE_PASSWORD_FAILED: break; case DELETE_ACCOUNT_SUCCESS: break; case DELETE_ACCOUNT_FAILED: break; default: break; } } @Override public void setProgressBarVisiblity(boolean visible) { view.onSetProgressVisibility(visible); } @Override public void doToast(String text) { view.onShowToast(text); } public enum AUTH { SIGN_IN_SUCCESS, SIGN_IN_FAILED, CREATE_SUCCESS, CREATE_FAILED, FORGOT_PASSWORD_SUCCESS, FORGOT_PASSWORD_FAILED, UPDATE_PASSWORD_SUCCESS, UPDATE_PASSWORD_FAILED, DELETE_ACCOUNT_SUCCESS, DELETE_ACCOUNT_FAILED } }
package edu.mit.streamjit.impl.common; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import static com.google.common.base.Preconditions.*; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import edu.mit.streamjit.api.StreamCompilationFailedException; import edu.mit.streamjit.api.StreamCompiler; import edu.mit.streamjit.api.Worker; import edu.mit.streamjit.impl.blob.Blob; import edu.mit.streamjit.impl.blob.Blob.Token; import edu.mit.streamjit.impl.concurrent.ConcurrentStreamCompiler; import edu.mit.streamjit.impl.distributed.DistributedStreamCompiler; /** * BlobGraph builds predecessor successor relationship for set of partitioned * workers, and verifies for cyclic dependencies among the partitions. Blob * graph doesn't keep blobs. Instead it keeps {@link BlobNode} that represents * blobs. </p> All BlobNodes in the graph can be retrieved and used in coupled * with {@link AbstractDrainer} to successfully perform draining process. * * @author Sumanan sumanan@mit.edu * @since Jul 30, 2013 */ public class BlobGraph { /** * All nodes in the graph. */ private final ImmutableSet<BlobNode> blobNodes; /** * The blob which has the overall stream input. */ private final BlobNode sourceBlobNode; public BlobGraph(List<Set<Worker<?, ?>>> partitionWorkers) { checkNotNull(partitionWorkers); Set<DummyBlob> blobSet = new HashSet<>(); for (Set<Worker<?, ?>> workers : partitionWorkers) { blobSet.add(new DummyBlob(workers)); } ImmutableSet.Builder<BlobNode> builder = new ImmutableSet.Builder<>(); for (DummyBlob b : blobSet) { builder.add(new BlobNode(b.id)); } this.blobNodes = builder.build(); Map<Token, BlobNode> blobNodeMap = new HashMap<>(); for (BlobNode node : blobNodes) { blobNodeMap.put(node.blobID, node); } for (DummyBlob cur : blobSet) { for (DummyBlob other : blobSet) { if (cur == other) continue; if (Sets.intersection(cur.outputs, other.inputs).size() != 0) { BlobNode curNode = blobNodeMap.get(cur.id); BlobNode otherNode = blobNodeMap.get(other.id); curNode.addSuccessor(otherNode); otherNode.addPredecessor(curNode); } } } checkCycles(blobNodes); BlobNode sourceBlob = null; for (BlobNode bn : blobNodes) { if (bn.getDependencyCount() == 0) { assert sourceBlob == null : "Multiple independent blobs found."; sourceBlob = bn; } } checkNotNull(sourceBlob); this.sourceBlobNode = sourceBlob; } /** * . * * @return All nodes in the graph. */ public ImmutableSet<BlobNode> getBlobNodes() { return blobNodes; } public BlobNode getBlobNode(Token blobID) { for (BlobNode bn : blobNodes) { if (bn.getBlobID().equals(blobID)) return bn; } return null; } /** * A Drainer can be set to the {@link BlobGraph} to perform draining. * * @param drainer */ public void setDrainer(AbstractDrainer drainer) { for (BlobNode bn : blobNodes) { bn.setDrainer(drainer); } } /** * TODO: Ensure whether providing this public method is useful. * * @return the sourceBlobNode */ public BlobNode getSourceBlobNode() { return sourceBlobNode; } /** * Does a depth first traversal to detect cycles in the graph. * * @param blobNodes */ private void checkCycles(Collection<BlobNode> blobNodes) { Map<BlobNode, Color> colorMap = new HashMap<>(); for (BlobNode b : blobNodes) { colorMap.put(b, Color.WHITE); } for (BlobNode b : blobNodes) { if (colorMap.get(b) == Color.WHITE) if (DFS(b, colorMap)) throw new StreamCompilationFailedException( "Cycles found among blobs"); } } /** * A cycle exits in a directed graph if a back edge is detected during a DFS * traversal. A back edge exists in a directed graph if the currently * explored vertex has an adjacent vertex that was already colored gray * * @param vertex * @param colorMap * @return <code>true</code> if cycle found, <code>false</code> otherwise. */ private boolean DFS(BlobNode vertex, Map<BlobNode, Color> colorMap) { colorMap.put(vertex, Color.GRAY); for (BlobNode adj : vertex.getSuccessors()) { if (colorMap.get(adj) == Color.GRAY) return true; if (colorMap.get(adj) == Color.WHITE) if (DFS(adj, colorMap)) return true; } colorMap.put(vertex, Color.BLACK); return false; } /** * BlobNode represents the vertex in the blob graph ({@link BlobGraph}). It * represents a {@link Blob} and carry the draining process of that blob. * * @author Sumanan */ public static final class BlobNode { private AbstractDrainer drainer; /** * The blob that wrapped by this blob node. */ private Token blobID; /** * Predecessor blob nodes of this blob node. */ private List<BlobNode> predecessors; /** * Successor blob nodes of this blob node. */ private List<BlobNode> successors; /** * The number of undrained predecessors of this blobs. Everytime, when a * predecessor finished draining, dependencyCount will be decremented * and once it reached to 0 this blob will be called for draining. */ private AtomicInteger dependencyCount; /** * Set to true iff this blob has been drained. */ private volatile boolean isDrained; private BlobNode(Token blob) { this.blobID = blob; predecessors = new ArrayList<>(); successors = new ArrayList<>(); dependencyCount = new AtomicInteger(0); isDrained = false; } /** * Should be called when the draining of the current blob has been * finished. This function stops all threads belong to the blob and * inform its successors as well. */ public void drained() { isDrained = true; for (BlobNode suc : this.successors) { suc.predecessorDrained(this); } drainer.drainingFinished(this); } /** * Drain the blob mapped by this blob node. */ private void drain() { checkNotNull(drainer); drainer.drain(this); } /** * @return <code>true</code> iff the blob mapped by this blob node was * drained. */ public boolean isDrained() { return isDrained; } /** * @return Identifier of {@link Blob} and blob node. */ public Token getBlobID() { return blobID; } private ImmutableList<BlobNode> getSuccessors() { return ImmutableList.copyOf(successors); } private void addPredecessor(BlobNode pred) { assert !predecessors.contains(pred) : String.format( "The BlobNode %s has already been set as a predecessors", pred); predecessors.add(pred); dependencyCount.set(dependencyCount.get() + 1); } private void addSuccessor(BlobNode succ) { assert !successors.contains(succ) : String .format("The BlobNode %s has already been set as a successor", succ); successors.add(succ); } private void predecessorDrained(BlobNode pred) { if (!predecessors.contains(pred)) throw new IllegalArgumentException("Illegal Predecessor"); assert dependencyCount.get() > 0 : String .format("Graph mismatch : My predecessors count is %d. But more than %d of BlobNodes claim me as their successor", predecessors.size(), predecessors.size()); if (dependencyCount.decrementAndGet() == 0) { drain(); } } /** * @return The number of undrained predecessors. */ private int getDependencyCount() { return dependencyCount.get(); } private void setDrainer(AbstractDrainer drainer) { checkNotNull(drainer); this.drainer = drainer; } } /** * Abstract drainer is to perform draining on a stream application. Both * {@link DistributedStreamCompiler} and {@link ConcurrentStreamCompiler} * may extends this to implement the draining on their particular context. * Works coupled with {@link BlobNode} and {@link BlobGraph}. * * @author Sumanan sumanan@mit.edu * @since Jul 30, 2013 */ public static abstract class AbstractDrainer { /** * Blob graph of the stream application that needs to be drained. */ protected final BlobGraph blobGraph; private final CountDownLatch latch; private AtomicInteger unDrainedNodes; /** * We cannot say draining is finished by checking unDrainedNodes ==0. * Even after unDrainedNodes become zero, all data in the tail buffers * have to be read by the CompiledStream.pull(). */ private AtomicBoolean isDrainingfinished; /** * Whether the {@link StreamCompiler} needs the drain data after * draining. */ protected boolean needDrainData; public AbstractDrainer(BlobGraph blobGraph, boolean needDrainData) { this.blobGraph = blobGraph; this.needDrainData = needDrainData; unDrainedNodes = new AtomicInteger(blobGraph.getBlobNodes().size()); latch = new CountDownLatch(1); blobGraph.setDrainer(this); isDrainingfinished = new AtomicBoolean(false); } public void drainingFinished(BlobNode blobNode) { drained(blobNode); if (unDrainedNodes.decrementAndGet() == 0) { drainingFinished(); isDrainingfinished.set(true); latch.countDown(); } } /** * Initiate the draining of the blobgraph. */ public final void startDraining() { blobGraph.getSourceBlobNode().drain(); } /** * @return true iff draining of the stream application is finished. */ public final boolean isDrained() { return isDrainingfinished.get(); } public final void awaitDrained() throws InterruptedException { latch.await(); } public final void awaitDrained(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { latch.await(timeout, unit); } /** * Once a {@link BlobNode}'s all preconditions are satisfied for * draining, blob node will call this function drain the blob. * * @param node */ protected abstract void drain(BlobNode node); /** * A blob thread ( Only one blob thread, if there are many threads on * the blob) must call this function through a callback once draining of * that particular blob is finished. * * @param node */ protected abstract void drained(BlobNode node); /** * Once all {@link BlobNode} have been drained, this function will get * called. This can be used to do the final cleanups ( e.g, All data in * the tail buffer should be consumed before this function returns.) * After the return of this function, isDrained() will start to return * true. */ protected abstract void drainingFinished(); } /** * Just used to build the input and output tokens of a partitioned blob * workers. imitate a {@link Blob}. */ private final class DummyBlob { private final ImmutableSet<Token> inputs; private final ImmutableSet<Token> outputs; private final Token id; private DummyBlob(Set<Worker<?, ?>> workers) { ImmutableSet.Builder<Token> inputBuilder = new ImmutableSet.Builder<>(); ImmutableSet.Builder<Token> outputBuilder = new ImmutableSet.Builder<>(); for (IOInfo info : IOInfo.externalEdges(workers)) { (info.isInput() ? inputBuilder : outputBuilder).add(info .token()); } inputs = inputBuilder.build(); outputs = outputBuilder.build(); id = Collections.min(inputs); } } /** * Color enumerator used by DFS algorithm to find cycles in the blob graph. */ private enum Color { WHITE, GRAY, BLACK } }
package hackathon.rc.ca.hackathon.controllers; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.SeekBar; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.Unbinder; import hackathon.rc.ca.hackathon.App; import hackathon.rc.ca.hackathon.R; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * Use the {@link MiniControllerFragment#newInstance} factory method to * create an instance of this fragment. */ public class MiniControllerFragment extends Fragment { private Unbinder mUnbinder; @BindView(R.id.Play) ImageButton mPlayButton; @BindView(R.id.Pause) ImageButton mPauseButton; public MiniControllerFragment() { // Required empty public constructor } // TODO: Rename and change types and number of parameters public static MiniControllerFragment newInstance() { MiniControllerFragment fragment = new MiniControllerFragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.mini_controller, container, false); mUnbinder = ButterKnife.bind(this, view); return view; } @Override public void onDestroyView() { super.onDestroyView(); if (mUnbinder != null) { mUnbinder.unbind(); } } @Override public void onDetach() { super.onDetach(); } private App getApp() { return (App) getActivity().getApplication(); } @OnClick(R.id.Play) public void onPlay() { getApp().getPlaybackManager().resume(); mPlayButton.setVisibility(View.INVISIBLE); } @OnClick(R.id.Pause) public void onPaused() { getApp().getPlaybackManager().pause(); mPlayButton.setVisibility(View.VISIBLE); } }